Difference between revisions of "Lazarus Packages/ru"

From Free Pascal wiki
Jump to navigationJump to search
Line 301: Line 301:
 
== Добавление существующих компонентов в пакет ==
 
== Добавление существующих компонентов в пакет ==
  
If you want to add a file that contains a component to an existing package, you can do the following:
+
Если вы хотите добавить файл, содержащий компонент, в существующий пакет, вы можете сделать следующее:
  
* Open the package file
+
* Откройте файл пакета
* Click on the 'Add' file to add a new item to the package.
+
* Нажмите 'Add file', чтобы добавить новый элемент в пакет.
* Select the unit tab in the 'Add to package' dialog.
+
* Выберите вкладку модуля в диалоговом окне 'Add to package'.
* Choose the file to add.
+
* Выберите файл для добавления.
* Check the 'Has register procedure' if the unit contains a Register procedure. If you do not do this, the component(s) will not be shown on the component palette.  
+
* Проверьте [наличие] 'Has register procedure', если модуль содержит процедуру Register. Если вы этого не сделаете, компонент(ы) не будут отображаться в палитре компонентов.
* Click 'Add unit'.
+
* Нажмите 'Add unit'.
* Recompile and install the package.
+
* Пересоберите и установите пакет.
  
That's it. The component should now show on the component palette.
+
Вот и все. Теперь компонент должен отображаться в палитре компонентов.
  
 
== Create a package with a unit that has the same name as the package ==
 
== Create a package with a unit that has the same name as the package ==

Revision as of 16:16, 12 December 2018

Deutsch (de) English (en) español (es) français (fr) 日本語 (ja) português (pt) русский (ru) slovenčina (sk)


ENG: AT THE MOMENT THIS PAGE IS UNDER TRANSLATION.
RUS: В НАСТОЯЩИЙ МОМЕНТ СТРАНИЦА НАХОДИТСЯ В ПРОЦЕССЕ ПЕРЕВОДА.


Обзор системы пакетов Lazarus

Другие значения Package в комбинированных проектах FPC/Lazarus см. Packages(disambiguation).

packagegraph1.png

Что такое пакет Lazarus?

Пакет Lazarus - это набор модулей и компонентов, содержащий информацию о том, как их можно скомпилировать и как они могут использоваться проектами или другими пакетами или IDE. Среда IDE автоматически компилирует пакеты, если некоторые из ее файлов изменены. В отличие от Delphi, пакеты не ограничиваются библиотеками и могут быть независимыми от ОС. ( Library Packages - это специально скомпилированные библиотеки, используемые приложениями, IDE или обоими. Для пакетов Delphi Library требуется поддержка внутри компилятора, на которую в настоящий момент FPC не способен, и, конечно, эта магия зависит от ОС.)

В настоящее время компилятор Free Pascal поддерживает только статические пакеты, а не динамические пакеты. Поэтому вы должны перекомпилировать и перезапускать IDE каждый раз, когда пакет устанавливается или удаляется.

Пакет Lazarus идентифицируется/различается по имени и его версии.

Пакеты идеально подходят для обмена кодом между проектами.

Вот типичный макет каталога пакета Lazarus:

/home/user/pascal/pkg1/  - произвольный каталог, часто он называется аналогично имени пакета
  pkg1.lpk               - файл пакета
  pkg1.pas               - этот модуль автоматически создается IDE и необходим только для компиляции
  apackageunit.pas       - ваш общий модуль, выбирайте уникальное имя, которое не конфликтует с другими исходниками/пакетами
  aform.pas              - ваша общая форма
  aform.lfm              - файл формы вашей общей формы
  lib/i386-linux/        - выходной каталог пакета. Каталог и его содержимое создаются автоматически
    pkg1.compiled        - файл состояния, содержащий параметры того, как пакет был скомпилирован в последний раз
    pkg1.o
    apackageunit.ppu
    apackageunit.o
    aform.ppu
    aform.o
    aform.lfm

Пришедшим из Delphi

Если вы знакомы с пакетами Delphi, прочитайте следующий параграф, потому что между пакетами Delphi и Lazarus есть некоторые важные различия.

  • Пакеты Lazarus'а - это не только динамические библиотеки. Они используются для обмена модулями между проектами и модульностью крупномасштабных проектов.
  • Иногда основной файл пакета Delphi называется "Пакетный проект". Этот термин не имеет смысла под Lazarus'ом.
  • Многие пакеты Delphi предоставляют один «пакетный проект» для каждой версии компилятора. Это вряд ли нужно при Лазаре. Но вы можете сделать это для совместимости с Delphi. Пакеты Lazarus содержат информацию о версии, и проекты могут определить, что им требуется, как минимум или максимум, конкретная версия пакета. Lazarus автоматически загрузит нужную версию.
  • Если модуль может быть не найден, под Delphi вы используете добавление каталога в глобальный путь поиска. Это имеет много недостатков при совместном использовании кода. Вот почему это не поддерживается Lazarus. Используйте вместо [этого] пакеты.

