Среда разработки: различия между версиями

Материал из wikiru.visual-prolog.com

Строка 17: Строка 17:
==Создание==
==Создание==


First we will create a project by selecting '''Project -> New...''' in the menu. In response to this you are presented to a dialog containing various properties of the project.
Прежде всего мы создадим проект, выбрав '''Project -> New...''' в меню. В ответ на это Вам представляется диалог, содержащщий различные свойства проекта.


[[Image:tut01_projectSettingsS.png]]
[[Image:tut01_projectSettingsS.png]]


I have chosen that my project should have the name ''tut01''.
Мы выбираем имя для проекта ''tut01''.


The project name is also used as the name of the target that is producedIn this case the target is an ''exe'' file so the target name will be ''tut01.exe''.
Имя проекта используется, кроме того, как имя сгенерированного продуктаЗдесь мы выбираем исполняемое приложение как ''exe''-файл, следовательно имя приложения будет ''tut01.exe''.


I have also chosen that the target should be a GUI program, i.e. a program with a graphical user interface.
Мы также выбираем, что это будет GUI-приложение ('''G'''raphic '''U'''ser '''I'''nterface), то есть программа с графическим пользовательским интерфейсом.


The '''Base Directory''' is the "base" of all your projects; you should choose a place that is convenient for you.
'''Базовая директория (Base Directory)''' является базовой ("base") всех Ваших проектов; здесь Вы должны выбрать место, которое Вам кажется удобным на Вашем компьютере.


The new project will be created in a '''Sub-Directory''' of the base directory. By default this directory have the same name as the project itself.
Новый проект будет создан как '''поддиректория''' ('''Sub-Directory''') базовой директории. По умолчанию эта директория будет иметь то же имя, что и сам проект.


The '''Package Prefix''' is used when creating new "packages" in the system (a later tutorial will explain about the package notion). In case your source files will ever be shared with somebody else it is a good idea if the prefix does not conflict with other prefixes. Therefore it is a good idea to use a prefix that start with a reverse Internet domain name, like ''com/visual-prolog ''(which is the reverse of ''visual-prolog.com'').
'''Префикс пакетов (Package Prefix)''' используется, когда создаются новые '''пакеты (packages)''' системы (позже в этом руководстве понятие пакета будет объяснено). В случае, если файлы с Вашими исходными кодами будут когда-либо разделяться с кем-либо еще, то было бы неплохо, если бы этот префикс не вступал бы в конфликт с другими префиксами. Поэтом неплохо использовать, например, преобразованное имя  Вашего интернет-домена (как ''com/visual-prolog '', который является обратным имени ''visual-prolog.com'').


For the moment you do not need to consider the remaining tabs and options.
Пока Вам нет необходимости рассматривать остальные закладки и установки.


Now create the project by pressing '''OK'''.
Теперь создадим проект нажатием '''OK'''.


The IDE will now look something like this:
Теперь IDE будет выглядеть примерно так:


[[Image:tut01_totalS.png]] [[Image:tut01_message.png]]
[[Image:tut01_totalS.png]] [[Image:tut01_message.png]]

Версия 12:08, 11 октября 2007

В этом руководстве мы рассмотрим Интегрированную Среду Разработки (Integrated Development Environment - IDE). IDE используется для создания, разработки и поддерки Visual Prolog - проектов.

Если говорить кратко, вы будете использовать IDE для решения следующих задач жизненного цикла проекта:

  • Создание:
    Если проект создается средствами IDE, то в момент создания Вы выбираете основные свойства Вашего проекта, такие как, является ли Ваш проект исполняемым приложением или DLL, использует ли он пользовательский интерфейс или основан на текстовом взоимодействии, и т.д.
  • Построение:
    Проект строится, т.е. он компилируется и связывается, используя IDE.
  • Просмотр:
    IDE и компилятор собирают информацию о проекте, которая используется различными способами для быстрой навигации по проекту, и т.д.
  • Разработка:
    В процессе разработки и поддержки проекта IDE используется для добавления и удаления в проект исходных файлов и элементов пользовательских интерфейсов и их редактирования.
  • Отладка:
    IDE используется также для отладки проекта. Отладчик используется для движения по тексту программы и наблюдения состояния ресурсов программы в процессе ее исполнения. Впоследствии мы рассмотрим детально каждую из этих функций.

Замечание. Руководство начинается с "чистого листа", и в процессе создается проект, который используется на протяжении всего руководства. Читателю предлагается сделать то же самое. Кроме того заметим, что нажатие на картинку маленького размера приводит к ее показу в полном размере в отдельном окне.

Создание

Прежде всего мы создадим проект, выбрав Project -> New... в меню. В ответ на это Вам представляется диалог, содержащщий различные свойства проекта.

Tut01 projectSettingsS.png

