Outils pour utilisateurs

Outils du site


issue111:tutoriel2

Many PC programmers started with one of Borland’s products, back in the day. Both Turbo Pascal and Turbo C ran on the MS-DOS operating system, and had excellent integrated development environments comprised not only of the compiler itself, but also a nice editor. To the point, they also contained a system of text-based widgets (buttons, radios, editing areas, menus…) called Turbo Vision that was not only used to build the IDE itself, but was also at the disposition of programmers for their own applications. For simplicity and for elegance, it has not yet been surpassed as a text-oriented human interface. This is not only my own very honest opinion, but also that of some others - as seen on the Internet. So, it must be true. It was with interest that I discovered the existence of Free Pascal (www.freepascal.org), a project led by Florian Paul Klämpfl, that aims to bring back a similar Pascal compiler, but open-source and adaptable to many different architectures. It also contains the interface environment, but adapted to modern times. This has been named Free Vision. As an aside, Lazarus (http://wiki.freepascal.org/Lazarus_Faq) is a companion project that continues along the same lines as the Borland Delphi graphical development interface; Vince DuBeau gave us a brief description of that project some time back in FCM#77 (http://fullcirclemagazine.org/issue-77/).

Il y a pas mal de temps, beaucoup de programmeurs sur PC ont commencé avec l'un des produits Borland. Turbo-Pascal et Turbo C tournaient tous les deux sur le système d'exploitation MS-DOS, et avaient d'excellents environnements de développement intégrés comprenant non seulement le compilateur lui-même, mais aussi un superbe éditeur. Ce qui nous intéresse, c'est qu'ils contenaient aussi un système de gadgets à base de texte (boutons, boutons-radio, zones d'édition, menus…) appelés Turbo Vision qui était non seulement utilisé pour construire l'environnement de développement lui-même, mais était aussi à la disposition des programmeurs pour leurs propres applications.

Pour la simplicité et l'élégance, cette interface homme-machine en mode texte n'a pas encore été surclassée. Ce n'est pas que ma modeste opinion, mais aussi celle de certains autres, comme on le voit sur Internet. Ainsi, cela doit être vrai. C'est avec intérêt que j'ai découvert l'existence de FreePascal (www.freepascal.org), un projet conduit par Florian Paul Klämpfl, dont le but est de ressusciter un compilateur comme celui du Pascal, mais en Open Source et adaptable à beaucoup d'architectures différentes. Il comporte aussi l'environnement d'interface, mais adapté aux temps présents. Celui-ci est appelé Free Vision. À cet égard, Lazarus (http://wiki.freepascal.org/Lazarus_Faq) est un projet compagnon qui perpétue les mêmes lignes que l'interface de développement graphique du Delphi de Borland ; Vince DuBeau nous a donné une courte description de ce projet-là dans le FCM n° 77.

In this series of articles, I will be building a text-based application with Free Pascal, using its text-based interface for user interaction. This will be combined with other, more modern, technologies such as database access using SQL, and Web access with HTTP. The final aim of the project is to demonstrate how Pascal can be used to build a modern application, while avoiding the overhead associated with a graphical interface (using a widget set such as GTK or Qt). This first part will describe installing the tools and writing some simple programs.

Dans cette série d'articles, je construirai des applications texte avec FreePascal, en me servant de son interface en mode texte pour l'interaction avec l'utilisateur. Ceci, en combinaison avec d'autres technologies plus actuelles, comme l'accès à une base de données utilisant SQL et un accès Web avec HTTP. Le but final du projet est de démontrer comment Pascal peut être utilisé pour construire une application moderne, tout en évitant la surcharge associée à une interface graphique (utilisant un ensemble de gadgets tels que GTK ou Qt). La première partie décrira l'installation des outils et l'écriture de programmes simples.