ЧаВо

В: Нужно ли устанавливать [любой] пакет?
О: Вам нужно устанавливать пакет только [в том случае], если он содержит элементы времени разработки, такие как компоненты для палитры компонентов IDE. Если вы не используете эти элементы, вам не нужно устанавливать пакет. Если вы хотите использовать пакет только в своем проекте, не устанавливайте его. Используйте инспектор проекта и добавьте зависимость [от него].

В: Я установил пакет, но IDE не находит модуль
О: Установка пакета означает, что пакет интегрирован в IDE, а не в ваш проект. Это отдельные вещи. Чтобы использовать пакет в вашем проекте, используйте Project -> Project Inspector -> Add -> New Requirement. И удалите пакет, если он не содержит каких-либо полезных свойств IDE.

Быстрый старт

Чтобы увидеть систему пакетов в действии и привыкнуть к ней, сделайте следующее:

Создание нового пакета

  • Package->New Package... или File->New... -> Package -> Package
  • Откроется редактор пакетов

Package Maker

  • Откроется окно с заголовком "Save Package NewPackage 0.0(*.lpk)". Выберите каталог и имя для вашего нового пакета. Имя должно быть действительным идентификатором Паскаля с расширением .lpk.
  • Используйте кнопку Save в правом нижнем углу, чтобы сохранить пакет в выбранном вами каталоге и с вашим названием.
  • В зависимости от настроек [раздела] 'naming' в 'параметрах среды', среда IDE попросит вас сохранить файл в нижнем регистре. Ответьте утвердительно.

Поздравляем: Вы только что создали свой первый пакет!

Добавление нового компонента

  • Используйте кнопку Add -> New component
  • Выберите компонент-предок в выпадающем списке. Например: TBevel.
  • Кликните Ok
  • Файл будет добавлен в пакет и открыт в редакторе
  • Установите пакет, нажав кнопку 'install' в верхней части редактора пакетов.
  • Lazarus сохранит пакет и спросит вас, нужно ли пересобирать IDE. Ответьте утвердительно.
  • Пакеты статически связаны, поэтому необходимо перезапустить IDE.
  • Перезапустите Lazarus и увидите ваш новый компонент в палитре компонентов (например: TBevel1 будет на странице 'Additional').
  • Если вы не видите свой новый компонент в палитре компонентов, скорее всего, вы используете не пересобранную версию Lazarus. Вы можете указать [каталог], где Lazarus [будет] пересобираться в меню:Tools -> Options -> Environment options -> Files -> Lazarus directory. Вместо непосредственного вызова lazarus вы также можете использовать startlazarus, который запускает только что созданный lazarus, например исполняемый файл lazarus в каталоге ~/.lazarus, если у вас нет прав на запись в каталог, внутрь которого был установлен [исполняемый файл] lazarus.

Поздравляем: Вы только что установили свой первый пакет с первым компонентом пакета.

Добавление иконки компонента

Иконки компонентов могут использовать ресурсы Lazarus или ресурсы FPC.

Использование ресурсов Lazarus'а

Также страница существует здесь: How_to_add_icons_my_package_components.

Идея состоит в том, чтобы создать png, преобразовать его в файл подключения lrs с помощью инструмента lazres и включить его. Начиная с версии 0.9.29 на странице нового компонента есть кнопка, которая делает это автоматически.

Вот подробности:

  • Размер файла PNG должен быть 24x24 px
  • Имя png должно быть именем класса нового компонента, регистр не имеет значения (например, tmyComponent.png для TMyComponent).

Чтобы создать файл lrs, запустите (где TMyComponent - это имя класса вашего компонента, а yourunit - имя модуля):

 ~/lazarus/tools/lazres yourunit.lrs TMyComponent.png
  • Вам может понадобиться скомпилировать lazres при первом использовании. Просто откройте lazres.lpi в IDE и в меню нажмите run > build.

Light bulb  Примечание: вы можете добавить более одного изображения в файл lrs, добавив имя файла изображения в конце. Например:

  ~/lazarus/tools/lazres yourunit.lrs TMyComponent.png TMyOtherCom.png ...