Мы выбираем имя для проекта tut01.

Имя проекта используется, кроме того, как имя сгенерированного продукта. Здесь мы выбираем исполняемое приложение как exe-файл, следовательно имя приложения будет tut01.exe.

Мы также выбираем, что это будет GUI-приложение (Graphic User Interface), то есть программа с графическим пользовательским интерфейсом.

Базовая директория (Base Directory) является базовой ("base") всех Ваших проектов; здесь Вы должны выбрать место, которое Вам кажется удобным на Вашем компьютере.

Новый проект будет создан как поддиректория (Sub-Directory) базовой директории. По умолчанию эта директория будет иметь то же имя, что и сам проект.

Префикс пакетов (Package Prefix) используется, когда создаются новые пакеты (packages) системы (позже в этом руководстве понятие пакета будет объяснено). В случае, если файлы с Вашими исходными кодами будут когда-либо разделяться с кем-либо еще, то было бы неплохо, если бы этот префикс не вступал бы в конфликт с другими префиксами. Поэтом неплохо использовать, например, преобразованное имя Вашего интернет-домена (как com/visual-prolog , который является обратным имени visual-prolog.com).

Пока Вам нет необходимости рассматривать остальные закладки и установки.

Теперь создадим проект нажатием OK.

Теперь IDE будет выглядеть примерно так:

Tut01 totalS.png Tut01 message.png


To the left you have the Project Window, which contains information about the entities in your project. Right now there is not very much information, but once we compile the project information will be added. We will explore this window more when we have compiled the project.

To the right/bottom you have the Messages Window, which will contain various status and progress messages.

Building

Before we make any modifications, we will build (i.e. compile and link) the project. In the Build menu you find commands for building, compiling and executing the project.

If you choose Execute the project is first build, so that it is an up to date version you execute. Therefore I will choose Execute.

If you have not registered Visual Prolog you will be presented to a special screen telling you so. I will suggest that you register, but you can also choose "Continue Evaluation".

In the Messages Window the IDE writes which files are compiled, etc.

If the build process succeeds, which it does in this case, the created program is executed. As a result you will see a little doing-nothing GUI program. You might notice that the program looks a bit like the IDE itself. This is no coincidence since the IDE is actually a Visual Prolog program.

Later in this tutorial we will also see what happens, if the compiler or the linker detects errors in the build process.

Browsing

Right now we will turn our eyes to the Project Tree in the Project Window, and explore that a bit. The tree itself is presented in a standard Windows tree control so you should already be familiar with its usage. Here we shall concentrate on the contents of the tree.

Right now the project tree will look like this:

Project Tree

The top node represents the project, and the project directory.

Right below that is the logical node $(ProDir) which represents the directory in which Visual Prolog is installed. This directory contains (as we shall shortly see) libraries and library code from the Visual Prolog system.

Then comes another directory TaskWindow, which is a subdirectory of the project directory. This directory contains all the code needed to produce the Task Window, its menu and toolbar and the about dialog.

Finally, you see a number of files. Visual Prolog uses the following conventions:

  • .ph files are package headers. A package is a collection of classes and interfaces that are intended to be used as a chunk.*.pack files are packages. They contain the implementation/definition of the corresponding .ph files.*.i file contains an interface.*.cl file contains a class declaration*.pro file contains a class implementationIf you expand the main.cl node completely you will see the following:

Project Tree

This sub-tree shows that the file main.cl contains a class called tut01, which contains two predicates called classinfo and run respectively. Predicates are subroutines, but they will not be considered further in this tutorial.

If we collapse this node again and instead expand the TaskWindow node, you will see this tree:

You will notice several new kinds of nodes:

  • .dlg file contains a dialog
  • .frm file contains a form
  • .win file contains a window (task window or conventional PFC GUI window)
  • .mnu file contains a menu
  • .ico file contains an icon

If you continue to explore you might also meet:

Project Tree: TaskWindow

  • .ctl files containing controls
  • .tb files containing toolbars
  • .cur files containing cursors
  • .bmp files containing bitmaps
  • .lib that are libraries

If you right click on a node a context menu will appear, with commands that have relevance for that particular node.

If you double click on a node the corresponding entity will be brought up in a suitable editor. All code is edited in a text editor, but windows resources like dialogs and menus are edited in graphical editors. We will look closer to graphical editors below, here we shall try to bring up a text editor.

Some entities are represented twice in the tree, because they have both a declaration and a definition/implementation. For example, the predicate run in the class tut01:

Project Tree Project Tree

Try double clicking on each of the run nodes, and notice that two editors open showing the declaration and the definition of the run predicate, respectively.

The IDE has other facilities for browsing to specific entities, but these will not be considered here.

Development