Why? Before delving into the technical intricacies of setting up the Free Pascal and Free Vision combination, perhaps it would be judicious to answer this basic question: why is it worthwhile for me to spend time on this technology? After all, there is a plethora of other languages for the programmer to choose from, such as Go, Swift, Haskell… just to name a few. The obvious answer is: “speed!” Just like that, with an exclamation mark. This stuff is seriously lightweight, and thus it also runs seriously fast. It gets to the point where a Raspberry Pi running an interface written in Free Vision can beat a proper modern computer with a multicore CPU and an SSD running a similar application, but interfaced through the Web. Which also makes sense, in a way, since the RPi has more processing horsepower than the 286 or 386 on which most Turbo Pascal programming was done. Meanwhile, the program using Free Vision is a compiled, executable binary that does not need to contend with all the quirks of a graphical interface or HTTP server. These are available, but the programmers do not need to waste CPU or RAM on them unless they are actually useful to what they are doing. A second, equally valid, answer may be: “for old times’ sake.” Pascal is also a nice, clear and structured programing language that can help us get into good habits - habits that JavaScript is not known for nurturing, just to give a quick example.

Pourquoi ?

Avant de plonger dans la complexité technique du paramétrage d'une combinaison de FreePascal et de Free Vision, il serait peut-être judicieux de répondre à cette simple question : pourquoi cela vaudrait-il le coup pour moi de passer du temps sur cette technologie ? Après tout, il y a pléthore d'autres langages parmi lesquels le programmeur peut choisir, tels que Go, Swift, Haskell…, pour n'en nommer que quelques-uns. La réponse évidente est : « La vitesse ! » Comme ça, avec un point d'exclamation. Ce truc est sacrément léger, et donc il tourne sacrément vite. À un point tel qu'un Raspberry Pi faisant tourner une interface écrite en Free Vision peut battre un ordinateur vraiment moderne, avec un CPU multi-cœur et un SSD, qui ferait tourner la même application, mais avec une interface Web. Ce qui est logique, d'une certaine façon, car le Rpi dispose d'une puissance de calcul supérieure à un 286 ou 386 sur lesquels la plupart des programmes Turbo Pascal ont été faits.

En attendant, le programme utilisant Free Vision est un binaire exécutable compilé qui n'a pas besoin d'affronter les bizarreries d'une interface graphique ou d'un serveur HTTP. Ceux-ci sont disponibles, mais les programmeurs n'ont pas à gaspiller du CPU ou de la RAM pour eux, sauf s'ils sont vraiment utiles pour ce qu'ils font.

Une seconde réponse, tout aussi valable, pourrait être : « En souvenir du passé ». Pascal est aussi un beau et clair langage de programmation structurée, qui peut nous aider à acquérir de bonnes habitudes - des habitudes que Javascript ne crée quasiment pas, pour prendre un rapide exemple.

Installation Free Pascal is installable using standard tools (apt, synaptic…) from Ubuntu 16.04’s repositories, where it is identified as package fp-ide. Package fp-units-base will also be required to make standard units available, as well as fp-units-fv for Free Vision, fp-units-db to access databases, etc. Just to see if there were differences with the original developer’s version, I downloaded FreePascal version 3.0.0 for the Intel 86-64 (64-bit) architecture, from the project’s web page at http://www.freepascal.org/download.var . The download is a .tar file, that in turn contains a further three compressed files (in the .tar and .tar.gz formats) that contain the compiler itself in binary or executable format, examples of programs, and the documentation. An install script is also provided. Running the install script as root will allow us to install the lot, choosing between either /usr or /usr/local as a starting point for our files. The decompression process is fast and hassle-free. Once done, we have the appropriate PATH variable set in our system, and can proceed with creating a directory for our source files, and opening it within a terminal. Something along the lines: mkdir Desktop/pascal cd Desktop/pascal fp

Installation

Free Pascal s'installe avec les outils classiques (apt, synaptic…), à partir des dépôts d'Ubuntu 16.04, où il est identifié comme le paquet fp-ide. Le paquet fp-units-base sera aussi nécessaire pour disposer des unités standard, tout comme fp-units-fv pour Free Vision, fp-units-db pour l'accès aux bases de données, etc.