Ниже приведен пример файла yourunit.lrs.

LazarusResources.Add('TMyComponent','PNG',[
  #137'PNG'#13#10#26#10#0#0#0#13'IHDR'#0#0#0#24#0#0#0#24#8#2#0#0#0'o'#21#170#175
  +#0#0#0#4'gAMA'#0#0#177#143#11#252'a'#5#0#0#0'|IDAT8O'#237#212#209#10#192' '#8
  +#5'P'#247#231#251's'#215#138#133#164#166'\'#220#195'`'#209'c'#157'L'#173#131
  +#153#169'd4'#168'dP'#137'r_'#235'5'#136'@Zmk'#16'd9'#144#176#232#164'1'#247
  +'I'#8#160'IL'#206'C'#179#144#12#199#140'.'#134#244#141'~'#168#247#209'S~;'#29
  +'V+'#196#201'^'#10#15#150'?'#255#18#227#206'NZ>42'#181#159#226#144#15'@'#201
  +#148#168'e'#224'7f<@4'#130'u_YD'#23#213#131#134'Q]'#158#188#135#0#0#0#0'IEND'
  +#174'B`'#130
]);
  • Нажмите кнопку Add еще раз, перейдите на вкладку Add File, найдите файл yourunit.lrs и нажмите Ok. Это необходимо, чтобы среда IDE проверила этот файл на наличие изменений и перекомпилировала ваш пакет.
  • Добавьте директиву включения [файла ресурсов] в YourUnit:
unit YourUnit;
...
uses 
  ..., LResources;
...
implementation
...
initialization
  {$I yourunit.lrs}
end.

Light bulb  Примечание: You can include more than one lrs file, but each only once.

Вы можете включить [в код модуля вашего компонента] более одного файла lrs, но каждый [из них] только один раз.
  • Вот и все. Скомпилируйте или установите ваш пакет

Использование ресурсов FPC

Создайте 16-цветное растровое изображение 24x24 для каждого компонента. Затем создайте файл rc следующим образом:

TMYCOMPONENT1NAME  BITMAP  "pathtobitmap1//bitmap1.bmp"
TMYCOMPONENT2NAME  BITMAP  "pathtobitmap2//bitmap2.bmp"
....  
TMYCOMPONENTnNAME  BITMAP  "pathtobitmapn//bitmapn.bmp"

Обратите внимание, что двойные слеши (Linux) и двойные обратные слешы (Windows) используются в пути к растровому изображению. Желательно, чтобы имя файла было таким же, как и имя пакета с расширением rc, т.е. [в нашем случае было] MyPackageName.rc

Пусть windres (Binutils) создаст текущий ресурс:

 pathtowindres/windres -J rc -O res "MyPackageName.rc" "MyPackageName.dcr"

Добавьте в модуле регистрации пакета {$R *.dcr} сразу после ключевого слова implementation и скомпилируйте/установите пакет.

Создание пакета для ваших общих модулей

Допустим, у вас есть несколько модулей, которые вы хотите использовать в своих проектах. Поместите модули в отдельный каталог, например, C:\ MySharedUnits.

  • Package->New Package или File->New... -> Package -> Standard Package
  • Откроется редактор пакетов
  • Используйте кнопку Save в левом верхнем углу. Выберите C:\MySharedUnits\MySharedUnits.lpk. Имя пакета не должно конфликтовать с каким-либо существующим модулем.
  • В зависимости от ваших настроек [подраздела] 'naming' в [разделе] 'environment options', среда IDE [возможно] попросит вас сохранить файл в нижнем регистре. Скажите да.
  • Теперь у вас есть пакет с именем MySharedUnits, сохраненный как C:\MySharedUnits\mysharedunits.lpk.
  • Добавление модулей: Add->Add Files->Add directory.
  • Появится диалоговое окно с каталогом C:\MySharedUnits и некоторыми включающими и исключающими фильтрами. Нажмите Ok, чтобы добавить все модули.
  • Модули теперь будут представлены списком. Нажмите Add files to package.
  • Файлы теперь добавлены в пакет. Нажмите Save.
  • Если для ваших модулей требуются только стандартные модули FPC, тогда вы можете просто нажать Compile. В противном случае смотрите ниже.

Добавление LCL в качестве зависимости

Если ваш пакет содержит формы или любой другой модуль LCL с графическим интерфейсом, то для него требуется пакет LCL.

  • В редакторе пакетов вашего пакета нажмите Add -> New Requirement
  • Выберите как package name LCL
  • Нажмите Ok.
  • LCL теперь добавлен как Required Packages [(требуемые пакеты)]. Нажмите Save.

