kylix developer's guide - freearmstrong.craig.free.fr/ebooks/sams/sams kylix developers...

986
Charles Calvert Marjorie Calvert John Kaster Bob Swart 201 West 103rd St., Indianapolis, Indiana, 46290 USA Kylix Developer’s Guide

Upload: dolien

Post on 05-Jul-2018

229 views

Category:

Documents


1 download

TRANSCRIPT

  • Charles Calvert

    Marjorie Calvert

    John Kaster

    Bob Swart

    201 West 103rd St., Indianapolis, Indiana, 46290 USA

    Kylix Developers Guide

    00 0672320606 FM 11/1/01 2:47 PM Page i

  • Kylix Developers GuideCopyright 2002 by Sams PublishingAll rights reserved. No part of this book shall be reproduced, stored in aretrieval 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 authors assume no responsibility for errors oromissions. Nor is any liability assumed for damages resulting from the use ofthe information contained herein.

    International Standard Book Number: 0-672-32060-6

    Library of Congress Catalog Card Number: 00-107408

    Printed in the United States of America

    First Printing: October 2001

    04 03 02 01 4 3 2 1

    TrademarksAll terms mentioned in this book that are known to be trademarks or servicemarks have been appropriately capitalized. Sams Publishing 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 norresponsibility to any person or entity with respect to any loss or damages aris-ing from the information contained in this book.

    EXECUTIVE EDITORMichael Stephens

    ACQUISITIONS EDITORCarol Ackerman

    DEVELOPMENT EDITORTiffany Taylor

    MANAGING EDITORMatt Purcell

    PROJECT EDITORAndy Beaster

    COPY EDITORKate Givens

    INDEXERDiane Brenner

    PROOFREADERDebra Neel

    TECHNICAL EDITORSBob SwartPaul Qualls

    TEAM COORDINATORPamalee Nelsen

    INTERIOR DESIGNERAnne Jones

    COVER DESIGNERAren Howell

    00 0672320606 FM 11/1/01 2:47 PM Page ii

  • OverviewIntroduction 1

    Part I Understanding Delphi and Linux

    1 Visual Development 15

    2 Looping and Branching, Operators, and Recursion 67

    3 Basic Pascal Syntax 97

    4 Objects and Interfaces 151

    5 The Editor and Debugger 219

    6 Understanding the Linux Environment 291

    Part II CLX

    7 CLX Architecture and Visual Development 329

    8 Packages: Sharing and Reusing Code 377

    9 Creating Components 413

    10 Advanced Component Design 471

    11 Graphics 533

    Part III Linux Systems Programming

    12 Console Applications, Memory Management, and File I/O in Kylix 627

    13 Processes and Threads 645

    Part IV DataCLX

    14 DataCLX Basics 666

    15 Working with Data-Aware Components 681

    16 Data Access Layer 717

    17 Creating a Real World Application 757

    18 Database Optimizations 791

    Part V Web

    19 Apache Web Server Applications 817

    20 Web Server Development 829

    21 Advanced Web Server Development 869

    Index 910

    00 0672320606 FM 11/1/01 2:47 PM Page iii

  • ContentsIntroduction 1

    PART I Understanding Delphi and Linux

    1 Visual Development 15The Kylix IDE ......................................................................................16

    A Plan of Attack ..............................................................................17The IDE from 20,000 Feet ..............................................................18

    The Menus ............................................................................................19Menu Shortcuts ................................................................................19Right-Click Pop-up Menus ..............................................................21Adding New Tools to the Menu ......................................................21The Toolbars ....................................................................................22

    Visual Development ..............................................................................23The Component Palette ....................................................................25Thinking About Packages ................................................................27Using the Kylix Form Designer ......................................................29Arranging Components ....................................................................29The Object Inspector ........................................................................30Tweaking the Object Inspector ........................................................31Editing an xfm File ..........................................................................32Constraints and Anchors ..................................................................35Tab Order..........................................................................................37The Object Inspector and Events ....................................................38

    The Source for a Kylix Unit ..................................................................39The Interface of a Kylix Unit ..........................................................40The Implementation of a Kylix Unit ................................................42Mystery Theater: Where Did the FormCreate Method Go? ............45

    Pascal Source Files ................................................................................46Delphi Project Files ..........................................................................46Units..................................................................................................46Pascal Program Entry Points ............................................................48Uses Clauses and Circular Unit References ....................................49

    Compilation Time in Kylix....................................................................52Working with Containers ......................................................................53

    The PanelDesign Program................................................................54Summary ................................................................................................66

    00 0672320606 FM 11/1/01 2:47 PM Page iv

  • 2 Looping and Branching, Operators, and Recursion 67Defining Our Terms: Statements and Expressions ................................68

    Expressions ......................................................................................68Statements ........................................................................................69

    if Statements ........................................................................................71Case Statements ....................................................................................73for Loops ..............................................................................................75While Statements ..................................................................................79repeat Statements..................................................................................81

    Last Words on Looping and Branching............................................84A Few Words About Operators..............................................................84

    The Assignment Operator ................................................................84The Division Operators ....................................................................84Boolean and Logical Operators........................................................85Relational Operators ........................................................................86Getting the Address of a Variable ....................................................87Operators In Strings and In Pointer Arithmetic ..............................87Final Words on Operators ................................................................88

    Recursion ..............................................................................................89Factorials ..........................................................................................89Fibonacci Series................................................................................92Drawing Recursion ..........................................................................94

    Summary ................................................................................................96

    3 Basic Pascal Syntax 97The Content of This Chapter ................................................................98Integer Types and Floating-Point Types ................................................99

    Ordinal Types ..................................................................................99Pascal Routines for Using Ordinal Numbers ................................102Enumerated Types ..........................................................................105Floating-Point Types ......................................................................107

    Pascal Strings ......................................................................................114ShortStrings..................................................................................116AnsiStrings....................................................................................117PChars ............................................................................................121WideStrings....................................................................................122

    Typecasts..............................................................................................123The as and is Operators and the Sender Parameter ....................124

    Arrays ..................................................................................................126Array Constants ..............................................................................127Dynamic Arrays and Arrays of Objects ........................................128Debug Your Arrays: Turn on Range Checking ..............................134

    00 0672320606 FM 11/1/01 2:47 PM Page v

  • KYLIX DEVELOPERS GUIDE

    Records ................................................................................................134Records and with Statements ........................................................135Variant Records ..............................................................................136

    Pointers ................................................................................................141Working with Pointers to Objects ..................................................143Pointers, Constructors, and Destructors ........................................147virtual Methods and the override Directive ..............................148

    What You Wont Find in Object Pascal ..............................................149Summary ..............................................................................................150

    4 Objects and Interfaces 151The Kylix Object Model......................................................................152

    Where to Declare an Object ..........................................................153Scoping in Object Pascal Classes ..................................................155Scoping Issues with Classes That Reference One Another ..........156Declaring a Method ........................................................................157The Object Pascal Inheritance Model: virtual and override ......158Using dynamic Rather Than virtual in a Declaration ..................159Calling the Ancestor of an Overridden Method: inherited ........163The abstract Directive ..................................................................164The overload Directive ..................................................................166Instantiating and Freeing Instances of Classes ..............................167Class Methods ................................................................................168

    Interfaces..............................................................................................169The Interface Type..........................................................................170An Interface Is Not a Class! ..........................................................171You Cant Directly Implement an Interface ..................................172Using a Class to Implement an Interface ......................................172Calling the Methods of an Interface ..............................................177Destroying Interfaces......................................................................179Multiple Interfaces on One Object ................................................181Method Resolution Clauses............................................................186The Declaration of IInterface ......................................................187The Theory Behind Interfaces........................................................191Reasons for Using Interfaces..........................................................192Maintaining or Updating an Interface ............................................195

    Variants ................................................................................................196RTTI and Floating-Point Types ..........................................................205Frames..................................................................................................212

    Creating a Frame ............................................................................213Reusing Frames ..............................................................................216

    The Command-Line Compiler ............................................................217Summary ..............................................................................................218

    vi

    00 0672320606 FM 11/1/01 2:47 PM Page vi

  • CONTENTS

    5 The Editor and Debugger 219The Source Code Editor and Its Friends ............................................220A Tale of Two Tools: The Editor and the Designer ............................221

    Influencing the Visual Tools from the Editor ................................221The Project Manager............................................................................225

    The Code Explorer ........................................................................228Giving the Code Explorer the Look You Want ..............................230Code Generation: Class Completion in the

    Editor and Explorer......................................................................232The Browser ........................................................................................238The To-Do List ....................................................................................240

    Tool Windows ................................................................................242Saving the Desktop and Debug Desktop........................................244

    Magic Tools: Code Insight ..................................................................245The Wonders of Code Completion ................................................245The Miracle of Parameter Insight ..................................................247Code Insight: Browsing Your Source ............................................248Code Templates Can Make You the Fastest

    Typist in the World ......................................................................249Using the Debugger ............................................................................251

    Stepping Through Code with the Debugger ..................................253Code That the Debugger Cant Step Through:

    Optimizations ..............................................................................255Code That You Cant Step Through: The Linker ..........................256Watching Your Code in the Watch List Window............................257Inspecting a Variable ......................................................................258Working with Breakpoints..............................................................259

    Using Exceptions to Clean Up Your Code ..........................................261Declaring Your Own Exception Classes ........................................263The finally Clause and Re-raising Exceptions ............................264Using the CPU Window in the Debugger ......................................266Online Help ....................................................................................268

    The Elf Debug Server ..........................................................................269Services Found in the Debug Help Unit ........................................283Output from the DebugHelp Unit ....................................................284Sending Information to a Text File ................................................285Sending Information to the HTTP Server ......................................287Receiving HTTP Information on the Server ..................................288The Owner Draw List Box ............................................................289

    Summary ..............................................................................................290

    vii

    00 0672320606 FM 11/1/01 2:47 PM Page vii

  • KYLIX DEVELOPERS GUIDE

    6 Understanding the Linux Environment 291Summary of the Linux Environment ..................................................293Linux Desktops ....................................................................................293

    Anatomy of a Desktop....................................................................295X Architectural Overview....................................................................296

    X History ........................................................................................296The X Window System Name........................................................296What Is the X Window System? ....................................................296Networks and the X Client/Server Model ......................................297The Slim Pipe Between an X-Server and X-Client ......................298Attaching to a Remote Server ........................................................298

    Programming X with Kylix ................................................................300A Hello, World Program in X ....................................................302Creating the Main Window with XCreateWindow ..........................311The Stacking Order ........................................................................318Creating the Graphics Context ......................................................319The Event Loop ..............................................................................320Summary of Writing a Program in X ............................................322

    Window Managers ..............................................................................323Why Window Managers Were Created ..........................................323The Power of the Window Manager ..............................................323Changing and Querying Window Managers ..................................324

    X Toolkits ............................................................................................324Controls, Components, and Widgets ..............................................324

    A Few Words About Desktops ............................................................325The KDE Desktop ..........................................................................325The GNOME Desktop....................................................................326

    Summary ..............................................................................................326

    PART II CLX

    7 CLX Architecture and Visual Development 329Qt and CLX..........................................................................................331

    FreeCLX ........................................................................................335Qt and Events ......................................................................................336

    Stalking the Elusive CLX Message................................................337Qt Signals and Slots ......................................................................339The Qt Application Object and the Event Loop ............................343Calling Raw Qt Code from Object Pascal ....................................344

    The Slider Program in CLX ................................................................345CLX, Qt, and the Hook Object............................................................347

    The Night CLX Let Me Down: EventFilter Mojo ......................352Working with Styles ............................................................................359

    viii

    00 0672320606 FM 11/1/01 2:47 PM Page viii

  • CONTENTS

    Working with Resources......................................................................362String Resources ............................................................................365

    Creating Nonrectangular Forms ..........................................................365Form Inheritance ............................................................................366Overriding the Initialization of a Widget ......................................368Painting the Shape of a Form ........................................................374

    Summary ..............................................................................................376

    8 Packaging and Sharing Code 377Component Theory ..............................................................................378Creating Descendants of an Existing Component ..............................379

    Saving Your Work ..........................................................................386Defining the Features of Your Component ....................................387Testing the Component ..................................................................389

    Packages: Placing a Component on the Component Palette ..............390What Is a Package? ........................................................................390Packages and the LD_LIBRARY_PATH ..............................................392Packages and the Component Palette ............................................394

    Creating Packages................................................................................395Design Time and Runtime Packages..............................................398Icons: Working with DCR Files ....................................................398Simultaneously Opening a Package and a Project ........................398The requires Clause......................................................................399Registering Components ................................................................399

    Exploring a Package at Runtime ........................................................400Getting Inside a Package at Runtime ..................................................404Creating a Shared Object ....................................................................406

    Calling Library Routines from a Kylix Program ..........................410Loading a Shared Object Dynamically................................................410Summary ..............................................................................................412

    9 Creating Components 413Working with Messages ......................................................................415

    Simple Messages: A Useful Control ..............................................415Responding to Messages ................................................................418Working with FilterEvents in Components ................................419

    Extending the Elves Unit ....................................................................423The Art of Naming CLX Components ..........................................437The TElfBigEdit and TElfEmptyPanel Controls ..........................437Creating Compound Components ..................................................438Creating Published Properties of a Component ............................442A Note on Streaming Properties ....................................................443

    ix

    00 0672320606 FM 11/1/01 2:47 PM Page ix

  • KYLIX DEVELOPERS GUIDE

    A Second Compound Component ......................................................444Creating a Combined TLabel and TEdit Component..........................452

    Changing the Position of the Label................................................465ElfLabelEdit and Compatibility with Windows ..........................4673D Text Labels ..............................................................................468

    Summary ..............................................................................................469

    10 Advanced Component Design 471Properties ............................................................................................472

    Declaring Properties ......................................................................473Viewing Properties in the Object Inspector ..................................477

    More on Properties ..............................................................................478Building Components from Scratch ....................................................490The Clock Component ........................................................................493

    Understanding TElfClock ..............................................................500The Clock Paint Method ..............................................................502The TElfColorClock Component ..................................................503Creating a Fancy Clock ..................................................................505

    Creating Icons for Components ..........................................................508The Tools API: Property Editors and Component Editors ..................510

    Design Time Code Versus Runtime Code ......................................516The State of Tools API on Kylix ....................................................517The Tools API and Wine ................................................................518The Tools API and Interfaces ........................................................518Property Editors..............................................................................519More on Registering Your Component and

    Component Editors ......................................................................525Component Editors ........................................................................527Some Notes on Component Maintenance ......................................529

    Component Templates ........................................................................529Summary ..............................................................................................530

    11 Graphics 533The Major Objects Found in QGraphics.pas ......................................534The TCanvas Object ............................................................................535Drawing Using Qt................................................................................538

    Changing the World Coordinates ..................................................539The TColor Type ................................................................................542Brushes ................................................................................................543Pens ....................................................................................................547Creating the PenMode Application......................................................552Fonts ....................................................................................................553Drawing Shapes ..................................................................................555

    x

    00 0672320606 FM 11/1/01 2:47 PM Page x

  • CONTENTS

    The Mandelbrot Example ....................................................................559Drawing the Mandelbrot Set ..........................................................571Drawing the Rubber Band..............................................................571TBitmap: Taking a Picture of the Mandelbrot Set ..........................573Creating Events and Handling OnPaint Methods ..........................575LoadResource: Creating the Opening Scene ..................................577

    A Pseudo-3D World ............................................................................577The Architecture of a Pseudo-3D World ........................................578Creating Graphics for the Game ....................................................582Double Buffering and Surfaces ......................................................583The Core Code for the Gaming Engine ........................................585Implementing ISimpleSurface and IDrawTools ..........................614ISimpleSurface: Creating a Plug-and-Play Back End ..................618Drawing the Wall Segments in the Right Location........................621

    Summary ..............................................................................................624

    PART III Linux Systems Programming

    12 Console Applications, Memory Management, and File I/O in Kylix 627

    Console Applications ..........................................................................628Console Development ....................................................................629Running the Console Application ..................................................630

    Memory Management..........................................................................630Variables and Data Structures ........................................................631Objects ............................................................................................632

    File I/O in Kylix ..................................................................................633Traditional Pascal File Operations ................................................634File I/O Using TFileStream ..........................................................637Specifics of Linux Files..................................................................641Using glibc Commands ................................................................644

    Summary ..............................................................................................644

    13 Processes and Threads 645Methods of Application Execution in Linux ......................................646Kylix Threads ......................................................................................648

    Memory Access by Threads ..........................................................650Synchronization Errors and Thread Safety ....................................650Using a Thread Objects Synchronize Method..............................651Critical Sections..............................................................................652Multi-Read Exclusive-Write Synchronizers ..................................653Locking Mechanisms......................................................................654Thread Completion and Termination ............................................654Debugging Multithreaded Applications ........................................656Final Thoughts on Threads ............................................................657

    xi

    00 0672320606 FM 11/1/01 2:47 PM Page xi

  • KYLIX DEVELOPERS GUIDE

    Linux Processes Control and Interprocess Communication................657Creating New Processes ................................................................658Signaling or Killing a Process........................................................660

    Summary ..............................................................................................661

    PART IV DataCLX

    14 DataCLX Basics 665DataCLX Architecture ........................................................................666Data Access..........................................................................................666

    Connecting to a Database ..............................................................666Retrieving Data ..............................................................................668

    Data Control ........................................................................................669Displaying Data with Visual Data Controls ..................................669

    Typical Data Flow................................................................................674Interactive Data Manipulation ........................................................674Data Publishing ..............................................................................676

    Configuring the Server ........................................................................677Connecting to InterBase ................................................................677Connecting to MySQL ..................................................................678Connecting to DB2 ........................................................................679Connecting to Oracle......................................................................680

    Summary ..............................................................................................680

    15 Working with Data-Aware Components 681TSQLConnection ..................................................................................682

    TSQLConnection Properties ............................................................684TSQLConnection Methods ..............................................................685TSQLConnection Events ..................................................................686

    TSQLDataSet ........................................................................................688TSQLQuery ............................................................................................689TSQLStoredProc ..................................................................................689TSQLTable ............................................................................................689TClientDataset ..................................................................................690

    TClientDataSet Properties ............................................................691TClientDataSet Methods ..............................................................693

    TDataSetProvider................................................................................697TSQLClientDataSet..............................................................................698TSQLMonitor ........................................................................................699Normal Dataset Usage Patterns ..........................................................701

    Queries............................................................................................701Lookup Fields ................................................................................701Parameterized Queries....................................................................703

    xii

    00 0672320606 FM 11/1/01 2:47 PM Page xii

  • CONTENTS

    Master/Detail Relationships ..........................................................703Customizing Detail Grids ..............................................................705Calculated Fields ............................................................................705Local Incremental Searching..........................................................706Local Filtering ................................................................................709Bookmarks......................................................................................709Using Stored Procedures ................................................................712Client-Side Temporary Keys ..........................................................714Aggregate Fields ............................................................................715

    Summary ..............................................................................................716

    16 Data Access Layer 717Goals of the Data Access Layer ..........................................................718

    Maximize Data Access Speed ........................................................718Provide Platform Independence ....................................................719Provide Easy Deployment ..............................................................719Minimize Size and Resource Usage ..............................................719Provide a Common Interface to Process SQL and

    Stored Procedures Efficiently ......................................................720Make Driver Development Easy and Extensible ..........................720Provide Access to Database Specific Features ..............................720

    The Big Picture ....................................................................................720MyBase Datasets..................................................................................722

    Formats (Binary and XML)............................................................722Metadata ........................................................................................723Constraints ......................................................................................725Data ................................................................................................725Field Types ....................................................................................725Special Fields..................................................................................725Deltas ..............................................................................................726Return to Sender ............................................................................728

    Database Connectivity ........................................................................729dbExpress Abstraction ....................................................................730Data Type Mapping ........................................................................744

    dbExpress Driver Development ..........................................................744Understanding the Database Vendor Client....................................745Initializing the Environment ..........................................................745Connecting to the Database Server ................................................746Initializing Statement Handles ......................................................746Preparing a SQL Statement ............................................................746Passing Runtime Parameters ..........................................................747Executing a SQL Statement ..........................................................747Binding a Record Buffer ................................................................748

    xiii

    00 0672320606 FM 11/1/01 2:47 PM Page xiii

  • KYLIX DEVELOPERS GUIDE

    Fetching Records ............................................................................749Free Handles and Disconnect ........................................................749

    dbExpress Core Implementation..........................................................750SQLDriver ......................................................................................750SQLConnection ................................................................................751SQLCommand ....................................................................................752SQLCursor ......................................................................................756SQLMetaData....................................................................................756

    Summary ..............................................................................................756

    17 Creating a Real-World Application 757Application Description ......................................................................758Database Definition ............................................................................759

    Tables..............................................................................................759Indices ............................................................................................763Data Constraints ............................................................................763Generators ......................................................................................764Stored Procedures ..........................................................................764Triggers ..........................................................................................767

    Basic Design ........................................................................................769Data Module ..................................................................................769

    GUI Interface ......................................................................................774Presenting the Data ........................................................................774Editing the Data..............................................................................774Extending Functionality ................................................................776

    Web Interface ......................................................................................778Formatting ......................................................................................778Layout ............................................................................................783Navigation ......................................................................................786

    Summary ..............................................................................................789

    18 Database Optimizations 791Introduction..........................................................................................792Populate Your Database ......................................................................792Monitor the SQL Communication ......................................................793Avoid Holding Transactions Open for Long Periods of Time ............794Do Not Parameterize Queries that Contain the Verb Like ..............794Avoid Primary Keys and Foreign Keys ..............................................795Use Stored Procedures ........................................................................796Be Trigger-Happy ................................................................................797Be Picky ..............................................................................................798Parameterize and Prepare Your Queries for Maximum

    Performance ......................................................................................798Avoid Fetchalls Like the Plague ........................................................798

    xiv

    00 0672320606 FM 11/1/01 2:47 PM Page xiv

  • CONTENTS

    Robs Rules of Left Outer Joins ..........................................................799Design Out the Left Outer Join ......................................................799Use a Correlated Subquery ............................................................800Use a Stored Procedure ..................................................................801Use a Left Outer Join ....................................................................801

    For Large Databases or Lots of Users, Cache Your Lookup Tables ..................................................................................801

    Use Smart Lookups..............................................................................802Turn Off Metadata ..............................................................................803Need Speed? Turn Off Asynchronous Writes, But

    Beware of the Risks ..........................................................................803Understand Database Indexing ............................................................804

    Understand Selectivity....................................................................804Be Careful Using Foreign Keys ....................................................804Multi-Column Indices ....................................................................804Ordering an Index ..........................................................................804Index Fields Sparingly....................................................................805

    InterBase-Specific Tips........................................................................805Do Not Use Large Varchars ..........................................................805Always Build Your Front-End Application Using a

    Remote Connection ....................................................................805Use a 2KB or 4KB Page Size for Your Database ........................806Understand Index Plans..................................................................806Set Your Database Cache Buffers with Gfix ................................812Use Single Processor Machines with InterBase ............................813

    Summary ..............................................................................................813

    PART V Web

    19 Apache Web Server Applications 817Web Server Applications ....................................................................818

    CGI Protocol ..................................................................................818CGI Forms ......................................................................................819

    Apache Web Server..............................................................................820Kylix and CGI ................................................................................820Configuration for CGI ....................................................................825Configuration for DSO ..................................................................826

    Summary ..............................................................................................828

    20 Web Server Development 829Web Modules ......................................................................................830New Web Server Application ..............................................................830WebBroker Components......................................................................834

    TWebDispatcher ..............................................................................834TWebModule ....................................................................................835

    xv

    00 0672320606 FM 11/1/01 2:47 PM Page xv

  • TWebResponse..................................................................................836TWebRequest....................................................................................837

    Presenting Content ..............................................................................839Simulating GET ................................................................................841

    PageProducers......................................................................................842TPageProducer................................................................................842HTMLDoc Versus HTMLFile ........................................................846TDataSetPageProducer ..................................................................846

    TableProducers ....................................................................................856TDataSetTableProducer ................................................................857Customizations ..............................................................................864Master-Detail Relationship ............................................................865

    Summary ..............................................................................................867

    21 Advanced Web Server Development 869New WebApp42 ..................................................................................870

    Producer and ProducerContent ....................................................870dbExpress ............................................................................................871TDataSetTableProducer ......................................................................873

    TSQLQueryTableProducer ..............................................................874PrepareSQLQueryTableProducer....................................................877

    Maintaining State Information ............................................................880Fat URLs ........................................................................................881Cookies ..........................................................................................887Hidden Fields..................................................................................888

    Advanced Page Producing ..................................................................891Images ..................................................................................................897Cross-Platform Strategies ....................................................................906Summary ..............................................................................................908

    Index 908

    00 0672320606 FM 11/1/01 2:47 PM Page xvi

  • ForewordThe Creation of Kylixby David Intersimone

    David I [email protected] President, Developer RelationsBorland Software Corporation

    One of the joys of working at Borland is the opportunity to watch creation in progress. I lovetaking a little time out from my daily grind to go down to where the Delphi team sits. Its greatfun to visit with Chuck, Danny, Allen, Eddie, and other team members to see what they arecooking up this week.

    The creation of Kylix was, of course, a very special event. I was privileged to watch its devel-opment from the very first days of its planning all the way through completion. It was, attimes, a tough road. Nevertheless, it was a wondrous joy to watch the product emerge step bystep by step over the months.

    It was thrilling to get the first successful builds of Kylix. Now at last I could boot up Linux,start a high-powered development environment, and begin creating powerful applications witha few clicks of the mouse. Tasks in Linux that had once seemed formidable soon were easilywithin reach.

    I have always been a big fan of Delphi. Having it transported to Linux intact was a very excit-ing event for me personally, and one that I think will end up, in the long run, having a hugeimpact on the future of not only Linux development, but also the entire Linux operating system.

    Learning the Ropes with the Kylix DevelopersGuideThroughout the development of Kylix, I shared the joy in watching its creation with my twofriends and co-workers, John Kaster and Charlie Calvert. We spent many hours together hov-ered over Linux machines testing new code, trying experiments, and sharing in the excitementof a new product. Both John and Charlie worked with Kylix from the very beginning, andindeed, they sat in on some of the earliest meetings involving the planning. The other authors,especially Bob Swart, were also working with the product from the moment it was released tofield test. Bob worked closely with both the development team itself, and with those of us whowork elsewhere in Borland.

    00 0672320606 FM 11/1/01 2:47 PM Page xvii

  • Development in Kylix is relatively easy compared to the trials encountered under other Linuxdevelopment systems. If you know how to use Kylix, then database, Web, and even systemdevelopment can be made relatively simple. Nevertheless, the product has a rich feature set,and mastering it can take time.

    Having Charlie, John, Bob, and the other authors to guide you through the product is the nextbest thing to being able to sit down with Danny, Allen, Eddie, or even Chuck himself. Thisbook examines all the major features, and many of the smaller features, of both the productitself, and the Delphi language. It contains a treasure trove of Kylix programming jewels,replete with a shimmering panoply of information that you can use again and again in yourLinux project development.

    I look forward to the upcoming months and years, when both Kylix and this book will helpprogrammers create solutions and tools that will prove useful to businesses, users, and thewhole Linux movement. Kylix is a great product, and having this book in your hands will helpyou take part in the exciting world of Linux development.

    00 0672320606 FM 11/1/01 2:47 PM Page xviii

  • by Chuck Jazdzewski

    Chief Architect of Kylix and DelphiOffice of Chief ScientistBorland Software Corporation

    As the chief architect of Kylix, I have had a chance to oversee this product from the momentof its conception until its release to the general public. Its very exciting for me to now seebooks on our compiler hitting the shelves. In particular, Kylix Developers Guide providesdevelopers with all the knowledge they need to begin creating powerful Linux applications.Whether you come from a Windows or a Linux background, and whether or not you haveexperience with similar tools, this book will provide you with all the information you need tocreate tools that users will love.

    Linux has proved to be one of the fastest growing and most exciting areas in computer devel-opment. Its success as a server platform is already fully established. What is needed now aretechnologies that will help the Linux community develop powerful, attractive, fast, and easy touse applications. Thats the role Kylix is designed to fill.

    When we put our Linux compiler and IDE together, we aimed from the beginning to create apractical, easy to use tool that would allow developers to create applications users will enjoy.Although still providing deep access to the low-level functionality available in Linux, Kylixgives users easy to use components from which they can create the kind of cutting edge appli-cations that users have come to expect. Developers, on the other hand, will love the sophisti-cated debugging and program analysis tools that are built into the IDE.

    Our goal in developing Kylix was to bring all the key features of Delphi to the Linux platform.In particular, that meant focusing on database- and Web-based applications. Databases formthe backbone on which many corporate applications are based, and we did everything we couldto ensure that there is no easier way for Linux developers to build data-centric applicationsthan Kylix itself. With just a few clicks of the mouse, you can put together simple databaseapplications that give users access to data from both open source and proprietary databaseservers. With a little more work, you can construct powerful applications that access dozens, oreven hundreds, of tables residing on multiple heterogeneous servers.

    Creating Kylix was an exciting, but often difficult, task for the Borland development team.Throughout our effort, we continuously sought out and found ways to encapsulate the mostcomplex parts of Linux development inside easy to use components. The result is a set of morethan one hundred extensible controls that you can use to assemble the highest possible qualityapplications.

    00 0672320606 FM 11/1/01 2:47 PM Page xix

  • Developer ExpertiseI cant think of anyone better prepared to write a book about Kylix than Charlie Calvert, JohnKaster, Bob Swart, and the other authors of this book. Charlie and John in particular wereinvolved with Kylix before it even became an official project at Borland. They participated inthe planning of the product as part of the Kylix core team. They helped decide what would bein the initial product release. I frequently saw them in the offices of various R&D engineersthroughout the development of Kylix, making sure they understood the nuances of the engi-neering decisions that were made for Kylix.

    Along with David Intersimone, they hosted the Kylix Kick Start on March 20, 2000, whichwas the first time we talked to anyone who was not a Borland employee about Kylix. The KickStart was a technology briefing for hundreds of technology partners and authors. Charlie andJohn put together the agenda for this meeting and worked directly with Kylix R&D to deter-mine the most useful information to provide the attendees. In the months following this initialKick Start, Charlie, John, and David went on the road, hosting Kylix Kick Starts in more than50 cities worldwide.

    Charlie and John frequently communicated with R&D to ensure that they completely under-stood the technological decisions we made. They know and understand the issues developersface. Charlie and John provided the original information on which all external Kylix publica-tions are based, including any other Kylix book you may buy. They have continued to provideand refine information on Kylix.

    All the authors of this book explain not only how Kylix works, but why it works the way itdoes. This book is the culmination of more than two years of intimate involvement with bothKylix the product and the project.

    I hope you enjoy the Kylix Developers Guide, and I hope you enjoy your development experi-ences with Kylix. We have lots of great things planned for future releases of the product, andCharlie, John, Bob, and the other authors provide you an excellent foundation for developingany kind of application with Kylix.

    00 0672320606 FM 11/1/01 2:47 PM Page xx

  • About the AuthorsCharlie Calvert is a programmer and writer who lives and works with his wife Margie and histwo cats in Santa Cruz, California. He is the author of Delphi 4 Unleashed, C++Builder 3Unleashed, Delphi 2 Unleashed, Teach Yourself Windows 95 Programming in 21 Days, DelphiUnleashed, Teach Yourself Windows Programming, Turbo Pascal Programming 101, and a con-tributing author of CBuilder 4 Unleashed. He worked with his wife Margie to create an inter-active Java tutorial, and he has been published in many different technical magazines. Charliehas spoken on technical subjects such as Delphi, C++, and Java at major industry conferences,and in many smaller conferences from Europe to Australia to the Far East. Originally trained asan English major, Charlie worked as a journalist and college English teacher before turning tothe world of computers. He has a BA in both Journalism and Computer Science fromEvergreen State College in Olympia, Washington.

    His interests include bicycling, hiking, playing folk guitar, listening to jazz, and writing poetryand fiction. A considerable portion of his free time is dedicated to spiritual pursuits within theEpiscopal Church and various Buddhist and Hindu meditation traditions.

    Online, he can be found at http://www.elvenware.com.

    Margie Calvert has been working with computers for the past six years. Her focus is ongraphics and the Internet. She has collaborated with Charlie Calvert on several books, helpingwith editing and graphics. Margie also has an MBA in business, an MA in English, and a back-ground in nursing.

    John Kaster is a Senior Developer Relations Manager for Borland, and architect for theBorland Community Web site. Previously, he was a product manager, responsible for distrib-uted computing and database connectivity for Delphi and C++ Builder. John is the author ofthe CodeCentral repository and other custom applications for the community Web site, all builtwith Borland technology. Before coming to Borland, he produced several award-winning soft-ware development tools. He is co-author of Delphi Database Development, Programming inClipper 5, and numerous articles for various computing magazines. He has been speaking atconferences and providing training around the world for more than 15 years. John loves toshare his discoveries about software development and discuss design philosophy with otherdevelopers.

    00 0672320606 FM 11/1/01 2:47 PM Page xxi

  • Bob Swart (www.drbob42.com) is a UK Borland User Group (UK-BUG) and UK BorlandConnections member and an independent technical author, trainer, and consultant usingDelphi, Kylix and C++Builder based in Helmond, The Netherlands. Bob writes regularcolumns for The Delphi Magazine, Delphi Developer, UK-BUG Developers Magazine, aswell as the DevX, TechRepublic and the Borland Community Web sites. Kylix DevelopersGuide is the second book where Bob Swarts name appears on the cover (the first one wasC++Builder 5 Developers Guide), but he has also participated and written chapters for TheRevolutionary Guide to Delphi 2, Delphi 4 Unleashed, C++Builder 4 Unleashed and theupcoming Delphi 6 Developers Guide (SAMS).

    Bob is a frequent speaker at Borland and Delphi/Kylix related seminars all over the world, andwrites his own training material for Dr.Bobs Delphi Clinics (in The Netherlands and the UK).

    In his spare time, Bob likes to watch video tapes of Star Trek Voyager and Deep Space Ninewith his 7-year old son Erik Mark Pascal and 5-year old daughter Natasha Louise Delphine.

    About the Contributing AuthorsPaul J. Freitas, Ph.D., has more than 10 years experience in object-oriented programming.After earning his bachelors degrees at Santa Clara University in 1991, he worked for severalyears as a software developer using rapid application development tools. Seeking greater chal-lenges, he entered graduate school, where he developed C++ software for use in his computa-tional physics research. He completed his doctoral studies in 2000; now he puts hisprogramming, teaching, and writing skills to work as a technical writer at Borland SoftwareCorporation. He lives in Santa Cruz, California with his cat Sassy, whom he tends to annoywith his drum studies.

    Bruno Sonnino is a Delphi Client/Server Developer certified by Borland Brazil and hasworked with Delphi since its first version, in 1995, developing medical and commercial appli-cations. He was a speaker at Borland Conference 2001, in Long Beach, California, and writesa monthly column in the Delphi Informant magazine, At Your Fingertips, and articles forBrazilian magazines.

    He has written the books KylixDelphi for Linux, Developing Applications with Delphi 6, and365 Delphi Tips, published in Brazil by Pearson Education Brazil.

    00 0672320606 FM 11/1/01 2:47 PM Page xxii

  • DedicationI would like to dedicate this book to all those who lost their lives in the World Trade Center

    and Pentagon attacks of Sept 11, 2001. My hope is that their sacrifice will, through some miracle, lead us to a safer, saner, and more peaceful worlda world filled

    with understanding rather than hatred and suspicion.

    Charlie Calvert

    This book is dedicated to my daughter Sydney Leilani Kaster, who decided to arrive in the world eightweeks early, so I couldnt finish the book project before my life-long one started. I also want to thankmy wife, Patricia White-Kaster, for her extreme patience with the time I spent on this book. I earnestly

    hope this book in some small way helps lead to a more educated and tolerant world where tragedies likethe bombings of the World Trade Center and the Pentagon, and the crash in Pennsylvania will no longeroccur. My heart goes out to those who were killed or injured, and their family and friends. I could easily

    have been one of those passengerssomething I will strive to always remember.

    John Kaster

    To Yvonne, Erik, and Natasha

    Bob Swart

    00 0672320606 FM 11/1/01 2:47 PM Page xxiii

  • AcknowledgmentsI want to thank the following people: my fellow authors for their hard work, the people atBorland for their support, and everyone at Sams for their hard work and support.

    I also want to thank the members of the Open Source community for the many resources theyhave made available, and for their ability to put a spirit of excitement, common decency, andeven altruism back into the art of computer software development.

    In particular my thanks go to John Kaster for the many days and nights he put into this project,and all the help he gave me preparing this book. Carol Ackerman also went well beyond thecall of duty in her efforts. She was a continual source of support, and offered me an inspiringexample of human decency and consideration.

    Most of all, my thanks goes to my wife Margie, who not only worked hard on this book, butalso supported me through the various ups and downs that always seem to accompany the pro-duction of a book.

    Charlie Calvert

    I would like to thank TeamB members Jeff Overcash and Rob Schieck, who provided indis-pensable help, material, and suggestions for the database chapters he wrote. I would also liketo thank the Kylix R&D team for their patience in answering questions, no matter how manytimes I pestered them.

    John Kaster

    00 0672320606 FM 11/1/01 2:47 PM Page xxiv

  • Tell Us What You Think!As the reader of this book, you are our most important critic and commentator. We value youropinion and want to know what were doing right, what we could do better, what areas youdlike to see us publish in, and any other words of wisdom youre willing to pass our way.

    As an Executive Editor for Sams, I welcome your comments. You can fax, e-mail, or write medirectly to let me know what you did or didnt like about this bookas well as what we cando 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 message.

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

    Fax: 317-581-4770

    E-mail: [email protected]

    Mail: Michael Stephens, Executive EditorSams Publishing201 West 103rd StreetIndianapolis, IN 46290 USA

    00 0672320606 FM 11/1/01 2:47 PM Page xxv

  • 00 0672320606 FM 11/1/01 2:47 PM Page xxvi

  • IntroductionBook OverviewThis book will teach you how to use Kylix. In these pages youll learn how to produce qualityapplications appropriate for open source development, the corporate marketplace, the con-sumer marketplace, or private use.

    The Intended Audience for this BookThis book is designed for experienced object-oriented programmers at the intermediate level orabove. Programmers who have experience with C++, Java, or Object Pascal will all be in agood position to understand this text.

    You need to know

    How to program

    Structured programming

    Object-oriented programming

    You dont need to know

    It is not important that you have experience with any particular computer language,though knowledge of Object Pascal will be helpful. A complete explanation of ObjectPascal is, however, included in the text.

    It is not important that you have experience with any particular operating system, thougha basic understanding of Linux will be helpful.

    Whats in the TextThe text of this book places a big emphasis on providing information for experienced program-mers. It is not expected that the reader have a knowledge of Kylixs sister product, Delphi forWindows. However, there will be numerous passages that directly address readers who havethat background.

    Newcomers to Object Pascal who have never seen Delphi will find many things to interestthem in this text. In particular, it lightly covers the basics of the language, in a fashion that willbe useful to experienced programmers. This is not an attempt to teach beginners how to pro-gram, but rather the goal is to give Java, C++, Python, Perl and VB programmers the informa-tion they need to quickly get up to speed on Kylix.

    01 0672320606 Intro 11/1/01 2:44 PM Page 1

  • KYLIX DEVELOPERS GUIDE

    After covering the basic syntax of the language, the text explains how visual programmingworks in Kylix. A certain emphasis will also be placed on assuring newcomers to the languagethat Kylix does not rely on black boxes or sleight of hand. In particular, you will see that thevisual tools are designed to help you write code quickly, without concealing the inner work-ings of the language. This is a programmers tool, and you can do everything in code if you sodesire.

    The book begins with an explanation of Object Pascal designed for experienced programmers.It is not a tutorial on how to program, but rather an overview of Object Pascal designed to beread by experienced C++, Java, Perl, Python, or VB users. In particular, developers with a C++or Java background will find many useful tips to help them get up to speed quickly.

    Visual programming in Kylix is dependent on an object-oriented library called CLX. The textexplains the CLX architecture and how it is structured. The study of this library consumes themajor portion of the second section of the book.

    With this foundation material out of the way, the next step is to plunge into Linux systems pro-gramming. You will learn how to push the GUI and high-end tools aside and interface directlywith the low-level functionality of the Linux operating system. These chapters should convinceskeptical readers that Object Pascal gives you full access to all the major services of the oper-ating system. Other readers with more Delphi experience might be getting their first in-depthlook at the internal workings of the Linux operating system, and so the text will also includeenough detail to help them grasp the fundamentals of a complicated new subject.

    The fourth section of the book, written primarily by John Kaster, deals with databases.Databases are one of Kylixs great strengths. As a result, you can expect this section to be fullof important information. It will contain in-depth explorations of the Kylix database architec-ture and the act of constructing Delphi database applications. It will also contain explicationsof how to use the tools Delphi provides to connect to and manipulate data. The text coversSQL databases such as InterBase and MySQL.

    Web development is the theme of the fifth and last section of the book. The text works primar-ily with the Apache server, since it is the dominant tool for Web development on the Linuxplatform. The text shows how to create CGI applications, how to expand the applications toencompass more complex data models, and how to use JavaScript and DOM to enhance appli-cations.

    Im Charlie Calvert, and Ill write the sections of the book on Object Pascal and CLX. As youknow, the database tools will be described by John Kaster. Bob Swart will be the primaryauthor handling the Web development chapters. The sections on the native Linux APIs werewritten by Paul Freitas. You can read more about us at the beginning of this book.

    2

    01 0672320606 Intro 11/1/01 2:44 PM Page 2

  • INTRODUCTION

    As writers, we strive to:

    Explain technology in a relatively clear and easy to read manner.

    Provide plenty of working code available in numerous sample programs.

    Organize material so it is easy to find important passages.

    Most of the code will be released as open source, and can be downloaded as a zip file or viaCVS from http://sourceforge.net/projects/elvenware. For updates on the code found inthe book, check the sourceforge site, and also www.elvenware.com.

    Rather than talk about it further, it will probably be best if we begin our exploration rightaway. The first step will be to define Kylix itself.

    What Is Kylix?Kylix is a tool for creating cross-platform applications. It is made by Borland, a highlyrespected tools development company.

    The application source code Kylix produces is cross-platform. The product is not based on anemulation layer, but instead allows you to recompile your source to create high performancenative applications for both Linux and Windows.

    Kylix is based on the award winning product Delphi for Windows. Like Delphi, Kylix uses theObject Pascal language and a visual programming metaphor to allow programmers to develophigh performance applications easily.

    It is the opinion of the authors of this book that Delphi is an excellent tool for buildingWindows applications. The product has won many prestigious awards, and it is highlyrespected by some of the best programmers in the industry. The act of creating Kylix by port-ing Delphi to Linux is a major event in the programming world, and will hopefully become animportant milestone in the history of Linux.

    Like Delphi, Kylix allows you to create the interface for an application by dropping compo-nents down on a form. For instance, Figure I.1 shows a Kylix application that consists ofseveral buttons and edit controls. Creating applications of this type is simple in Kylix. Anexperienced Kylix programmer could easily build such an application in less than 30 seconds.

    Kylix has many features that help you arrange, align, resize, and reformat the components youdrop on your form. Visual design is easy in Kylix, and there are repositories and other mecha-nisms available that make it easy for you to reuse or share your creations in multiple projects.

    3

    01 0672320606 Intro 11/1/01 2:44 PM Page 3

  • KYLIX DEVELOPERS GUIDE

    FIGURE I.1A simple Kylix form with components on it.

    Included in Kylix are sophisticated debuggers that help you explore your code at runtime.Browsers are available to help you examine your code in depth at design time. Kylix willoptionally help you write code, popping up windows showing the parameters for a particularcall, or alphabetized lists of legal calls you can make at any one place in your code. Figure I.2shows Kylix popping up a window showing the methods available on a particular object.Though I personally find tools of this kind invaluable, it is nice to know that they can beturned on and off to suit your needs or preferences.

    4

    FIGURE I.2Kylix pops up a list showing all the legal methods you can call on an instance of a button component.

    There are many other excellent features of the Kylix programming environment. You will findtools for creating shared objects, wizards to help you build forms, dialog boxes for helpingyou create components, and a Tools API that can help you program the Kylix developmentenvironment itself. There is not enough room here to explain all these things in depth, butmost of them will be covered in the first two sections of this text.

    01 0672320606 Intro 11/1/01 2:44 PM Page 4

  • INTRODUCTION

    Object PascalDelphi and Kylix both use the Object Pascal programming language. Object Pascal is a won-derful language. It fully supports basic OOP features such as polymorphism, inheritance, andencapsulation. It has support for most of the features of sophisticated modern programminglanguages, such as pointers and interfaces.

    The programming language that most closely mirrors the features of Object Pascal is Java. Thebiggest difference between Java and Object Pascal is that the latter is a compiled language withperformance characteristics similar to C++. Just as Java was based on C, so is Object Pascalbased on Niklas Wirths original Pascal programming language. However, Object Pascal, likeJava, has many powerful modern programming features that make it architecturally much moresophisticated than the language on which it is based.

    Hopefully, you now have some very general sense of the feature set found in Kylix.Throughout this brief overview, Ive stressed that one of the primary goals of the Kylix projectwas to bring Delphi to Linux. The aim was to give Linux programmers a chance to work witha state of the art development environment similar in quality to Delphi. It is, however, impor-tant to stress that Kylix is not identical to Delphi. Instead, it is based on Delphi. In the nextsection you will learn something about the Kylix architecture and its relationship to Delphi.

    The Kylix ArchitectureDelphi for Windows is based on an objected-oriented library called the VCL. The creators ofKylix could have set 100% compatibility with the Delphi VCL as their goal. However, they didnot end up taking that position. Delphi is a Windows product based on the Windows API. TheWindows API is not natively available on Linux, though it is available on that platform throughan API called WINE. The Kylix team, decided, however, not to use WINE. Instead, theydecided to create a compiler that generated applications that were truly native to Linux.

    To port Delphi to Linux, the developers had a number of choices. In the end, they chose towrite an OOP layer called CLX that allowed Delphi apps to run on Linux with a minimum setof modifications.

    What Is This Thing Named CLX?CLX is an OOP library whose visual controls are based on Qt, a native Linux library thatforms the basis for the KDE, which is the most popular Linux desktop. (In this case, the worddesktop refers to the GUI interface of the Linux operating system. KDE plays much thesame role in Linux that the Start bar and core utilities such as Notepad, Wordpad, Calc, and theControl Panel do in Windows. Qt is the C++ OOP library that was used to build the KDE.)

    5

    01 0672320606 Intro 11/1/01 2:44 PM Page 5

  • KYLIX DEVELOPERS GUIDE

    Later chapters include an in-depth description of Qt, KDE, and the entire Linux GUI architec-ture. In particular, see Chapter 1, Visual Development, and Chapter 7, CLX Architectureand Visual Development.

    CLX allows developers to create applications that integrate seamlessly with Linux. In particu-lar, it allows you to produce truly native Linux applications with no reliance on Windows codeor any sort of emulation layer. It does, however, force existing Delphi developers to rewritetheir codeat least, in part. Furthermore, it forces customers to use a Qt DLL when they taketheir Kylix applications back to Windows. (Remember, the apps must run on both Windowsand Linux, so you are in a bind no matter which way you go. This is a Catch-22 factor.However the Qt DLL required on Windows is only about a megabyte in size, which is not asignificant factor in an OS such as Windows that routinely uses more than 80MB of RAM andswap space just to load its basic tools.)

    It is important to stress that although CLX and the VCL are very much alike, they are not iden-tical. They are enough alike, however, that Delphi apps can run on Linux with a minimum setof modifications.

    The decision that the team made when deciding how to port Delphi to Linux brought numer-ous consequences. Perhaps the largest was that Delphi programmers had to abandon theirfamiliar object-oriented library, named the Visual Component Library (VCL). In its place, anew library was born: CLX.

    It is possible to place too much significance on that fact that Qt was developed by a differentgroup of developers than those who created the Linux Kernel. Qt, however, is no more a layeron top of Linux than the buttons or list boxes found on Windows are part of a layer that sits ontop of the Windows OS. Both Linux and Windows have a core OS with buttons and list boxessitting on top of it. Windows has the controls as part of the OS; Linux delivers them separately.They both have the same architecture, but Linux gives you the option to choose which widgetset you want to use. (Of course, the Linux world does not have the luxury of needing to refineand plan for only one set of widget tools!)

    Whatever compromises the Kylix team made in other areas, it did a conscientious job of find-ing a good way to allow programmers to write native GUI applications that perform well onLinux. There is no denying that Qt is a real native Linux widget set. Furthermore, the teamchose an architecture that closely mirrored the Linux way of thinking about applications.Within reasonable limitations, the team did everything that it could to help you produce high-performance Linux applications. The only caveat is that these applications contain as manyfeatures of the Delphi architecture as could be preserved without fundamentally violating thearchitectural vision of native Linux programs.

    6

    01 0672320606 Intro 11/1/01 2:44 PM Page 6

  • INTRODUCTION

    Compatibility Between Delphi for Windows and Kylix forLinuxYou can perform two kinds of programming tasks in Delphi and Kylix:

    1. Application programming tasks

    2. Component writing tasks

    The Delphi team tried to maintain a high degree of compatibility between Delphi and Kylixwhen it comes to application development tasks. However, the Kylix team decided that itwould be impossible to maintain this same charmed relationship when it came to writing com-ponents.

    In short, if you know how to build an application in Delphi with the visual tools, it should notbe hard to learn how to do the same thing in Kylix. If you know how to write components inDelphi, however, those skills will not transfer as readily. The same can be said of porting appsfrom Windows to Linux: Applications should come over fairly easily, but custom componentscould be quite difficult to port. In many cases, you will be able to take a form designed forDelphi for Windows and port it to Kylix with only a small amount of fuss, if you have a cer-tain degree of patience and a good knowledge of both Kylix and Delphi. (Giving you a goodunderstanding of Kylix is the task of this book.)

    Porting ApplicationsThe Kylix teams stated goal was to make it possible to move a large application from Delphito Kylix in one to two months. Except in the most trivial cases, you should not expect a portfrom the VCL to CLX to be a simple recompile. As weve tried to make clear, significant dif-ferences exist between the two models.

    A one- or two-month port of a large application from Windows to Linux might sound like afairly substantial effort. However, large applications can take six months to a year to writeperhaps even longer. If you can move that app to Linux in one month, you are saving betweenone-sixth and one-twelfth the time involved in a full rewrite.

    7

    Dont become confused: Were talking about porting VCL apps from Windows toKylix. If you have a Kylix app that you developed on Linux, you can port it toWindows with a simple recompileat least, in theory. Your success will be based onyour ability to avoid using Linux APIs in your program. If you write directly to theLinux APIs, your app will not port easily to Windows. However, if all your code is CLX-based, it should port to Windows with a simple recompile.

    NOTE

    01 0672320606 Intro 11/1/01 2:44 PM Page 7

  • KYLIX DEVELOPERS GUIDE

    One of the most severe problems youre likely to encounter when porting VCL apps to Kylix isa dependency on third-party controls. It will be important for Borland to get the third parties tomove over their controls.

    Porting ComponentsComponent writers likely will not find their tasks as easy to perform as the tasks of applicationdevelopers. Applications are based on CLX, and CLX looks a lot like the VCL. Components,on the other hand, are often based on the Windows API, and the Linux API looks nothing likethe Windows API. Even components based on the VCL will be hard to port. The problem willbe that components usually rely on the very lowest, most complex parts of the VCL. It is thispart of the object-oriented library that changed most radically when ported to Linux.

    Borlands goal was to make sure that CLX meshed well with Qt and decided not to try to makeCLX fit in with the Windows architecture. In particular, it did not try to set up a close relation-ship between Qt messages and Windows messages. If your Windows code sticks to Borlandsknown events, such as OnKeyDown and OnMouseDown, then it will be easy to port to Linux. Onthe other hand, if you use the Windows messages WM_KEYDOWN and WM_LBUTTONDOWN, you willhave trouble.

    The more Delphi programmers rely on the Windows API, the harder time they will have port-ing components. Porting non-visual components should be simpler than porting visual compo-nents, if you dont rely on the Windows API too heavily.

    With Kylix, Borland introduces a new architecture named dbExpress for accessing databases.Designed to work with SQL servers, dbExpress performs much better than the old SQL linkstools that were part of the BDE. (dbExpress provides no tools for Paradox, Access or dBasetables. Instead, Borland is focusing on SQL databases.)

    Just as CLX is as much like the VCL as possible, so is dbExpress as much like the BDE aspossible. Moving from the BDE to dbExpress is a challenge, but many of the tools will seemvery familiar to Delphi developers.

    Borland has great hopes for this architecture. In fact, the company would like to make this thedatabase access API that is standard under Linux.

    Types of Kylix ProgramsLinux is used most frequently as a server. As a result, many of the tools used in Linux runfrom the command line. Kylix is primarily aimed at people who want to build GUI applica-tions with widgets on them; However, its a flexible tool and will be of use to people who justwant to build utilities or servers that run from the command line.

    8

    01 0672320606 Intro 11/1/01 2:44 PM Page 8

  • INTRODUCTION

    Kylix comes with a wizard that automatically generates a default, nearly empty, command-line,or console, program. (You will read about this utility in Chapter 1.) You have complete accessto the core OS-level functions that such command-line programs will typically need to call.For instance, experienced Linux programmers will be glad to know that Kylix offers full andready access to nearly everything in Libc. (For those who dont know Linux well, Libc is ashared object containing all the core functions in the C library.) But Kylix doesnt stop atmerely letting you build command-line and widget-based tools. You can also use Kylix to buildapplications that use only the X Window Library but contain no widgets. Such an applicationwould run in a GUI environment but would not need to include Qt. In short, it would have nocontrols, only text or bitmaps. Programs of this type are usually very small and very fast, butthey still contain some of the features of typical GUI applications. However, Kylix does noth-ing to help you build this kind of program; constructing it is just as difficult as building theprogram in C. (Windows programmers can think of it as being similar in difficulty to buildinga typical Windows API program from scratch. In fact, there are many direct parallels betweenthe two types of programsfor example, the Windows call CreateWindow becomesXCreateSimpleWindow or XCreateWindow. We discuss this topic in depth in Chapter 6,Understanding the Linux Environment.)

    Further Questions: GTK and Kernel DevelopmentIn the first version of Kylix, Borland has done nothing to make it easy for you to use the GTK.You can use it, if you want, but doing so requires considerable effort.

    The Linux kernel is not a part of Kylix development. The kernel is intimately wed to the GNUC++ compiler; it is built with the GNU compiler, and it depends on certain bugs in that com-piler. As a result, there is no practical way to program the Linux kernel with Kylixthat is stilla task for programmers armed with GCC.

    However, most of the low-level functionality for Linux development is not in the kernel itself,but instead is in Libc. Libc contains routines for opening and closing files, creating and delet-ing files and directories, changing directories, working with threads, setting the time, workingwith dates, scheduling tasks, and so on.

    Kylix and DatabasesDelphi is most famous as a database development tool. As mentioned earlier, Delphi dependson a database access layer named the BDE; however, the Kylix team decided not to port theBDE to Linux.

    Because of the shift away from local databases and toward SQL databases, the Kylix teamdecided that the new dbExpress database engine would target SQL databases. Currently, you

    9

    01 0672320606 Intro 11/1/01 2:44 PM Page 9

  • KYLIX DEVELOPERS GUIDE