Difference between revisions of "Show Application Title, Version, and Company/ru"

From Free Pascal wiki
Jump to navigationJump to search
Line 71: Line 71:
 
Использует [[fcl-res]]; вклад через список рассылки: [http://lists.lazarus.freepascal.org/pipermail/lazarus/attachments/20100723/8db6b97e/attachment.ksh]
 
Использует [[fcl-res]]; вклад через список рассылки: [http://lists.lazarus.freepascal.org/pipermail/lazarus/attachments/20100723/8db6b97e/attachment.ksh]
  
Use this like
+
Используйте это как
 
<syntaxhighlight lang="pascal">
 
<syntaxhighlight lang="pascal">
 
uses
 
uses
Line 78: Line 78:
 
  FUNCTION resourceVersionInfo: STRING;
 
  FUNCTION resourceVersionInfo: STRING;
 
   
 
   
  (* Unlike most of AboutText (below), this takes significant activity at run-    *)
+
  (* В отличие от большинства AboutText (см.ниже), это требует значительных усилий  *)
  (* time to extract version/release/build numbers from resource information      *)
+
  (* во время выполнения программы для извлечения номеров версий/выпусков/сборок из *)
  (* appended to the binary.                                                     *)
+
  (* информации о ресурсах, добавленной в двоичный файл.                           *)
 
   
 
   
 
  VAR    Stream: TResourceStream;
 
  VAR    Stream: TResourceStream;
Line 90: Line 90:
 
   TRY
 
   TRY
 
   
 
   
  (* This raises an exception if version info has not been incorporated into the  *)
+
  (* Это вызывет исключение, если информация о версии не была включена в двоичный *)
  (* binary (Lazarus Project -> Project Options -> Version Info -> Version       *)
+
  (* файл (Lazarus Project -> Project Options -> Version Info -> Version           *)
  (* numbering).                                                                 *)
+
  (* numbering).                                                                   *)
+
 
 
     Stream:= TResourceStream.CreateFromID(HINSTANCE, 1, PChar(RT_VERSION));
 
     Stream:= TResourceStream.CreateFromID(HINSTANCE, 1, PChar(RT_VERSION));
 
     TRY
 
     TRY
Line 115: Line 115:
  
  
Using vinfo: [http://forum.lazarus.freepascal.org/index.php?topic=12435.0] and [http://forum.lazarus.freepascal.org/index.php?topic=13957.0]
+
Использоаавние vinfo: [http://forum.lazarus.freepascal.org/index.php?topic=12435.0 здесь] и [http://forum.lazarus.freepascal.org/index.php?topic=13957.0 здесь]
  
 
== Related tips ==
 
== Related tips ==

Revision as of 14:30, 18 August 2020

English (en) русский (ru)

Обзор

Windows

С самых ранних версий Microsoft Windows имела возможность хранить информацию о версии и т.д. в исполняемом файле. Поддержка этого была добавлена в Delphi в районе v3 и частично работала в Lazarus 0.9.24.

Linux

В формате файла ELF нет неявных положений о номерах версий, авторских правах и так далее, но Lazarus хранит это в разделах ресурсов. Чтение информации во время исполнения программы зависит от модулей FPC, ниже - некоторая полезная информация.

macOS и iOS

Для macOS информация о версии файла Lazarus может храниться в двух местах:

  • исполняемый файл MACH-O (например, в Windows, Linux); см. ниже
  • комплект приложения (если он есть) в plist. См. Mac Show Application Title, Version, and Company для получения дополнительной информации.

Реализации

FPC 3.0

Реализация в FPC 3.0.x с использованием fcl-res: см. [announcement in User Changes 3.0]

В приведенном ниже коде показано, как получить информацию об исполняемых файлах из

  • .exe/.dll/.ocx (формат Windows) файлов
  • исполняемых файлов ELF, скомпилированных в Lazarus (Linux),
  • исполняемых файлов MACH-O, скомпилированных в Lazarus (OSX)
program printfileinfo;
{Отображает информацию о версии файла для 
- исполняемых файлов Windows PE 
- исполняемых Linux ELF (скомпилированных в Lazarus)
- исполняемых файлов MACH-O OSX (скомпилированных в Lazarus)
Запускается на Windows, Linux, OSX...
}

{$mode objfpc}{$H+}
{$ifdef mswindows}{$apptype console}{$endif}
uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes,sysutils
  // FPC 3.0 fileinfo читает ресурсы exe, пока вы регистрируете соответствующие модули
  , fileinfo
  , winpeimagereader {это нужно для чтения информации exe}
  , elfreader {необходимо для чтения исполняемых файлов ELF}
  , machoreader {необходимо для чтения исполняемых файлов MACH-O}
  ;

var
  FileVerInfo: TFileVersionInfo;

{$R *.res}

begin
  FileVerInfo:=TFileVersionInfo.Create(nil);
  try
    FileVerInfo.ReadFileInfo;
    writeln('Company: ',FileVerInfo.VersionStrings.Values['CompanyName']);
    writeln('File description: ',FileVerInfo.VersionStrings.Values['FileDescription']);
    writeln('File version: ',FileVerInfo.VersionStrings.Values['FileVersion']);
    writeln('Internal name: ',FileVerInfo.VersionStrings.Values['InternalName']);
    writeln('Legal copyright: ',FileVerInfo.VersionStrings.Values['LegalCopyright']);
    writeln('Original filename: ',FileVerInfo.VersionStrings.Values['OriginalFilename']);
    writeln('Product name: ',FileVerInfo.VersionStrings.Values['ProductName']);
    writeln('Product version: ',FileVerInfo.VersionStrings.Values['ProductVersion']);
  finally
    FileVerInfo.Free;
  end;
end.

Реализации с использованием устаревшего FPC 2.6.x

Использует fcl-res; вклад через список рассылки: [1]

Используйте это как

uses
  resource, versiontypes, versionresource;

 FUNCTION resourceVersionInfo: STRING;
 
 (* В отличие от большинства AboutText (см.ниже), это требует значительных усилий  *)
 (* во время выполнения программы для извлечения номеров версий/выпусков/сборок из *)
 (* информации о ресурсах, добавленной в двоичный файл.                            *)
 
 VAR     Stream: TResourceStream;
         vr: TVersionResource;
         fi: TVersionFixedInfo;
 
 BEGIN
   RESULT:= '';
   TRY
 
 (* Это вызывет исключение, если информация о версии не была включена в двоичный *)
 (* файл (Lazarus Project -> Project Options -> Version Info -> Version           *)
 (* numbering).                                                                   *)

     Stream:= TResourceStream.CreateFromID(HINSTANCE, 1, PChar(RT_VERSION));
     TRY
       vr:= TVersionResource.Create;
       TRY
         vr.SetCustomRawDataStream(Stream);
         fi:= vr.FixedInfo;
         RESULT := 'Version ' + IntToStr(fi.FileVersion[0]) + '.' + IntToStr(fi.FileVersion[1]) +
                ' release ' + IntToStr(fi.FileVersion[2]) + ' build ' + IntToStr(fi.FileVersion[3]) + eol;
         vr.SetCustomRawDataStream(nil)
       FINALLY
         vr.Free
       END
     FINALLY
       Stream.Free
     END
   EXCEPT
   END
 END { resourceVersionInfo } ;


Использоаавние vinfo: здесь и здесь

Related tips

SVN/Git/Hg/Mercurial revision

Use $(lazarusdir)/tools/svn2revisioninc to get revision number (from a subversion, git or mercurial repository) into a file revision.inc, e.g. something like:

// Created by Svn2RevisionInc
const RevisionStr = '43594';

Unix-only hacks

These work with Linux on various platforms, and probably with Solaris provided that the GNU-derived utilities are installed.

Getting Subversion revision information as a program-accessible string

Put this into Project options -> Compilation -> Execute before -> Command:

/bin/sh -c "echo -n C`svnversion -n`C |tr A-G %-+ >project_svnrevision.inc"

Note quote and backtick positions. The tr is converting C into another layer of quotes which is necessary for things to work as required.

Put this into the program:

   (*$IFDEF UNIX   *)
           rev= (*$I project_svnrevision.inc *) ;
   (*$ELSE         *)
           rev= 'unimplemented';
   (*$ENDIF        *)

Note that that has to be a string, since the revision number will have a non-numeric suffix if the project has been updated since it was last committed.

Renaming the final executable to include platform and timestamp

Put this into Project options -> Paths -> Unit output directory:

lib/$(TargetCPU)-$(TargetOS)

Put this into Project options -> Paths -> Target file name:

UnyokedBackend-$(TargetCPU)-$(TargetOS)-$(LCLWidgetType)

Make sure that "Apply conventions" is ticked (checked). This might vary slightly according to IDE and compiler/linker versions.

Put this into Project options -> Compilation -> Execute after -> Command:

 /bin/sh -c "mv libunyokedbackend-$(TargetCPU)-$(TargetOS)-$(LCLWidgetType).so UnyokedBackend-$(TargetCPU)-$(TargetOS)-$(LCLWidgetType).`date +%F.%R`.so"

That should be a single line. Note quote and backtick positions.