Вы можете увидеть, что делает LCL, щелкнув в редакторе пакетов вашего пакета Compiler Options / Inherited.

Если вы используете только компоненты LCL без GUI, такие как fileutil, вы можете [вместо LCL] добавить в зависимости LCLBase

Использование вашего пакета в вашем проекте

Вам нужно добавить зависимость от проекта в ваш новый пакет. Есть несколько способов сделать это:

  • Откройте свой пакет. Например, через Package / Open recent package. В редакторе пакетов вашего пакета нажмите More ... / Add to project.
  • Или вы можете воспользоваться инспектором проекта:
    • Project / Project Inspector.
    • Нажмите на кнопку Add с плюсиком.
    • Перейдите на страницу New Requirement
    • Выберите в качестве имени пакета свой пакет
    • Нажмите Ok

Элементы меню IDE для пакетов

  • Package -> New Package или File->New... -> Package -> Standard Package
    • Создает новый пакет.
  • Project -> Project Inspector
    • Здесь вы можете увидеть, какие пакеты требуются для открытого в данный момент проекта.
    • Вы можете добавить новые зависимости и удалить ненужные.
  • Run -> Compiler options -> Inherited
    • Здесь вы можете увидеть, какие параметры компилятора наследуются от какого пакета.
  • Package
    • Open package: Диалог показывает все открытые пакеты с их состоянием.
    • Open package file: Открывает файл .lpk.
    • Open package of current unit: Открывает файл .lpk, принадлежащий файлу в редакторе исходного кода.
    • Open recent package: Открывает ранее открывавшийся файл пакета (файл lpk).
    • Add active unit to a package: Добавляет в пакет модуль в редакторе исходного кода.
    • Package Graph: На графике пакетов показываются все открытые пакеты и их зависимости.
    • Configure installed packages: Редактирует список пакетов, установленных в IDE. [Позволяет] устанавливать или удалять несколько пакетов одновременно.

Удаление пакетов

  • Чтобы удалить установленные компоненты, в меню IDE выберите Package > Configure. На следующем рисунке показан инструмент Installed Packages.

Installed Components

  • Выберите пакет, который вы хотите удалить, и нажмите Uninstall selection.

Если что-то пойдет не так с пакетом (например, каталог пакета будет удален без предварительной деинсталляции), Lazarus может не позволить вам удалить пакеты. Чтобы устранить проблему, в меню IDE выберите Tools > Build Lazarus. Lazarus пересоберет все пакеты и перезапустится. Теперь вы сможете удалить проблемные пакеты.

Теория

Каждый пакет Lazarus имеет файл .lpk. Пакет идентифицируется по имени и версии. Имя должно соответствовать имени файла lpk. Например:

Имя: Package1, Version: 1.0, Имя файла: /home/.../package1.lpk.

  • Среда IDE автоматически создает основной исходный файл (package1.pas). См. ниже. Файл lpk содержит информацию о необходимых пакетах, файлах, которые он использует, о том, как их скомпилировать, и о том, что необходимо для использования пакета другими пакетами/проектами. Каталог, в котором находится файл lpk, называется "package directory" [(«каталогом пакетов»)].
  • В среде IDE содержится список всех файлов пакетов (<каталог конфигурации>/packagelinks.xml). Каждый раз, когда пакет открывается в IDE, он будет добавляться в этот список. Когда пакет открыт, IDE автоматически открывает все необходимые пакеты через этот список.
  • Обычно пакет имеет исходный каталог с некоторыми модулями на паскале. И обычно там будет файл lpk. Пакет также имеет выходной каталог. По умолчанию это подкаталог 'lib/$(TargetCPU)-$(TargetOS)/' в каталоге пакета.
  • Перед компиляцией пакета IDE проверяет все необходимые пакеты, и, если они нуждаются в обновлении и имеют флаг автоматического обновления, они компилируются в первую очередь. Затем IDE создает основной исходный файл пакета. Если файл lpk был package1.lpk, то основным исходным файлом является package1.pas. Этот файл содержит все модули в секции uses плюс 'Register' procedure, которая вызывается в секции initialization.

Например:

{ This file was automatically created by Lazarus. Do not edit!
   This source is only used to compile and install
   the package GTKOpenGL 1.0.
}
unit GTKOpenGL;

interface

uses GTKGLArea, GTKGLArea_Int, NVGL, NVGLX, LazarusPackageIntf;