Now lets try to modify the project a bit. Since we have not yet concerned ourselves with how to program in Visual Prolog, we will keep the changes simple.

We will start by deliberately introducing an error, that way you will not be completely surprised if you make some thing wrong, at the same time you can see the error window.

First you should locate the clauses for the run predicate in the file main.pro. If you double click the last of the two run nodes in the project tree, an editor opens with the caret placed like this:

Tut01 editRun1S.png

Try inserting a fail like this (notice the comma after show):

clauses
    run():-
        TaskWindow = taskWindow::new(),
        TaskWindow:show(),
        fail.

After that we try to build the project again: simply press F9. The system will now save and compile the file, but since we have made an error, the Error Window will open:

Error Wondow

We will consider what the error message actually means. Instead you should try to double-click on the error message. You will notice that the editor gets focus again and that the caret points exactly to the fail we inserted.

Reestablish the code without the fail and build the project again.

Next we will try to make a modification in the about dialog. It is not a very sensible change, but it will illustrate a number of things.

First we will open the About dialog in the Dialog Editor, to do this you double click the dialog in the project tree. The node you have to double click is shown here:

Project Window: About Dialog

Once you have clicked it you will see the dialog in the Dialog Editor, two toolbars and properties window.

We will add a button to the dialog. You click on the "button" on the controls toolbar, and then you click in the dialog next to the project icon in the AboutDialog window. As a result you can see the properties of the new control and you can edit them. I have changed the Text to "Press Me", this is the text that will appear on the button. I can also see the Name field, the IDE will identify this particular control in various contexts by this Name.

Now it should look something like this:

Dialog Editor: About Dialog with new button

Now we want to do something whenever the button is pressed. To do this we will open the Code Expert: Right click the dialog and select Code Expert. The code expert will open and I have located my button.

The blue dot indicates that the control is not handled. The IDE has suggested the name onPushButton for the handling predicate. We will choose Add to add this predicate to our code and to bind it to this control.

If you double-click the line corresponding to the control in the code expert, an editor will open positioned at the newly inserted code.

We will change the button text when the button is pressed. To do this we modify the code as follows:

predicates
    onPushButtonClick : button::clickResponder.
clauses
    onPushButtonClick(_Source) = button::defaultAction() :-
        pushButton_ctl:setText("Pressed").

Now try to build and execute the program again (i.e. press F9). If you have followed the steps carefully this should be a success. In the program you should of course open the About dialog, by selecting the menu entry Help -> About; and then press the new button.

This is how it looked in my application:

About: Press MeAbout Pressed

Debugging

The development environment contains a debugger. With the debugger you can trace the execution of your program and examine the program state.

It does not make much sense to go into details with debugging before you have learned the Visual Prolog language. But I will briefly explain the debugger anyway, because it can be very useful for understanding and experimenting with the language.

To start the debugger, select Debug -> Run in the menu. If the project is not up-to-date it will first be build, after that the debugging session will start.

Notice you can stop the debugging at any time by selecting Debug -> Stop Debugging in the menu.

When debugging starts the IDE will first load the debug information and then it will enter the program. The program execution is stopped just before the goal is executed. To indicate this, the goal is opened in an editor window, and the blue arrow points to the goal:

Editor: Current Position

You can single step in the program using the Step Into and Step Over commands in the Debug menu.

Try Step Into: this will open another editor with the code of mainExe::run, and the arrow will point to the entry of this code.

In the view menu you can open various debugger windows, which I will briefly explain.

The Run Stack window:

Run Stack

contains a "picture" of the run stack. Exactly what you see depends on your settings in Tools -> Options... -> Debugger. In principle, the run stack contains a number of lines corresponding to calls that has been made. However, optimization (so called last call optimization) might have removed some entries.

The run stack not only shows the calls, it also shows trap points and backtrack points, these is described in a later tutorial and there I also describe the run stack window in more details.

The Local Variables window:

Local Variables

contains the local variables corresponding to the selection in the run stack window. Some variables might not yet have received a value, these are show as an underscore (i.e. like originalraiser in the above picture).

The Facts window:

Facts

Contains the global state of the program, this state is stored in fact databases. Fact databases are a unique Visual Prolog feature, which will be described in a later tutorial. You can also add objects from the Local Variables window to the Facts window, that way you can track the state changes in interesting objects.

The Breakpoints window:

Tut01 breakPointsWindow.png

shows the current breakpoints in the program (I have set open breakpoint so that the window would not be empty). You can set/remove breakpoints by selecting Debug -> Toggle Breakpoint.

The remaining debug windows are for low level debugging and will not be considered here.

Summary

The Integrated Development Environment (IDE) makes it possible for you to:

  • create
  • build
  • maintain, and
  • debug

your projects. It contains a number of tools, editor and wizards that will help you in your tasks.

References