Juste pour voir s'il y a des différences avec la version originale du développeur, j'ai téléchargé FreePascal dans la version 3.0.0 pour l'architecture Intel 86-64 (64-bit), depuis la page du projet sur http://www.freepascal.org/download.var. Le fichier téléchargé est un .tar, qui contient trois fichiers compressés (dans les formats .tar et .tar.gz) qui contiennent le compilateur lui-même en format binaire ou exécutable, des exemples de programmes et la documentation. Un script d'installation est aussi fourni.

Le lancement du script d'installation en tant que root nous permettra d'installer beaucoup de choses, en choisissant entre /usr et /usr/local comme point de départ de nos fichiers. Le processus de décompression est rapide et sans problème. Une fois fait, nous avons le jeu de variables PATH adéquat dans notre système, et nous pouvons procéder à la création d'un répertoire pour nos fichiers source et l'ouvrir depuis un terminal. Quelque chose comme :

mkdir Desktop/pascal

cd Desktop/pascal

fp

There were no detectable differences with the version from the repositories. The final command launches the integrated Pascal IDE (Integrated Development Environment), which will bring back memories to users of Turbo Pascal. Some of us have spent hours staring at this screen. A configuration file is created for the environment within this directory. At this point, we can immediately begin programming. However, if we need to use units such as Crt, we will need to direct the IDE to use the appropriate unit directory. This is a step the installer does not seem to take care of. Simply choose Options > Directories in the main menu, and add the following two lines. If you have installed in /usr instead of in /usr/local, do the appropriate modifications: /usr/local/lib/fpc/3.0.0/units/x86_64-linux /usr/local/lib/fpc/3.0.0/units/x86_64-linux/* The first line is to include the unit directory itself, while the second also includes any subdirectories within the search path.

Il n'y a pas de différence visible avec la version des dépôts. La dernière commande lance l'IDE (Integrated Development Environment - Environnement de Développement Intégré) intégré à Pascal, qui rappellera des souvenirs aux programmeurs en Turbo Pascal. Certains d'entre nous ont passé des heures à fixer cet écran.

Un fichier de configuration pour l'environnement est créé dans ce répertoire. À ce stade, nous pouvons commencer immédiatement à programmer. Cependant, si nous devons utiliser des unités comme Crt, nous aurons besoin de rediriger l'IDE pour utiliser le répertoire approprié de cette unité. C'est un point dont l'installeur ne se soucie pas. Simplement, choisissez Options > Directories dans le menu principal, et ajoutez les deux lignes suivantes. Si vous l'avez installé dans /usr plutôt que dans /user/local, faites les modifications appropriées :

/usr/local/lib/fpc/3.0.0/units/x86_64-linux

/usr/local/lib/fpc/3.0.0/units/x86_64-linux/*

La première ligne est pour inclure le répertoire propre de l'unité, alors qu'avec la deuxième, tous les sous-répertoires sont inclus dans le chemin de recherche.

Compiling a console program To start, let us write a very simple program. This will serve just to test the compilation process, and see if units are in fact correctly detected. Choose File > New in the menu, and type in a test program (such as http://pastebin.com/wJhgry5A). Keyboard shortcut command F2 saves the file (with extension .pas), and F9 compiles it (top right). The program can be both compiled and executed in one step using command Ctrl+F9. The result is shown in the terminal, and execution goes back to the IDE whenever a key is pressed.

Compiler un programme à la console

Pour commencer, écrivons un programme très simple. Il servira juste à tester le processus de compilation et voir si les unités sont bien correctement détectées. Choisissez File > New dans le menu et tapez un programme de test (tel que http://pastebin.com/wJhgry5A). Le raccourci clavier F2 commande la sauvegarde du fichier (avec l'extension .pas) et F9 le compile (en haut à droite).

Le programme peut être compilé et exécuté en une étape en utilisant Ctrl-F9. Le résultat est présenté sur le terminal et l'exécution retourne à l'IDE dès que vous appuyez sur une touche quelconque.

A first Free Vision application Let us get on to using the modern equivalent of Borland’s Turbo Vision text-based user interface, now called Free Vision. The corresponding units are grouped in subdirectory: /usr/local/lib/fpc/3.0.0/units/x86_64-linux/fv The first one to use is simply the App unit itself. With the ten-liner in http://pastebin.com/13UfNBNS, we can set up a sample text-based application. The corresponding code is quite minimalistic. We have simply created a new application type, TMyApp, based on the pre-existing TApplication. This application is then instantiated in a variable. The application is initialized in method Init. Method Run is the main loop, where user keyboard and mouse events are handled. Finally, we clean up in method Done. That’s it - but it is already a working application, written in less lines of code than are needed to describe the process. var MyApp : TMyApp; begin MyApp.Init; MyApp.Run; MyApp.Done; end.

Une première application avec Free Vision

Continuons en utilisant l'équivalent moderne de l'interface utilisateur en mode texte Turbo Vision de Borland, maintenant appelée Free Vision. Les unités correspondantes sont groupées dans le sous-répertoire :

/usr/local/lib/fpc/3.0.0/units/x86_64-linux/fv

La première à utiliser est l'unité de l'application elle-même. Avec les 10 lignes sur http://pastebin.com/13UfNBNS, nous pouvons préparer un exemple d'application en mode texte.

Le code correspondant est très minimaliste. Nous avons simplement créé un nouveau type d'application, TMyApp, basé sur TApplication pré-existant. Cette application est ensuite instanciée dans une variable. L'application est initialisée dans la méthode Init. La méthode Run est la boucle principale, où les événements clavier et souris de l'utilisateur sont gérés. Enfin, nous nettoyons tout avec la méthode Done. C'est tout, mais c'est déjà une application qui fonctionne, écrite en moins de lignes de codes que ce qui a été nécessaire pour la description du processus.

var MyApp : TMyApp;

begin

  	MyApp.Init;
  	MyApp.Run;
  	MyApp.Done;

end.

One point that can be noticed is that the resulting executable files are rather small, even if using FreeVision. The first one - using merely Crt - takes up about 400 kBytes, and the second - with fv - takes less than 800 kBytes. This is quite small by modern standards. $ ls -lh test? test?.pas -rwxrwxr-x 1 alan alan 416K jun 7 09:05 test1 -rw-rw-r– 1 alan alan 175 jun 7 09:04 test1.pas -rwxrwxr-x 1 alan alan 781K jun 7 09:06 test2 -rw-rw-r– 1 alan alan 162 jun 7 08:45 test2.pas This will be all for this first part in our series on Free Pascal - and Free Vision. In the next part, we will make the user interface responsive, and create some simple dialog windows.

Un point qui peut être noté est que les fichiers exécutables résultants sont plutôt petits, même en utilisant Free Vision. Le premier, utilisant seulement Crt, prend environ 400 Ko, et le second, avec fv, prend moins de 800 Ko. C'est vraiment petit selon les normes modernes.

$ ls -lh test? test?.pas -rwxrwxr-x 1 alan alan 416K jun 7 09:05 test1 -rw-rw-r– 1 alan alan 175 jun 7 09:04 test1.pas -rwxrwxr-x 1 alan alan 781K jun 7 09:06 test2 -rw-rw-r– 1 alan alan 162 jun 7 08:45 test2.pas

Ce sera tout pour cette première partie de notre série sur Free Pascal et Free Vision. Dans la prochaine partie, nous construirons une interface utilisateur interactive et nous créerons quelques simples fenêtres de dialogue.

issue111/tutoriel2.txt · Dernière modification : 2016/08/23 18:51 de andre_domenech