implementation

procedure Register;
begin
  RegisterUnit('GTKGLArea', @GTKGLArea.Register);
end;

initialization
  RegisterPackage('GTKOpenGL', @Register);
end.
  • Затем вызывается компилятор и пакет компилируется в выходной каталог.
  • Среда IDE сравнивает текущие параметры компилятора с последними, которые хранятся в файле .compiled. Если они различаются, IDE очищает выходной каталог и компилирует пакет с [флагом] -B, указывая компилятору перекомпилировать все, что может. Различия в путях поиска и параметрах вывода не приводят к очистке. Начиная с версии 0.9.31, среда IDE удаляет все файлы в выходном каталоге модуля при очистке, если выходной каталог не содержит исходных файлов (перечисленных в редакторе пакетов) и не используется совместно с необходимыми пакетами.
  • После компиляции (успешной или нет) создается файл состояния. Файл состояния помещается в выходной каталог. Он имеет имя <packagename>.compiled и содержит информацию о том, как был скомпилирован пакет и удалось ли его собрать. Этот файл состояния используется в среде IDE для проверки необходимости обновления и необходимости полной перекомпиляции ([с флагом] -B).

Например: gtkopengl.compiled:

<?xml version="1.0"?>
<CONFIG>
  <Compiler Value="/usr/bin/ppc386" Date="781388725"/>
  <Params Value=" -Rintel -S2cgi -CD -Ch8000000 -OG1p1
    -Tlinux -gl -vewnhi -l -Fu../../../lcl/units
    -Fu../../../lcl/units/gtk -Fu../../../packager/units
    -Fu. -FElib/ gtkopengl.pas"/>
</CONFIG>
  • IDE автоматически открывает все необходимые пакеты. Это означает, что он открывает все установленные пакеты, все пакеты, помеченные для установки (автоматическая установка), все пакеты с открытым редактором, все пакеты, требуемые проектом, и все пакеты, требуемые одним из других пакетов. Ненужные пакеты автоматически выгружаются, когда IDE простаивает.
  • IDE никогда не открывает два пакета с одним и тем же именем одновременно. Когда пользователь открывает другой файл пакета с тем же именем, IDE спросит, должен ли он заменить старый.
  • В среде IDE есть два дополнительных набора пакетов: 'installed'(«установленные») пакеты и 'auto install' пакеты («автоматической установки»). Пакеты автоматической установки будут связаны с IDE при следующей компиляции. Он создает два новых файла в каталоге config: staticpackages.inc и idemake.cfg. Затем они вызывают 'make ide OPT=@/path/to/your/config/idemake.cfg', чтобы скомпилировать самих себя.

Состояние пакета

Пакет может не иметь ни одного, иметь один или несколько из следующих состояний:

  • used (используемый) - пакет может использоваться проектом или пакетом, т.е. он является обязательным и перечислен в Инспекторе проекта или Редакторе пакетов соответственно. Когда вы открываете проект или пакет, все используемые пакеты автоматически загружаются в IDE.
  • loaded (загруженный) - Когда IDE открывает файл .lpk, пакет загружается. IDE знает свои настройки и файлы. Среда автоматически загружает все используемые пакеты проекта и свои установленные пакеты. Это не загружает код пакета, так как компилятор и IDE еще не поддерживают динамические пакеты.
  • marked for installation (помеченный для установки) - Чтобы запустить код пакета внутри IDE, необходимо пересобрать IDE и перезапустить его. Это означает, что первым шагом будет пометить пакет для установки. Затем пересобрать IDE и, наконец, перезапустить ее.
  • installed (установленный) - Скомпилированный код пакета загружается и регистрируется в текущей запущенной IDE. Если в среде IDE удалось найти файл .lpk, он будет загружен.
  • uninstall on next start (удаляемый при следующем запуске) - Пакет является установленным, но не будет скомпилирован в новую среду IDE. Это означает, что когда вы пересоберете среду IDE и перезапустите ее, пакет больше не будет установлен. Имейте в виду, что пакет может быть косвенно запрошен [другим] установленным пакетом и, следовательно, будет также [опять] установлен.

Советы и подсказки

Пожалуйста, добавляйте здесь любые советы, подсказки или ошибки.

  • Чтобы переименовать пакет, используйте 'сохранить как'.
  • Вы можете добавить к каждой зависимости имя файла по умолчанию. Например, вы предоставляете пример проекта для вашего пакета. Когда другой программист впервые открывает ваш пример, IDE не знает, где находится файл lpk. Просто щелкните правой кнопкой мыши по зависимости в инспекторе проектов и выберите 'Store file name as default for this dependency' («Сохранить имя файла по умолчанию для этой зависимости»). Имя файла хранится относительно проекта. Вы можете сделать то же самое для зависимостей пакетов.
  • Использование пакета: чтобы использовать все модули пакета в проекте, включите [опцию] Add package unit to uses section («Добавить модуль пакета в секцию uses») в package editor / Options / Usage. Когда пакет добавляется в проект, секция uses файла lpr расширяется основным модулем пакета. Например, если пакет реализует новый графический тип, он имеет только секцию initialization, но код проекта не использует его напрямую.

Добавление существующих компонентов в пакет

Если вы хотите добавить файл, содержащий компонент, в существующий пакет, вы можете сделать следующее:

  • Откройте файл пакета
  • Нажмите 'Add file', чтобы добавить новый элемент в пакет.
  • Выберите вкладку модуля в диалоговом окне 'Add to package'.
  • Выберите файл для добавления.
  • Проверьте [наличие] 'Has register procedure', если модуль содержит процедуру Register. Если вы этого не сделаете, компонент(ы) не будут отображаться в палитре компонентов.
  • Нажмите 'Add unit'.
  • Пересоберите и установите пакет.

Вот и все. Теперь компонент должен отображаться в палитре компонентов.

Create a package with a unit that has the same name as the package

Normally the IDE auto creates the registration code into a unit with the same name as the package. If you want to name your package the same as an existing unit, for example because the package has only one unit, then you need at least Lazarus 0.9.29 and use this:

  • Make a backup of your unit mypackage.pas.
  • Create the package mypackage.lpk normally and do not add the unit yet.
  • Add a new unit, for example mypackageall.pas.
  • Select the unit mypackageall.pas in the package editor and right click for the popup menu.
  • Change File type to Main Unit.
  • Now restore your unit mypackage.pas and add it to the package.

The Register procedure

To show a component on the component palette, it must be registered in Lazarus. This is done in the 'Register' procedure. This is a procedure that must appear in the interface section of the unit it is in, and must issue one or more RegisterComponent calls, as well as install property and component editors for the components.

One or more Register procedures can be present in a package: in the package editor, you must indicate the units that have a 'register' procedure, so Lazarus knows which procedures it must call when the package is installed.

There are 2 ways to mark a unit as having a register procedure:

  • You can do this while adding the units to the package (see the 'Adding existing components to a package' section),
  • or you can select the unit in the package dialog, and set the 'Register' checkbox in the details panel.

Do not forget to recompile and install the package after changing the properties.

Search paths

All search paths are stored relative to the directory of the .lpk file. If you use an absolute path you have either not understood packages or you don't care.

Each package has two types of search paths:

  • Paths in the Options / Compiler Options are used to compile the package itself.
  • Paths in the Options / Package Options / Usage are used by packages and projects that require this package. In other words these paths are added to the search paths of the project (or requiring package). Keep in mind that if project uses package A and that uses package B, the Usage options of B are appended to A and the project.

Since 0.9.29 you can specify compiler options depending on the target platform.

Your package provides a library, how to extend the linker search path in all your projects

A package can define search paths that are added to packages and projects using it. See Options / Package Options / Usage.

Design Time vs Run Time package

There are four different types of packages.

  1. A design and runtime package can be installed in the IDE and can be used normally by projects. This is the default.
  2. A design time package can be installed in the IDE and provides IDE extensions like new components, new file or project types, new menu items, new component or property editors, etc. Projects can use design time packages (i.e. they are listed in the project inspector requirements), but by default a design time package is not compiled into the project. That means project units cannot use units of the design time package. When a project uses such a package the IDE warns before opening a form of the project, so the user can install it first. To test a design time package outside the IDE you may want to use it in a test project. For this case you can change this in Project Options / Miscellaneous / Use design time packages.
  3. A run time package can be used by projects. A user cannot install such a package directly (it is not listed). It cannot register things in the IDE. It can be used by design time packages, so it can be installed indirectly.
  4. A run time only package can only be used by projects. It cannot be installed in the IDE, not even indirectly. For example if the package is incompatible with the core IDE packages like the LCL. Since 0.9.31.


Typical scenario for a run time and design time package

You have a component library called Awesome and you want to write some IDE editors for some special properties. For example a property editor for the property Datafile which shows a TOpenDialog to let the user select a file. You can put the components into one run time package named AwesomeLaz.lpk' and create another directory design for the design time package AwesomeIDELaz.lpk. Move all units containing the IDE editors and registering stuff into the design directory. Add a dependency in AwesomeIDELaz to AwesomeLaz. Make sure they do not share units or search paths. For an example see components/turbopower_ipro/: The run time package is turbopoweripro.lpk and the design time package is design/turbopoweriprodsgn.lpk.

For Delphians: I can not install a run time package, why not?

Installing a package means compiling the whole code into the IDE. A run time package does not contain code for the IDE or maybe even bites it. In order to use a package in your project, simply open the package, right click on the package editor for the popup menu and click Add to project. Alternatively you can use View / Project Inspector. The project inspector shows what packages are used by your project, you can add dependencies or delete them.

Examples

Example for extending the Usage / Units path.

The tiOPF framework has the following directory layout, due to the fact that it compiles for FPC, Delphi 5-7, D2005 and D2006:

Source                <= full path \Programming\3rdParty\tiOPF\Source
  \Compilers
     \Delphi7          <= Delphi 7 package files live here
     \D2005
     \FPC              <= the tiOPF.lpk lived here
  \Core                <= core unit files
  \Options             <= optional unit file for extra features
  \GUI

Using this example, the following paths are included in the "Options - Usage - Units" editbox:

"$(PkgOutDir);..\..\Core;..\..\Options;..\..\GUI" 

This search path will be added to whatever project uses this package. The default is $(PkgOutDir), which would add only the ppu files to the project. Adding more search paths has the effect that the .pas source files are found by the compiler a second time - once when compiling the package and once when compiling your project. Since package and project use different settings the compiler might create a second version of the ppu, which is put into your project's output directory. Then you have two ppu for one unit and then you can get strange errors. To avoid the duplication disable the compilation of the package, by setting it to compile only manually.

Platform specific units

There are various ways to deal with separating platform-specific code:

One unit per platform, several units with same name

For example the unit myconnect.pas has two versions, one for Windows and one for Unix/Linux/OSX/BSD. The idea is to put the units into different sub directories and use macros in search paths.

  • Create two sub directories: win and unix.
  • Add to the package options / Compiler options / Paths / Other unit files the path $(SrcOS). SrcOS is a macro, that translates to win under Windows and unix under Linux/OSX/BSD.
  • Create a new package unit (package / Add / New file / Pascal unit) and save it under win/myconnect.pas.
  • If the unit is not selected in the package editor, select it.
  • Disable use unit.
  • Create a second package unit (package / Add / New file / Pascal unit) and save it under unix/myconnect.pas.
  • Keep the use unit enabled. It should be used once.

One unit for only one platform / conditional unit

For example: the unit mywin.pas should only be used under Windows, i.e. it should only be used and compiled if the flag Windows is defined.

The idea is to use the unit indirectly using IFDEFs. The following example shows how the unit mywin.pas is only used and compiled when the flag Windows is defined.

  • Create a new package unit (package / Add / New file / Pascal unit) and save it under mywin.pas.
  • If the unit is not selected in the package editor, select it.
  • Disable use unit.
  • Create a new package unit (package / Add / New file / Pascal unit) and save it under mypkgcompile.pas.
  • Add to the uses section of mypkgcompile.pas:
uses
  Classes
  {$IFDEF Windows}
  ,mywin
  {$ENDIF}
  ;

Note: mypkgcompile will be compiled under all platforms. mywin will only be compiled under Windows. You don't need to use the unit mypkgcompile in your project.

Different versions of a package

If you work with different versions of a package, you can open at any time the other package file. The old package will be closed and the new one will be opened. Registered items will be transferred to the new package. For example the component palette still shows the components of the old package, with which the IDE was built. But right clicking on a component will show a menu item to open the recently used package.

You can specify the minimum, maximum version required. When the project is opened and there are multiple .lpk files the IDE will automatically open the one with the right version.

If you work with different projects that require different versions of a package (for example with different branches of the same package), you can define the preferred one in the dependencies. In the project inspector right click on the dependency and click on Set file name as preferred for this dependency. When the project is opened, the preferred package will be opened. If there is already a package with the same name it will be replaced. This feature exists since 0.9.29.

SetDefaultPkDependency1.png

Project Inspector

Example library with multiple lpk

A library has two lpk files, main.lpk and sub.lpk. main depends on sub. The library has two version 1.0 and 2.0.

trunk/
  main.lpk  version 2.0, requires sub
  sub.lpk   version 2.0
fixes/
  main.lpk  version 1.0, requires sub
  sub.lpk   version 1.0

When you open main.lpk 1.0 for the first time, the IDE searches the package sub in its database and then it searches sub.lpk in the current folder. It finds sub.lpk 1.0 and loads it.

When you then open main.lpk 2.0, the IDE knows already a sub.lpk, the version 1.0 and loads it. It does not load the sub.lpk 2.0.

There are two solutions:

Using minimum, maximum version

You can set for each dependency the minimum and maximum version. When you set the minimum and maximum version of the dependency the following will happen: The main 1.0 and sub 1.0 is open. You open main 2.0 which requires sub >=2.0 and <=2.0. The IDE unloads main 1.0, loads main 2.0. The sub 1.0 does not fit, so the IDE searches for sub 2.0. Again it first searches in its database and then in the current folder. It finds sub.lpk and loads sub 2.0.

Using preferred file name

If the two lpk files are always distributed together you can use instead of minimum and maximum versions the preferred option. Open from trunk the main.lpk and sub.lpk to make sure that the right versions are loaded. Then right click on the dependency from main to sub and choose preferred file name. The file name will appear to the right of the dependency. Repeat this step with the lpk files from version 2.0. The IDE will now always open the right sub.lpk.

Build modes

You can add build modes to your package. See here for the various ways to achieve this:

Build modes for packages

Compiling a package via make

The IDE can create a simple Makefile for a package via Package editor / More ... / Create Makefile. The IDE creates the file Makefile.fpc and calls fpcmake, which creates the Makefile. Since 0.9.29 the IDE also creates the file Makefile.compiled. If you are using a version control system like svn or git, add all three files to the repository:

Makefile
Makefile.fpc
Makefile.compiled

You can now run make (e.g. open a console, cd to the package directory with the Makefile) to compile the package. This will compile the package and after successful compilation copy the Makefile.compiled to the unit output directory.

Notes:

  • The Makefile uses fixed paths, so it will not automatically adapt to changes as the IDE or lazbuild.
  • The IDE can recreate the Makefile on every compile. Enable the option Package editor / Options / Compiler Options / Compilation / Create Makefile.
  • The Makefile does not contain the logic for conditionals and build macros, it contains the settings at the time of creation.
  • The macros $(TargetOS), $(TargetCPU) and $(LCLWidgetType) are replaced by %TargetOS%, %TargetCPU% and %LCLPlatform%. The Makefile has somelogic to set some default values. You can override them (e.g. make LCLPlatform=qt).
  • The Makefile.compiled file is copied by the Makefile after successful compilation to <PkgOutDir>/<PkgName>.compiled and is checked by the IDE (and lazbuild) if a package needs a recompile. For example the Lazarus binaries (Windows Installer, deb and rpm packages, OS X dmg package) are compiled via make and when the IDE is started and compiles a program it will not recompile used packages, unless the user set some extra flags. For example when the user changes the IDEBuildOptions via the Configure Build Lazarus dialog the IDE will detect the difference and recompile the package on next compile.
  • If you forget to add the Makefile.compiled to svn you will get on make the error: /bin/cp: cannot stat `Makefile.compiled': No such file or directory

Creating a closed sourced package

Goal: you want to publish a package, but you want to keep the source closed.

At the moment many IDE functions require the source; the IDE warns if the source of a unit is missing. Therefore you must publish the interface parts of the units, and the files the compiler creates (ppu and o files).

Steps:

  • Create a copy of the package folder and change this copy as follows.
  • In the package editor / Options / IDE integration, set Update / Rebuild to Manual compilation.
  • Compile it once.
  • Delete the implementation sections of all units (i.e. everything after the implementation keyword of each unit including the initialization and finalization, only keeping the "end."). You can also remove the private section.
  • Optional: You can use the publish package tool (Package Editor / More... / Publish Package) to create a zip of the package.
  • You can delete the .compiled file, Makefile, rst files, lrt files. All other files in the output directory like .ppu, .o, .lfm files are needed by the compiler. The IDE needs the .lpk and the stripped .pas and .inc files.

There is a command line utility sourcecloser which alters the lpk and removes implementation sections. You can find it under lazarus/components/codetools/examples/sourcecloser.lpi.

See also:

Parallel Compilation

The IDE and lazbuild compile packages in parallel (since 1.3). Each package is still compiled with one call of fpc (single threaded).

You can set the maximum number of parallel processes in Tools / Options / Messages Window. By default it tries to guess the amount of cpu cores with the function GetSystemThreadCount in unit UTF8Process.

See also