text
stringlengths
14
6.51M
unit UtelaCadastro; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UTela, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Rtti; type TStatusTela = (stNavegandoGrid, stInserindo, stEditando); TFTelaCadastro = class(TFTela) DadosCadastrais: TTabSheet; PanelBotoes: TPanel; BitBtnNovo: TBitBtn; BitBtnAltera: TBitBtn; BitBtnGrava: TBitBtn; BitBtnExclui: TBitBtn; BitBtnCancela: TBitBtn; PageControlEdit: TPageControl; DadosPrincipais: TTabSheet; PanelEdits: TPanel; BitBtnIncluirC: TBitBtn; procedure PageControlChange(Sender: TObject); procedure SetStatusTela(const Value: TStatusTela); virtual; procedure BitBtnNovoClick(Sender: TObject); procedure BitBtnAlteraClick(Sender: TObject); procedure BitBtnCancelaClick(Sender: TObject); procedure BitBtnExcluiClick(Sender: TObject); procedure BitBtnGravaClick(Sender: TObject); private public FStatusTela: TStatusTela; { Public declarations } function DoInserir: Boolean; virtual; function DoEditar: Boolean; virtual; function DoExcluir: Boolean; virtual; function DoCancelar: Boolean; virtual; function DoSalvar: Boolean; virtual; property StatusTela: TStatusTela read FStatusTela write SetStatusTela; end; var FTelaCadastro: TFTelaCadastro; implementation {$R *.dfm} { TFTelaCadastro } procedure TFTelaCadastro.BitBtnAlteraClick(Sender: TObject); begin DoEditar; end; procedure TFTelaCadastro.BitBtnCancelaClick(Sender: TObject); begin DoCancelar; end; procedure TFTelaCadastro.BitBtnExcluiClick(Sender: TObject); begin if CDSGrid.IsEmpty then Application.MessageBox('Não existe registro selecionado.', 'Erro', MB_OK + MB_ICONERROR) else begin if Application.MessageBox ('Deseja realmente excluir o registro selecionado?', 'Confirmação', MB_YESNO + MB_ICONQUESTION) = IDYES then begin if (DoExcluir) then begin PageControl.ActivePage := Consulta; DoConsultar; SetStatusTela(TStatusTela.stNavegandoGrid); end; end; end; end; procedure TFTelaCadastro.BitBtnGravaClick(Sender: TObject); begin inherited; if (DoSalvar) then begin PageControl.ActivePage := Consulta; DoConsultar; SetStatusTela(TStatusTela.stNavegandoGrid); end; end; procedure TFTelaCadastro.BitBtnNovoClick(Sender: TObject); begin DoInserir; end; function TFTelaCadastro.DoCancelar: Boolean; begin if (StatusTela = TStatusTela.stInserindo) then PageControl.ActivePage := Consulta; SetStatusTela(TStatusTela.stNavegandoGrid); Result := True; end; function TFTelaCadastro.DoEditar: Boolean; begin Result := false; if CDSGrid.IsEmpty then Application.MessageBox('Não existe registro selecionado.', 'Erro', MB_OK + MB_ICONERROR) else begin StatusTela := stEditando; Result := True; end; end; function TFTelaCadastro.DoExcluir: Boolean; begin Result := True; end; function TFTelaCadastro.DoInserir: Boolean; begin LimparCampos; StatusTela := stInserindo; PageControl.ActivePage := DadosCadastrais; Result := True; end; function TFTelaCadastro.DoSalvar: Boolean; begin Result := True; end; procedure TFTelaCadastro.PageControlChange(Sender: TObject); begin inherited; if (PageControl.ActivePage = DadosCadastrais) then begin if (not CDSGrid.IsEmpty) then begin LimparCampos; GridParaEdits; end; end; StatusTela := stNavegandoGrid; end; procedure TFTelaCadastro.SetStatusTela(const Value: TStatusTela); begin FStatusTela := Value; BitBtnNovo.Enabled := True; BitBtnIncluirC.Enabled := True; BitBtnAltera.Enabled := True; BitBtnGrava.Enabled := True; BitBtnExclui.Enabled := True; BitBtnCancela.Enabled := false; PanelEdits.Enabled := True; case Value of stNavegandoGrid: begin PanelEdits.Enabled := false; BitBtnNovo.Enabled := True; BitBtnIncluirC.Enabled := True; BitBtnAltera.Enabled := True; BitBtnGrava.Enabled := false; BitBtnExclui.Enabled := True; BitBtnCancela.Enabled := false; end; stInserindo, stEditando: begin PanelEdits.Enabled := True; BitBtnNovo.Enabled := false; BitBtnIncluirC.Enabled := false; BitBtnAltera.Enabled := false; BitBtnGrava.Enabled := True; BitBtnExclui.Enabled := false; BitBtnCancela.Enabled := True; end; end; end; end.
program opsi_doc_generator; {$mode objfpc}{$H+} uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} fileinfo, winpeimagereader, // {need this for reading exe info} elfreader, // {needed for reading ELF executables} Classes, SysUtils, CustApp, oslog, odg_main; type { opsidocgenerator } opsidocgenerator = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { opsidocgenerator } var myversion : string; procedure opsidocgenerator.DoRun; var ErrorMsg: string; myoptions, mynonoptions : TStringList; infilename : string; FileVerInfo : TFileVersionInfo; begin //from http://wiki.freepascal.org/Show_Application_Title,_Version,_and_Company FileVerInfo := TFileVersionInfo.Create(nil); try FileVerInfo.FileName := ParamStr(0); FileVerInfo.ReadFileInfo; myversion := FileVerInfo.VersionStrings.Values['FileVersion']; finally FileVerInfo.Free; end; myoptions := TStringList.Create; mynonoptions := TStringList.Create; // quick check parameters ErrorMsg := CheckOptions('h', ['help'], myoptions, mynonoptions); if ErrorMsg <> '' then begin ShowException(Exception.Create(ErrorMsg)); Terminate; Exit; end; // parse parameters if HasOption('h', 'help') then begin WriteHelp; Terminate; Exit; end; if mynonoptions.Count = 0 then begin WriteHelp; Terminate; Exit; end; infilename := mynonoptions.Strings[0]; infilename := ExpandFileName(infilename); if not FileExists(infilename) then begin writeln('Error: Could not find given file: '+infilename); WriteHelp; Terminate; Exit; end; sourcelist.LoadFromFile(infilename); if ExtractFileExt(infilename) = '.opsiscript' then begin convertOslibToAsciidoc(infilename); end else begin convertPylibToAsciidoc(infilename); end; save_compile_show(infilename); // stop program loop Terminate; end; constructor opsidocgenerator.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException := True; end; destructor opsidocgenerator.Destroy; begin inherited Destroy; end; procedure opsidocgenerator.WriteHelp; var filename: string; begin filename := ExtractFileName(ParamStr(0)); //writeln(ParamStr(0)); writeln('Creates asciidoc from commented opsiscript library code'); writeln(' and calls asciidoctor to convert asciidoc to html'); writeln('and shows created html file in browser.'); writeln(filename); writeln('Version: ' + myversion); writeln('Usage:'); writeln(filename + ' [Options] inputfile'); writeln('Options:'); writeln(' --help -> write this help and exit'); (* if Assigned(LogDatei) then LogDatei.Close; *) Terminate; halt(-1); Exit; end; var Application: opsidocgenerator; {$R *.res} begin Application := opsidocgenerator.Create(nil); Application.Title := 'opsi doc generator'; Application.Run; Application.Free; end.
// // Generated by JavaToPas v1.4 20140526 - 132729 //////////////////////////////////////////////////////////////////////////////// unit java.nio.charset.Charset; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JCharset = interface; JCharsetClass = interface(JObjectClass) ['{EF6C78FA-F03C-4C86-B126-CB5F9DDB4C1E}'] function &contains(JCharsetparam0 : JCharset) : boolean; cdecl; // (Ljava/nio/charset/Charset;)Z A: $401 function &name : JString; cdecl; // ()Ljava/lang/String; A: $11 function aliases : JSet; cdecl; // ()Ljava/util/Set; A: $11 function availableCharsets : JSortedMap; cdecl; // ()Ljava/util/SortedMap; A: $9 function canEncode : boolean; cdecl; // ()Z A: $1 function compareTo(charset : JCharset) : Integer; cdecl; // (Ljava/nio/charset/Charset;)I A: $11 function decode(buffer : JByteBuffer) : JCharBuffer; cdecl; // (Ljava/nio/ByteBuffer;)Ljava/nio/CharBuffer; A: $11 function defaultCharset : JCharset; cdecl; // ()Ljava/nio/charset/Charset; A: $9 function displayName : JString; cdecl; overload; // ()Ljava/lang/String; A: $1 function displayName(l : JLocale) : JString; cdecl; overload; // (Ljava/util/Locale;)Ljava/lang/String; A: $1 function encode(buffer : JCharBuffer) : JByteBuffer; cdecl; overload; // (Ljava/nio/CharBuffer;)Ljava/nio/ByteBuffer; A: $11 function encode(s : JString) : JByteBuffer; cdecl; overload; // (Ljava/lang/String;)Ljava/nio/ByteBuffer; A: $11 function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $11 function forName(charsetName : JString) : JCharset; cdecl; // (Ljava/lang/String;)Ljava/nio/charset/Charset; A: $9 function hashCode : Integer; cdecl; // ()I A: $11 function isRegistered : boolean; cdecl; // ()Z A: $11 function isSupported(charsetName : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $9 function newDecoder : JCharsetDecoder; cdecl; // ()Ljava/nio/charset/CharsetDecoder; A: $401 function newEncoder : JCharsetEncoder; cdecl; // ()Ljava/nio/charset/CharsetEncoder; A: $401 function toString : JString; cdecl; // ()Ljava/lang/String; A: $11 end; [JavaSignature('java/nio/charset/Charset')] JCharset = interface(JObject) ['{AD9E40BF-1B04-4B96-A571-6A8877FD2916}'] function &contains(JCharsetparam0 : JCharset) : boolean; cdecl; // (Ljava/nio/charset/Charset;)Z A: $401 function canEncode : boolean; cdecl; // ()Z A: $1 function displayName : JString; cdecl; overload; // ()Ljava/lang/String; A: $1 function displayName(l : JLocale) : JString; cdecl; overload; // (Ljava/util/Locale;)Ljava/lang/String; A: $1 function newDecoder : JCharsetDecoder; cdecl; // ()Ljava/nio/charset/CharsetDecoder; A: $401 function newEncoder : JCharsetEncoder; cdecl; // ()Ljava/nio/charset/CharsetEncoder; A: $401 end; TJCharset = class(TJavaGenericImport<JCharsetClass, JCharset>) end; implementation end.
// // Generated by JavaToPas v1.5 20180804 - 083109 //////////////////////////////////////////////////////////////////////////////// unit android.content.pm.ShortcutInfo; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.os, android.content.ComponentName, android.content.ClipData; type JShortcutInfo = interface; JShortcutInfoClass = interface(JObjectClass) ['{F21BFCCD-7A84-45FE-A120-50FAD570455A}'] function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19 function _GetDISABLED_REASON_APP_CHANGED : Integer; cdecl; // A: $19 function _GetDISABLED_REASON_BACKUP_NOT_SUPPORTED : Integer; cdecl; // A: $19 function _GetDISABLED_REASON_BY_APP : Integer; cdecl; // A: $19 function _GetDISABLED_REASON_NOT_DISABLED : Integer; cdecl; // A: $19 function _GetDISABLED_REASON_OTHER_RESTORE_ISSUE : Integer; cdecl; // A: $19 function _GetDISABLED_REASON_SIGNATURE_MISMATCH : Integer; cdecl; // A: $19 function _GetDISABLED_REASON_UNKNOWN : Integer; cdecl; // A: $19 function _GetDISABLED_REASON_VERSION_LOWER : Integer; cdecl; // A: $19 function _GetSHORTCUT_CATEGORY_CONVERSATION : JString; cdecl; // A: $19 function describeContents : Integer; cdecl; // ()I A: $1 function getActivity : JComponentName; cdecl; // ()Landroid/content/ComponentName; A: $1 function getCategories : JSet; cdecl; // ()Ljava/util/Set; A: $1 function getDisabledMessage : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1 function getDisabledReason : Integer; cdecl; // ()I A: $1 function getExtras : JPersistableBundle; cdecl; // ()Landroid/os/PersistableBundle; A: $1 function getId : JString; cdecl; // ()Ljava/lang/String; A: $1 function getIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1 function getIntents : TJavaArray<JIntent>; cdecl; // ()[Landroid/content/Intent; A: $1 function getLastChangedTimestamp : Int64; cdecl; // ()J A: $1 function getLongLabel : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1 function getPackage : JString; cdecl; // ()Ljava/lang/String; A: $1 function getRank : Integer; cdecl; // ()I A: $1 function getShortLabel : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1 function getUserHandle : JUserHandle; cdecl; // ()Landroid/os/UserHandle; A: $1 function hasKeyFieldsOnly : boolean; cdecl; // ()Z A: $1 function isDeclaredInManifest : boolean; cdecl; // ()Z A: $1 function isDynamic : boolean; cdecl; // ()Z A: $1 function isEnabled : boolean; cdecl; // ()Z A: $1 function isImmutable : boolean; cdecl; // ()Z A: $1 function isPinned : boolean; cdecl; // ()Z A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19 property DISABLED_REASON_APP_CHANGED : Integer read _GetDISABLED_REASON_APP_CHANGED;// I A: $19 property DISABLED_REASON_BACKUP_NOT_SUPPORTED : Integer read _GetDISABLED_REASON_BACKUP_NOT_SUPPORTED;// I A: $19 property DISABLED_REASON_BY_APP : Integer read _GetDISABLED_REASON_BY_APP; // I A: $19 property DISABLED_REASON_NOT_DISABLED : Integer read _GetDISABLED_REASON_NOT_DISABLED;// I A: $19 property DISABLED_REASON_OTHER_RESTORE_ISSUE : Integer read _GetDISABLED_REASON_OTHER_RESTORE_ISSUE;// I A: $19 property DISABLED_REASON_SIGNATURE_MISMATCH : Integer read _GetDISABLED_REASON_SIGNATURE_MISMATCH;// I A: $19 property DISABLED_REASON_UNKNOWN : Integer read _GetDISABLED_REASON_UNKNOWN;// I A: $19 property DISABLED_REASON_VERSION_LOWER : Integer read _GetDISABLED_REASON_VERSION_LOWER;// I A: $19 property SHORTCUT_CATEGORY_CONVERSATION : JString read _GetSHORTCUT_CATEGORY_CONVERSATION;// Ljava/lang/String; A: $19 end; [JavaSignature('android/content/pm/ShortcutInfo$Builder')] JShortcutInfo = interface(JObject) ['{D2BF75A9-5AF9-43E8-B465-360760AE30A7}'] function describeContents : Integer; cdecl; // ()I A: $1 function getActivity : JComponentName; cdecl; // ()Landroid/content/ComponentName; A: $1 function getCategories : JSet; cdecl; // ()Ljava/util/Set; A: $1 function getDisabledMessage : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1 function getDisabledReason : Integer; cdecl; // ()I A: $1 function getExtras : JPersistableBundle; cdecl; // ()Landroid/os/PersistableBundle; A: $1 function getId : JString; cdecl; // ()Ljava/lang/String; A: $1 function getIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1 function getIntents : TJavaArray<JIntent>; cdecl; // ()[Landroid/content/Intent; A: $1 function getLastChangedTimestamp : Int64; cdecl; // ()J A: $1 function getLongLabel : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1 function getPackage : JString; cdecl; // ()Ljava/lang/String; A: $1 function getRank : Integer; cdecl; // ()I A: $1 function getShortLabel : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1 function getUserHandle : JUserHandle; cdecl; // ()Landroid/os/UserHandle; A: $1 function hasKeyFieldsOnly : boolean; cdecl; // ()Z A: $1 function isDeclaredInManifest : boolean; cdecl; // ()Z A: $1 function isDynamic : boolean; cdecl; // ()Z A: $1 function isEnabled : boolean; cdecl; // ()Z A: $1 function isImmutable : boolean; cdecl; // ()Z A: $1 function isPinned : boolean; cdecl; // ()Z A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 end; TJShortcutInfo = class(TJavaGenericImport<JShortcutInfoClass, JShortcutInfo>) end; const TJShortcutInfoDISABLED_REASON_APP_CHANGED = 2; TJShortcutInfoDISABLED_REASON_BACKUP_NOT_SUPPORTED = 101; TJShortcutInfoDISABLED_REASON_BY_APP = 1; TJShortcutInfoDISABLED_REASON_NOT_DISABLED = 0; TJShortcutInfoDISABLED_REASON_OTHER_RESTORE_ISSUE = 103; TJShortcutInfoDISABLED_REASON_SIGNATURE_MISMATCH = 102; TJShortcutInfoDISABLED_REASON_UNKNOWN = 3; TJShortcutInfoDISABLED_REASON_VERSION_LOWER = 100; TJShortcutInfoSHORTCUT_CATEGORY_CONVERSATION = 'android.shortcut.conversation'; implementation end.
{ Conversion from Linux Kernel input.h 1.0 - 2019.04.24 - Nicola Perotto <nicola@nicolaperotto.it> } { https://github.com/torvalds/linux/blob/master/include/uapi/linux/input.h /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (c) 1999-2002 Vojtech Pavlik * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. } {$I+,R+,Q+} {$IFDEF FPC}{$MODE DELPHI}{$ENDIF} Unit Input; Interface Uses {$IFDEF FPC}BaseUnix, {$ENDIF} IOCtl; {$IFNDEF FPC}//Syntax Check in Delphi IDE Type cInt = integer; TIOCtlRequest = cInt; QWord = Int64; clong = LongInt; {$ENDIF} Type time_t = clong; timeval = record tv_sec : time_t; tv_usec : clong; end; Const //Protocol version. EV_VERSION = $010001; EV_SYN = 0; INPUT_KEYMAP_BY_INDEX = (1 shl 0); NUM_SLOTS = 8; Const //IDs ID_BUS = 0; ID_VENDOR = 1; ID_PRODUCT = 2; ID_VERSION = 3; BUS_PCI = $01; BUS_ISAPNP = $02; BUS_USB = $03; BUS_HIL = $04; BUS_BLUETOOTH = $05; BUS_VIRTUAL = $06; BUS_ISA = $10; BUS_I8042 = $11; BUS_XTKBD = $12; BUS_RS232 = $13; BUS_GAMEPORT = $14; BUS_PARPORT = $15; BUS_AMIGA = $16; BUS_ADB = $17; BUS_I2C = $18; BUS_HOST = $19; BUS_GSC = $1A; BUS_ATARI = $1B; BUS_SPI = $1C; BUS_RMI = $1D; BUS_CEC = $1E; BUS_INTEL_ISHTP = $1F; //MT_TOOL types MT_TOOL_FINGER = $00; MT_TOOL_PEN = $01; MT_TOOL_PALM = $02; MT_TOOL_DIAL = $0a; MT_TOOL_MAX = $0f; //Values describing the status of a force-feedback effect FF_STATUS_STOPPED = $00; FF_STATUS_PLAYING = $01; FF_STATUS_MAX = $01; Const //Force feedback effect types FF_RUMBLE = $50; FF_PERIODIC = $51; FF_CONSTANT = $52; FF_SPRING = $53; FF_FRICTION = $54; FF_DAMPER = $55; FF_INERTIA = $56; FF_RAMP = $57; FF_EFFECT_MIN = FF_RUMBLE; FF_EFFECT_MAX = FF_RAMP; //Force feedback periodic effect types FF_SQUARE = $58; FF_TRIANGLE = $59; FF_SINE = $5a; FF_SAW_UP = $5b; FF_SAW_DOWN = $5c; FF_CUSTOM = $5d; FF_WAVEFORM_MIN = FF_SQUARE; FF_WAVEFORM_MAX = FF_CUSTOM; //Set ff device properties FF_GAIN = $60; FF_AUTOCENTER = $61; { * ff->playback(effect_id = FF_GAIN) is the first effect_id to * cause a collision with another ff method, in this case ff->set_gain(). * Therefore the greatest safe value for effect_id is FF_GAIN - 1, * and thus the total number of effects should never exceed FF_GAIN. } FF_MAX_EFFECTS = FF_GAIN; FF_MAX = $7f; FF_CNT = (FF_MAX+1); Type { * The event structure itself * Note that __USE_TIME_BITS64 is defined by libc based on * application's request to use 64 bit time_t.} TInput_Event = packed record Time : timeval; etype : Word; code : Word; value : LongInt; end; TInput_ID = packed record bustype, vendor, product, version : Word end; { * struct input_absinfo - used by EVIOCGABS/EVIOCSABS ioctls * @value: latest reported value for the axis. * @minimum: specifies minimum value for the axis. * @maximum: specifies maximum value for the axis. * @fuzz: specifies fuzz value that is used to filter noise from * the event stream. * @flat: values that are within this value will be discarded by * joydev interface and reported as 0 instead. * @resolution: specifies resolution for the values reported for * the axis. * * Note that input core does not clamp reported values to the * [minimum, maximum] limits, such task is left to userspace. * * The default resolution for main axes (ABS_X, ABS_Y, ABS_Z) * is reported in units per millimeter (units/mm), resolution * for rotational axes (ABS_RX, ABS_RY, ABS_RZ) is reported * in units per radian. * When INPUT_PROP_ACCELEROMETER is set the resolution changes. * The main axes (ABS_X, ABS_Y, ABS_Z) are then reported in * in units per g (units/g) and in units per degree per second * (units/deg/s) for rotational axes (ABS_RX, ABS_RY, ABS_RZ). } TInput_Absinfo = packed record value : LongInt; minimum : LongInt; maximum : LongInt; fuzz : LongInt; flat : LongInt; resolution : LongInt; end; { * struct input_keymap_entry - used by EVIOCGKEYCODE/EVIOCSKEYCODE ioctls * @scancode: scancode represented in machine-endian form. * @len: length of the scancode that resides in @scancode buffer. * @index: index in the keymap, may be used instead of scancode * @flags: allows to specify how kernel should handle the request. For * example, setting INPUT_KEYMAP_BY_INDEX flag indicates that kernel * should perform lookup in keymap by @index instead of @scancode * @keycode: key code assigned to this scancode * * The structure is used to retrieve and modify keymap data. Users have * option of performing lookup either by @scancode itself or by @index * in keymap entry. EVIOCGKEYCODE will also return scancode or index * (depending on which element was used to perform lookup). } TInput_Keymap_Entry = packed record flags : byte; len : byte; index : word; keycode : LongWord; scancode : array[0..31] of byte; end; TInput_Mask = packed record etype : LongWord; codes_size : LongWord; codes_ptr : QWord; end; TInput_My_Request_Layout = packed record code : LongWord; values : array[0..NUM_SLOTS -1] of LongInt; end; { * Structures used in ioctls to upload effects to a device * They are pieces of a bigger structure (called ff_effect) * All duration values are expressed in ms. Values above 32767 ms (0x7fff) * should not be used and have unspecified results. } { * struct ff_replay - defines scheduling of the force-feedback effect * @length: duration of the effect * @delay: delay before effect should start playing } TFF_Replay = packed record length : word; delay : word; end; { * struct ff_trigger - defines what triggers the force-feedback effect * @button: number of the button triggering the effect * @interval: controls how soon the effect can be re-triggered } TFF_Trigger = packed record button : word; interval : word; end; { * struct ff_envelope - generic force-feedback effect envelope * @attack_length: duration of the attack (ms) * @attack_level: level at the beginning of the attack * @fade_length: duration of fade (ms) * @fade_level: level at the end of fade * * The @attack_level and @fade_level are absolute values; when applying * envelope force-feedback core will convert to positive/negative * value based on polarity of the default level of the effect. * Valid range for the attack and fade levels is 0x0000 - 0x7fff } TFF_Envelope = packed record attack_length : word; attack_level : word; fade_length : word; fade_level : word; end; { * struct ff_constant_effect - defines parameters of a constant force-feedback effect * @level: strength of the effect; may be negative * @envelope: envelope data } TFF_Constant_Effect = packed record level : Smallint; envelope : TFF_Envelope; end; { * struct ff_ramp_effect - defines parameters of a ramp force-feedback effect * @start_level: beginning strength of the effect; may be negative * @end_level: final strength of the effect; may be negative * @envelope: envelope data } TFF_Ramp_Effect = packed record start_level : Smallint; end_level : Smallint; envelope : TFF_Envelope; end; { * struct ff_condition_effect - defines a spring or friction force-feedback effect * @right_saturation: maximum level when joystick moved all way to the right * @left_saturation: same for the left side * @right_coeff: controls how fast the force grows when the joystick moves * to the right * @left_coeff: same for the left side * @deadband: size of the dead zone, where no force is produced * @center: position of the dead zone } TFF_Condition_Effect = packed record right_saturation : word; left_saturation : word; right_coeff : Smallint; left_coeff : Smallint; deadband : word; center : Smallint; end; { * struct ff_periodic_effect - defines parameters of a periodic force-feedback effect * @waveform: kind of the effect (wave) * @period: period of the wave (ms) * @magnitude: peak value * @offset: mean value of the wave (roughly) * @phase: 'horizontal' shift * @envelope: envelope data * @custom_len: number of samples (FF_CUSTOM only) * @custom_data: buffer of samples (FF_CUSTOM only) * * Known waveforms - FF_SQUARE, FF_TRIANGLE, FF_SINE, FF_SAW_UP, * FF_SAW_DOWN, FF_CUSTOM. The exact syntax FF_CUSTOM is undefined * for the time being as no driver supports it yet. * * Note: the data pointed by custom_data is copied by the driver. * You can therefore dispose of the memory after the upload/update. } TFF_Periodic_Effect = packed record waveform : word; period : word; magnitude : SmallInt; offset : SmallInt; phase : word; envelope : TFF_Envelope; custom_len : LongWord; custom_data : Pointer; //to SmallInt / __s16 end; { * struct ff_rumble_effect - defines parameters of a periodic force-feedback effect * @strong_magnitude: magnitude of the heavy motor * @weak_magnitude: magnitude of the light one * * Some rumble pads have two motors of different weight. Strong_magnitude * represents the magnitude of the vibration generated by the heavy one. } TFF_Rumble_Effect = packed record strong_magnitude : word; weak_magnitude : word; end; { * struct ff_effect - defines force feedback effect * @type: type of the effect (FF_CONSTANT, FF_PERIODIC, FF_RAMP, FF_SPRING, * FF_FRICTION, FF_DAMPER, FF_RUMBLE, FF_INERTIA, or FF_CUSTOM) * @id: an unique id assigned to an effect * @direction: direction of the effect * @trigger: trigger conditions (struct ff_trigger) * @replay: scheduling of the effect (struct ff_replay) * @u: effect-specific structure (one of ff_constant_effect, ff_ramp_effect, * ff_periodic_effect, ff_condition_effect, ff_rumble_effect) further * defining effect parameters * * This structure is sent through ioctl from the application to the driver. * To create a new effect application should set its @id to -1; the kernel * will return assigned @id which can later be used to update or delete * this effect. * * Direction of the effect is encoded as follows: * 0 deg -> 0x0000 (down) * 90 deg -> 0x4000 (left) * 180 deg -> 0x8000 (up) * 270 deg -> 0xC000 (right) } TFF_Effect = packed record etype : word; id : SmallInt; direction : word; trigger : TFF_Trigger; replay : TFF_Replay; //union u constant : TFF_Constant_Effect; ramp : TFF_Ramp_Effect; periodic : TFF_Periodic_Effect; condition : array[0..1] of TFF_Condition_Effect ; //One for each axis rumble : TFF_Rumble_Effect; end; Const //#define EVIOCGVERSION _IOR('E', 0x01, int) /* get driver version */ EVIOCGVERSION = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($01 shl _IOC_NRSHIFT) or (SizeOf(LongInt) shl _IOC_SIZESHIFT); //#define EVIOCGID _IOR('E', 0x02, struct input_id) /* get device ID */ EVIOCGID = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($02 shl _IOC_NRSHIFT) or (SizeOf(TInput_ID) shl _IOC_SIZESHIFT); //#define EVIOCGREP _IOR('E', 0x03, unsigned int[2]) /* get repeat settings */ EVIOCGREP = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($03 shl _IOC_NRSHIFT) or ((2*SizeOf(LongWord)) shl _IOC_SIZESHIFT); //#define EVIOCSREP _IOW('E', 0x03, unsigned int[2]) /* set repeat settings */ EVIOCSREP = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($03 shl _IOC_NRSHIFT) or ((2*SizeOf(LongWord)) shl _IOC_SIZESHIFT); //#define EVIOCGKEYCODE _IOR('E', 0x04, unsigned int[2]) /* get keycode */ EVIOCGKEYCODE = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($04 shl _IOC_NRSHIFT) or ((2*SizeOf(LongWord)) shl _IOC_SIZESHIFT); //#define EVIOCGKEYCODE_V2 _IOR('E', 0x04, struct input_keymap_entry) EVIOCGKEYCODE_V2 = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($04 shl _IOC_NRSHIFT) or (SizeOf(Tinput_keymap_entry) shl _IOC_SIZESHIFT); //#define EVIOCSKEYCODE _IOW('E', 0x04, unsigned int[2]) /* set keycode */ EVIOCSKEYCODE = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($04 shl _IOC_NRSHIFT) or ((2*SizeOf(LongWord)) shl _IOC_SIZESHIFT); //#define EVIOCSKEYCODE_V2 _IOW('E', 0x04, struct input_keymap_entry) EVIOCSKEYCODE_V2 = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($04 shl _IOC_NRSHIFT) or (SizeOf(Tinput_keymap_entry) shl _IOC_SIZESHIFT); //these return a string (c, #0 terminated) so len is fixed (by me) at 256 //#define EVIOCGNAME(len) _IOC(_IOC_READ, 'E', 0x06, len) /* get device name */ EVIOCGNAME_size = 256; EVIOCGNAME = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($06 shl _IOC_NRSHIFT) or (EVIOCGNAME_size shl _IOC_SIZESHIFT); //#define EVIOCGPHYS(len) _IOC(_IOC_READ, 'E', 0x07, len) /* get physical location */ EVIOCGPHYS_size = 256; EVIOCGPHYS = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($07 shl _IOC_NRSHIFT) or (EVIOCGPHYS_size shl _IOC_SIZESHIFT); //#define EVIOCGUNIQ(len) _IOC(_IOC_READ, 'E', 0x08, len) /* get unique identifier */ EVIOCGUNIQ_size = 256; EVIOCGUNIQ = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($08 shl _IOC_NRSHIFT) or (EVIOCGUNIQ_size shl _IOC_SIZESHIFT); //#define EVIOCGPROP(len) _IOC(_IOC_READ, 'E', 0x09, len) /* get device properties */ EVIOCGPROP_size = 256; EVIOCGPROP = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($09 shl _IOC_NRSHIFT) or (EVIOCGPROP_size shl _IOC_SIZESHIFT); { * EVIOCGMTSLOTS(len) - get MT slot values * @len: size of the data buffer in bytes * * The ioctl buffer argument should be binary equivalent to * * struct input_mt_request_layout { * __u32 code; * __s32 values[num_slots]; * * * where num_slots is the (arbitrary) number of MT slots to extract. * * The ioctl size argument (len) is the size of the buffer, which * should satisfy len = (num_slots + 1) * sizeof(__s32). If len is * too small to fit all available slots, the first num_slots are * returned. * * Before the call, code is set to the wanted ABS_MT event type. On * return, values[] is filled with the slot values for the specified * ABS_MT code. * * If the request code is not an ABS_MT value, -EINVAL is returned. } //#define EVIOCGMTSLOTS(len) _IOC(_IOC_READ, 'E', 0x0a, len) EVIOCGMTSLOTS_len = SizeOf(TInput_My_Request_Layout); EVIOCGMTSLOTS = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($0a shl _IOC_NRSHIFT) or (EVIOCGMTSLOTS_len shl _IOC_SIZESHIFT); //#define EVIOCGKEY(len) _IOC(_IOC_READ, 'E', 0x18, len) /* get global key state */ EVIOCGKEY_len = 16; EVIOCGKEY = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($18 shl _IOC_NRSHIFT) or (EVIOCGKEY_len shl _IOC_SIZESHIFT); //#define EVIOCGLED(len) _IOC(_IOC_READ, 'E', 0x19, len) /* get all LEDs */ EVIOCGLED_len = 16; EVIOCGLED = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($19 shl _IOC_NRSHIFT) or (EVIOCGLED_len shl _IOC_SIZESHIFT); //#define EVIOCGSND(len) _IOC(_IOC_READ, 'E', 0x1a, len) /* get all sounds status */ EVIOCGSND_len = 16; EVIOCGSND = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($1a shl _IOC_NRSHIFT) or (EVIOCGSND_len shl _IOC_SIZESHIFT); //#define EVIOCGSW(len) _IOC(_IOC_READ, 'E', 0x1b, len) /* get all switch states */ EVIOCGSW_len = 16; EVIOCGSW = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($0b shl _IOC_NRSHIFT) or (EVIOCGSW_len shl _IOC_SIZESHIFT); //#define EVIOCGBIT(ev,len) _IOC(_IOC_READ, 'E', 0x20 + (ev), len) /* get event bits */ //@@@ use Compose_IOC() //ev = 0 -> return all EVIOCGBIT = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($20 shl _IOC_NRSHIFT) or (0 shl _IOC_SIZESHIFT); //#define EVIOCGABS(abs) _IOR('E', 0x40 + (abs), struct input_absinfo) /* get abs value/limits */ //@@@ abs EVIOCGABS = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($40 shl _IOC_NRSHIFT) or (SizeOf(TInput_Absinfo) shl _IOC_SIZESHIFT); //#define EVIOCSABS(abs) _IOW('E', 0xc0 + (abs), struct input_absinfo) /* set abs value/limits */ //@@@ abs EVIOCSABS = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($c0 shl _IOC_NRSHIFT) or (SizeOf(TInput_Absinfo) shl _IOC_SIZESHIFT); //#define EVIOCSFF _IOW('E', 0x80, struct ff_effect) /* send a force effect to a force feedback device */ EVIOCSFF = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($80 shl _IOC_NRSHIFT) or (SizeOf(TFF_Effect) shl _IOC_SIZESHIFT); //#define EVIOCRMFF _IOW('E', 0x81, int) /* Erase a force effect */ EVIOCRMFF = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($81 shl _IOC_NRSHIFT) or (SizeOf(LongInt) shl _IOC_SIZESHIFT); //#define EVIOCGEFFECTS _IOR('E', 0x84, int) /* Report number of effects playable at the same time */ EVIOCGEFFECTS = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($84 shl _IOC_NRSHIFT) or (SizeOf(LongInt) shl _IOC_SIZESHIFT); //#define EVIOCGRAB _IOW('E', 0x90, int) /* Grab/Release device */ EVIOCGRAB = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($90 shl _IOC_NRSHIFT) or (SizeOf(LongInt) shl _IOC_SIZESHIFT); //#define EVIOCREVOKE _IOW('E', 0x91, int) /* Revoke device access */ EVIOCREVOKE = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($91 shl _IOC_NRSHIFT) or (SizeOf(LongInt) shl _IOC_SIZESHIFT); { * EVIOCGMASK - Retrieve current event mask * * This ioctl allows user to retrieve the current event mask for specific * event type. The argument must be of type "struct input_mask" and * specifies the event type to query, the address of the receive buffer and * the size of the receive buffer. * * The event mask is a per-client mask that specifies which events are * forwarded to the client. Each event code is represented by a single bit * in the event mask. If the bit is set, the event is passed to the client * normally. Otherwise, the event is filtered and will never be queued on * the client's receive buffer. * * Event masks do not affect global state of the input device. They only * affect the file descriptor they are applied to. * * The default event mask for a client has all bits set, i.e. all events * are forwarded to the client. If the kernel is queried for an unknown * event type or if the receive buffer is larger than the number of * event codes known to the kernel, the kernel returns all zeroes for those * codes. * * At maximum, codes_size bytes are copied. * * This ioctl may fail with ENODEV in case the file is revoked, EFAULT * if the receive-buffer points to invalid memory, or EINVAL if the kernel * does not implement the ioctl. } //#define EVIOCGMASK _IOR('E', 0x92, struct input_mask) /* Get event-masks */ EVIOCGMASK = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($92 shl _IOC_NRSHIFT) or (SizeOf(TInput_Mask) shl _IOC_SIZESHIFT); { * EVIOCSMASK - Set event mask * * This ioctl is the counterpart to EVIOCGMASK. Instead of receiving the * current event mask, this changes the client's event mask for a specific * type. See EVIOCGMASK for a description of event-masks and the * argument-type. * * This ioctl provides full forward compatibility. If the passed event type * is unknown to the kernel, or if the number of event codes specified in * the mask is bigger than what is known to the kernel, the ioctl is still * accepted and applied. However, any unknown codes are left untouched and * stay cleared. That means, the kernel always filters unknown codes * regardless of what the client requests. If the new mask doesn't cover * all known event-codes, all remaining codes are automatically cleared and * thus filtered. * * This ioctl may fail with ENODEV in case the file is revoked. EFAULT is * returned if the receive-buffer points to invalid memory. EINVAL is returned * if the kernel does not implement the ioctl. } //#define EVIOCSMASK _IOW('E', 0x93, struct input_mask) /* Set event-masks */ EVIOCSMASK = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($93 shl _IOC_NRSHIFT) or (SizeOf(TInput_Mask) shl _IOC_SIZESHIFT); //#define EVIOCSCLOCKID _IOW('E', 0xa0, int) /* Set clockid to be used for timestamps */ EVIOCSCLOCKID = (_IOC_WRITE shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or ($a0 shl _IOC_NRSHIFT) or (SizeOf(LongInt) shl _IOC_SIZESHIFT); Implementation end.
unit Objekt.Global; interface uses SysUtils, Classes, variants, Allgemein.SysFolderlocation, Allgemein.Types, Allgemein.RegIni, shellapi, Winapi.Windows, Vcl.dialogs; type TGlobal = class(TComponent) private fUserPfad: string; function getUserPfad: string; function getIniFilename: string; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Userpfad: string read getUserPfad; property IniFilename: string read getIniFilename; function ProgrammPfad: string; end; var Global: TGlobal; implementation { TGlobal } constructor TGlobal.Create(AOwner: TComponent); begin inherited; fUserPfad := ''; end; destructor TGlobal.Destroy; begin inherited; end; function TGlobal.getIniFilename: string; begin Result := getUserPfad + 'TokyoInstaller.ini'; end; function TGlobal.getUserPfad: string; begin Result := fUserPfad; if Result = '' then begin Result := IncludeTrailingPathDelimiter(TSysFolderLocation.GetFolder(cCSIDL_APPDATA)) + 'MiniTools\TokyoInstaller\'; fUserPfad := Result; if not DirectoryExists(fUserPfad) then ForceDirectories(fUserPfad); end; end; function TGlobal.ProgrammPfad: string; begin Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); end; end.
unit TpDbProperties; interface uses SysUtils, Classes, Controls, TypInfo, dcedit, dcfdes, dcsystem, dcdsgnstuff, Db; type TTpListingProperty = class(TStringProperty) protected procedure GetValueList(List: TStrings); virtual; abstract; public procedure GetValues(Proc: TGetStrProc); override; end; // TTpTableNameProperty = class(TTpListingProperty) protected function GetConnectionPropName: string; procedure GetValueList(List: TStrings); override; public function GetAttributes: TPropertyAttributes; override; end; // TTpFieldNameProperty = class(TTpListingProperty) protected function GetDataSourcePropName: string; procedure GetValueList(List: TStrings); override; public function GetAttributes: TPropertyAttributes; override; end; procedure RegisterDbProperties; implementation uses TpDataConnection, TpDb; procedure RegisterDbProperties; begin RegisterPropertyEditor(TypeInfo(string), nil, 'TableName', TTpTableNameProperty); RegisterPropertyEditor(TypeInfo(string), nil, 'FieldName', TTpFieldNameProperty); end; { TTpListingProperty } procedure TTpListingProperty.GetValues(Proc: TGetStrProc); var i: Integer; values: TStringList; begin values := TStringList.Create; try GetValueList(values); for i := 0 to Pred(values.Count) do Proc(values[I]); finally values.Free; end; end; { TTpTableNameProperty } function TTpTableNameProperty.GetAttributes: TPropertyAttributes; begin Result := [ paValueList ]; end; function TTpTableNameProperty.GetConnectionPropName: string; begin Result := 'Db'; end; procedure TTpTableNameProperty.GetValueList(List: TStrings); var db: TTpDb; begin try db := GetObjectProp(GetComponent(0), GetConnectionPropName) as TTpDb; if (db <> nil) and (db.DesignConnection.Connected) then db.DesignConnection.Connection.GetTableNames(List); except end; end; { TTpFieldNameProperty } function TTpFieldNameProperty.GetAttributes: TPropertyAttributes; begin Result := [ paValueList ]; end; function TTpFieldNameProperty.GetDataSourcePropName: string; begin Result := 'DataSource'; end; procedure TTpFieldNameProperty.GetValueList(List: TStrings); var ps: TTpDataSource; begin try ps := GetObjectProp(GetComponent(0), GetDataSourcePropName) as TTpDataSource; if (ps <> nil) and (ps.DataSet <> nil) then ps.DataSet.GetFieldNames(List); except end; end; end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, GLScene, GLVectorFileObjects, GLMaterial, GLObjects, GLWin32Viewer, MD3Helper, GLCadencer, GLGraph, GLVectorGeometry, GLCollision, GLTexture, GLCelShader, GLHiddenLineShader, GLHUDObjects, GLBitmapFont, GLWindowsFont, GLCoordinates, GLCrossPlatform, GLBaseClasses; const aamType: array [false .. true] of TGLActorAnimationMode = (aamLoop, aamLoopBackward); type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; Actor: TGLDummyCube; GLCamera1: TGLCamera; GLCadencer1: TGLCadencer; GLLightSource1: TGLLightSource; GLPlane1: TGLPlane; GLXYZGrid1: TGLXYZGrid; Map: TGLDummyCube; GLCube1: TGLCube; GLCube2: TGLCube; GLCube3: TGLCube; GLCube4: TGLCube; CollisionManager1: TGLCollisionManager; GLCamera2: TGLCamera; GLMemoryViewer1: TGLMemoryViewer; GLDummyCube2: TGLDummyCube; GLSphere1: TGLSphere; GLCube5: TGLCube; Panel1: TPanel; PaintBox1: TPaintBox; Font: TGLWindowsBitmapFont; Help: TGLHUDText; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure SetLegAnimation(an: String); procedure SetTorsoAnimation(an: String); procedure MakeRotation; procedure MakeAnimations; procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure GLActor1EndFrameReached(Sender: TObject); procedure CollisionManager1Collision(Sender: TObject; object1, object2: TGLBaseSceneObject); procedure GLMemoryViewer1BeforeRender(Sender: TObject); procedure GLMemoryViewer1AfterRender(Sender: TObject); procedure Timer1Timer(Sender: TObject); private public Act: TGLMD3Actor; Beh: TGLBCollision; mx, my: Integer; Angel: Double; Keys: Array [0 .. 255] of boolean; HeadRot, HeadRotN: Double; Jump, Run, Crouch, Back, Walk, Fire, Rotate, Attack, CollLegs: boolean; end; var Form1: TForm1; const HELP_TEXT = 'Cursor keys - walk'#13#10 + 'Shift - run'#13#10 + 'Enter - jump'#13#10 + 'Space - fire'#13#10 + 'Ctrl - crouch'; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var i: Longint; begin for i := 0 to 255 do Keys[i] := false; Act := TGLMD3Actor.Create(Actor); Act.CharacterModel := 'doom'; Act.Animation := 'stand'; Act.WeaponModel := 'mp5k'; Act.Legs.OnEndFrameReached := GLActor1EndFrameReached; Beh := TGLBCollision.Create(Act.Legs.Behaviours); Beh.BoundingMode := cbmSphere; Beh.Manager := CollisionManager1; Act.Legs.Behaviours.Add(Beh); Act.Legs.Name := 'Repa'; Crouch := false; Back := false; Walk := false; Fire := false; Angel := 0; Jump := false; HeadRotN := 0; HeadRot := 0; GLCamera1.TargetObject := Act.Head; GLCamera2.MoveTo(Act.Head); GLDummyCube2.Position.Z := GLCamera2.Position.Z; Help.Text := HELP_TEXT; end; procedure TForm1.SetLegAnimation(an: String); begin if AnsiUpperCase(Act.Legs.CurrentAnimation) <> AnsiUpperCase(an) then Act.Legs.SwitchToAnimation(an); end; procedure TForm1.SetTorsoAnimation(an: String); begin if AnsiUpperCase(Act.Torso.CurrentAnimation) <> AnsiUpperCase(an) then Act.Torso.SwitchToAnimation(an); end; procedure TForm1.MakeAnimations; begin Act.Legs.AnimationMode := aamType[Back]; Act.Torso.AnimationMode := aamType[Back]; Act.Head.AnimationMode := aamType[Back]; if Jump then SetLegAnimation('LEGS_JUMP') else if Walk then if Crouch then SetLegAnimation('LEGS_WALKCR') else if Run then SetLegAnimation('LEGS_RUN') else SetLegAnimation('LEGS_WALK') else if Crouch then SetLegAnimation('LEGS_IDLECR') else if Rotate then SetLegAnimation('LEGS_TURN') // LEGS_TURN else SetLegAnimation('LEGS_IDLE'); if Attack then SetTorsoAnimation('TORSO_ATTACK') else SetTorsoAnimation('TORSO_STAND'); end; procedure TForm1.MakeRotation; begin Act.Legs.RollAngle := Angel; Act.Head.Roll(HeadRot); end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); var px, py, dx, dy, X, Y: Real; bmp: TBitmap; begin dx := 0; dy := 0; px := Act.Legs.Position.X; py := Act.Legs.Position.Y; Walk := false; Back := false; Rotate := false; Run := false; CollLegs := false; if Keys[vk_up] then begin Walk := true; Back := false; end; if Keys[vk_down] then begin Walk := true; Back := true; end; if Keys[vk_left] then begin Angel := Angel + 120 * deltaTime;; Rotate := true; end; if Keys[vk_right] then begin Angel := Angel - 120 * deltaTime;; Rotate := true; end; Attack := Keys[vk_space]; if Keys[65] then begin Rotate := true; dy := 5; end; if Keys[68] then begin Rotate := true; dy := -5; end; Crouch := Keys[VK_CONTROL]; if Walk then if Back then dx := -5 else dx := 5; if Keys[vk_shift] then begin dx := dx * 2; dy := dy * 2; Run := true; end; if Keys[VK_RETURN] then begin Jump := true; end; if HeadRotN = 0 then HeadRotN := 1; HeadRot := HeadRot + 30 * HeadRotN * deltaTime; if Abs(HeadRot) > 20 then begin HeadRot := 20 * HeadRotN; HeadRotN := -HeadRotN; end; Act.HeadRot := HeadRot; MakeRotation; MakeAnimations; if (dx <> 0) or (dy <> 0) then begin dx := 10 * dx * deltaTime; dy := 10 * dy * deltaTime; X := dx * cos(DegToRadian(Angel)) + dy * cos(DegToRadian(Angel + 90)); Y := dx * sin(DegToRadian(Angel)) + dy * sin(DegToRadian(Angel + 90));; Act.Legs.Position.X := Act.Legs.Position.X + X; Act.Legs.Position.Y := Act.Legs.Position.Y + Y; CollisionManager1.CheckCollisions; if CollLegs then begin Act.Legs.Position.X := px; Act.Legs.Position.Y := py; end; end; Act.Progress(deltaTime); GLMemoryViewer1.render; bmp := GLMemoryViewer1.Buffer.CreateSnapShotBitmap; PaintBox1.Canvas.Draw(0, 0, bmp); bmp.Free; end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin Keys[Key] := true; end; procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin Keys[Key] := false; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx := X; my := Y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if ssLeft in Shift then GLCamera1.MoveAroundTarget(my - Y, mx - X); mx := X; my := Y; end; procedure TForm1.GLActor1EndFrameReached(Sender: TObject); begin Jump := false; end; procedure TForm1.CollisionManager1Collision(Sender: TObject; object1, object2: TGLBaseSceneObject); begin CollLegs := true; end; procedure TForm1.GLMemoryViewer1BeforeRender(Sender: TObject); begin GLSphere1.Material.FrontProperties.Diffuse.AsWinColor := clGreen; Actor.Visible := false; Help.Visible := false; end; procedure TForm1.GLMemoryViewer1AfterRender(Sender: TObject); begin GLSphere1.Material.FrontProperties.Diffuse.AsWinColor := clRed; Actor.Visible := true; Help.Visible := true; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption := Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083220 //////////////////////////////////////////////////////////////////////////////// unit android.telephony.mbms.MbmsErrors; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JMbmsErrors = interface; JMbmsErrorsClass = interface(JObjectClass) ['{39B2C4DA-99CB-4B2E-AEAC-73B94125E419}'] function _GetERROR_MIDDLEWARE_LOST : Integer; cdecl; // A: $19 function _GetERROR_MIDDLEWARE_NOT_BOUND : Integer; cdecl; // A: $19 function _GetERROR_NO_UNIQUE_MIDDLEWARE : Integer; cdecl; // A: $19 function _GetSUCCESS : Integer; cdecl; // A: $19 function _GetUNKNOWN : Integer; cdecl; // A: $19 property ERROR_MIDDLEWARE_LOST : Integer read _GetERROR_MIDDLEWARE_LOST; // I A: $19 property ERROR_MIDDLEWARE_NOT_BOUND : Integer read _GetERROR_MIDDLEWARE_NOT_BOUND;// I A: $19 property ERROR_NO_UNIQUE_MIDDLEWARE : Integer read _GetERROR_NO_UNIQUE_MIDDLEWARE;// I A: $19 property SUCCESS : Integer read _GetSUCCESS; // I A: $19 property UNKNOWN : Integer read _GetUNKNOWN; // I A: $19 end; [JavaSignature('android/telephony/mbms/MbmsErrors$DownloadErrors')] JMbmsErrors = interface(JObject) ['{7C30C9AC-0835-4B0D-95DC-F4788B4AD109}'] end; TJMbmsErrors = class(TJavaGenericImport<JMbmsErrorsClass, JMbmsErrors>) end; const TJMbmsErrorsERROR_MIDDLEWARE_LOST = 3; TJMbmsErrorsERROR_MIDDLEWARE_NOT_BOUND = 2; TJMbmsErrorsERROR_NO_UNIQUE_MIDDLEWARE = 1; TJMbmsErrorsSUCCESS = 0; TJMbmsErrorsUNKNOWN = -1; implementation end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uChildForm; {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Menus, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.Types, Vcl.ComCtrls, Vcl.ClipBrd, System.UITypes, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Menus, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Types, ComCtrls, ClipBrd, {$ENDIF} uMainForm, uCEFChromium, uCEFWindowParent, uCEFInterfaces, uCEFConstants, uCEFTypes; type TChildForm = class(TForm) Panel1: TPanel; Edit1: TEdit; Button1: TButton; Chromium1: TChromium; CEFWindowParent1: TCEFWindowParent; StatusBar1: TStatusBar; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser); procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure Chromium1Close(Sender: TObject; const browser: ICefBrowser; out Result: Boolean); procedure FormDestroy(Sender: TObject); procedure Chromium1BeforeClose(Sender: TObject; const browser: ICefBrowser); procedure Chromium1LoadingStateChange(Sender: TObject; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); procedure Chromium1StatusMessage(Sender: TObject; const browser: ICefBrowser; const value: ustring); private // Variables to control when can we destroy the form safely FCanClose : boolean; // Set to True in TChromium.OnBeforeClose FClosing : boolean; // Set to True in the CloseQuery event. protected procedure BrowserCreatedMsg(var aMessage : TMessage); message CEFBROWSER_CREATED; procedure BrowserDestroyMsg(var aMessage : TMessage); message CEFBROWSER_DESTROY; procedure WMMove(var aMessage : TWMMove); message WM_MOVE; procedure WMMoving(var aMessage : TMessage); message WM_MOVING; procedure WMEnterMenuLoop(var aMessage: TMessage); message WM_ENTERMENULOOP; procedure WMExitMenuLoop(var aMessage: TMessage); message WM_EXITMENULOOP; public property Closing : boolean read FClosing; end; implementation {$R *.dfm} // Destruction steps // ================= // 1. FormCloseQuery calls TChromium.CloseBrowser // 2. TChromium.OnClose sends a CEFBROWSER_DESTROY message to destroy CEFWindowParent1 in the main thread. // 3. TChromium.OnBeforeClose sets FCanClose := True and sends WM_CLOSE to the form. uses uCEFRequestContext, uCEFApplication; procedure TChildForm.Button1Click(Sender: TObject); begin Chromium1.LoadURL(Edit1.Text); end; procedure TChildForm.Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser); begin PostMessage(Handle, CEFBROWSER_CREATED, 0, 0); end; procedure TChildForm.Chromium1BeforeClose(Sender: TObject; const browser: ICefBrowser); begin FCanClose := True; PostMessage(Handle, WM_CLOSE, 0, 0); end; procedure TChildForm.Chromium1Close(Sender: TObject; const browser: ICefBrowser; out Result: Boolean); begin PostMessage(Handle, CEFBROWSER_DESTROY, 0, 0); Result := False; end; procedure TChildForm.Chromium1LoadingStateChange(Sender: TObject; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); begin if isLoading then begin StatusBar1.Panels[0].Text := 'Loading...'; cursor := crAppStart; end else begin StatusBar1.Panels[0].Text := ''; cursor := crDefault; end; end; procedure TChildForm.Chromium1StatusMessage(Sender: TObject; const browser: ICefBrowser; const value: ustring); begin StatusBar1.Panels[1].Text := value; end; procedure TChildForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TChildForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := FCanClose; if not(FClosing) and Panel1.Enabled then begin FClosing := True; Panel1.Enabled := False; Chromium1.CloseBrowser(True); end; end; procedure TChildForm.FormCreate(Sender: TObject); begin FCanClose := False; FClosing := False; end; procedure TChildForm.FormDestroy(Sender: TObject); begin // Tell the main form that a child has been destroyed. // The main form will check if this was the last child to close itself PostMessage(MainForm.Handle, CEFBROWSER_CHILDDESTROYED, 0, 0); end; procedure TChildForm.FormShow(Sender: TObject); var TempContext : ICefRequestContext; begin // The new request context overrides several GlobalCEFApp properties like : // cache, AcceptLanguageList, PersistSessionCookies, PersistUserPreferences, // IgnoreCertificateErrors and EnableNetSecurityExpiration // If you use an empty cache path, CEF will use in-memory cache. if MainForm.NewContextChk.Checked then TempContext := TCefRequestContextRef.New('', '', False, False, False, False) else TempContext := nil; // In case you used a custom cookies path in the GlobalCEFApp you can // override it in the TChromium.CreateBrowser function Chromium1.CreateBrowser(CEFWindowParent1, '', TempContext); end; procedure TChildForm.WMMove(var aMessage : TWMMove); begin inherited; if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted; end; procedure TChildForm.WMMoving(var aMessage : TMessage); begin inherited; if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted; end; procedure TChildForm.WMEnterMenuLoop(var aMessage: TMessage); begin inherited; if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := True; end; procedure TChildForm.WMExitMenuLoop(var aMessage: TMessage); begin inherited; if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := False; end; procedure TChildForm.BrowserCreatedMsg(var aMessage : TMessage); begin CEFWindowParent1.UpdateSize; Panel1.Enabled := True; Button1.Click; end; procedure TChildForm.BrowserDestroyMsg(var aMessage : TMessage); begin CEFWindowParent1.Free; end; end.
unit uOrgChangeDetails; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, MemDS, DBAccess, Ora, uOilQuery, ActnList, Grids, DBGridEh, VirtualTable, DBTables, MemTable, uCommonForm, Menus, StdCtrls, Buttons, ExtCtrls, uHelpButton; type TSelectionType = (stSelectAll,stUnselectAll,stInvertSelect); TOrgChangeDetails = class(TCommonForm) q: TOilQuery; grMain: TDBGridEh; ds: TOraDataSource; ac: TActionList; actChange: TAction; actSelectAll: TAction; actUnselectAll: TAction; actInvertSelect: TAction; vt: TVirtualTable; qOilOrgChange: TOilQuery; pBottom: TPanel; pm: TPopupMenu; miSelectAll: TMenuItem; miUnselectAll: TMenuItem; miInvertSelect: TMenuItem; OilHelpButton1: TOilHelpButton; pBtn: TPanel; bbChange: TBitBtn; bbCancel: TBitBtn; procedure actSelectAllExecute(Sender: TObject); procedure actUnselectAllExecute(Sender: TObject); procedure actInvertSelectExecute(Sender: TObject); procedure actChangeExecute(Sender: TObject); procedure bbCancelClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private { Private declarations } procedure Init(); procedure ChangeDetails(ADepId, ACurrentValNum: integer); procedure ChangeSelection(AType: TSelectionType); public end; function GetAzsParFirst(AId: integer):integer; var OrgChangeDetails: TOrgChangeDetails; implementation uses uDbFunc, OilStd, uExeSql, ExFunc; {$R *.dfm} procedure TOrgChangeDetails.Init(); begin if q.Active then q.Close; q.Open; if vt.Active then vt.Close; vt.Assign(q); q.Close; vt.AddField('TO_CHANGE',ftBoolean,0); vt.Open; Self.actUnselectAll.Execute; end; procedure TOrgChangeDetails.ChangeDetails(ADepId, ACurrentValNum: integer); var NextValue, UpdSql: string; begin if ACurrentValNum = 1 then NextValue := '2' else NextValue := '1'; _OpenQueryPar(qOilOrgChange, ['ADepId', ADepId]); UpdSql := format('update %s set',[qOilOrgChange.FieldByName('table_name').AsString]); while not qOilOrgChange.Eof do begin UpdSql := UpdSql + format(' %s = ''%s'' ', [qOilOrgChange.FieldByName('field_name').AsString, qOilOrgChange.FieldByName('value' + NextValue).AsString]); qOilOrgChange.Next; if qOilOrgChange.Eof then begin UpdSql := UpdSql + ' where id = inst and id = :ADepId'; _ExecSql(UpdSql, ['ADepId', ADepId]); end else UpdSql := UpdSql + ','; end; end; procedure TOrgChangeDetails.ChangeSelection(AType: TSelectionType); begin vt.DisableControls; try vt.First; while not vt.Eof do begin vt.Edit; case AType of stSelectAll: vt.FieldByName('TO_CHANGE').AsBoolean := True; stUnselectAll: vt.FieldByName('TO_CHANGE').AsBoolean := False; stInvertSelect: vt.FieldByName('TO_CHANGE').AsBoolean := not vt.FieldByName('TO_CHANGE').AsBoolean; end; vt.Next; end; finally vt.EnableControls; end; end; procedure TOrgChangeDetails.actSelectAllExecute(Sender: TObject); begin ChangeSelection(stSelectAll); end; procedure TOrgChangeDetails.actUnselectAllExecute(Sender: TObject); begin ChangeSelection(stUnselectAll); end; procedure TOrgChangeDetails.actInvertSelectExecute(Sender: TObject); begin ChangeSelection(stInvertSelect); end; procedure TOrgChangeDetails.actChangeExecute(Sender: TObject); begin vt.DisableControls; try StartSql; vt.First; while not vt.Eof do begin if vt.FieldByName('TO_CHANGE').AsBoolean then begin ChangeDetails( vt.FieldByName('DEP_ID').AsInteger, vt.FieldByName('CURRENT_VALUE_NUM').AsInteger); end; vt.Next; end; CommitSql; _ExecSQLOra('begin dbms_mview.refresh(''V_CARD_AZS''); end;'); Self.Init; finally vt.EnableControls; end; end; procedure TOrgChangeDetails.bbCancelClick(Sender: TObject); begin Self.Close; end; procedure TOrgChangeDetails.FormShow(Sender: TObject); begin Self.Init; end; procedure TOrgChangeDetails.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TOrgChangeDetails.FormCreate(Sender: TObject); begin inherited; LoadSQLByForm(TForm(Self)); end; function GetAzsParFirst(AId:integer):integer; begin result := nvl(GetSqlValueParSimple('select value1 from oil_org_change where dep_id = :id and field_name=''PAR'' ', ['id', AId]),0); end; end.
unit Balls; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type { Gruppe für Bälle, enthält gemeinsam genutzte Systemressourcen für alle darin enthaltenen TBall-Objekte } TBall = class; TBallStatus = (bsNormal, bsStopped); TBallGroup = class(TComponent) private FBallList: TList; FParent: TWinControl; FTimer: TTimer; FStopped: Boolean; function GetBallList: TList; function GetBalls(I: Integer): TBall; function GetTimer: TTimer; function GetInterval: Integer; procedure SetInterval(Value: Integer); procedure TimerEvent(Sender: TObject); property BallList: TList read GetBallList; property Timer: TTimer read GetTimer; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Go; procedure InsertBall(ABall: TBall); function NewBall(ARadius: Integer; APos, ASpeed: TPoint; AStatus: TBallStatus; AColor: TColor): Integer; procedure RemoveBall(ABall: TBall); procedure Stop; property Balls[I: Integer]: TBall read GetBalls; property Stopped: Boolean read FStopped; published property Interval: Integer read GetInterval write SetInterval; property Parent: TWinControl read FParent write FParent; end; { Klasse für Kugeln } TBall = class(TShape) private { Private-Deklarationen } FRadius: Integer; FStatus: TBallStatus; FPos, FInitialSpeed: TPoint; FTimer: TTimer; FOnMouseOver: TMouseMoveEvent; {XPlace, YPlace: TBallPlace;} function GetTimer: TTimer; procedure SetTimer(Value: TTimer); procedure SetPos(Value: TPoint); function GetInterval: Integer; procedure SetInterval(Value: Integer); procedure SetRadius(Value: Integer); procedure TimerEvent(Sender: TObject); protected { Protected-Deklarationen } procedure AssignTo(Dest: TPersistent); override; public { Public-Deklarationen } Speed: TPoint; constructor Create(AOwner: TComponent); override; procedure Step; property InitialSpeed: TPoint read FInitialSpeed write FInitialSpeed; property Pos: TPoint read FPos write SetPos; published { Published-Deklarationen } property Interval: Integer read GetInterval write SetInterval; property Radius: Integer read FRadius write SetRadius; property Status: TBallStatus read FStatus write FStatus; property Timer: TTimer read GetTimer write SetTimer; property OnMouseOver: TMouseMoveEvent read FOnMouseOver write FOnMouseOver; end; procedure Register; implementation function TBallGroup.GetBallList: TList; begin if not Assigned(FBallList) then FBallList := TList.Create; Result := FBallList end; function TBallGroup.GetBalls(I: Integer): TBall; begin Result := BallList[I] end; function TBallGroup.GetTimer: TTimer; begin if not Assigned(FTimer) then begin FTimer := TTimer.Create(Self); FTimer.OnTimer := TimerEvent; end; Result := FTimer; end; function TBallGroup.GetInterval: Integer; begin Result := Timer.Interval end; procedure TBallGroup.SetInterval(Value: Integer); begin Timer.Interval := Value end; constructor TBallGroup.Create(AOwner: TComponent); begin inherited Create(AOwner); Interval := 40; end; destructor TBallGroup.Destroy; begin Stop; FBallList.Free; inherited Destroy end; procedure TBallGroup.Go; begin FStopped := False; end; procedure TBallGroup.InsertBall(ABall: TBall); begin ABall.Timer := Timer; InsertComponent(ABall); ABall.Parent := Parent; BallList.Add(ABall); end; function TBallGroup.NewBall(ARadius: Integer; APos, ASpeed: TPoint; AStatus: TBallStatus; AColor: TColor): Integer; var Ball: TBall; begin Ball := TBall.Create(Self); Ball.Parent := Parent; with Ball do begin Radius := ARadius; Pos := APos; Speed := ASpeed; Status := AStatus; Brush.Color := AColor; Timer.OnTimer := nil; end; Result := BallList.Add(Ball) end; procedure TBallGroup.RemoveBall(ABall: TBall); begin BallList.Remove(ABall); BallList.Pack; ABall.Free end; procedure TBallGroup.Stop; begin FStopped := True; end; procedure TBallGroup.TimerEvent(Sender: TObject); var i: Integer; begin if not Stopped then for i := 0 to BallList.Count - 1 do Balls[i].Step end; procedure TBall.SetPos(Value: TPoint); begin FPos := Value; Left := FPos.X - Radius; Top := FPos.Y - Radius; end; function TBall.GetInterval: Integer; begin Result := Timer.Interval end; procedure TBall.SetInterval(Value: Integer); begin if Timer.Owner = Self then Timer.Interval := Value end; procedure TBall.SetRadius(Value: Integer); begin FRadius := Value; Width := 2 * Value; Height := 2 * Value; end; function TBall.GetTimer: TTimer; begin if not Assigned(FTimer) then begin FTimer := TTimer.Create(Self); FTimer.Interval := 40; FTimer.OnTimer := TimerEvent; end; Result := FTimer end; procedure TBall.SetTimer(Value: TTimer); begin if FTimer <> Value then begin if FTimer.Owner = Self then FTimer.Free; FTimer := Value end end; procedure TBall.TimerEvent(Sender: TObject); begin Step; end; procedure TBall.AssignTo(Dest: TPersistent); begin (Dest as TBall).Brush := Brush; (Dest as TBall).Pos := Pos; (Dest as TBall).Radius := Radius; (Dest as TBall).Speed := Speed; (Dest as TBall).Brush := Brush end; constructor TBall.Create(AOwner: TComponent); begin inherited Create(AOwner); Shape := stCircle; Interval := 40; Pos := Point(Radius + 1, Radius + 1); Timer.OnTimer := TimerEvent; Font.Size := 24; Font.Color := clBlack; end; procedure TBall.Step; var PosLeft, PosRight, PosTop, PosBottom: Boolean; begin if Parent <> nil then begin Pos := Point(Pos.X + Speed.X, Pos.Y + Speed.Y); PosLeft := Pos.X < Radius; PosRight := Pos.X > Parent.ClientWidth - Radius; PosTop := Pos.Y < Radius; PosBottom := Pos.Y > Parent.ClientHeight - Radius; if (Status <> bsStopped) then begin if (Speed.X = 0) and (Speed.Y = 0) then Speed := InitialSpeed end else if (Speed.X <> 0) or (Speed.Y <> 0) then Speed := Point(0, 0); if PosLeft and (Speed.X < 0) or PosRight and (Speed.X > 0) then Speed.X := -Speed.X; if PosTop and (Speed.Y < 0) or PosBottom and (Speed.Y > 0) then Speed.Y := -Speed.Y; end end; procedure Register; begin RegisterComponents('Jakobsche', [TBall, TBallGroup]); end; end.
unit uLockBox_CipherTestCases; interface uses TestFramework, uTPLb_Hash, uTPLb_CryptographicLibrary, Classes, uTPLb_Codec, uTPLb_StreamCipher, uLockBox_TestCases, uTPLb_Random; type TBlockSizeCase = ( scZero, // size = 0 scSmall, // size ~= 0.3 blocks scUnit, // size = 1 block scSmallish, // size = 1.5 blocks scRough, // size = large N + about 0.1 blocks scRound); // size = exactly N blocks. N is a large number. TBlockMode_TestCase = class( TTestCase) protected FLib: TCryptographicLibrary; FCodec: TCodec; FOriginal : TMemoryStream; FCiphertext : TMemoryStream; FKeyStream : TMemoryStream; FReferenceStream : TMemoryStream; FBlockSize: integer; FFeatures: TAlgorithmicFeatureSet; procedure SetUp; override; procedure TearDown; override; class function CipherId: string; virtual; abstract; procedure NormalizeKeyStream; virtual; procedure InversionTest( DataSize: TBlockSizeCase; const ChainMode: string); published procedure Test_Reference; procedure GeneralInversionTests; end; TAES_Reference_TestCase = class( TBlockMode_TestCase) protected class function KeySize: integer; virtual; abstract; class function CipherId: string; override; end; TAES128_RefTestCase = class( TAES_Reference_TestCase) protected class function KeySize: integer; override; end; TAES192_RefTestCase = class( TAES_Reference_TestCase) protected class function KeySize: integer; override; end; TAES256_RefTestCase = class( TAES_Reference_TestCase) protected class function KeySize: integer; override; end; TStreamModeInversion_TestCase = class( TTestCase) protected FLib: TCryptographicLibrary; FCodec: TCodec; FOriginal : TMemoryStream; FCiphertext : TMemoryStream; FReconstructed : TMemoryStream; FFeatures: TAlgorithmicFeatureSet; procedure SetUp; override; procedure TearDown; override; class function CipherId: string; virtual; abstract; class procedure TestSizeRange( var MinBytes, MaxBytes: integer); virtual; abstract; published procedure GeneralInversionTest; virtual; end; TBase64_TestCases = class( TStreamModeInversion_TestCase) private FKAT_Source :TStream; protected procedure SetUp; override; procedure TearDown; override; class function CipherId: string; override; class procedure TestSizeRange( var MinBytes, MaxBytes: integer); override; published procedure Marks_KAT; end; TDES_TestCase = class( TTestCase) published procedure PC1; procedure PC2; procedure IP; procedure Inverse_IP; procedure ExpandKey; procedure EncryptBlock; procedure YourLipsAreSmoother; end; TDES_Reference_TestCase = class( TBlockMode_TestCase) protected class function CipherId: string; override; procedure NormalizeKeyStream; override; end; T3DES_Reference_TestCase = class( TBlockMode_TestCase) protected class function CipherId: string; override; procedure NormalizeKeyStream; override; end; T3DES_KO1_Reference_TestCase = class( TBlockMode_TestCase) protected class function CipherId: string; override; procedure NormalizeKeyStream; override; end; TBlowfish_Reference_TestCase = class( TBlockMode_TestCase) protected class function CipherId: string; override; end; TTwofish_Reference_TestCase = class( TBlockMode_TestCase) protected class function CipherId: string; override; published procedure TwoFishPrimitives; end; TMasBug_TestCase = class( TTestCase) protected FRand: TRandomStream; P: PByte; Len: integer; procedure SetUp; override; procedure TearDown; override; published procedure Mas_RandomStream_Bug; end; implementation uses SysUtils, uTPLb_HashDsc, uTPLb_BinaryUtils, uTPLb_StreamUtils, uTPLb_ECB, uTPLb_BlockCipher, uTPLb_HugeCardinalUtils, uTPLb_IntegerUtils, uTPLb_DES, uTPLb_Constants, DCPtwofish_LB3Modified, uTPLb_StrUtils; { TTestCaseFirst } procedure InitUnit_CipherTestCases; begin TestFramework.RegisterTest( TAES128_RefTestCase.Suite); TestFramework.RegisterTest( TAES192_RefTestCase.Suite); TestFramework.RegisterTest( TAES256_RefTestCase.Suite); TestFramework.RegisterTest( TBase64_TestCases.Suite); TestFramework.RegisterTest( 'DES.Basic DES', TDES_TestCase.Suite); TestFramework.RegisterTest( 'DES.Basic DES', TDES_Reference_TestCase.Suite); TestFramework.RegisterTest( 'DES.3DES.KO2', T3DES_Reference_TestCase.Suite); TestFramework.RegisterTest( 'DES.3DES.KO1', T3DES_KO1_Reference_TestCase.Suite); TestFramework.RegisterTest( TBlowfish_Reference_TestCase.Suite); TestFramework.RegisterTest( TTwofish_Reference_TestCase.Suite); TestFramework.RegisterTest( TMasBug_TestCase.Suite); end; procedure DoneUnit_CipherTestCases; begin end; const sPure_ECB_Id = 'dunit.ECB'; type TPure_ECB = class( TECB) protected function ChainingFeatures: TChainingFeatureSet; override; function ProgId: string; override; end; function TPure_ECB.ChainingFeatures: TChainingFeatureSet; begin result := inherited ChainingFeatures + [cfKeyStream] // The inclusion of cfKeyStream disables block padding. // We can only use this class in situations where be plaintext size // is an exact multiple of the block size. end; function TPure_ECB.ProgId: string; begin result := sPure_ECB_Id end; { TStreamModeReference_TestCase } procedure TBlockMode_TestCase.GeneralInversionTests; procedure TestChainMode( const ChainMode: string); var j: TBlockSizeCase; begin for j := Low( TBlockSizeCase) to High( TBlockSizeCase) do InversionTest( j, ChainMode) end; begin TestChainMode( 'native.ECB'); TestChainMode( 'native.CBC'); TestChainMode( 'native.CFB'); TestChainMode( 'native.CTR'); TestChainMode( 'native.OFB'); TestChainMode( 'native.CFB-8bit'); TestChainMode( 'native.PCBC') end; procedure TBlockMode_TestCase.InversionTest( DataSize: TBlockSizeCase; const ChainMode: string); var TestSize, TestsCount: integer; j: integer; Ok: boolean; function RandomSizableNumber: integer; begin TRandomStream.Instance.Read( result, SizeOf( result)); result := (abs( result) mod 200) + 50 end; begin FCodec.ChainModeId := ChainMode; FCodec.Password := 'Monkey''s uncle'; TestSize := 0; TestsCount := 0; case DataSize of scZero: begin TestSize := 0; TestsCount := 1 end; scSmall: begin TestSize := Round( FBlockSize * 0.3); TestsCount := 1 end; scUnit: begin TestSize := FBlockSize; TestsCount := 1 end; scSmallish: begin TestSize := Round( FBlockSize * 1.5); TestsCount := 10 end; scRough: begin TestSize := (RandomSizableNumber * FBlockSize) + RandomSizableNumber; TestsCount := 100 end; scRound: begin TestSize := RandomSizableNumber * FBlockSize; TestsCount := 10 end; end; for j := 1 to TestsCount do begin FOriginal.Size := TestSize; RandomFillStream( FOriginal); FCiphertext.Size := 0; FCodec.EncryptStream( FOriginal, FCiphertext); FCodec.Reset; FReferenceStream.Size := 0; FCodec.DecryptStream( FReferenceStream, FCiphertext); FCodec.Reset; Ok := CompareMemoryStreams( FOriginal, FReferenceStream); Check( Ok, Format( '%s fails the general inversion test!', [FCodec.Cipher])); if TestSize = 0 then Check( FCiphertext.Size = 0, Format( '%s fails the zero test!', [FCodec.Cipher])); if not Ok then break end end; procedure TBlockMode_TestCase.NormalizeKeyStream; begin end; procedure TBlockMode_TestCase.SetUp; var Codec_TestAccess: ICodec_TestAccess; s: ansistring; begin FLib := TCryptographicLibrary.Create( nil); FLib.RegisterBlockChainingModel( TPure_ECB.Create as IBlockChainingModel); FCodec := TCodec.Create( nil); FCodec.CryptoLibrary := FLib; FCodec.StreamCipherId := 'native.StreamToBlock'; FCodec.BlockCipherId := CipherId; FCodec.ChainModeId := sPure_ECB_Id; FOriginal := TMemoryStream.Create; FCiphertext := TMemoryStream.Create; FKeyStream := TMemoryStream.Create; FReferenceStream := TMemoryStream.Create; if Supports( FCodec, ICodec_TestAccess, Codec_TestAccess) and (Codec_TestAccess.GetCodecIntf.BlockCipher <> nil) then with Codec_TestAccess.GetCodecIntf.BlockCipher do begin FFeatures := Features; FBlockSize := BlockSize div 8; {$WARNINGS OFF} Read_BigEndien_u32_Hex(TEncoding.ANSI.GetString(SelfTest_Key), FKeyStream); FKeyStream.Position := 0; NormalizeKeyStream; FKeyStream.Position := 0; s := TEncoding.ANSI.GetString(SelfTest_Plaintext); Read_BigEndien_u32_Hex( s , FOriginal); // Original MUST be an exact multiple (probably 1) of the block size. s := TEncoding.ANSI.GetString(SelfTest_Ciphertext); Read_BigEndien_u32_Hex( s, FReferenceStream) {$WARNINGS ON} end else begin FFeatures := [afNotImplementedYet]; FBlockSize := 1 end end; procedure TBlockMode_TestCase.TearDown; begin FCodec.Free; FLib.Free; FOriginal.Free; FCiphertext.Free; FKeyStream.Free; FReferenceStream.Free end; procedure TBlockMode_TestCase.Test_Reference; begin if FOriginal.Size = 0 then exit; // Reference test not available. Check( not (afNotImplementedYet in FFeatures), Format( '%s is not yet implemented!', [FCodec.Cipher])); FKeyStream.Position := 0; FCodec.InitFromStream( FKeyStream); FCodec.EncryptStream( FOriginal, FCiphertext); Check( CompareMemoryStreams( FCiphertext, FReferenceStream), Format( '%s fails the reference check!', [FCodec.Cipher])) end; { TAES_Reference_TestCase } class function TAES_Reference_TestCase.CipherId: string; begin result := Format( 'native.AES-%d', [KeySize]) end; { TAES128_RefTestCase } class function TAES128_RefTestCase.KeySize: integer; begin result := 128 end; { TAES192_RefTestCase } class function TAES192_RefTestCase.KeySize: integer; begin result := 192 end; { TAES256_RefTestCase } class function TAES256_RefTestCase.KeySize: integer; begin result := 256 end; { TStreamModeInversion_TestCase } procedure TStreamModeInversion_TestCase.SetUp; var Codec_TestAccess: ICodec_TestAccess; begin FLib := TCryptographicLibrary.Create( nil); FCodec := TCodec.Create( nil); FCodec.CryptoLibrary := FLib; FCodec.StreamCipherId := CipherId; FOriginal := TMemoryStream.Create; FCiphertext := TMemoryStream.Create; FReconstructed := TMemoryStream.Create; if Supports( FCodec, ICodec_TestAccess, Codec_TestAccess) and (Codec_TestAccess.GetCodecIntf.StreamCipher <> nil) then with Codec_TestAccess.GetCodecIntf.StreamCipher do FFeatures := Features else FFeatures := [afNotImplementedYet]; FCodec.Password := 'Fancy pants'; end; procedure TStreamModeInversion_TestCase.TearDown; begin FLib.Free; FCodec.Free; FOriginal.Free; FCiphertext.Free; FReconstructed.Free end; procedure TStreamModeInversion_TestCase.GeneralInversionTest; var MinBytes, MaxBytes: integer; TestSize: integer; j: integer; Ok: boolean; begin TestSizeRange( MinBytes, MaxBytes); for j := 1 to 100 do begin TRandomStream.Instance.Read( TestSize, SizeOf( TestSize)); TestSize := (abs( TestSize) mod (MaxBytes - MinBytes + 1)) + MinBytes; FOriginal.Size := TestSize; RandomFillStream( FOriginal); FCiphertext.Size := 0; FCodec.EncryptStream( FOriginal, FCiphertext); FCodec.Reset; FReconstructed.Size := 0; FCodec.DecryptStream( FReconstructed, FCiphertext); FCodec.Reset; Ok := CompareMemoryStreams( FOriginal, FReconstructed); Check( Ok, Format( '%s fails the general inversion test!', [FCodec.Cipher])); Check( (FCiphertext.Size >= FOriginal.Size) or (([afCompressor,afConverter]*FFeatures) <> []), 'Suspicious size of ciphertext.'); if not Ok then break end end; { TBase64Inversion_TestCase } class function TBase64_TestCases.CipherId: string; begin result := 'native.base64' end; procedure TBase64_TestCases.SetUp; const {$IF CompilerVersion > 19} MarksVector: rawbytestring = rawbytestring(#$1D#$F3#$71#$2D#$EC#$BE#$03#$77#$87#$1C#$80#$B8#$5B#$FD#$FE#$8A#$C7#$75#$D3#$B1); {$ELSE} MarksVector: ansistring = #$1D#$F3#$71#$2D#$EC#$BE#$03#$77#$87#$1C + #$80#$B8#$5B#$FD#$FE#$8A#$C7#$75#$D3#$B1; {$IFEND} begin inherited; FKAT_Source := TMemoryStream.Create; FKAT_Source.WriteBuffer( MarksVector[1], Length( MarksVector)); FKAT_Source.Position := 0 end; procedure TBase64_TestCases.Marks_KAT; // Thanks to Mark for supplying this KAT. // (Mark is user name odie34 on the lockbox forums). var pLeft, pRight: TBytes; begin pLeft := Stream_to_Base64(FKAT_Source); pRight := AnsiBytesOf('HfNxLey+A3eHHIC4W/3+isd107E='); Check(Length(pLeft) = Length(pRight)); Check(CompareMem(@pLeft[0], @pRight[0], Length(pLeft))); end; procedure TBase64_TestCases.TearDown; begin FKAT_Source.Free; inherited end; class procedure TBase64_TestCases.TestSizeRange( var MinBytes, MaxBytes: integer); begin MinBytes := 0; MaxBytes := 200 end; { TDES_TestCase } procedure TDES_TestCase.PC1; var K, res: uint64; begin //K = 00010011 00110100 01010111 01111001 10011011 10111100 11011111 11110001 (big-endien) {$IF compilerversion <= 15} // Delphi 7 case. K := {<UtoS_Cnvt>}uint64( -$0E20436486A8CBED){</UtoS_Cnvt>}; // Little-endien encoding. {$ELSE} K := $F1DFBC9B79573413; // Little-endien encoding. {$IFEND} res := PC_1( K); //K+ = 1111000 0110011 0010101 0101111 0101010 1011001 1001111 0001111 (big-endien 7-bit "rows") // = 11110000 11001100 10101010 11110101 01010110 01100111 10001111 00000000 (little-endien 8-bit bytes) // = F0 CC AA F5 56 67 8F 00 (big-endien) // = Check( res = $008F6756F5AACCF0, // Little-endien encoding. 'PC-1 J. Orlin Grabbe (http://orlingrabbe.com/des.htm) example test datum failed.') end; const {$IF compilerversion <= 15} // Delphi 7 case. IP_M: uint64 = {<UtoS_Cnvt>}uint64( -$1032547698BADCFF){</UtoS_Cnvt>}; {$ELSE} IP_M: uint64 = $EFCDAB8967452301; {$IFEND} IP_L: uint32 = $FFCC00CC; IP_R: uint32 = $AAF0AAF0; procedure TDES_TestCase.IP; var Datum: uint64; L, R: uint32; begin //M = 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 (big-endien) Datum := IP_M; // Little-endien encoding. IP_Transform( Datum, L, R); //IP = 1100 1100 0000 0000 1100 1100 1111 1111 1111 0000 1010 1010 1111 0000 1010 1010 (big-endien) // L = 1100 1100 0000 0000 1100 1100 1111 1111 (big-endien) // R = 1111 0000 1010 1010 1111 0000 1010 1010 (big-endien) Check( L = IP_L, 'IP.L J. Orlin Grabbe (http://orlingrabbe.com/des.htm) example test datum failed.'); Check( R = IP_R, 'IP.R J. Orlin Grabbe (http://orlingrabbe.com/des.htm) example test datum failed.') end; procedure TDES_TestCase.Inverse_IP; var L, R: uint32; Datum: uint64; begin L := IP_L; R := IP_R; IP_InverseTransform( L, R, Datum); Check( Datum = IP_M, 'INV-IP J. Orlin Grabbe (http://orlingrabbe.com/des.htm) example test datum failed.'); end; procedure TDES_TestCase.PC2; var L, R: uint32; K: uint64; const TestMsg = 'PC-2 J. Orlin Grabbe (http://orlingrabbe.com/des.htm) example test datum failed.'; begin // Test C1D1 --> K1 // C1D1 = 1110000 1100110 0101010 1011111 1010101 0110011 0011110 0011110 (big-endien, 7-bit "rows") // C1 = 1110000110011001010101011111 (big-endien 28) // C1 = 11100001100110010101010111110000 (big-endien 32) // C1 = 1110 0001 | 1001 1001 | 0101 0101 | 1111 0000 (big-endien 32) // C1 = 1111 0000 | 0101 0101 | 1001 1001 | 1110 0001 (little-endien 32) // = $F05599E1 (Delphi, encoding by putting the 4 LSB of the 4th byte as zero.) // D1 = 1010101011001100111100011110 (big-endien 28) // = $E0F1CCAA (Delphi, encoding by putting the 4 LSB of the 4th byte as zero.) L := $F05599E1; // Little-endien encoding. R := $E0F1CCAA; // Little-endien encoding. K := uTPLb_DES.PC_2( L, R); // K1 = 000110 110000 001011 101111 111111 000111 000001 110010 (big-endien, 6-bit "rows") Check( K = $3201073F2F0B3006, TestMsg); // Test C2D2 --> K2 L := $F0AB32C3; R := $D0E39955; K := uTPLb_DES.PC_2( L, R); Check( K = $25273C36193B1A1E, TestMsg) end; procedure TDES_TestCase.YourLipsAreSmoother; var PlaintextStr, Recon: ansistring; Key: uint64; Ex: TExpandedKey; Plaintext: uint64; Ciphertext: uint64; procedure CheckOneBlock( BlockIdx: integer; Expected: uint64); begin Move( PlaintextStr[ BlockIdx * 8 + 1], Plaintext, 8); uTPLb_DES.DES_EncryptBlock( Plaintext, Ciphertext, Ex); Check( Ciphertext = Expected, Format('Your lips are smoother than ' + 'vaseline [%d]',[BlockIdx])) end; begin // Case data from preliminary example of http://orlingrabbe.com/des.htm PlaintextStr := 'Your lips are smoother than vaseline'#13#10#0#0; SetLength( Recon, Length( PlaintextStr)); Key := $730D6DEA3292320E; uTPLb_DES.ExpandKey( Key, Ex); {$IF compilerversion <= 15} // Delphi 7 case. CheckOneBlock( 0, {<UtoS_Cnvt>}uint64( -$1228871C22606640){</UtoS_Cnvt>}); CheckOneBlock( 1, {<UtoS_Cnvt>}uint64( -$117BA535F45F828E){</UtoS_Cnvt>}); CheckOneBlock( 2, {<UtoS_Cnvt>}uint64( -$6F7EBC295B960DB9){</UtoS_Cnvt>}); CheckOneBlock( 3, {<UtoS_Cnvt>}uint64( -$667BCA0A87D02A27){</UtoS_Cnvt>}); // Orlan says $998435F5782FD59D // but I think this is wrong. CheckOneBlock( 4, {<UtoS_Cnvt>}uint64( $53E6E053B4C98A82){</UtoS_Cnvt>}); uTPLb_DES.DES_DecryptBlock( {<UtoS_Cnvt>}uint64( -$1228871C22606640){</UtoS_Cnvt>}, Plaintext, Ex); Move( Plaintext, Recon[1], 8); uTPLb_DES.DES_DecryptBlock( {<UtoS_Cnvt>}uint64( -$117BA535F45F828E){</UtoS_Cnvt>}, Plaintext, Ex); Move( Plaintext, Recon[9], 8); uTPLb_DES.DES_DecryptBlock( {<UtoS_Cnvt>}uint64( -$6F7EBC295B960DB9){</UtoS_Cnvt>}, Plaintext, Ex); Move( Plaintext, Recon[17], 8); uTPLb_DES.DES_DecryptBlock( {<UtoS_Cnvt>}uint64( -$667BCA0A87D02A27){</UtoS_Cnvt>}, Plaintext, Ex); Move( Plaintext, Recon[25], 8); uTPLb_DES.DES_DecryptBlock( {<UtoS_Cnvt>}uint64( $53E6E053B4C98A82){</UtoS_Cnvt>}, Plaintext, Ex); {$ELSE} CheckOneBlock( 0, $EDD778E3DD9F99C0); CheckOneBlock( 1, $EE845ACA0BA07D72); CheckOneBlock( 2, $908143D6A469F247); CheckOneBlock( 3, $998435F5782FD5D9); // Orlan says $998435F5782FD59D // but I think this is wrong. CheckOneBlock( 4, $53E6E053B4C98A82); uTPLb_DES.DES_DecryptBlock( $EDD778E3DD9F99C0, Plaintext, Ex); Move( Plaintext, Recon[1], 8); uTPLb_DES.DES_DecryptBlock( $EE845ACA0BA07D72, Plaintext, Ex); Move( Plaintext, Recon[9], 8); uTPLb_DES.DES_DecryptBlock( $908143D6A469F247, Plaintext, Ex); Move( Plaintext, Recon[17], 8); uTPLb_DES.DES_DecryptBlock( $998435F5782FD5D9, Plaintext, Ex); Move( Plaintext, Recon[25], 8); uTPLb_DES.DES_DecryptBlock( $53E6E053B4C98A82, Plaintext, Ex); {$IFEND} Move( Plaintext, Recon[33], 8); SetLength( Recon, 38); Check( Recon = 'Your lips are smoother than vaseline'#13#10, 'Inverse: Your lips are smoother than vaseline') end; procedure TDES_TestCase.EncryptBlock; var Plaintext: uint64; Ciphertext: uint64; Key: TExpandedKey; begin // M = 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 Plaintext := IP_M; Key[ 0] := $3201073F2F0B3006; Key[ 1] := $25273C36193B1A1E; Key[ 2] := $193E2C100A321F15; Key[ 3] := $1D14333616372A1C; Key[ 4] := $280E353A07300E1F; Key[ 5] := $2F2C07143E143A18; Key[ 6] := $3C22213D3712083B; Key[ 7] := $3B2F13303A28383D; Key[ 8] := $011E1E3B2B2F0D38; Key[ 9] := $0F19242E070D1F2C; Key[10] := $060E2D37133F1508; Key[11] := $291F06253507171D; Key[12] := $01292B3E11173C25; Key[13] := $3A1C2E3C370E3417; Key[14] := $0A3C130F0D06392F; Key[15] := $351F21030B363332; uTPLb_DES.DES_EncryptBlock( Plaintext, Ciphertext, Key); Check( Ciphertext = $05B40A0F5413E885, 'DES_EncryptBlock'); uTPLb_DES.DES_DecryptBlock( Ciphertext, Plaintext, Key); Check( Plaintext = IP_M, 'DES_DecryptBlock'); end; procedure TDES_TestCase.ExpandKey; var Key: uint64; Ex: TExpandedKey; R: uint32; E: uint64; procedure CheckI( Idx: integer; Expected: uint64); begin Check( Ex[ Idx] = Expected, Format( 'DES ExpandKey[%d]; Should have be' + 'en $%x, but got $%x',[ Idx, Expected, Ex[ Idx]])) end; begin R := $AAF0AAF0; E := E_Bit_Selection( R); {$IF compilerversion <= 15} // Delphi 7 case. Check( E = {<UtoS_Cnvt>}uint64( $1515211E1515211E){</UtoS_Cnvt>}, 'E-Bit'); Key := {<UtoS_Cnvt>}uint64( -$0E20436486A8CBED){</UtoS_Cnvt>}; uTPLb_DES.ExpandKey( Key, Ex); // Done: // K1 = 000110 110000 001011 101111 111111 000111 000001 110010 (bigendien compact) CheckI( 0, {<UtoS_Cnvt>}uint64( $3201073F2F0B3006){</UtoS_Cnvt>}); // K2 = 011110 011010 111011 011001 110110 111100 100111 100101 (bigendien compact) CheckI( 1, {<UtoS_Cnvt>}uint64( $25273C36193B1A1E){</UtoS_Cnvt>}); // K3 = 010101 011111 110010 001010 010000 101100 111110 011001 CheckI( 2, {<UtoS_Cnvt>}uint64( $193E2C100A321F15){</UtoS_Cnvt>}); // K4 = 011100 101010 110111 010110 110110 110011 010100 011101 CheckI( 3, {<UtoS_Cnvt>}uint64( $1D14333616372A1C){</UtoS_Cnvt>}); // K5 = 011111 001110 110000 000111 111010 110101 001110 101000 CheckI( 4, {<UtoS_Cnvt>}uint64( $280E353A07300E1F){</UtoS_Cnvt>}); // K6 = 011000 111010 010100 111110 010100 000111 101100 101111 CheckI( 5, {<UtoS_Cnvt>}uint64( $2F2C07143E143A18){</UtoS_Cnvt>}); // K7 = 111011 001000 010010 110111 111101 100001 100010 111100 CheckI( 6, {<UtoS_Cnvt>}uint64( $3C22213D3712083B){</UtoS_Cnvt>}); // K8 = 111101 111000 101000 111010 110000 010011 101111 111011 CheckI( 7, {<UtoS_Cnvt>}uint64( $3B2F13303A28383D){</UtoS_Cnvt>}); // K9 = 111000 001101 101111 101011 111011 011110 011110 000001 CheckI( 8, {<UtoS_Cnvt>}uint64( $011E1E3B2B2F0D38){</UtoS_Cnvt>}); // K10 = 101100 011111 001101 000111 101110 100100 011001 001111 CheckI( 9, {<UtoS_Cnvt>}uint64( $0F19242E070D1F2C){</UtoS_Cnvt>}); // K11 = 001000 010101 111111 010011 110111 101101 001110 000110 CheckI( 10, {<UtoS_Cnvt>}uint64( $060E2D37133F1508){</UtoS_Cnvt>}); // K12 = 011101 010111 000111 110101 100101 000110 011111 101001 CheckI( 11, {<UtoS_Cnvt>}uint64( $291F06253507171D){</UtoS_Cnvt>}); // K13 = 100101 111100 010111 010001 111110 101011 101001 000001 CheckI( 12, {<UtoS_Cnvt>}uint64( $01292B3E11173C25){</UtoS_Cnvt>}); // K14 = 010111 110100 001110 110111 111100 101110 011100 111010 CheckI( 13, {<UtoS_Cnvt>}uint64( $3A1C2E3C370E3417){</UtoS_Cnvt>}); // K15 = 101111 111001 000110 001101 001111 010011 111100 001010 CheckI( 14, {<UtoS_Cnvt>}uint64( $0A3C130F0D06392F){</UtoS_Cnvt>}); // K16 = 110010 110011 110110 001011 000011 100001 011111 110101 CheckI( 15, {<UtoS_Cnvt>}uint64( $351F21030B363332){</UtoS_Cnvt>}) {$ELSE} Check( E = $1515211E1515211E, 'E-Bit'); Key := $F1DFBC9B79573413; uTPLb_DES.ExpandKey( Key, Ex); // Done: // K1 = 000110 110000 001011 101111 111111 000111 000001 110010 (bigendien compact) CheckI( 0, $3201073F2F0B3006); // K2 = 011110 011010 111011 011001 110110 111100 100111 100101 (bigendien compact) CheckI( 1, $25273C36193B1A1E); // K3 = 010101 011111 110010 001010 010000 101100 111110 011001 CheckI( 2, $193E2C100A321F15); // K4 = 011100 101010 110111 010110 110110 110011 010100 011101 CheckI( 3, $1D14333616372A1C); // K5 = 011111 001110 110000 000111 111010 110101 001110 101000 CheckI( 4, $280E353A07300E1F); // K6 = 011000 111010 010100 111110 010100 000111 101100 101111 CheckI( 5, $2F2C07143E143A18); // K7 = 111011 001000 010010 110111 111101 100001 100010 111100 CheckI( 6, $3C22213D3712083B); // K8 = 111101 111000 101000 111010 110000 010011 101111 111011 CheckI( 7, $3B2F13303A28383D); // K9 = 111000 001101 101111 101011 111011 011110 011110 000001 CheckI( 8, $011E1E3B2B2F0D38); // K10 = 101100 011111 001101 000111 101110 100100 011001 001111 CheckI( 9, $0F19242E070D1F2C); // K11 = 001000 010101 111111 010011 110111 101101 001110 000110 CheckI( 10, $060E2D37133F1508); // K12 = 011101 010111 000111 110101 100101 000110 011111 101001 CheckI( 11, $291F06253507171D); // K13 = 100101 111100 010111 010001 111110 101011 101001 000001 CheckI( 12, $01292B3E11173C25); // K14 = 010111 110100 001110 110111 111100 101110 011100 111010 CheckI( 13, $3A1C2E3C370E3417); // K15 = 101111 111001 000110 001101 001111 010011 111100 001010 CheckI( 14, $0A3C130F0D06392F); // K16 = 110010 110011 110110 001011 000011 100001 011111 110101 CheckI( 15, $351F21030B363332) {$IFEND} end; { TDES_Reference_TestCase } class function TDES_Reference_TestCase.CipherId: string; begin result := DES_ProgId end; procedure TDES_Reference_TestCase.NormalizeKeyStream; var NativeKey: uint64; begin FKeyStream.Read( NativeKey, 8); FKeyStream.Position := 0; SetParityBitsOnKey( NativeKey); FKeyStream.Write( NativeKey, 8) end; class function T3DES_Reference_TestCase.CipherId: string; begin result := TripleDES_ProgId end; class function TBlowfish_Reference_TestCase.CipherId: string; begin result := Blowfish_ProgId end; class function TTwofish_Reference_TestCase.CipherId: string; begin result := Twofish_ProgId end; procedure TTwofish_Reference_TestCase.TwoFishPrimitives; var Key: TBytes; Size: longword; SubKeys: TSubKeys; SBox: TSBox; InData, OutData, RefOutData: T128; I: integer; begin DCP_towfish_Precomp; // This data from http://www.schneier.com/code/ecb_ival.txt //KEYSIZE=128 Size := 16; SetLength( Key, Size); RefOutData[0] := $5C9F589F; // at I=1, CT=9F589F5CF6122C32B6BFEC2F2AE8C35A RefOutData[1] := $322C12F6; RefOutData[2] := $2FECBFB6; RefOutData[3] := $5AC3E82A; FillChar( Key[0], Size, 0); FillChar( InData, SizeOf( InData), 0); for I := 1 to 49 do begin if I >= 2 then begin Move( InData , Key[0], 16); Move( OutData, InData, 16) end; DCP_twofish_InitKey( Key[0], Size*8, SubKeys, SBox); DCP_twofish_EncryptECB( SubKeys, SBox, InData, OutData); if I = 1 then Check( CompareMem( @OutData, @RefOutData, SizeOf( T128)), 'LockBox TwoFish primitives failed the 128 reference test at I=1. ' + '(http://www.schneier.com/code/ecb_ival.txt)'); end; RefOutData[0] := $EF4E9D5D; // at I=49, CT=5D9D4EEFFA9151575524F115815A12E0 RefOutData[1] := $575191FA; RefOutData[2] := $15F12455; RefOutData[3] := $E0125A81; Check( CompareMem( @OutData, @RefOutData, SizeOf( T128)), 'LockBox TwoFish primitives failed the 128 reference test at I=49. ' + '(http://www.schneier.com/code/ecb_ival.txt)'); //KEYSIZE=192 //I=1 //KEY=000000000000000000000000000000000000000000000000 //PT=00000000000000000000000000000000 //I=49 //CT=E75449212BEEF9F4A390BD860A640941 Size := 24; SetLength( Key, Size); RefOutData[0] := $214954E7; // at I=49, CT=E75449212BEEF9F4A390BD860A640941 RefOutData[1] := $F4F9EE2B; RefOutData[2] := $86BD90A3; RefOutData[3] := $4109640A; FillChar( Key[0], Size, 0); FillChar( InData, SizeOf( InData), 0); for I := 1 to 49 do begin if I >= 2 then begin Move( Key[0] , Key[16], Size-16); Move( InData , Key[0], 16); Move( OutData, InData, 16) end; DCP_twofish_InitKey( Key[0], Size*8, SubKeys, SBox); DCP_twofish_EncryptECB( SubKeys, SBox, InData, OutData); end; Check( CompareMem( @OutData, @RefOutData, SizeOf( T128)), 'LockBox TwoFish primitives failed the 192 reference test at I=49. ' + '(http://www.schneier.com/code/ecb_ival.txt)'); //KEYSIZE=256 //I=1 //KEY=0000000000000000000000000000000000000000000000000000000000000000 //PT=00000000000000000000000000000000 //I=49 //CT=37FE26FF1CF66175F5DDF4C33B97A205 Size := 32; SetLength( Key, Size); RefOutData[0] := $FF26FE37; // at I=49, CT=37FE26FF1CF66175F5DDF4C33B97A205 RefOutData[1] := $7561F61C; RefOutData[2] := $C3F4DDF5; RefOutData[3] := $05A2973B; FillChar( Key[0], Size, 0); FillChar( InData, SizeOf( InData), 0); for I := 1 to 49 do begin if I >= 2 then begin Move( Key[0] , Key[16], Size-16); Move( InData , Key[0], 16); Move( OutData, InData, 16) end; DCP_twofish_InitKey( Key[0], Size*8, SubKeys, SBox); DCP_twofish_EncryptECB( SubKeys, SBox, InData, OutData); end; Check( CompareMem( @OutData, @RefOutData, SizeOf( T128)), 'LockBox TwoFish primitives failed the 256 reference test at I=49. ' + '(http://www.schneier.com/code/ecb_ival.txt)'); end; { T3DES_KO1_Reference_TestCase } class function T3DES_KO1_Reference_TestCase.CipherId: string; begin result := TripleDES_KO1_ProgId end; procedure T3DES_Reference_TestCase.NormalizeKeyStream; var NativeKey: uint64; SubKey: integer; begin for SubKey := 1 to 2 do begin FKeyStream.Position := (SubKey - 1) * 8; if FKeyStream.Read( NativeKey, 8) < 8 then break; FKeyStream.Position := (SubKey - 1) * 8; SetParityBitsOnKey( NativeKey); FKeyStream.Write( NativeKey, 8) end end; procedure T3DES_KO1_Reference_TestCase.NormalizeKeyStream; var NativeKey: uint64; SubKey: integer; begin for SubKey := 1 to 3 do begin FKeyStream.Position := (SubKey - 1) * 8; if FKeyStream.Read( NativeKey, 8) < 8 then break; FKeyStream.Position := (SubKey - 1) * 8; SetParityBitsOnKey( NativeKey); FKeyStream.Write( NativeKey, 8) end end; { TMasBug_TestCase } procedure TMasBug_TestCase.SetUp; begin FRand := TRandomStream.Instance ; Len := 32; GetMem( P, Len); end; procedure TMasBug_TestCase.TearDown; begin FreeMem( P, Len) end; procedure TMasBug_TestCase.Mas_RandomStream_Bug; var j: Integer; PreviousFirstByte: byte; CollisionCount: integer; begin FRand.Randomize; CollisionCount := 0; PreviousFirstByte := 0; for j := 1 to 20 do begin FRand.Read( P^, Len); if (j >= 2) and (PreviousFirstByte = P^) then Inc( CollisionCount); PreviousFirstByte := P^ end; Check( CollisionCount < 4, 'Random number generator is suspect.') end; initialization InitUnit_CipherTestCases; finalization DoneUnit_CipherTestCases; end.
unit CodeEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, ToolWin, LMDCustomScrollBox, LMDScrollBox, LMDSplt, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, EasyStrings, EasyEditor, EasyEditSource, EasyClasses, EasyParser, CodeExplorer; type TCodeEditForm = class(TForm) PhpParser: TEasyEditorParser; Source: TEasyEditSource; ChangeTimer: TTimer; ToolBar1: TToolBar; CollapseButton: TToolButton; JsParser: TEasyEditorParser; HtmlParser: TEasyEditorParser; Edit: TEasyEdit; procedure EditSourceChanged(Sender: TObject; State: TEasyEditSourceStates); procedure ChangeTimerTimer(Sender: TObject); procedure EditAutoComplete(Sender: TObject; Strings: TStrings; AKey: Char; var AllowPopup: Boolean); procedure CollapseButtonClick(Sender: TObject); procedure EditEnter(Sender: TObject); procedure EditExit(Sender: TObject); private FExplorer: TCodeExplorerForm; FOnModified: TNotifyEvent; FOnLazyUpdate: TNotifyEvent; protected function GetStrings: TStrings; procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED; procedure CreateHandle; override; procedure LazyUpdate; procedure Modified; procedure SetStrings(const Value: TStrings); procedure UpdateExplorer; public property Explorer: TCodeExplorerForm read FExplorer write FExplorer; property OnLazyUpdate: TNotifyEvent read FOnLazyUpdate write FOnLazyUpdate; property OnModified: TNotifyEvent read FOnModified write FOnModified; property Strings: TStrings read GetStrings write SetStrings; end; // THtmlEditForm = class(TCodeEditForm) public procedure AfterConstruction; override; end; var CodeEditForm: TCodeEditForm; function CreateHtmlViewForm: TCodeEditForm; implementation //uses // LrUtils; {$R *.dfm} function CreateHtmlViewForm: TCodeEditForm; begin Result := TCodeEditForm.Create(Application); with Result do begin Source.Parser := HtmlParser; Source.ReadOnly := true; Edit.LineBreak := lbCR; end; end; procedure TCodeEditForm.CreateHandle; begin inherited; // if Visible and Edit.CanFocus then // Edit.SetFocus; end; procedure TCodeEditForm.CMShowingChanged(var Message: TMessage); begin inherited; if Showing and Edit.CanFocus then Edit.SetFocus; end; function TCodeEditForm.GetStrings: TStrings; begin Result := Source.Strings; end; procedure TCodeEditForm.SetStrings(const Value: TStrings); begin Source.Strings.Assign(Value); end; procedure TCodeEditForm.EditSourceChanged(Sender: TObject; State: TEasyEditSourceStates); begin if (State <> [csPositionChanged]) or ChangeTimer.Enabled then if Edit.Modified then begin ChangeTimer.Enabled := false; ChangeTimer.Enabled := true; Modified; end; end; procedure TCodeEditForm.Modified; begin if Assigned(OnModified) then OnModified(Self); end; procedure TCodeEditForm.UpdateExplorer; begin if Explorer <> nil then Explorer.EasyEdit := Edit; end; procedure TCodeEditForm.ChangeTimerTimer(Sender: TObject); begin ChangeTimer.Enabled := false; LazyUpdate; end; procedure TCodeEditForm.LazyUpdate; begin UpdateExplorer; if Assigned(OnLazyUpdate) then OnLazyUpdate(Self); end; procedure TCodeEditForm.EditAutoComplete(Sender: TObject; Strings: TStrings; AKey: Char; var AllowPopup: Boolean); begin // end; procedure TCodeEditForm.CollapseButtonClick(Sender: TObject); begin if CollapseButton.Down then Edit.CollapseCode([ '{' ], [ '}'], [ {'*'} ], [], true, true, true, true) else Edit.UnCollapseCode; end; procedure TCodeEditForm.EditEnter(Sender: TObject); begin UpdateExplorer; end; procedure TCodeEditForm.EditExit(Sender: TObject); begin // end; { THtmlEditForm } procedure THtmlEditForm.AfterConstruction; begin inherited; Source.Parser := HtmlParser; Source.ReadOnly := true; Edit.LineBreak := lbCR; end; end.
unit uSubCadastros; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, uDM; type TfrmSubCadastros = class(TForm) GroupBox8: TGroupBox; btNovo: TButton; btSalvar: TButton; brImprimir: TButton; btExcluir: TButton; btLimpar: TButton; GroupBox9: TGroupBox; btSair: TButton; PageControl1: TPageControl; TabSheet1: TTabSheet; gbNome: TGroupBox; Label2: TLabel; edtDescricao: TEdit; gbCodigo: TGroupBox; Label1: TLabel; edtCodigo: TEdit; gridCategoria: TDBGrid; dsCategoria: TDataSource; procedure btSairClick(Sender: TObject); procedure btExcluirClick(Sender: TObject); procedure HabilitaCampos; procedure DesabilitaCampos; procedure btLimparClick(Sender: TObject); procedure btNovoClick(Sender: TObject); procedure btSalvarClick(Sender: TObject); procedure gridCategoriaDblClick(Sender: TObject); procedure edtCodigoExit(Sender: TObject); procedure edtCodigoKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var frmSubCadastros: TfrmSubCadastros; Operacao : string; implementation {$R *.dfm} procedure TfrmSubCadastros.HabilitaCampos; begin Operacao := 'Inclusão'; edtCodigo.Clear; edtDescricao.Clear; gbCodigo.Enabled := False; gbNome.Enabled := True; btNovo.Enabled := False; btSalvar.Enabled := True; btLimpar.Enabled := True; btExcluir.Enabled := True; end; procedure TfrmSubCadastros.DesabilitaCampos; begin edtCodigo.Clear; edtDescricao.Clear; gbCodigo.Enabled := True; gbNome.Enabled := False; btNovo.Enabled := True; btSalvar.Enabled := False; btLimpar.Enabled := False; btExcluir.Enabled := False; end; procedure TfrmSubCadastros.edtCodigoExit(Sender: TObject); begin if edtCodigo.Text <> '' then begin With DM.FDQuery do begin Close; SQL.Clear; SQL.Text := 'SELECT * FROM Categoria WHERE Codigo = ' + edtCodigo.Text; Open; if RecordCount = 0 then begin Application.MessageBox(PChar('Nenhum registro encontrado para o código: ' + edtCodigo.Text),'Aviso',MB_ICONERROR); edtCodigo.Clear; edtCodigo.SetFocus; end else begin HabilitaCampos(); edtCodigo.Text := FieldByName('Codigo').Value; edtDescricao.Text := FieldByName('Descricao').Value; Operacao := 'Alteração'; end; // Fim do if RecordCount = 0 end; end; // Fim do if edtCodigo.Text = '' end; procedure TfrmSubCadastros.edtCodigoKeyPress(Sender: TObject; var Key: Char); begin // Enter vira Tab if Key = #13 then begin Key := #0; Perform(Wm_NextDlgCtl,0,0); end; // Permite somente números no Edit if not( Key in['0'..'9',#08] ) then key:=#0; end; procedure TfrmSubCadastros.FormClose(Sender: TObject; var Action: TCloseAction); begin frmSubCadastros := Nil; Action := caFree; end; procedure TfrmSubCadastros.gridCategoriaDblClick(Sender: TObject); begin if btLimpar.Enabled then begin Application.MessageBox(PChar('Já existe um registro na tela para alteração ou cadastro.' + #13 + #13 + 'Salve ou cancele a alteração antes de alterar outro registro.'),'Aviso',MB_ICONINFORMATION); Exit; end; edtCodigo.Text := DM.FDQuery_Categoria.FieldByName('Codigo').Value; edtCodigo.SetFocus; // Executa um Tab Perform(Wm_NextDlgCtl,0,0); end; procedure TfrmSubCadastros.btExcluirClick(Sender: TObject); begin if Application.MessageBox(PChar('Deseja realmente excluir o registro: ' + edtCodigo.Text + '?'),'Aviso',MB_ICONQUESTION + MB_YESNO) = IDYES then begin With DM.FDQuery do begin Close; SQL.Clear; SQL.Text := 'DELETE FROM Categoria WHERE Codigo = ' + edtCodigo.Text; ExecSQL; Application.MessageBox(PChar('Registro excluído com sucesso'),'Aviso',MB_ICONINFORMATION); DesabilitaCampos(); // Atualiza os dados da grid de consulta if (DM.FDQuery_Categoria.Active = True) then DM.FDQuery_Categoria.Active := False; DM.FDQuery_Categoria.Active := True; end; end; end; procedure TfrmSubCadastros.btLimparClick(Sender: TObject); begin DesabilitaCampos(); edtCodigo.SetFocus; end; procedure TfrmSubCadastros.btNovoClick(Sender: TObject); begin HabilitaCampos(); With DM.FDQuery do begin Close; SQL.Clear; SQL.Text := 'SELECT (MAX(Codigo)+1) AS Proximo FROM Categoria'; Open; if FieldByName('Proximo').Value <> Null then begin edtCodigo.Text := FieldByName('Proximo').Value; end else begin edtCodigo.Text := '1'; end; end; edtDescricao.SetFocus; end; procedure TfrmSubCadastros.btSairClick(Sender: TObject); begin Self.Close; end; procedure TfrmSubCadastros.btSalvarClick(Sender: TObject); begin if edtDescricao.Text = '' then begin Application.MessageBox(PChar('O campo "Descrição" deve ser preenchido'),'Aviso',MB_ICONERROR); edtDescricao.SetFocus; Exit; end; With DM.FDQuery do begin Close; SQL.Clear; if Operacao = 'Inclusão' then begin SQL.Add(' INSERT INTO Categoria (Descricao) VALUES (''' + edtDescricao.Text + ''' )'); end else if Operacao = 'Alteração' then begin SQL.Add(' UPDATE Categoria SET Descricao = ''' + edtDescricao.Text + ''' WHERE Codigo = ' + edtCodigo.Text + ' '); end; ExecSQL; Application.MessageBox(PChar('Registro salvo com sucesso'),'Aviso',MB_ICONINFORMATION); DesabilitaCampos(); // Atualiza os dados da grid de consulta if (DM.FDQuery_Categoria.Active = True) then DM.FDQuery_Categoria.Active := False; DM.FDQuery_Categoria.Active := True; edtCodigo.SetFocus; end; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFChromiumFontOptions; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} System.Classes, {$ELSE} Classes, {$ENDIF} uCEFTypes; type TChromiumFontOptions = class(TPersistent) protected FStandardFontFamily : ustring; FCursiveFontFamily : ustring; FSansSerifFontFamily : ustring; FMinimumLogicalFontSize : Integer; FFantasyFontFamily : ustring; FSerifFontFamily : ustring; FDefaultFixedFontSize : Integer; FDefaultFontSize : Integer; FRemoteFontsDisabled : TCefState; FFixedFontFamily : ustring; FMinimumFontSize : Integer; public constructor Create; virtual; published property StandardFontFamily : ustring read FStandardFontFamily write FStandardFontFamily; property FixedFontFamily : ustring read FFixedFontFamily write FFixedFontFamily; property SerifFontFamily : ustring read FSerifFontFamily write FSerifFontFamily; property SansSerifFontFamily : ustring read FSansSerifFontFamily write FSansSerifFontFamily; property CursiveFontFamily : ustring read FCursiveFontFamily write FCursiveFontFamily; property FantasyFontFamily : ustring read FFantasyFontFamily write FFantasyFontFamily; property DefaultFontSize : Integer read FDefaultFontSize write FDefaultFontSize default 0; property DefaultFixedFontSize : Integer read FDefaultFixedFontSize write FDefaultFixedFontSize default 0; property MinimumFontSize : Integer read FMinimumFontSize write FMinimumFontSize default 0; property MinimumLogicalFontSize : Integer read FMinimumLogicalFontSize write FMinimumLogicalFontSize default 0; property RemoteFonts : TCefState read FRemoteFontsDisabled write FRemoteFontsDisabled default STATE_DEFAULT; end; implementation constructor TChromiumFontOptions.Create; begin FStandardFontFamily := ''; FCursiveFontFamily := ''; FSansSerifFontFamily := ''; FMinimumLogicalFontSize := 0; FFantasyFontFamily := ''; FSerifFontFamily := ''; FDefaultFixedFontSize := 0; FDefaultFontSize := 0; FRemoteFontsDisabled := STATE_DEFAULT; FFixedFontFamily := ''; FMinimumFontSize := 0; end; end.
unit uProtocolMessage; interface uses Classes, Windows, SysUtils, DynamicArrays, uCommonUnitObj; type TProtocolMessage = class private // FOwner: TObject; FPacketSize: cardinal; FCommand: string; FCryptedText: string; FPlainText: string; FDefaultKey: string; function CheckBufAvail(buffer: PChar; bufferSize: cardinal): boolean; public // constructor Create(Owner: TObject; DefaultKey: string); constructor Create(DefaultKey: string); function ParseBuffer(buffer:PChar; bufferSize:cardinal): cardinal; // size is used for buffer overflow checking function GetFormattedMessage(): string; overload; function GetAsBuffer(): PChar; class function GetFormattedMessage(buffer:PChar; bufferSize:cardinal):string; overload; class function GetMessage(Key: string; buffer:PChar; bufferSize:cardinal): TProtocolMessage; // properties property PacketSize: cardinal read FPacketSize; property Command: string read FCommand; property CryptedText: string read FCryptedText; property PlainText: string read FPlainText; property DefaultKey: string read FDefaultKey write FDefaultKey; end; TProtocolMessageManager = class private FMessages: TList; FDefaultKey: string; FLeftBuffer: THArrayByte; procedure InternalParse(buffer:PChar; bufferSize:cardinal); procedure ClearMessages(); public constructor Create(Key: string); destructor Destroy(); override; procedure Parse(buffer:PChar; bufferSize:cardinal); procedure Export(MessageQueue: TStringList); property DefaultKey: string read FDefaultKey write FDefaultKey; end; EIncorrectData = class(EConvertError); implementation uses DCPcrypt2, DCPrc4, {$IFDEF USELOG4D} log4d, {$ENDIF USELOG4D} DreamChatExceptions; { TProtocolMessage } // check if buffer is large enough for holding string representation of size of message function TProtocolMessage.CheckBufAvail(buffer: PChar; bufferSize: cardinal): boolean; var index: cardinal; begin Result := False; if (buffer = nil) or (bufferSize = 0) then exit; // empty buffers are also not allowed if buffer[0] = #0 then exit; index := 0; repeat if(buffer[index] = #0) then begin // buffer is enough, return true Result := True; exit; end; inc(index); until index >= bufferSize; // by default it is considered that buffer is not enough and False will be returned end; constructor TProtocolMessage.Create({Owner: TObject;} DefaultKey: string); begin FPacketSize := 0; if Length(DefaultKey) = 0 then raise DreamChatTechnicalException.Create('Key is empty.'); FDefaultKey := DefaultKey; end; function TProtocolMessage.GetFormattedMessage: string; begin Result := Format('[%d][$00][%s][$00][%s]', [FPacketSize, FCommand, FCryptedText]); end; function TProtocolMessage.GetAsBuffer: PChar; begin Result := AllocMem(Length(FPlainText)); CopyMemory(Result, PChar(FPlainText), Length(FPlainText)); end; class function TProtocolMessage.GetFormattedMessage(buffer: PChar; bufferSize: cardinal): string; var mess: TProtocolMessage; begin // mess := TProtocolMessage.Create(nil, '0'); // TODO: KEY absent! mess := TProtocolMessage.Create('0'); // TODO: KEY absent! try mess.ParseBuffer(buffer, bufferSize); Result := mess.GetFormattedMessage(); finally mess.Free; end; end; class function TProtocolMessage.GetMessage(Key: string; buffer: PChar; bufferSize: cardinal): TProtocolMessage; begin // Result := TProtocolMessage.Create(nil, Key); Result := TProtocolMessage.Create(Key); Result.ParseBuffer(buffer, bufferSize); end; // parses one message from a buffer // buffer may contain more than one message, second, etc messages are not parsed // returns index of first character of next message in buffer function TProtocolMessage.ParseBuffer(buffer: PChar; bufferSize: cardinal): cardinal; var IChatPacketSize: cardinal; CommandOffset: cardinal; DataOffset: cardinal; LenOfFieldMessLen: cardinal; LenOfFieldCommand: cardinal; IChatDataLen: cardinal; PacketSizeStr: string; Command: string; PPlainText, PCryptedText: PChar; DCP_rc41 :TDCP_rc4; UncryptoKey: string; i: integer; begin if (buffer = nil) or (bufferSize = 0) then raise EConvertError.Create('Message buffer is NULL.'); // check if buffer is large enough to hold size of received message and trailing zero if not CheckBufAvail(buffer, bufferSize) then raise EConvertError.Create('Incorrect data in message buffer received. Packet size is incorrect.'); // size of entire message as int PacketSizeStr := StrPas(buffer); IChatPacketSize := StrToInt(PacketSizeStr); if IChatPacketSize = 0 then raise EIncorrectData.Create('Incorrect data in message buffer received. Packet size is zero.'); LenOfFieldMessLen := Length(PacketSizeStr); CommandOffset := LenOfFieldMessLen + 1; // offset in buffer for command // это проверка на взлом, чтобы не присылали пакет или ложной длиной сообщения // TODO: так же возможно просто сообщение большое и не влезло в буфер. if ((IChatPacketSize + CommandOffset) > bufferSize) then raise EConvertError.Create('Incorrect data in message buffer received. Packet size is incorrect.'); // check if buffer is large enough to hold command and trailing zero // command cannot be empty and must contain at least one symbol if not CheckBufAvail(@buffer[CommandOffset], bufferSize - CommandOffset) then raise EConvertError.Create('Incorrect data in message buffer received. ' + 'Empty command detected.'); Command := StrPas(@buffer[CommandOffset]); LenOfFieldCommand := Length(Command); DataOffset := CommandOffset + LenOfFieldCommand + 1; // IChatPacketSize считается с первого символа команды а не символа размера пакета. // Поэтому проверяем что указаный размер пакета не меньше длины команды + 1 if (IChatPacketSize < LenOfFieldCommand + 1) then raise EIncorrectData.Create('Incorrect data in message buffer received. Packet size is too small.'); // check if buffer is large enough to hold message data and trailing zero // message data cannot be empty and must contain at least one symbol //if not CheckBufAvail(@buffer[DataOffset], bufferSize - DataOffset) // then raise EConvertError.Create('Incorrect data in message buffer received. Empty message data detected.'); // вычисляем размер данных (самого сообщения) IChatDataLen := IChatPacketSize - LenOfFieldCommand - 1; if IChatDataLen = 0 then raise EIncorrectData.Create('Incorrect data in message buffer received. Message size is zero.'); if(DataOffset + IChatDataLen > bufferSize) then raise EConvertError.Create('Incorrect data in message buffer received. Packet size exceeds buffer size.'); // all sems ok, assign actual values to fields FPacketSize := IChatPacketSize; FCommand := Command; //перемещаем защифрованное сообщение IChat в строку FCryptedText SetString(FCryptedText, PChar(@(buffer[DataOffset])), Integer(IChatDataLen)); // create string filled by zeros FPlainText := StringOfChar(#0, Length(FCryptedText)); // TODO: размер сообщения меняется при расшифровке или нет? PPlainText := PChar(FPlainText); PCryptedText := PChar(FCryptedText); DCP_rc41 := TDCP_rc4.Create(nil); try UncryptoKey := FDefaultKey; { проблема в следующем: если мы хотим использовать персональные ключи надо знать от кого пришло ссобщение if (CryptoKeyForRemoteComputers.Count > 0) then begin i := CryptoKeyForRemoteComputers.IndexOf(sNetBiosNameOfRemoteComputer); end; if i >= 0 then begin //устанавливаем персональный секретный ключ шифрования pPersonalCrypto := pPersonalCrypto(CryptoKeyForRemoteComputers.Objects[i]); UncryptoKey := pPersonalCrypto. end; } DCP_rc41.Init(UncryptoKey[1], Length(UncryptoKey) * 8, nil); DCP_rc41.Decrypt(PCryptedText^, PPlainText^, IChatDataLen); finally DCP_rc41.Free; end; Result := DataOffset + IChatDataLen; end; { TProtocolMessageManager } constructor TProtocolMessageManager.Create(Key: string); begin FMessages := TList.Create; FDefaultKey := Key; FLeftBuffer := THArrayByte.Create(); end; destructor TProtocolMessageManager.Destroy; begin FMessages.Free; FLeftBuffer.Free; inherited Destroy; end; procedure TProtocolMessageManager.Parse(buffer: PChar; bufferSize: cardinal); var mergedBuffer: THArrayByte; begin if FLeftBuffer.Count > 0 then begin mergedBuffer := THArrayByte.Create; try mergedBuffer.AddMany(FLeftBuffer.Memory, FLeftBuffer.Count); mergedBuffer.AddMany(buffer, bufferSize); FLeftBuffer.Clear; InternalParse(mergedBuffer.Memory, mergedBuffer.Count); finally mergedBuffer.Free; end; end else begin InternalParse(buffer, bufferSize); end; end; // buffer: PChar is merged buffer with remained from last Parse() call procedure TProtocolMessageManager.InternalParse(buffer: PChar; bufferSize: cardinal); var currMessageIndex: cardinal; mess: TProtocolMessage; {$IFDEF USELOG4D} logger: TlogLogger; {$ENDIF USELOG4D} begin currMessageIndex := 0; try ClearMessages; while currMessageIndex < bufferSize do begin mess := TProtocolMessage.Create(FDefaultKey); //ParseBuffer return index related to buffer buffer[currMessageIndex]. // Therefore we add this index to previous one to get correct index regarding to initial buffer currMessageIndex := currMessageIndex + mess.ParseBuffer(@buffer[currMessageIndex], bufferSize - currMessageIndex); FMessages.Add(mess); end; except on E: EIncorrectData do begin // exception means that last message is partially included in buffer or we have // at least one incorrect message in buffer {$IFDEF USELOG4D} logger := TlogLogger.GetLogger('tcpkrnl'); logger.Info('Error parsing message.', E); {$ENDIF USELOG4D} end; on E: EConvertError do begin // it seems that partail message left in buffer, remember this buffer and appent to next piece of data received from network. FLeftBuffer.Clear; // move rest of symbols to buffer for future parsing FLeftBuffer.AddMany(@buffer[currMessageIndex], bufferSize - currMessageIndex); end; end; end; procedure TProtocolMessageManager.Export(MessageQueue: TStringList); var i: integer; begin for i := 0 to FMessages.Count - 1 do begin MessageQueue.AddObject(IntToStr(Length(TProtocolMessage(FMessages[i]).FPlainText)), Pointer(TProtocolMessage(FMessages[i]).GetAsBuffer())); end; ClearMessages; end; procedure TProtocolMessageManager.ClearMessages; var i: integer; begin for i := 0 to FMessages.Count - 1 do TProtocolMessage(FMessages[i]).Free; FMessages.Clear; end; end.
{$I CetusOptions.inc} unit ctsTypesDef; interface uses SysUtils; type TctsNotifyAction = (naAdded, naDeleting, naForEach); TctsNameString = string[31]; EctsError = class(Exception); EctsListError = class(EctsError); EctsStackError = class(EctsError); EctsQueueError = class(EctsError); EctsTreeError = class(EctsError); const {$IFDEF DEBUG} ctsDebugSign = $CC; {$ENDIF} ctsMaxBlockSize = MaxLongInt div 16; ctsDefaultNodeQuantity = $80; ctsDefaultCapacity = $10; implementation end.
{----------------------------------------------------------------------------- Unit Name: frmAbout Author: HochwimmerA Purpose: About Form. $Id: frmAbout.pas,v 1.7 2003/08/12 00:01:01 hochwimmera Exp $ -----------------------------------------------------------------------------} unit frmAbout; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons,ExtCtrls, ComCtrls; type TInfoItem = class(TObject) private fDisplayName: string; fInternalName: string; fValue: string; public property DisplayName: string read fDisplayName write fDisplayName; property InternalName: string read fInternalName write fInternalName; property Value: string read fValue write fValue; function DisplayValue: string; function DisplayValueForList: string; end; TAboutInfo = class(TObject) private fInfoItems: TList; fMajor: Word; fMinor: Word; fRelease: Word; fBuild: Word; fBuildDateAsStr: string; procedure LoadInfoItems; procedure GetFileDetails(const sFile: string); function ReadVersionInfo(sProgram: string; Major, Minor, Release, Build : pWord) :Boolean; public constructor Create(const aFile: string); destructor Destroy; override; property FileInfoItems: TList read fInfoItems; property FileBuildDate: string read fBuildDateAsStr; function FileVersion: string; end; TformAbout = class(TForm) pnlAboutTop: TPanel; lblUrl: TLabel; lblCopyright: TLabel; lblTitle: TLabel; lblVersion: TLabel; lblBuildDate: TLabel; PageControl1: TPageControl; tsCredits: TTabSheet; tsChanges: TTabSheet; bOk: TBitBtn; memChanges: TMemo; tsSecretPage: TTabSheet; memQuality: TMemo; tsLicence: TTabSheet; memLicence: TMemo; jvspCredits: TMemo; procedure FormShow(Sender: TObject); procedure lblUrlClick(Sender: TObject); procedure memQualityClick(Sender: TObject); procedure lblTitleClick(Sender: TObject); procedure jvspCreditsDblClick(Sender: TObject); procedure memQualityDblClick(Sender: TObject); private public end; var formAbout: TformAbout; implementation uses shellapi,WinProcs,WinTypes; {$R *.dfm} // ----- TInfoItem.DisplayValue ------------------------------------------------ function TInfoItem.DisplayValue: string; begin result := fDisplayName + ' = ' + fValue; end; // ----- TInfoItem.DisplayValueForList ----------------------------------------- function TInfoItem.DisplayValueForList: string; begin result := Copy(fDisplayName + ' ', 1, 19) + '= ' + fValue; end; // ----- TAboutInfo.Create ----------------------------------------------------- Constructor TAboutInfo.Create(const aFile: string); begin inherited Create; fInfoItems := TList.Create; LoadInfoItems; GetFileDetails(aFile); end; // ----- TAboutInfo.Destroy ---------------------------------------------------- Destructor TAboutInfo.Destroy; begin fInfoItems.Clear; fInfoItems.Free; inherited Destroy; end; // ----- TAboutInfo.LoadInfoItems ---------------------------------------------- procedure TAboutInfo.LoadInfoItems; const InfoNum = 11; InfoStr : array [1..InfoNum] of String = ('CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright', 'LegalTradeMarks', 'OriginalFilename', 'ProductName', 'ProductVersion', 'Comments', 'Author'); LabelStr : array [1..InfoNum] of String = ('Company Name', 'Description', 'File Version', 'Internal Name', 'Copyright', 'TradeMarks', 'Original File Name', 'Product Name', 'Product Version', 'Comments', 'Author'); var i: integer; myInfoItem :TInfoItem; begin for i:= 1 to InfoNum do begin myInfoItem := TInfoItem.Create; myInfoItem.InternalName := InfoStr[i]; myInfoItem.DisplayName := LabelStr[i]; myInfoItem.Value := ''; fInfoItems.Add(myInfoItem); end; end; // ----- TAboutInfo.GetFileDetails --------------------------------------------- procedure TAboutInfo.GetFileDetails(const sFile: string); var DosDate: integer; Major, Minor, Release, Build : Word; begin DosDate := FileAge(sFile); if DosDate > 0 then fBuildDateAsStr := FormatDateTime('dd-mmmm-yyyy hh:mm', FileDateToDateTime(DosDate)) else fBuildDateAsStr := ''; if ReadVersionInfo(sFile, @Major, @Minor, @Release, @Build) then begin fMajor := Major; fMinor := Minor; fRelease := Release; fBuild := Build; end else begin fMajor := 0; fMinor := 0; fRelease := 0; fBuild := 0; end; end; // ----- TAboutInfo.FileVersion ------------------------------------------------ function TAboutInfo.FileVersion: string; begin result := IntToStr(fMajor) + '.' + IntToStr(fMinor) + '.' + IntToStr(fRelease) + '.' + IntToStr(fBuild); end; // ----- TAboutInfo.ReadVersionInfo -------------------------------------------- function TAboutInfo.ReadVersionInfo(sProgram: string; Major, Minor, Release, Build : pWord) :Boolean; var i: integer; Info : PVSFixedFileInfo; {$ifdef VER120} InfoSize : Cardinal; {$else} InfoSize : UINT; {$endif} nHwnd : DWORD; BufferSize : DWORD; Buffer : Pointer; Value: PChar; begin BufferSize := GetFileVersionInfoSize(pchar(sProgram),nHWnd); {Get buffer size} Result := True; if BufferSize <> 0 then begin {if zero, there is no version info} GetMem( Buffer, BufferSize); {allocate buffer memory} try if GetFileVersionInfo(PChar(sProgram),nHWnd,BufferSize,Buffer) then begin {got version info} for i:= 0 to fInfoItems.Count - 1 do begin if VerQueryValue(Buffer,PChar('StringFileInfo\140904E4\'+ TInfoItem(fInfoItems[i]).InternalName),Pointer(Value),InfoSize) then if Length(value) > 0 then TInfoItem(fInfoItems[i]).Value := value; end; if VerQueryValue(Buffer, '\', Pointer(Info), InfoSize) then begin {got root block version information} if Assigned(Major) then begin Major^ := HiWord(Info^.dwFileVersionMS); {extract major version} end; if Assigned(Minor) then begin Minor^ := LoWord(Info^.dwFileVersionMS); {extract minor version} end; if Assigned(Release) then begin Release^ := HiWord(Info^.dwFileVersionLS); {extract release version} end; if Assigned(Build) then begin Build^ := LoWord(Info^.dwFileVersionLS); {extract build version} end; end else begin Result := False; {no root block version info} end; end else begin Result := False; {couldn't get version info} end; finally FreeMem(Buffer, BufferSize); {release buffer memory} end; end else begin Result := False; {no version info at all} end; end; // ----- TformAbout.FormShow --------------------------------------------------- procedure TformAbout.FormShow(Sender: TObject); var ai : TAboutInfo; sFileName :string; begin sFileName := ExtractFilePath(ParamStr(0))+'ChangeLog.txt'; if FileExists(sFileName) then memChanges.Lines.LoadFromFile(sFileName) else tsChanges.TabVisible := false; sFileName := ExtractFilePath(ParamStr(0))+'MPL-1_1.txt'; if FileExists(sFileName) then memLicence.Lines.LoadFromFile(sFileName) else tsLicence.TabVisible := false; ai := TAboutInfo.Create(ParamStr(0)); lblVersion.Caption := 'Pre-Release v' + ai.FileVersion; lblBuildDate.Caption := 'Built: ' + ai.FileBuildDate; ai.Free; end; // ----- TformAbout.lblUrlClick ------------------------------------------------ procedure TformAbout.lblUrlClick(Sender: TObject); begin ShellExecute(0,'open','http://gldata.sourceforge.net','','',SW_SHOW); end; // ----- TformAbout.memQualityClick -------------------------------------------- procedure TformAbout.memQualityClick(Sender: TObject); // just like the matrix reloaded - an easter egg inside an easter egg begin memQuality.Color := RGB(Random(255),Random(255),Random(255)); end; // ----- TformAbout.lblTitleClick ---------------------------------------------- procedure TformAbout.lblTitleClick(Sender: TObject); begin lbltitle.Font.color := RGB(Random(255),Random(255),Random(255)); end; // ----- TformAbout.jvspCreditsDblClick ---------------------------------------- procedure TformAbout.jvspCreditsDblClick(Sender: TObject); begin tsSecretPage.TabVisible := not tsSecretPage.TabVisible; if tsSecretPage.TabVisible then jvspCredits.color := RGB(Random(255),Random(255),Random(255)) else jvspCredits.Color := clwhite; end; // ----- TformAbout.memQualityDblClick ----------------------------------------- procedure TformAbout.memQualityDblClick(Sender: TObject); begin memQuality.Color := RGB(Random(255),Random(255),Random(255)); end; // ============================================================================= end.
// // Generated by JavaToPas v1.5 20150831 - 132345 //////////////////////////////////////////////////////////////////////////////// unit android.print.PrintJobInfo; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.os, android.print.PrintJobId, android.print.PrinterId, android.print.PageRange, android.print.PrintAttributes; type JPrintJobInfo = interface; JPrintJobInfoClass = interface(JObjectClass) ['{8EE4D10A-4207-429B-BB95-A0412F32B890}'] function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19 function _GetSTATE_BLOCKED : Integer; cdecl; // A: $19 function _GetSTATE_CANCELED : Integer; cdecl; // A: $19 function _GetSTATE_COMPLETED : Integer; cdecl; // A: $19 function _GetSTATE_CREATED : Integer; cdecl; // A: $19 function _GetSTATE_FAILED : Integer; cdecl; // A: $19 function _GetSTATE_QUEUED : Integer; cdecl; // A: $19 function _GetSTATE_STARTED : Integer; cdecl; // A: $19 function describeContents : Integer; cdecl; // ()I A: $1 function getAttributes : JPrintAttributes; cdecl; // ()Landroid/print/PrintAttributes; A: $1 function getCopies : Integer; cdecl; // ()I A: $1 function getCreationTime : Int64; cdecl; // ()J A: $1 function getId : JPrintJobId; cdecl; // ()Landroid/print/PrintJobId; A: $1 function getLabel : JString; cdecl; // ()Ljava/lang/String; A: $1 function getPages : TJavaArray<JPageRange>; cdecl; // ()[Landroid/print/PageRange; A: $1 function getPrinterId : JPrinterId; cdecl; // ()Landroid/print/PrinterId; A: $1 function getState : Integer; cdecl; // ()I A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19 property STATE_BLOCKED : Integer read _GetSTATE_BLOCKED; // I A: $19 property STATE_CANCELED : Integer read _GetSTATE_CANCELED; // I A: $19 property STATE_COMPLETED : Integer read _GetSTATE_COMPLETED; // I A: $19 property STATE_CREATED : Integer read _GetSTATE_CREATED; // I A: $19 property STATE_FAILED : Integer read _GetSTATE_FAILED; // I A: $19 property STATE_QUEUED : Integer read _GetSTATE_QUEUED; // I A: $19 property STATE_STARTED : Integer read _GetSTATE_STARTED; // I A: $19 end; [JavaSignature('android/print/PrintJobInfo$Builder')] JPrintJobInfo = interface(JObject) ['{70008638-381F-4584-A00C-B3783FEC5C1F}'] function describeContents : Integer; cdecl; // ()I A: $1 function getAttributes : JPrintAttributes; cdecl; // ()Landroid/print/PrintAttributes; A: $1 function getCopies : Integer; cdecl; // ()I A: $1 function getCreationTime : Int64; cdecl; // ()J A: $1 function getId : JPrintJobId; cdecl; // ()Landroid/print/PrintJobId; A: $1 function getLabel : JString; cdecl; // ()Ljava/lang/String; A: $1 function getPages : TJavaArray<JPageRange>; cdecl; // ()[Landroid/print/PageRange; A: $1 function getPrinterId : JPrinterId; cdecl; // ()Landroid/print/PrinterId; A: $1 function getState : Integer; cdecl; // ()I A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 end; TJPrintJobInfo = class(TJavaGenericImport<JPrintJobInfoClass, JPrintJobInfo>) end; const TJPrintJobInfoSTATE_BLOCKED = 4; TJPrintJobInfoSTATE_CANCELED = 7; TJPrintJobInfoSTATE_COMPLETED = 5; TJPrintJobInfoSTATE_CREATED = 1; TJPrintJobInfoSTATE_FAILED = 6; TJPrintJobInfoSTATE_QUEUED = 2; TJPrintJobInfoSTATE_STARTED = 3; implementation end.
unit frmShowScript; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TfShowScript = class(TForm) Panel1: TPanel; bbtnSave: TBitBtn; bbtnClose: TBitBtn; Memo1: TMemo; lstScripts: TListBox; Splitter1: TSplitter; bbtnRefresh: TBitBtn; procedure bbtnRefreshClick(Sender: TObject); procedure lstScriptsDblClick(Sender: TObject); procedure bbtnSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FLoadFileName: WideString; procedure RefreshScriptsList; public { Public declarations } end; var fShowScript: TfShowScript; implementation uses UnitConsts; {$R *.dfm} procedure TfShowScript.RefreshScriptsList; var sr: TSearchRec; begin lstScripts.Items.Clear; if FindFirst(IDS_ScriptFilesPath + '*.ini', faAnyFile, sr) = 0 then repeat lstScripts.Items.Add(sr.Name); until FindNext(sr) <> 0; FindClose(sr); end; procedure TfShowScript.FormCreate(Sender: TObject); begin RefreshScriptsList; end; procedure TfShowScript.bbtnRefreshClick(Sender: TObject); begin RefreshScriptsList; end; procedure TfShowScript.lstScriptsDblClick(Sender: TObject); begin FLoadFileName := IDS_ScriptFilesPath + lstScripts.Items[lstScripts.ItemIndex]; self.Memo1.Lines.LoadFromFile(FLoadFileName); end; procedure TfShowScript.bbtnSaveClick(Sender: TObject); begin if Length(FLoadFileName) > 0 then self.Memo1.Lines.SaveToFile(FLoadFileName); end; procedure TfShowScript.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (ssCtrl in Shift) and (Key = Ord('A')) then Memo1.SelectAll; end; end.
unit Fake.FDConnection; interface uses System.SysUtils; type TFDCommandExceptionKind = (ekOther, ekNoDataFound, ekTooManyRows, ekRecordLocked, ekUKViolated, ekFKViolated, ekObjNotExists, ekUserPwdInvalid, ekUserPwdExpired, ekUserPwdWillExpire, ekCmdAborted, ekServerGone, ekServerOutput, ekArrExecMalfunc, ekInvalidParams); EFDDBEngineException = class(Exception) kind: TFDCommandExceptionKind; end; TFDConnectionDefParams = record function UserName: string; end; TFDStanConnectionDef = record Params: TFDConnectionDefParams; end; TConnectionDefs = record function ConnectionDefByName(const AName: string): TFDStanConnectionDef; end; TFDConnectionMock = record function ConnectionDefName: string; procedure Open(); overload; procedure Open(const AUserName, APassword: string); overload; function ExecSQLScalar(const ASQL: String): Variant; end; TFDManagerMock = record function ConnectionDefs: TConnectionDefs; end; var FDManager: TFDManagerMock; implementation { TFDConnectionMock } function TFDConnectionMock.ConnectionDefName: string; begin Result := 'IB_Mailing'; end; function TFDConnectionMock.ExecSQLScalar(const ASQL: String): Variant; begin Result := 2001; end; type RecError = record kind: TFDCommandExceptionKind; msg: string; end; const DatabaseErrors: array [1 .. 3] of RecError = ((kind: ekServerGone; msg: '[FireDAC] Unavailable database'), (kind: ekUserPwdInvalid; msg: '[FireDAC] Your user name and password are not defined. Ask your database administrator to set up a login.'), (kind: ekObjNotExists; msg: '[FireDAC] Dynamic SQL Error (code = -204) Table unknown: DBINFO')); procedure TFDConnectionMock.Open; var E: EFDDBEngineException; RaiseErrorNr: Integer; begin RaiseErrorNr := 0; if RaiseErrorNr>0 then begin E := EFDDBEngineException.Create(DatabaseErrors[RaiseErrorNr].msg); E.kind := DatabaseErrors[RaiseErrorNr].kind; raise E; end; end; procedure TFDConnectionMock.Open(const AUserName, APassword: string); begin self.Open end; { TConnectionDefs } function TConnectionDefs.ConnectionDefByName(const AName: string) : TFDStanConnectionDef; var cdp: TFDStanConnectionDef; begin Result := cdp; end; { TFDConnectionDefParams } function TFDConnectionDefParams.UserName: string; begin Result := 'sysdba'; end; { TFDManagerMock } function TFDManagerMock.ConnectionDefs: TConnectionDefs; var ConDefs: TConnectionDefs; begin Result := ConDefs; end; end.
//***************************************************************************** //Печать ведомостей или платежной ведомости //Параметры: //AId - идентификатор ведомости или реестра //ATypeForm - идентификатор типа: 1 - ведомость, 2 - ведомости реестра, 3 - платежная ведомомсть //***************************************************************************** unit UV_SheetPrint_Form; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, FIBDataSet, frxClass, frxDBSet, FIBDatabase, pFIBDatabase, pFIBDataSet, Dates, IBase, frxDesgn, ZProc, IniFiles, Unit_SheetPrint_Consts,UV_SheetPrint_Dates_Form; type TFPrintVed = class(TForm) DataBase: TpFIBDatabase; DSetSetup: TpFIBDataSet; DSetGrSheet: TpFIBDataSet; ReadTransaction: TpFIBTransaction; DSetSheet: TpFIBDataSet; frxDBDSetSetup: TfrxDBDataset; frxDBDSetSheet: TfrxDBDataset; frxDBDSetGrSheet: TfrxDBDataset; DSourceGrSheet: TDataSource; frxReport: TfrxReport; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure frxReportGetValue(const VarName: String; var Value: Variant); private PResault:Variant; PTypePrint:Byte; public constructor Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;AId:LongWord;ATypeForm:Byte);reintroduce; property Resault:variant read PResault; end; function CreateReportPrintSheet(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;AId:LongWord;ATypeForm:Byte):variant;stdcall; exports CreateReportPrintSheet; implementation const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini'; const SectionSheetOfIniFile = 'SHEET'; const SectionReeSheetsOfIniFile = 'REESHEETS'; const SectionSheetReeOfIniFile = 'SHEETREE'; {$R *.dfm} function CreateReportPrintSheet(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;AId:LongWord;ATypeForm:Byte):Variant; var ViewForm:TFPrintVed; begin ViewForm := TFPrintVed.Create(AOwner,DB_HANDLE,AId,ATypeForm); if ViewForm.Resault <> NULL then MessageBox((AOwner as TForm).Handle,PChar(ViewFormResault),PChar(CaptionError),mb_Ok+mb_IconError) else ViewForm.Close; ViewForm.Free; end; constructor TFPrintVed.Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;AId:LongWord;ATypeForm:Byte); begin inherited Create(AOwner); PTypePrint := ATypeForm; DataBase.Connected := False; DataBase.Handle := DB_HANDLE; ReadTransaction.StartTransaction; DSetSetup.SQLs.SelectSQL.Text:='SELECT SHORT_NAME,DIRECTOR,GLAV_BUHG,OKPO FROM Z_SETUP'; DSetGrSheet.SQLs.SelectSQL.Text := 'SELECT * FROM UV_PRINT_SHEETONE('+IntToStr(AId)+', '+IntToStr(PTypePrint)+')'; if PTypePrint<3 then DSetSheet.SQLs.SelectSQL.Text := 'SELECT * FROM UV_PRINT_SHEETONE_DATA(?ID_GRSHEET,1) ORDER BY TN' else DSetSheet.SQLs.SelectSQL.Text := 'SELECT * FROM UV_PRINT_SHEETONE_DATA('+IntToStr(AId)+',2) ORDER BY TN'; end; procedure TFPrintVed.FormCreate(Sender: TObject); var IniFile:TIniFile; ViewMode:byte; PathReport:string; _summa:Extended; FormTerms:TFTermsSheetPrint; MR:TModalResult; begin MR:=mrYes; if PTypePrint=3 then begin FormTerms:=TFTermsSheetPrint.Create(self); MR:=FormTerms.ShowModal; end; if MR=mrYes then begin DSetSetup.Open; DSetGrSheet.Open; DSetSheet.Open; If (DSetSetup.IsEmpty) or (DSetSheet.IsEmpty) or (DSetGrSheet.IsEmpty) then PResault := 'Error' else begin DSetSheet.First; _summa:=0; while not DSetSheet.Eof do begin _summa:=_summa+DSetSheet.FieldValues['SUMMA']; DSetSheet.Next; end; PResault := Null; IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports); case PTypePrint of 1: begin ViewMode:=IniFile.ReadInteger(SectionSheetOfIniFile,'ViewMode',1); PathReport:=IniFile.ReadString(SectionSheetOfIniFile,'NameReport','Reports\GrSheetOne.fr3'); end; 2: begin ViewMode:=IniFile.ReadInteger(SectionReeSheetsOfIniFile,'ViewMode',1); PathReport:=IniFile.ReadString(SectionReeSheetsOfIniFile,'NameReport','Reports\GrSheetsForReestr.fr3'); end; 3: begin ViewMode:=IniFile.ReadInteger(SectionSheetReeOfIniFile,'ViewMode',1); PathReport:=IniFile.ReadString(SectionSheetReeOfIniFile,'NameReport','Reports\PlatSheetForReestr.fr3'); end; end; try frxReport.Clear; frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True); frxReport.Variables['RPageOfPages'] := ''''+UV_SheetPrint_RPageOfPages_Text+''''; frxReport.Variables['RPage'] := ''''+UV_SheetPrint_RPage_Text+''''; frxReport.Variables['RHeaderPost'] := ''''+UV_SheetPrint_RHeaderPost_Text+''''; frxReport.Variables['RMoneyPost'] := ''''+UV_SheetPrint_RMoneyPost_Text+''''; frxReport.Variables['RSheet'] := ''''+UV_SheetPrint_RSheet_Text+ifthen(PTypePrint=3,' №''',''''); frxReport.Variables['RFromMonth'] := ''''+UV_SheetPrint_RFromMonth_Text+ '<b>'+KodSetupToPeriod(DSetGrSheet.FieldValues['KOD_SETUP'],2)+'</b>'''; frxReport.Variables['RFio'] := ''''+UV_SheetPrint_RFio_Text+''''; frxReport.Variables['RNumMan'] := ''''+UV_SheetPrint_RNumMan_Text+''''; frxReport.Variables['RTn'] := ''''+UV_SheetPrint_RTn_Text+''''; frxReport.Variables['RSumma'] := ''''+UV_SheetPrint_RSumma_Text+''''; frxReport.Variables['RSignature'] := ''''+UV_SheetPrint_RSignature_Text+''''; frxReport.Variables['RStBuhg'] := ''''+UV_SheetPrint_RStBuhg_Text+''''; frxReport.Variables['RPeoplePC'] := ''''+UV_SheetPrint_RPeoplePC_Text+''''; frxReport.Variables['RVidano'] := ''''+UV_SheetPrint_RVidano_Text+''''; frxReport.Variables['RDeponir'] := ''''+UV_SheetPrint_RDeponir_Text+''''; frxReport.Variables['Rraznoe'] := ''''+UV_SheetPrint_Rraznoe_Text+''''; frxReport.Variables['RSumOnList'] := ''''+UV_SheetPrint_RSumOnList_Text+''''; frxReport.Variables['RSumOnReport'] := ''''+UV_SheetPrint_RSumOnReport_Text+''''; if PTypePrint=3 then begin frxReport.Variables['RSum'] := ''''+UV_SheetPrint_RSum_Text+''''; frxReport.Variables['RSumOnReport'] := ''''+UV_SheetPrint_RSumOnReport_Text+''''; frxReport.Variables['RIdKod'] := ''''+UV_SheetPrint_RIdKod_Text+''''; frxReport.Variables['RKassaOnVipl'] := ''''+UV_SheetPrint_RKassaOnVipl_Text+FormTerms.DateFrom.Text+UV_SheetPrint_RKassaOnViplTo_Text+FormTerms.DateTo.Text+''''; frxReport.Variables['RKassaSumma'] := ''''+UV_SheetPrint_RKassaSumma_Text+VarToStr(DSetGrSheet['GRSUMMA'])+''''; frxReport.Variables['RKassaOrder'] := ''''+UV_SheetPrint_RKassaOrder_Text+''''; frxReport.Variables['RBuhgVipl'] := ''''+UV_SheetPrint_RBuhgVipl_Text+''''; frxReport.Variables['RBuhgProv'] := ''''+UV_SheetPrint_RBuhgProv_Text+''''; frxReport.Variables['ROnViplata'] := ''''+UV_SheetPrint_ROnViplata_Text+UV_SheetPrint_RFromMonth_Text+ KodSetupToPeriod(DSetGrSheet.FieldValues['KOD_SETUP'],2)+''''; end; // frxReport.Variables['RSumLetters'] := '''''';//+SumToString(_summa,1,False)+''''; //************************************************************************** case ViewMode of 1: frxReport.ShowReport; 2: frxReport.DesignReport; end; except on E:Exception do MessageBox(self.Handle,PChar(E.Message),PChar(CaptionError),mb_ok+MB_ICONERROR); end; frxReport.Free; end; end else PResault:=NULL; end; procedure TFPrintVed.FormClose(Sender: TObject; var Action: TCloseAction); begin if ReadTransaction.InTransaction then ReadTransaction.Commit; end; procedure TFPrintVed.frxReportGetValue(const VarName: String; var Value: Variant); begin if UpperCase(VarName)='RSUMLETTERS' then Value:=SumToString(DSetGrSheet['GRSUMMA'],1); end; end.
unit LoginScreen.View.Styles.Colors; interface uses Vcl.ExtCtrls; type TStyles = class public H1, H2, H3, H4 : integer; MOVE_BUTTON_COLOR, PANELCOLOR: integer; procedure PANEL_COLOR(Value: Integer; Panel: TPanel); procedure SHAPE_COLOR(Value: Integer; Shape: TShape); constructor Create; private end; implementation { TColor } constructor TStyles.Create; begin PANELCOLOR := $00DA8E49; MOVE_BUTTON_COLOR := $00DCA847; H1 := 20; H2 := 18; H3 := 14; H4 := 12; inherited end; procedure TStyles.PANEL_COLOR(Value: Integer; Panel: TPanel); begin Panel.Color := Value; end; procedure TStyles.SHAPE_COLOR(Value: Integer; Shape: TShape); begin Shape.Brush.Color := Value; Shape.Pen.Color := Value; end; end.
{ @abstract Implements classes that are used when performing runtime language switch. } unit NtBaseTranslator; {$I NtVer.inc} interface uses SysUtils, Classes, TypInfo, NtBase; const { All string types. } STRING_TYPES = [ //FI:O803 tkString, tkLString, tkWString {$IFDEF UNICODE} , tkUString {$ENDIF} ]; type TNtBaseTranslator = class; { This event is called before translating a property value. @param host Either form or data module where the object belongs to. @param obj Component or a sub component that is currenty being translated. @param propertyInfo Property info. @param currentValue Current value of the property. @param newValue New value of the property. Change it if you want to use different value. @param cancel Set True if you want to cancel the translation. } TNtBeforeTranslateEvent = procedure( host: TComponent; obj: TObject; propertyInfo: PPropInfo; const currentValue: Variant; var newValue: Variant; var cancel: Boolean); { This event is called before translating a property value. @param translator Instance of translator that is performing the translation. @param host Either form or data module where the object belongs to. @param component Component that is current being translated. @param obj Component or a sub component that is currenty being translated. @param propertyInfo Property info. @param currentValue Current value of the property. @param newValue New value of the property. Change it if you want to use different value. @param cancel Set True if you want to cancel the translation. } TNtBeforeTranslateEventEx = procedure( translator: TNtBaseTranslator; host: TComponent; component: TComponent; obj: TObject; propertyInfo: PPropInfo; const currentValue: Variant; var newValue: Variant; var cancel: Boolean); { This event is called after translating a property value. @param host Either form or data module where the object belongs to. @param obj Component or a sub component that was translated. @param propertyInfo Property info. } TNtAfterTranslateEvent = procedure( host: TComponent; obj: TObject; propertyInfo: PPropInfo); { @abstract Abstract translator class. } TNtBaseTranslator = class(TObject) private FCurrent: TComponent; FHost: TComponent; FIndex: Integer; FName: String; FObj: TObject; FPropertyName: String; FPropInfo: PPropInfo; FReader: TReader; FSubName: String; FUnnamedTypes: TStringList; FTranslateLayout: Boolean; function GetTypeInfo: PTypeInfo; {$IFDEF DELPHIXE} function ProcessBinary: TBytes; {$ELSE} function ProcessBinary: AnsiString; {$ENDIF} procedure ProcessBytes(count: Integer); procedure ProcessCollection; procedure ProcessComponent(parent: TComponent; root: Boolean); procedure ProcessList; procedure ProcessProperty(obj: TObject); procedure ProcessSet; procedure ProcessPropertyValue; function GetPropValue(instance: TObject): Variant; procedure SetPropValue(instance: TObject; const value: Variant); property TypeInfo: PTypeInfo read GetTypeInfo; protected procedure AfterProcessComponent(component: TComponent); virtual; function DoTranslate(component: TComponent; resourceName: String = ''): Boolean; procedure Translate(component: TComponent); virtual; constructor Create; property TranslateLayout: Boolean read FTranslateLayout write FTranslateLayout; public destructor Destroy; override; class function IsString(varType: TVarType): Boolean; end; { @abstract Class that extends @link(TNtTranslator). @link(TNtTranslator) can translate all normal properties but can not translate complex properties. A complex property is either a property that contains a string list, defined property or defined binary property. Defined properties can contain anything and the format can either be the same as normal properties (defined property) or propiertary binary format (defined binary property). In either case @link(TNtTranslator) does not know the format can not either read it or map the data into the real properties of the object. This is where translator extensions are used. An translator extension is derived from TNtTranslatorExtension class and it implements translations of a defined property of a component. For example @link(TNtPictureTranslator) translation the binary image data of the TPicture. If you have a 3rd party component that does not translate you may have to implement an extension for it. Derive your extension from this class and implement @link(TNtTranslatorExtension.Translate) function. You may also have to implement @link(TNtTranslatorExtension.GetActualObject) and/or @link(TNtTranslatorExtension.GetActualName) functions. @seealso(TNtStringsTranslator) @seealso(TNtPictureTranslator) @seealso(TNtTreeViewTranslator) @seealso(TNtListViewTranslator) @seealso(TNtShortcutItemsTranslator) @seealso(TNtVirtualTreeViewTranslator) } TNtTranslatorExtension = class(TNtExtension) public { Checks if the extension can translate the object. @param obj The object to be transalted. @return @true if the object can be translated, @false if not. } function CanTranslate(obj: TObject): Boolean; virtual; abstract; { An abstract function that translate the comple property. Each extension class has to implement this function. @param component The component where the property belongs to. @param obj The object where the property belongs to. @param name The name of the property. @param value The value of the property. @param index The index of the item if the value is an array value. } procedure Translate( component: TComponent; obj: TObject; const name: String; value: Variant; index: Integer); virtual; abstract; { Get the runtime object of a resource property. @param obj Object that contains the property in the form file. @param propName Name of the property in the form file. @return Object. } function GetActualObject(obj: TObject; const propName: String): TObject; virtual; { Get the runtime property name of a resource property. @param obj Object that contains the property in the form file. @param propName Name of the property in the form file. @return Property name. } function GetActualName(obj: TObject; const propName: String): String; virtual; end; { Class type of the translator extension class. } TNtTranslatorExtensionClass = class of TNtTranslatorExtension; { @abstract Extension class that translates TStrings objects. } TNtStringsTranslator = class(TNtTranslatorExtension) public { @seealso(TNtTranslatorExtension.CanTranslate) } function CanTranslate(obj: TObject): Boolean; override; { @seealso(TNtTranslatorExtension.Translate) } procedure Translate( component: TComponent; obj: TObject; const name: String; value: Variant; index: Integer); override; end; { @abstract Class that stores installed extension. If you derive a new extension from @link(TNtExtension) you have to register it in order to take it in use. A good place to register an extension is to call the @link(TNtExtensions.Register) in the initialization block of your extension class unit. @longCode(# initialization NtExtensions.Register(TYourExtension); end. #) } TNtTranslatorExtensions = class(TNtExtensions) private function GetItem(i: Integer): TNtTranslatorExtension; function CanTranslate(obj: TObject; var extension: TNtTranslatorExtension): Boolean; function GetActualObject(obj: TObject; const propName: String): TObject; function GetActualName(obj: TObject; const propName: String): String; public { Array of the registered extension. } property Items[i: Integer]: TNtTranslatorExtension read GetItem; default; end; { @abstract Binary stream class that read integer and strings values. This class extends TMemoryStream to provide function to read integer, pointer and strings values. } TNtStream = class(TMemoryStream) public { Creates a binary stream. } {$IFDEF DELPHIXE} constructor Create(value: TBytes); {$ELSE} constructor Create(value: AnsiString); {$ENDIF} { Read one byte. @return The byte value that was read. } function ReadByte: Byte; { Read one word. @return The word value that was read. } function ReadWord: Word; { Read one integer. @return The integer value that was read. } function ReadInteger: Integer; { Read one pointer. @return The pointer value that was read. } function ReadPointer: Pointer; { Read string Ansi string. @return The string that was read. } {$IFDEF DELPHIXE} function ReadShortString: TBytes; {$ELSE} function ReadShortString: AnsiString; {$ENDIF} { Read string Unicode string. @return The string that was read. } function ReadShortUnicodeString: UnicodeString; end; var { Set of types that are translated. If empty then all properties are translated. If not empty then only those properties whose type is include in this set are translated. The following sample shows how to translate only string properties. @longCode(# unit Unit1; ... initialization NtEnabledProperties := STRING_TYPES; end.#) } NtEnabledProperties: TTypeKinds; { If @true the form position (Left and Top properties) is also translated (e.g. changed if the new resource file contains different Left or Top properties). If @false postion is not changed. } NtFormPositionTranslationEnabled: Boolean; { If @true data modiles are also translated If @false data modules are not translated. } NtTranslateDataModules: Boolean; { An event that is called before translating a property value. Use this to disable or change the translation process. If you assign this value, make sure that the event is as fast as possible because this event is called on every single property of the application. See @italic(Samples\Delphi\VCL\DualLanguage) sample to see how to use the event. @seealso(NtAfterTranslate) } NtBeforeTranslate: TNtBeforeTranslateEvent; { An event that is called before translating a property value. Use this to disable or change the translation process. If you assign this value, make sure that the event is as fast as possible because this event is called on every single property of the application. See @italic(Samples\Delphi\VCL\DualLanguage) sample to see how to use the event. @seealso(NtAfterTranslate) } NtBeforeTranslateEx: TNtBeforeTranslateEventEx; { Event that is called after a property value has been translated. If you assing this value make sure that the event is as fast as possible because this event is called on every single property of the application. @seealso(NtBeforeTranslate) } NtAfterTranslate: TNtAfterTranslateEvent; { Collections of registered extensions. Use it to register your custom extension. @longCode(# unit MyExtension; ... initialization NtTranslatorExtensions.Register(TMyExtension); end.#) } NtTranslatorExtensions: TNtTranslatorExtensions; implementation uses {$IFDEF DELPHI_FMX} Types, {$ELSE} Windows, ActnList, {$ENDIF} {$IFDEF DELPHIXE} NtResource, {$ENDIF} SysConst, Variants; // TNtBaseTranslator constructor TNtBaseTranslator.Create; begin inherited; FUnnamedTypes := TStringList.Create; end; destructor TNtBaseTranslator.Destroy; begin FUnnamedTypes.Free; inherited; end; function TNtBaseTranslator.GetTypeInfo: PTypeInfo; begin if (FPropInfo <> nil) and (FPropInfo.PropType <> nil) then Result := FPropInfo.PropType^ else Result := nil; end; {$IFDEF DELPHIXE} function TNtBaseTranslator.ProcessBinary: TBytes; var size: Integer; begin FReader.ReadValue; FReader.Read(size, SizeOf(size)); if size > 0 then begin SetLength(Result, size); FReader.Read(Result[0], Length(Result)); end else SetLength(Result, 0); end; {$ELSE} function TNtBaseTranslator.ProcessBinary: AnsiString; var size: Integer; begin FReader.ReadValue; FReader.Read(size, SizeOf(size)); if size > 0 then begin SetLength(Result, size); FReader.Read(PAnsiChar(Result)^, Length(Result)); end else Result := ''; end; {$ENDIF} procedure TNtBaseTranslator.ProcessBytes(count: Integer); {$IFDEF DELPHIXE} var data: TBytes; begin FReader.ReadValue; if count > 0 then begin SetLength(data, count); FReader.Read(data[0], count); end; {$ELSE} var data: AnsiString; begin FReader.ReadValue; if count > 0 then begin SetLength(data, count); FReader.Read(PAnsiChar(data)^, count); end; {$ENDIF} end; procedure TNtBaseTranslator.ProcessCollection; var i: Integer; thisObj, actualObj: TObject; propInfo: PPropInfo; item: TCollectionItem; collection: TCollection; begin //FI:C101 if (TypeInfo <> nil) and (TypeInfo.Kind <> tkClass) then raise Exception.Create('Error'); actualObj := FObj; if actualObj <> nil then begin propInfo := GetPropInfo(actualObj, FName); if (propInfo = nil) and (FSubName <> '') then propInfo := GetPropInfo(actualObj, FSubName); if (propInfo = nil) then begin thisObj := NtTranslatorExtensions.GetActualObject(actualObj, FName); if thisObj <> nil then begin actualObj := thisObj; propInfo := GetPropInfo(actualObj, FName); end; end; end else propInfo := nil; if propInfo <> nil then collection := TObject(GetOrdProp(actualObj, propInfo)) as TCollection else collection := nil; FReader.ReadValue; i := 0; while not FReader.EndOfList do begin if (collection <> nil) and (i < collection.Count) then item := collection.Items[i] else item := nil; if FReader.NextValue in [vaInt8, vaInt16, vaInt32] then FReader.ReadInteger; FReader.ReadListBegin; while not FReader.EndOfList do ProcessProperty(item); FReader.ReadListEnd; Inc(i); end; FReader.ReadListEnd; end; procedure TNtBaseTranslator.ProcessList; begin FReader.ReadListBegin; FIndex := 0; while not FReader.EndOfList do begin ProcessPropertyValue; Inc(FIndex); end; FReader.ReadListEnd; end; procedure TNtBaseTranslator.ProcessSet; var ident: String; begin FReader.ReadValue; while True do begin ident := FReader.ReadStr; if ident = '' then Break; end; end; {$IFDEF DELPHIXE3} function InternalGetPropInfo(typeInfo: PTypeInfo; const propName: String): PPropInfo; function AfterString(const p: PByte): Pointer; inline; begin Result := p + p^ + 1; end; var i: Integer; utf8Length: Integer; s1, s2: string; typeData: PTypeData; propData: PPropData; begin if typeInfo = nil then Exit(nil); s1 := PropName; utf8Length := Length(UTF8Encode(propName)); typeData := GetTypeData(typeInfo); while typeData <> nil do begin propData := typeData.PropData; Result := PPropInfo(@propData^.PropList); for i := 1 to propData^.PropCount do //FI:W528 begin if Result.NameFld.UTF8Length = UTF8Length then begin S2 := Result.NameFld.ToString;; if SameText(S1, S2) then Exit; end; Result := AfterString(@(Result^.Name)); end; if TypeData^.ParentInfo = nil then TypeData := nil else TypeData := GetTypeData(TypeData^.ParentInfo^); end; Result := nil; end; function DoesPropertyExists(Instance: TObject; const PropName: string): Boolean; begin Result := InternalGetPropInfo(PTypeInfo(Instance.ClassInfo), PropName) <> nil; end; {$ENDIF} procedure TNtBaseTranslator.ProcessProperty(obj: TObject); var p: Integer; propName, actualName: String; objNames: TStringList; i: Integer; begin //FI:C101 FPropertyName := FReader.ReadStr; FName := FPropertyName; FSubName := ''; FObj := obj; if FObj <> nil then begin FPropInfo := GetPropInfo(FObj, FName); if FPropInfo = nil then begin p := Pos('.', FName); if p > 0 then begin objNames := TStringList.Create; try propName := FName; while p > 0 do begin objNames.Add(Copy(propName, 1, p - 1)); Delete(propName, 1, p); p := Pos('.', propName); end; for i := 0 to objNames.Count - 1 do begin {$IFDEF DELPHIXE3} if DoesPropertyExists(FObj, objNames[i]) then {$ENDIF} begin FObj := TObject(GetOrdProp(FObj, objNames[i])); if FObj = nil then Break; end; end; if FObj <> nil then begin FSubName := propName; FPropInfo := GetPropInfo(FObj, propName); end; finally objNames.Free; end; end else begin actualName := NtTranslatorExtensions.GetActualName(FObj, FName); if (actualName <> '') and (actualName <> FName) then FPropInfo := GetPropInfo(FObj, actualName); end; end; end else FPropInfo := nil; ProcessPropertyValue; end; function TNtBaseTranslator.GetPropValue(instance: TObject): Variant; {$IFDEF DELPHI2005} var dynArray: Pointer; {$ENDIF} begin //FI:C101 Result := Null; case FPropInfo^.PropType^^.Kind of tkInteger, tkClass: Result := GetOrdProp(instance, FPropInfo); tkChar: Result := Char(GetOrdProp(instance, FPropInfo)); tkWChar: Result := WideChar(GetOrdProp(instance, FPropInfo)); tkEnumeration: if GetTypeData(FPropInfo^.PropType^)^.BaseType^ = System.TypeInfo(Boolean) then Result := Boolean(GetOrdProp(instance, FPropInfo)) else Result := GetOrdProp(instance, FPropInfo); tkSet: Result := GetOrdProp(Instance, FPropInfo); tkFloat: Result := GetFloatProp(Instance, FPropInfo); tkMethod: Result := FPropInfo^.PropType^.Name; tkString, tkLString: Result := GetStrProp(instance, FPropInfo); tkWString: {$IFNDEF NEXTGEN} Result := GetWideStrProp(instance, FPropInfo); {$ELSE} Result := GetStrProp(instance, FPropInfo); {$ENDIF} {$IFDEF UNICODE} tkUString: {$IFNDEF NEXTGEN} {$IFDEF DELPHIDX2} Result := GetStrProp(instance, FPropInfo); {$ELSE} Result := GetUnicodeStrProp(instance, FPropInfo); {$ENDIF} {$ELSE} Result := GetStrProp(instance, FPropInfo); {$ENDIF} {$ENDIF} tkVariant: Result := GetVariantProp(instance, FPropInfo); tkInt64: Result := GetInt64Prop(instance, FPropInfo); tkDynArray: begin {$IFDEF DELPHI2005} DynArray := GetDynArrayProp(instance, FPropInfo); DynArrayToVariant(Result, dynArray, FPropInfo^.PropType^); {$ELSE} DynArrayToVariant(Result, Pointer(GetOrdProp(instance, FPropInfo)), FPropInfo^.PropType^); {$ENDIF} end; end; end; class function TNtBaseTranslator.IsString(varType: TVarType): Boolean; begin Result := (varType = varString) or {$IFDEF UNICODE} (varType = varUString) or {$ENDIF} (varType = varOleStr); end; procedure TNtBaseTranslator.SetPropValue( instance: TObject; const value: Variant); procedure RangeError; begin raise ERangeError.CreateRes(@SRangeError); end; function RangedValue(const aMin, aMax: Int64): Int64; begin Result := Trunc(value); if (Result < aMin) or (Result > aMax) then RangeError; end; function RangedCharValue(const aMin, aMax: Int64): Int64; var ansi: String; wide: String; begin case VarType(value) of varString: begin ansi := value; if Length(ansi) = 1 then {$IFDEF DELPHIXE3} Result := Ord(ansi[Low(String)]) {$ELSE} Result := Ord(ansi[1]) {$ENDIF} else Result := aMin - 1; end; {$IFDEF UNICODE} varUString, {$ENDIF} varOleStr: begin wide := value; if Length(wide) = 1 then {$IFDEF DELPHIXE3} Result := Integer(wide[Low(String)]) {$ELSE} Result := Integer(wide[1]) {$ENDIF} else Result := aMin - 1; end; else Result := Trunc(value); end; if (Result < aMin) or (Result > aMax) then RangeError; end; var typeData: PTypeData; dynArray: Pointer; {$IFNDEF DELPHI2006} oldFarEast: Boolean; {$ENDIF} begin //FI:C101 typeData := GetTypeData(FPropInfo^.PropType^); {$IFNDEF DELPHI2006} oldFarEast := SysLocale.FarEast; if instance is TAction then SysLocale.FarEast := True; {$ENDIF} case FPropInfo.PropType^^.Kind of tkString, tkLString: SetStrProp(instance, FPropInfo, VarToStr(value)); tkWString: {$IFNDEF NEXTGEN} SetWideStrProp(instance, FPropInfo, VarToWideStr(value)); {$ELSE} SetStrProp(instance, FPropInfo, VarToStr(value)); {$ENDIF} {$IFDEF UNICODE} tkUString: {$IFNDEF NEXTGEN} {$IFDEF DELPHIDX2} SetStrProp(instance, FPropInfo, VarToStr(value)); {$ELSE} SetUnicodeStrProp(instance, FPropInfo, VarToWideStr(value)); {$ENDIF} {$ELSE} SetStrProp(instance, FPropInfo, VarToStr(value)); {$ENDIF} {$ENDIF} tkChar, tkWChar: SetOrdProp( instance, FPropInfo, RangedCharValue(typeData^.MinValue, typeData^.MaxValue)); tkInteger: if typeData^.MinValue < typeData^.MaxValue then SetOrdProp( instance, FPropInfo, RangedValue(typeData^.MinValue, typeData^.MaxValue)) else SetOrdProp( instance, FPropInfo, RangedValue(LongWord(typeData^.MinValue), LongWord(typeData^.MaxValue))); tkInt64: SetInt64Prop( instance, FPropInfo, RangedValue(typeData^.MinInt64Value, typeData^.MaxInt64Value)); tkFloat: SetFloatProp(instance, FPropInfo, value); tkEnumeration: if IsString(value) then SetEnumProp(instance, FPropInfo, VarToStr(value)) else if VarType(value) = varBoolean then SetOrdProp(instance, FPropInfo, Abs(Trunc(value))) else SetOrdProp(instance, FPropInfo, RangedValue(typeData^.MinValue, typeData^.MaxValue)); tkSet: if VarType(value) = varInteger then SetOrdProp(instance, FPropInfo, value) else SetSetProp(instance, FPropInfo, VarToStr(value)); tkVariant: SetVariantProp(instance, FPropInfo, value); tkDynArray: begin dynArray := nil; DynArrayFromVariant(dynArray, value, FPropInfo^.PropType^); SetOrdProp(instance, FPropInfo, NativeInt(dynArray)); end; end; {$IFNDEF DELPHI2006} if instance is TAction then SysLocale.FarEast := oldFarEast; {$ENDIF} end; procedure TNtBaseTranslator.ProcessPropertyValue; var current, value: Variant; function TypesEqual: Boolean; var currentType, newType: TVarType; begin currentType := VarType(current); newType := VarType(value); Result := (currentType = newType) or (IsString(currentType) and IsString(newType)); end; function IgnoreByEvent: Boolean; begin Result := False; if Assigned(NtBeforeTranslateEx) then NtBeforeTranslateEx(Self, FHost, FCurrent, FObj, FPropInfo, current, value, Result); if Assigned(NtBeforeTranslate) then NtBeforeTranslate(FHost, FObj, FPropInfo, current, value, Result); end; procedure AfterTranslate; begin if Assigned(NtAfterTranslate) then NtAfterTranslate(FHost, FObj, FPropInfo); end; function IgnoreProperty: Boolean; var typeKind: TypInfo.TTypeKind; begin if (FName = 'Font.Charset') or (NtEnabledProperties = []) then Result := False else begin if FPropInfo <> nil then typeKind := FPropInfo.PropType^.Kind else typeKind := tkLString; if FTranslateLayout and (typeKind in [tkInteger]) then Result := False else Result := not (typeKind in NtEnabledProperties); end; if Result then Exit; if FObj = FHost then Result := (FName = 'Visible') or ( not NtFormPositionTranslationEnabled and ((FName = 'Position') or (FName = 'Left') or (FName = 'Top')) ) else Result := (FName = 'ConnectionString'); if Result then Exit; Result := IgnoreByEvent; end; var int: Integer; str: String; identToInt: TIdentToInt; extension: TNtTranslatorExtension; begin //FI:C101 case FReader.NextValue of vaNull: FReader.ReadValue; vaList: ProcessList; vaCollection: ProcessCollection; vaBinary: value := ProcessBinary; vaSet: ProcessSet; vaIdent: begin str := FReader.ReadIdent; if TypeInfo <> nil then begin case TypeInfo.Kind of tkEnumeration: value := GetEnumValue(TypeInfo, str); tkInteger: begin identToInt := FindIdentToInt(TypeInfo); if Assigned(identToInt) and IdentToInt(str, int) then value := int; end; end; end; end; vaInt8, vaInt16, vaInt32: value := FReader.ReadInteger; vaExtended: value := FReader.ReadFloat; vaSingle: value := FReader.ReadSingle; vaString, vaLString: value := FReader.ReadString; vaWString: {$IFDEF DELPHIXE3} value := FReader.ReadString; {$ELSE} value := FReader.ReadWideString; {$ENDIF} vaFalse, vaTrue: value := FReader.ReadBoolean; vaNil: ProcessBytes(0); vaCurrency: value := FReader.ReadCurrency; vaDate: ProcessBytes(Sizeof(TDateTime)); vaInt64: ProcessBytes(Sizeof(Int64)); vaUTF8String: {$IFDEF DELPHIXE3} value := FReader.ReadString; {$ELSE} value := FReader.ReadWideString; {$ENDIF} {$IFDEF DELPHI2005} vaDouble: value := FReader.ReadDouble; {$ENDIF} else raise Exception.Create('Unknown TValueType'); end; if not VarIsNull(value) and not VarIsEmpty(value) then begin if FPropInfo <> nil then begin try current := GetPropValue(FObj); if FObj.ClassName = 'TFieldDef' then begin FObj := FObj; end; if TypesEqual and (current <> value) and not IgnoreProperty then begin SetPropValue(FObj, value); AfterTranslate; end; except on e: Exception do raise Exception.CreateFmt('Could not translate %s.%s from "%s" to "%s": %s', [FObj.ClassName, FName, current, value, e.Message]); end; end else if NtTranslatorExtensions.CanTranslate(FObj, extension) then begin if not IgnoreByEvent then begin extension.Translate(FCurrent, FObj, FPropertyName, value, FIndex); AfterTranslate; end; end; end; end; procedure TNtBaseTranslator.AfterProcessComponent(component: TComponent); begin end; procedure TNtBaseTranslator.ProcessComponent(parent: TComponent; root: Boolean); function FindUnnamedComponent( parent: TComponent; const typeName: String; index: Integer): TComponent; var i, thisIndex: Integer; component: TComponent; begin Result := nil; thisIndex := 0; for i := 0 to parent.ComponentCount - 1 do begin component := parent.Components[i]; if (component.Name = '') and (component.ClassName = typeName) then begin if thisIndex = index then begin Result := component; Break; end; Inc(thisIndex); end; end; end; var i, childPos, index: Integer; typeName, componentName: String; flags: TFilerFlags; thisComponent: TComponent; begin FReader.ReadPrefix(flags, childPos); typeName := FReader.ReadStr; componentName := FReader.ReadStr; if root then thisComponent := FHost else if parent = nil then thisComponent := nil else if componentName = '' then begin index := 0; for i := 0 to FUnnamedTypes.Count - 1 do if FUnnamedTypes[i] = typeName then Inc(index); FUnnamedTypes.Add(typeName); thisComponent := FindUnnamedComponent(parent, typeName, index); if thisComponent = nil then thisComponent := FindUnnamedComponent(FHost, typeName, index); end else begin thisComponent := parent.FindComponent(componentName); if thisComponent = nil then thisComponent := FHost.FindComponent(componentName); end; FCurrent := thisComponent; while not FReader.EndOfList do ProcessProperty(thisComponent); FReader.ReadListEnd; while not FReader.EndOfList do ProcessComponent(thisComponent, False); FReader.ReadListEnd; AfterProcessComponent(thisComponent); end; function FindInstance(classType: TClass): THandle; begin Result := FindResourceHInstance(FindClassHInstance(classType)); end; function TNtBaseTranslator.DoTranslate(component: TComponent; resourceName: String): Boolean; var instance: THandle; header: array[0..3] of Byte; stream: TStream; begin Result := False; FHost := component; if resourceName = '' then resourceName := component.ClassName; instance := FindInstance(component.ClassType); if FindResource(instance, PChar(resourceName), RT_RCDATA) <> 0 then begin {$IFDEF DELPHIXE} stream := NtResources.FindForm(resourceName); {$ELSE} stream := nil; {$ENDIF} if stream = nil then stream := TResourceStream.Create(instance, PChar(resourceName), RT_RCDATA); FReader := TReader.Create(stream, stream.Size); try FReader.Read(header, 4); if CompareMem(@VCL_FORM_HEADER, @header[0], Length(VCL_FORM_HEADER)) then begin ProcessComponent(nil, True); Result := True; end; finally FReader.Free; stream.Free; end; end; end; procedure TNtBaseTranslator.Translate(component: TComponent); function DoesResourceExists(classType: TClass): Boolean; var resourceName: String; begin resourceName := classType.ClassName; {$IFDEF DELPHIXE} if NtResources.Count > 0 then begin Result := NtResources.FormExists(resourceName); if Result then Exit; end; {$ENDIF} Result := FindResource(FindInstance(classType), PChar(resourceName), RT_RCDATA) <> 0; end; var i: Integer; thisClass: TClass; names: TStringList; begin names := TStringList.Create; try thisClass := component.ClassType; while DoesResourceExists(thisClass) do begin names.Insert(0, thisClass.ClassName); thisClass := thisClass.ClassParent; end; for i := 0 to names.Count - 1 do DoTranslate(component, names[i]); finally names.Free; end; end; // TNtTranslatorExtension function TNtTranslatorExtension.GetActualObject(obj: TObject; const propName: String): TObject; begin Result := nil; end; function TNtTranslatorExtension.GetActualName(obj: TObject; const propName: String): String; begin Result := ''; end; // TNtStringsTranslator function TNtStringsTranslator.CanTranslate(obj: TObject): Boolean; begin Result := obj is TStrings; end; procedure TNtStringsTranslator.Translate( component: TComponent; obj: TObject; const name: String; value: Variant; index: Integer); const ITEM_INDEX = 'ItemIndex'; var oldItemIndex: Integer; strings: TStrings; begin strings := obj as TStrings; if index >= strings.Count then Exit; if IsPublishedProp(component, ITEM_INDEX) then oldItemIndex := GetOrdProp(component, ITEM_INDEX) else oldItemIndex := -2; strings[index] := value; if oldItemIndex >= -1 then SetOrdProp(component, ITEM_INDEX, oldItemIndex); end; // TNtTranslatorExtensions function TNtTranslatorExtensions.GetItem(i: Integer): TNtTranslatorExtension; begin Result := inherited Items[i] as TNtTranslatorExtension; end; function TNtTranslatorExtensions.CanTranslate(obj: TObject; var extension: TNtTranslatorExtension): Boolean; var i: Integer; begin for i := 0 to Count - 1 do begin extension := Items[i]; Result := extension.CanTranslate(obj); if Result then Exit; end; extension := nil; Result := False; end; function TNtTranslatorExtensions.GetActualObject( obj: TObject; const propName: String): TObject; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i].GetActualObject(obj, propName); if Result <> nil then Exit; end; Result := nil; end; function TNtTranslatorExtensions.GetActualName(obj: TObject; const propName: String): String; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i].GetActualName(obj, propName); if Result <> '' then Exit; end; Result := ''; end; // TNtStream {$IFDEF DELPHIXE} constructor TNtStream.Create(value: TBytes); begin inherited Create; if Length(value) > 0 then begin Write(value[0], Length(value)); Seek(0, TSeekOrigin.soBeginning); end; end; {$ELSE} constructor TNtStream.Create(value: AnsiString); begin inherited Create; if Length(value) > 0 then begin Write(PAnsiChar(value)^, Length(value)); Seek(0, soFromBeginning); end; end; {$ENDIF} function TNtStream.ReadByte: Byte; begin Read(Result, SizeOf(Result)); end; function TNtStream.ReadWord: Word; begin Read(Result, SizeOf(Result)); end; function TNtStream.ReadInteger: Integer; begin Read(Result, SizeOf(Result)); end; function TNtStream.ReadPointer: Pointer; begin Read(Result, SizeOf(Result)); end; {$IFDEF DELPHIXE} function TNtStream.ReadShortString: TBytes; var size: Byte; begin Read(size, SizeOf(size)); SetLength(Result, size); Read(Result[0], size); end; {$ELSE} function TNtStream.ReadShortString: AnsiString; var size: Byte; begin Read(size, SizeOf(size)); SetLength(Result, size); Read(PAnsiChar(Result)^, size); end; {$ENDIF} function TNtStream.ReadShortUnicodeString: UnicodeString; var size: Byte; begin Read(size, SizeOf(size)); SetLength(Result, size); Read(PWideChar(Result)^, 2*size); end; initialization NtEnabledProperties := []; NtFormPositionTranslationEnabled := False; NtTranslateDataModules := True; NtBeforeTranslate := nil; NtAfterTranslate := nil; NtTranslatorExtensions := TNtTranslatorExtensions.Create; NtTranslatorExtensions.Register(TNtStringsTranslator); finalization NtTranslatorExtensions.Free; end.
procedure Clear; var t: TRttiType; prop: TRttiProperty; begin t := TRttiContext.Create.GetType(Self.ClassType); for prop in t.GetProperties do begin if not prop.IsWritable then Continue; case prop.PropertyType.TypeKind of tkInteger, tkInt64, tkFloat: prop.SetValue(Self, 0); tkString, tkUString, tkWString: prop.SetValue(Self, ''); end; end; end;
unit KeyCodeToKeyName; interface uses W3System; function CodeToKeyName(KeyCode : integer) : string; implementation //Used to get key name from a key code, meaning it will show you your controls //with proper key names, not just the numbered key codes function CodeToKeyName(KeyCode : integer) : string; begin case KeyCode of 8 : Exit("Backspace"); 9 : Exit("Tab"); 13 : Exit("Enter"); 16 : Exit("Shift"); 17 : Exit("Ctrl"); 18 : Exit("Alt"); 19 : Exit("Pause/Break"); 20 : Exit("Caps Lock"); 27 : Exit("Escape"); 32 : Exit("Space"); 33 : Exit("Page Up"); 34 : Exit("Page Down"); 35 : Exit("End"); 36 : Exit("Home"); 37 : Exit("Left Arrow"); 38 : Exit("Up Arrow"); 39 : Exit("Right Arrow"); 40 : Exit("Down Arrow"); 45 : Exit("Insert"); 46 : Exit("Delete"); 48 : Exit("0"); 49 : Exit("1"); 50 : Exit("2"); 51 : Exit("3"); 52 : Exit("4"); 53 : Exit("5"); 54 : Exit("6"); 55 : Exit("7"); 56 : Exit("8"); 57 : Exit("9"); 65 : Exit("A"); 66 : Exit("B"); 67 : Exit("C"); 68 : Exit("D"); 69 : Exit("E"); 70 : Exit("F"); 71 : Exit("G"); 72 : Exit("H"); 73 : Exit("I"); 74 : Exit("J"); 75 : Exit("K"); 76 : Exit("L"); 77 : Exit("M"); 78 : Exit("N"); 79 : Exit("O"); 80 : Exit("P"); 81 : Exit("Q"); 82 : Exit("R"); 83 : Exit("S"); 84 : Exit("T"); 85 : Exit("U"); 86 : Exit("V"); 87 : Exit("W"); 88 : Exit("X"); 89 : Exit("Y"); 90 : Exit("Z"); 91 : Exit("Left Window Key"); 92 : Exit("Right Window Key"); 93 : Exit("Select Key"); 96 : Exit("Numpad 0"); 97 : Exit("Numpad 1"); 98 : Exit("Numpad 2"); 99 : Exit("Numpad 3"); 100 : Exit("Numpad 4"); 101 : Exit("Numpad 5"); 102 : Exit("Numpad 6"); 103 : Exit("Numpad 7"); 104 : Exit("Numpad 8"); 105 : Exit("Numpad 9"); 106 : Exit("Multiply"); 107 : Exit("Add"); 109 : Exit("Subtract"); 110 : Exit("Decimal Point"); 111 : Exit("Divide"); 112 : Exit("F1"); 113 : Exit("F2"); 114 : Exit("F3"); 115 : Exit("F4"); 116 : Exit("F5"); 117 : Exit("F6"); 118 : Exit("F7"); 119 : Exit("F8"); 120 : Exit("F9"); 121 : Exit("F10"); 122 : Exit("F11"); 123 : Exit("F12"); 144 : Exit("Num Lock"); 145 : Exit("Scroll Lock"); 186 : Exit("Semi-Colon"); 187 : Exit("Equal Sign"); 188 : Exit("Comma"); 189 : Exit("Dash"); 190 : Exit("Full Stop"); 191 : Exit("Forward Slash"); 192 : Exit("Apostrophe"); 219 : Exit("Open Bracket"); 220 : Exit("Back Slash"); 221 : Exit("Close Braket"); 222 : Exit("Hash Tag"); else Exit(IntToStr(KeyCode)); //If it could not find it, send back the number end; end; end.
unit define_types; {$IFDEF Darwin} {$modeswitch objectivec1} {$ENDIF} interface {$ifndef isTerminalApp} uses graphics; {$endif} const {$include vers.inc} //kVers = 'v1.0.20210825'; NaN : double = 1/0; kTab = chr(9); kCR = chr (13); kDel = #127 ; // Delete kBS = #8 ; // Backspace kUNIXeoln = chr(10); {$IFDEF UNIX} //end of line kEOLN = kUNIXeoln; //Windows CRLF ; {$ELSE} kEOLN = #13#10; //Windows CRLF {$ENDIF} type TRGBA = packed record //Next: analyze Format Header structure R,G,B,A : byte; end; {$ifdef isTerminalApp} TColor = -$7FFFFFFF-1..$7FFFFFFF; TLUT = array [0..255] of TRGBA; {$endif} TPoint4f = packed record X: single; Y: single; Z: single; W: single end; TPoint3f = packed record X: single; Y: single; Z: single end; TPoint3i = packed record X: longint; //ensure 32-bit for simple GIfTI writing Y: longint; Z: longint; end; TFaces = array of TPoint3i; TVertices = array of TPoint3f; TVertexRGBA = array of TRGBA; TBools = array of boolean; TInts = array of integer; TUInt8s = array of uint8; TInt16s = array of int16; TUInt16s = array of uint16; TInt32s = array of int32; TFloats = array of single; TDoubles = array of double; TMat33 = array [1..3, 1..3] of single; TMat44 = array [1..4, 1..4] of single; TFByte = File of Byte; TStrRA = Array of String; TUnitRect = record L,T,R,B: single; end; function ParseFileName(Filename: string): string; procedure FilenameParts (lInName: string; out lPath,lName,lExt: string); procedure SensibleUnitRect (var U: TUnitRect); procedure SortSingle(var lLo,lHi: single); function RealToStr(lR: double; lDec: integer): string; function RGBA(lR,lG,lB,lA: byte): TRGBA; function CreateUnitRect (L,T,R,B: single) : TUnitRect; procedure IntBound (var lVal: integer; lMin, lMax: integer); function UnitBound (lS: single): single; //procedure ReadLnBin(var f: TFByte; var s: string); function ReadLnBin(var f: TFByte; var s: string): boolean; inline; procedure SwapSingle(var s : single); procedure SwapDouble(var d : double); procedure SwapLongInt(var s : LongInt); procedure SwapLongWord(var s : LongWord); function asPt4f(x,y,z,w: single): TPoint4f; function asSingle(i : longint): single; overload; function asSingle(b0,b1,b2,b3: byte): single; overload; function asInt(s : single): longint; function StrToFloatX(Const S : String) : Extended; function specialsingle (var s:single): boolean; //isFinite function ExtractFileExtGzUpper(FileName: string): string; function FileExistsF(fnm: string): boolean; //returns false if file exists but is directory function FSize (lFName: String): longint; function ChangeFileExtX( lFilename: string; lExt: string): string; function ReadNumBin(var f: TFByte): string; //read next ASCII number in binary file function float2str(Avalue:double; ADigits:integer):string; //e.g x:single=2.6; floattostrf(x,8,4); function DefaultToHomeDir(FileName: string; Force: boolean = false): string; //set path to home if not provided function UpCaseExt(lFileName: string): string; // "file.gii.dset" -> ".DSET" function UpCaseExt2(lFileName: string): string; // "file.gii.dset" -> ".GII.DSET" {$ifdef isTerminalApp} function RGBToColor(R, G, B: Byte): TColor; procedure ShowMessage(msg: string); function Red(rgb: TColor): BYTE; function Green(rgb: TColor): BYTE; function Blue(rgb: TColor): BYTE; {$else} function asRGBA(clr: TColor): TRGBA; {$endif} procedure Xswap4r ( var s:single); implementation uses {$IFDEF UNIX} BaseUnix, {$ELSE} windows, shlobj, {$ENDIF} {$IFDEF Darwin}CocoaAll,{$ENDIF} fileutil, sysutils, math; procedure Xswap4r ( var s:single); type swaptype = packed record case byte of 0:(Word1,Word2 : word); //word is 16 bit end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @s; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word2); outguy.Word2 := swap(inguy^.Word1); inguy^.Word1 := outguy.Word1; inguy^.Word2 := outguy.Word2; end; function UpCaseExt(lFileName: string): string; // "file.gii.dset" -> ".GII.DSET" var fnm : string; begin result := UpperCase(ExtractFileExt(lFileName)); end; function UpCaseExt2(lFileName: string): string; // "file.gii.dset" -> ".GII.DSET" var fnm : string; begin result := UpperCase(ExtractFileExt(lFileName)); fnm := ExtractFileNameWithoutExt(lFileName); result := UpperCase(ExtractFileExt(fnm))+ result; end; function StrToFloatX(Const S : String) : Extended; //like StrToFloat but accepts either decimal separator: '1.23' or '1,23' var fmt: TFormatSettings; begin fmt := DefaultFormatSettings; fmt.DecimalSeparator := '.'; if TryStrToFloat(s, result, fmt) then exit; fmt.DecimalSeparator := ','; result := StrToFloat(S,fmt); end; function FileExistsF(fnm: string): boolean; //returns false if file exists but is directory begin result := FileExists(fnm); if result = false then exit; result := not DirectoryExists(fnm); {$IFDEF UNIX} if result = false then exit; //showmessage(fnm + inttostr( fpAccess (fnm,R_OK))); if fpAccess(fnm,R_OK) < 0 then result := false; {$ENDIF} end; function HomeDir: string; //set path to home if not provided {$IFDEF UNIX} begin result := expandfilename('~/'); end; {$ELSE} var SpecialPath: PWideChar; begin Result := ''; SpecialPath := WideStrAlloc(MAX_PATH); try FillChar(SpecialPath^, MAX_PATH, 0); if SHGetSpecialFolderPathW(0, SpecialPath, CSIDL_PERSONAL, False) then Result := SpecialPath+pathdelim; finally StrDispose(SpecialPath); end; end; {$ENDIF} function DefaultToHomeDir(FileName: string; Force: boolean = false ): string; //set path to home if not provided var p,n,x: string; begin result := FileName; FilenameParts (Filename, p,n,x); if (not Force) and (p <> '') and (DirectoryExists(p)) then exit; {$IFDEF LCLCocoa} //p := HomeDir; //set path to home if not provided p := NSTemporaryDirectory.UTF8String; {$ELSE} p := HomeDir; //set path to home if not provided {$ENDIF} result := p+n+x; end; {$IFDEF oldFloat2Str} function float2str(Avalue:double; ADigits:integer):string; //e.g x:single=2.6; floattostrf(x,8,4); begin result := FloatToStrF(Avalue, ffFixed,7,ADigits); end; {$ELSE} function float2str(Avalue:double; ADigits:integer):string; //e.g x:single=2.6; floattostrf(x,8,4); //http://stackoverflow.com/questions/5650051/how-to-keep-2-decimal-places-in-delphi var v:double; p:integer; e:string; begin if abs(Avalue)<1 then begin result:=floatTostr(Avalue); p:=pos('E',result); if p>0 then begin e:=copy(result,p,length(result)); setlength(result,p-1); v:=RoundTo(StrToFloat(result),-Adigits); result:=FloatToStr(v)+e; end else result:=FloatToStr(RoundTo(Avalue,-Adigits)); end else result:=FloatToStr(RoundTo(Avalue,-Adigits)); end; {$ENDIF} {$ifdef isTerminalApp} function Blue(rgb: TColor): BYTE; begin Result := (rgb shr 16) and $000000ff; end; function Green(rgb: TColor): BYTE; begin Result := (rgb shr 8) and $000000ff; end; function Red(rgb: TColor): BYTE; begin Result := rgb and $000000ff; end; function RGBToColor(R, G, B: Byte): TColor; begin Result := (B shl 16) or (G shl 8) or R; end; procedure ShowMessage(msg: string); begin writeln(msg); end; {$else} function asRGBA(clr: TColor): TRGBA; begin result.R := red(clr); result.G := green(clr); result.B := blue(clr); result.A := 255; end; {$endif} function ReadNumBin(var f: TFByte): string; //read next ASCII number in binary file var bt : Byte; ch : Char; begin result := ''; while (not EOF(f)) do begin Read(f,bt); ch := Chr(bt); if ch in ['-','.','E','e','0'..'9'] then result := result + ch else if length(result) > 0 then exit; end; end; function asPt4f(x,y,z,w: single): TPoint4f; begin result.x := x; result.y := y; result.z := z; result.w := w; end; function ChangeFileExtX( lFilename: string; lExt: string): string; //sees .nii.gz as single extension var lPath,lName,lOrigExt: string; begin FilenameParts (lFilename, lPath,lName,lOrigExt); result := lPath+lName+lExt; end; function FSize (lFName: String): longint; var F : File Of byte; begin result := 0; if not fileexistsF(lFName) then exit; FileMode := fmOpenRead; Assign (F, lFName); Reset (F); result := FileSize(F); Close (F); end; function ParseFileName(Filename: string): string; var lPath,lName,lExt: string; begin FilenameParts (FileName, lPath,lName,lExt); result := (lName); end; function ExtractFileExtGzUpper(FileName: string): string; //the file 'img.nii.gz' returns '.NII.GZ', not just '.gz' var lPath,lName,lExt: string; begin //result := UpperCase(ExtractFileExt(FileName)); FilenameParts (FileName, lPath,lName,lExt); result := UpperCase(lExt); end; procedure IntBound (var lVal: integer; lMin, lMax: integer); begin if lVal < lMin then lVal := lMin; if lVal > lMax then lVal := lMax; end; function specialsingle (var s:single): boolean; //returns true if s is Infinity, NAN or Indeterminate //4byte IEEE: msb[31] = signbit, bits[23-30] exponent, bits[0..22] mantissa //exponent of all 1s = Infinity, NAN or Indeterminate const kSpecialExponent = 255 shl 23; var Overlay: LongInt absolute s; begin if ((Overlay and kSpecialExponent) = kSpecialExponent) then RESULT := true else RESULT := false; end; function asSingle(i : longint): single; overload; type swaptype = packed record case byte of 0:(Lng : longint); 1:(Sngl : single); end; swaptypep = ^swaptype; var inguy:swaptypep; begin inguy := @i; //assign address of s to inguy result := inguy^.Sngl; end; // asSingle() function asSingle(b0,b1,b2,b3: byte): single; overload; type swaptype = packed record case byte of 0:(b0,b1,b2,b3 : byte); 1:(Sngl : single); end; //swaptypep = ^swaptype; var //inguy:swaptypep; outguy:swaptype; begin //should work with both little and big endian, as order is same outguy.b0 := b0; outguy.b1 := b1; outguy.b2 := b2; outguy.b3 := b3; result := outguy.Sngl; end; // asSingle() function asInt(s : single): longint; type swaptype = packed record case byte of 0:(Lng : longint); 1:(Sngl : single); end; swaptypep = ^swaptype; var inguy:swaptypep; begin inguy := @s; //assign address of s to inguy result := inguy^.Lng; end; // asInt() procedure SwapDouble(var d : double); type swaptype = packed record case byte of 0:(Word1,Word2,Word3,Word4 : word); //word is 16 bit 1:(float:double); end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @d; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word4); outguy.Word2 := swap(inguy^.Word3); outguy.Word3 := swap(inguy^.Word2); outguy.Word4 := swap(inguy^.Word1); try d:=outguy.float; except d := 0; exit; end; end; //func SwapDouble procedure SwapSingle(var s : single); type swaptype = packed record case byte of 0:(Word1,Word2 : word); 1:(Sngl : single); end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @s; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word2); outguy.Word2 := swap(inguy^.Word1); s := outguy.Sngl; end; // SwapSingle() procedure SwapLongInt(var s : LongInt); type swaptype = packed record case byte of 0:(Word1,Word2 : word); //word is 16 bit 1:(Long:LongInt); end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @s; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word2); outguy.Word2 := swap(inguy^.Word1); s := outguy.Long; end; // SwapLongInt() procedure SwapLongWord(var s : LongWord); type swaptype = packed record case byte of 0:(Word1,Word2 : word); //word is 16 bit 1:(Long:LongWord); end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @s; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word2); outguy.Word2 := swap(inguy^.Word1); s := outguy.Long; end; // SwapLongWord() {$IFDEF SLOWREADLNBIN} procedure ReadLnBin(var f: TFByte; var s: string); const kEOLN = $0A; var bt : Byte; begin s := ''; while (not EOF(f)) do begin Read(f,bt); if bt = kEOLN then exit; s := s + Chr(bt); end; end; {$ELSE} function ReadLnBin(var f: TFByte; var s: string): boolean; inline; const kEOLN = $0A; var bt : Byte; begin s := ''; //while (not EOF(f)) do begin //<- half the speed! while (true) do begin try Read(f,bt); except exit(false); end; if bt = kEOLN then exit(true); s := s + Chr(bt); end; end; {$ENDIF} function RGBA(lR,lG,lB,lA: byte): TRGBA; //set red,green,blue and alpha of a Quad begin result.r := lR; result.g := lG; result.b := lB; result.a := lA; end; function RealToStr(lR: double; lDec: integer): string; begin result := FloatToStrF(lR, ffFixed,7,lDec); end; procedure FilenameParts (lInName: string; out lPath,lName,lExt: string); var lX: string; begin lPath := ExtractFilePath(lInName); lName := ExtractFileName(lInName); lExt := ExtractFileExt(lInName); if lExt = '' then exit; Delete(lName, length(lName)-length(lExt)+1, length(lExt)); //nam.ext -> nam lX := lExt; if UpperCase(lX) <> '.GZ' then exit; lExt := ExtractFileExt(lName); Delete(lName, length(lName)-length(lExt)+1, length(lExt)); //nam.ext -> nam lExt := lExt + lX; //showmessage(lName+':'+lExt); end; (*function FilenameParts (lInName: string; var lPath,lName,lExt: string): boolean; var lLen,lPos,lExtPos,lPathPos: integer; begin result := false; lPath := ''; lName := ''; lExt := ''; lLen := length(lInName); if lLen < 1 then exit; //next find final pathdelim lPathPos := lLen; while (lPathPos > 0) and (lInName[lPathPos] <> '\') and (lInName[lPathPos] <> '/') do dec(lPathPos); if (lInName[lPathPos] = '\') or (lInName[lPathPos] = '/') then begin for lPos := 1 to lPathPos do lPath := lPath + lInName[lPos]; end; // else // dec(lPathPos); inc(lPathPos); //next find first ext lExtPos := 1; while (lExtPos <= lLen) and (lInName[lExtPos] <> '.') do inc(lExtPos); if (lInName[lExtPos] = '.') then begin for lPos := lExtPos to lLen do lExt := lExt + lInName[lPos]; end; // else // inc(lExtPos); dec(lExtPos); //next extract filename //fx(lPathPos,lExtPos); if (lPathPos <= lExtPos) then for lPos := lPathPos to lExtPos do lName := lName + lInName[lPos]; result := true; end; *) procedure SortSingle(var lLo,lHi: single); var lSwap: single; begin if lLo > lHi then begin lSwap := lLo; lLo := lHi; lHi := lSwap; end; //if Lo>Hi end; //proc SortSingle function UnitBound (lS: single): single; begin if lS < 0 then result := 0 else if lS > 1 then result := 1 else result := lS; end; procedure SensibleUnitRect (var U: TUnitRect); begin U.L := UnitBound(U.L); U.T := UnitBound(U.T); U.R := UnitBound(U.R); U.B := UnitBound(U.B); //left should be lower value than right SortSingle(U.L,U.R); if U.L = U.R then begin if U.R < 0.1 then U.R := 0.1 else U.L := U.R -0.1; end; //bottom should lower value than top SortSingle(U.B,U.T); if U.B = U.T then begin if U.T < 0.1 then U.T := 0.1 else U.B := U.T -0.1; end; end; function CreateUnitRect (L,T,R,B: single) : TUnitRect; begin result.L := UnitBound(L); result.T := UnitBound(T); result.R := UnitBound(R); result.B := UnitBound(B); end; end.
{------------------------------------------------------------------------------} { } { ImageAscii - Image to Ascii conversion } { Copyright(C) 2003 Kambiz R. Khojasteh, all rights reserved. } { } { kambiz@delphiarea.com } { http://www.delphiarea.com } { } { This unit is provided "AS IS" without any warranty of any kind, either } { express or implied. The entire risk as to the quality and performance } { of the functions provided in this unit are with you. The author is NOT } { liable for any DAMAGES resulting from the use and misuse of the unit, } { especially he is NOT liable for DAMAGES that were caused BY ANY VERSION } { WHICH HAS NOT BEEN PROGRAMMED BY THE AUTHOR HIMSELF. } { } { This Delphi unit is FREEWARE for non-COMMERCIAL use. If you want to } { change the source code in order to improve the features, performance, } { etc. please send to the author the new source code so that the author } { can have a look at it. The changed source code should contain } { descriptions what you have changed, and your name. The only thing you } { MAY NOT CHANGE is the original COPYRIGHT information. } { } {------------------------------------------------------------------------------} unit ImageAscii; interface uses Windows, Classes, Graphics; type TConvertMode = (cmColor, cmGrayscale, cmMono); procedure ImageToHTML(const FileName: String; out HTML: String; const Map: String; Mode: TConvertMode; MaxRowWidth: Integer = 0; Font: TFont = nil; const Head: String = ''; const Tail: String = ''); procedure GraphicToHTML(G: TGraphic; out HTML: String; const Map: String; Mode: TConvertMode; MaxRowWidth: Integer = 0; Font: TFont = nil; const Head: String = ''; const Tail: String = ''); implementation uses SysUtils; const FontColorTagBegin = '<FONT COLOR="#%2.2x%2.2x%2.2x">'; FontNameTagBegin = '<FONT NAME="%s" STYLE="font-size: %dpt">'; FontTagEnd = '</FONT>'; BoldTagBegin = '<B>'; BoldTagEnd = '</B>'; ItalicTagBegin = '<I>'; ItalicTagEnd = '</I>'; UnderlineTagBegin = '<U>'; UnderlineTagEnd = '</U>'; StrikeOutTagBegin = '<S>'; StrikeOutTagEnd = '<S>'; TeleTypeTagBegin = '<TT>'; TeleTypeTagEnd = '</TT>'; LineBreakTag = '<BR>'; SpecialSpace = '&nbsp;'; { Helpper Functions } // Calculate the propertionally shrinked size of the graphic // according to the specified dimensions and text metrics. procedure CalcShrinkedSize(G: TGraphic; MaxWidth, MaxHeight: Integer; const tm: TTextMetric; out Width, Height: Integer); begin // Scale the image's width according to the text metrics Width := MulDiv(G.Width, tm.tmHeight + tm.tmExternalLeading, tm.tmAveCharWidth); Height := G.Height; // if MaxWidth is zero, don't scale horizontally if MaxWidth = 0 then MaxWidth := Width; // if MaxHeight is zero, don't scale vertically if MaxHeight = 0 then MaxHeight := Height; // if image size is biger than max. dimensions, shrink it proportionally if (Width > MaxWidth) or (Height > MaxHeight) then begin if (MaxWidth / Width) < (MaxHeight / Height) then begin Height := MulDiv(Height, MaxWidth, Width); Width := MaxWidth; end else begin Width := MulDiv(Width, MaxHeight, Height); Height := MaxHeight; end; end; end; // Returns the bitmap version of the given graphic object. The bitmap is // proportionally scaled according to the specified dimensions and font's // text metrics. function GetBitmapOf(G: TGraphic; MaxWidth, MaxHeight: Integer; Font: TFont): TBitmap; var Width, Height: Integer; TextMetric: TTextMetric; begin Result := TBitmap.Create; try // Get the text metrics of the font if Font <> nil then Result.Canvas.Font.Assign(Font); GetTextMetrics(Result.Canvas.Handle, TextMetric); // Shrink the image size according to the max. dimensions and text metrics CalcShrinkedSize(G, MaxWidth, MaxHeight, TextMetric, Width, Height); // Draw the image on the bitmap Result.Width := Width; Result.Height := Height; Result.Canvas.StretchDraw(Rect(0, 0, Width, Height), G); except // free the bitmap if any exception occured Result.Free; raise; end; end; { Global Procedures } // Converts the given graphic object to ASCII image as HTML format procedure GraphicToHTML(G: TGraphic; out HTML: String; const Map: String; Mode: TConvertMode; MaxRowWidth: Integer; Font: TFont; const Head, Tail: String); var Buffer: PChar; Bitmap: TBitmap; BitmapWidth: Integer; BitmapHeight: Integer; Colors: PRGBQuad; LastColor: Integer; Gray: Integer; LastGray: Integer; X, Y: Integer; M: PChar; // Formats the arguments and appends them to the buffer. procedure AppendFormat(const Format: String; const Args: array of const); begin Inc(Buffer, FormatBuf(Buffer^, MaxInt, PChar(Format)^, Length(Format), Args)); end; // Appends the text to the buffer. procedure AppendText(const Text: String); begin Buffer := StrCopy(Buffer, PChar(Text)) + Length(Text); end; // Calculates the worst-case size of the buffer function GetWorstCaseBufferSize: Integer; var PixelCount: Integer; begin PixelCount := BitmapWidth * BitmapHeight; // Calculates the worst-case length of the HTML for saving pixels, and // header and footer tags Result := Length(Head) + Length(TeleTypeTagBegin) + BitmapHeight * Length(LineBreakTag) + Length(TeleTypeTagEnd) + Length(Tail); if Mode = cmMono then Inc(Result, PixelCount * Length(SpecialSpace) + (Length(FontColorTagBegin + FontTagEnd) - 8)) else Inc(Result, PixelCount * Length(SpecialSpace) * (Length(FontColorTagBegin + FontTagEnd) - 8)); // Increases the calculated size by adding the space required to // font related tags if Font <> nil then begin Inc(Result, Length(FontNameTagBegin) + Length(Font.Name) + Length(FontTagEnd)); if fsBold in Font.Style then Inc(Result, Length(BoldTagBegin) + Length(BoldTagEnd)); if fsItalic in Font.Style then Inc(Result, Length(ItalicTagBegin) + Length(ItalicTagEnd)); if fsUnderline in Font.Style then Inc(Result, Length(UnderlineTagBegin) + Length(UnderlineTagEnd)); if fsStrikeOut in Font.Style then Inc(Result, Length(StrikeOutTagBegin) + Length(StrikeOutTagEnd)); end; end; begin Bitmap := GetBitmapOf(G, MaxRowWidth, 0, Font); try // Save bitmap's dimensions for quick retrival BitmapWidth := Bitmap.Width; BitmapHeight := Bitmap.Height; // Change bitmap format to high-color Bitmap.PixelFormat := pf32bit; // Reserve space for the HTML text SetLength(HTML, GetWorstCaseBufferSize); Buffer := PChar(HTML); // Add HTML header tags AppendText(Head); AppendText(TeleTypeTagBegin); // Add font related tags if Font <> nil then begin AppendFormat(FontNameTagBegin, [Font.Name, Font.Size]); if fsBold in Font.Style then AppendText(BoldTagBegin); if fsItalic in Font.Style then AppendText(ItalicTagBegin); if fsUnderline in Font.Style then AppendText(UnderlineTagBegin); if fsStrikeOut in Font.Style then AppendText(StrikeOutTagBegin); if Mode = cmMono then AppendFormat(FontColorTagBegin, [GetRValue(Font.Color), GetGValue(Font.Color), GetBValue(Font.Color)]); end; // Create the rest of HTML using the bitmap's pixels M := PChar(Map); LastColor := -1; LastGray := -1; for Y := 0 to BitmapHeight - 1 do begin Colors := Bitmap.ScanLine[Y]; // Start a new row by adding a line break if Y <> 0 then AppendText(LineBreakTag); // Convert pixels in the current row for X := 0 to BitmapWidth - 1 do begin if PInteger(Colors)^ <> LastColor then begin // Change the color with Colors^ do begin if Mode = cmColor then begin // If there's any open font color tag, close it if LastColor <> -1 then AppendText(FontTagEnd); // Add a new font color tag AppendFormat(FontColorTagBegin, [rgbRed, rgbGreen, rgbBlue]) end else begin Gray := (rgbRed * 30 + rgbGreen * 59 + rgbBlue * 11) div 100; if Gray <> LastGray then begin if Mode = cmGrayscale then begin // If there's any open font color tag, close it if LastGray <> -1 then AppendText(FontTagEnd); // Add a new font color tag AppendFormat(FontColorTagBegin, [Gray, Gray, Gray]) end else M := PChar(Map) + (Length(Map) * Gray div 256); LastGray := Gray; end; end; end; LastColor := PInteger(Colors)^; end; // Add a character for this pixel if M^ <> ' ' then begin Buffer^ := M^; Inc(Buffer); end else AppendText(SpecialSpace); // Move the pixel chanacter to the next one if the mode is not mono if Mode <> cmMono then begin Inc(M); if M^ = #0 then M := PChar(Map); end; // Move to the next pixel Inc(Colors); end; end; // If there's any open font color tag, close it if (Mode <> cmMono) and (LastColor <> -1) then AppendText(FontTagEnd); // Close the open font related tags if Font <> nil then begin if Mode = cmMono then AppendText(FontTagEnd); if fsStrikeOut in Font.Style then AppendText(StrikeOutTagEnd); if fsUnderline in Font.Style then AppendText(UnderlineTagEnd); if fsItalic in Font.Style then AppendText(ItalicTagEnd); if fsBold in Font.Style then AppendText(BoldTagEnd); AppendText(FontTagEnd); end; // Add the HTML fotter tags AppendText(TeleTypeTagEnd); AppendText(Tail); // Set the size of the HTML text to actual size SetLength(HTML, Buffer - PChar(HTML)); finally Bitmap.Free; end; end; // Converts the given imagefile to color/grayscale ASCII image as HTML format procedure ImageToHTML(const FileName: String; out HTML: String; const Map: String; Mode: TConvertMode; MaxRowWidth: Integer; Font: TFont; const Head, Tail: String); var Picture: TPicture; begin Picture := TPicture.Create; try Picture.LoadFromFile(FileName); GraphicToHTML(Picture.Graphic, HTML, Map, Mode, MaxRowWidth, Font, Head, Tail); finally Picture.Free; end; end; end.
unit gr_Stud_DM; interface uses SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, IBase, RxMemDS, FIBQuery, pFIBQuery, pFIBStoredProc, frxClass, frxDBSet, Forms, gr_uCommonConsts, gr_uCommonProc, gr_uMessage, Dialogs, frxDesgn, frxExportXLS, frxExportRTF,gr_uCommonTypes,Dates,Variants, gr_FilterDate; type TDM = class(TDataModule) DSource21: TDataSource; DSet21: TpFIBDataSet; DSource1: TDataSource; DSet1: TpFIBDataSet; DB: TpFIBDatabase; DefaultTransaction: TpFIBTransaction; DSource31: TDataSource; DSet31: TpFIBDataSet; DSource32: TDataSource; DSet32: TpFIBDataSet; DSource33: TDataSource; DSet33: TpFIBDataSet; DSource22: TDataSource; DSet22: TpFIBDataSet; DSet4: TpFIBDataSet; DSource4: TDataSource; DSourceMain: TDataSource; DSetMain: TpFIBDataSet; StProcTransaction: TpFIBTransaction; StProc: TpFIBStoredProc; DBDataset: TfrxDBDataset; Report: TfrxReport; DSetPrint: TpFIBDataSet; DSourcePrint: TDataSource; RTFExport: TfrxRTFExport; XLSExport: TfrxXLSExport; DSet34: TpFIBDataSet; DSource34: TDataSource; DSet5: TpFIBDataSet; DSource5: TDataSource; pFIBDataSet6: TpFIBDataSet; DataSource6: TDataSource; pFIBTransaction5: TpFIBTransaction; procedure DataModuleDestroy(Sender: TObject); procedure ReportGetValue(const VarName: String; var Value: Variant); private public CDate:string; form:TFFilterDate; constructor Create(AOwner:TComponent;AHandle:TISC_DB_HANDLE; Param:TParamFilter);reintroduce; procedure Print(TypePrint:integer); end; implementation uses StrUtils; {$R *.dfm} const NameReport1 = 'PeoplePrint.fr3'; const NameReport2 = 'PeoplePrintGrant.fr3'; const NameReport3 = 'PeoplePrintCat.fr3'; const NameReport4 = 'PeoplePrintKurs.fr3'; constructor TDM.Create(AOwner:TComponent;AHandle:TISC_DB_HANDLE; Param:TParamFilter); begin inherited Create(AOwner); DB.Handle:=AHandle; DefaultTransaction.StartTransaction; //pFIBTransaction5.StartTransaction; //****************************************************************************** DSet1.SQLs.SelectSQL.Text:='SELECT * FROM GR_CN_DT_STUD_S_FIO(' +varToStrDef(Param.KodSetup,'Null')+',''' +Param.Contract+''',''' +Param.Butget+''',' +varToStrDef(Param.id_dep,'Null')+',' +varToStrDef(Param.id_man,'Null')+',' +varToStrDef(Param.id_prop,'Null')+',' +varToStrDef(Param.id_cat,'Null')+',' +IfThen(Param.Bal_B<>'', StringReplace(Param.Bal_B, ',' , '.' , [rfIgnoreCase]) , 'Null')+',' +IfThen(Param.Bal_E<>'',StringReplace(Param.Bal_E, ',' , '.' , [rfIgnoreCase]),'Null')+',' +varToStrDef(Param.id_vidopl,'Null') +') order by FIO'; DSet21.SQLs.SelectSQL.Text:='SELECT * FROM GR_CN_DT_STUD_S(?ID_MAN,'''+Param.Contract+''') order by date_beg desc'; DSet22.SQLs.SelectSQL.Text:='SELECT * FROM Z_ALIMONY_SELECT(:ID_MAN)'; DSet31.SQLs.SelectSQL.Text:='SELECT * FROM GR_CN_DT_STUD_INF_S(?ID_STUD)'; DSet32.SQLs.SelectSQL.Text:='SELECT * FROM GR_DT_GRANTS_S(?ID_STUD)order by date_beg desc'; DSet33.SQLs.SelectSQL.Text:='SELECT * FROM GR_CURRENT_S(?ID_STUD)order by kod_setup desc'; DSet34.SQLs.SelectSQL.Text:='SELECT * FROM GR_DT_VACATION_S(?ID_STUD)order by DATE_BEG desc'; //Art DSet4.SQLs.SelectSQL.Text:='SELECT * FROM Z_PEOPLE_PROP_SELECT_FORMAN(?ID_MAN,''T'')'; pFIBDataSet6.SQLs.SelectSQL.Text:='SELECT * FROM GR_INDEX_BASE_KOD_SETUP(?ID_MAN,'+VarToStrDef(Param.KodSetup-1,'Null')+')'; DSet5.SQLs.SelectSQL.Text:='SELECT * FROM GR_GET_INDEX_ACTS(?ID_MAN)order by kod_setup desc'; DSetMain.SQLs.SelectSQL.Text:='SELECT * FROM PUB_SP_MAIN_SCH_SELECT_EX(''NOW'',1,9)'; //ShowMessage(DSet1.SQLs.SelectSQL.Text); DSet1.Open; DSet21.Open; DSet31.Open; DSet34.Open; DSet4.Open; //pFIBDataSet6.Open; Осторожно! пишущая транзакция блокирует закинчення операции DSet5.Open; DSetMain.Open; //****************************************************************************** end; procedure TDM.Print(TypePrint:integer); begin try Report.Clear; case TypePrint of 0: Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReports+NameReport1,True); 1: Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReports+NameReport2,True); 2: Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReports+NameReport3,True); 3: Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReports+NameReport4,True); end; if grDesignReport then Report.DesignReport else Report.ShowReport; except on E:Exception do begin grShowMessage(ECaption[Indexlanguage],e.Message,mtError,[mbOK]); end; end; end; procedure TDM.DataModuleDestroy(Sender: TObject); begin if DefaultTransaction.InTransaction then DefaultTransaction.Commit; Report.Free; form.Free; end; procedure TDM.ReportGetValue(const VarName: String; var Value: Variant); begin if UpperCase(VarName)='FIRM' then Value:=grNameFirm(DB.Handle); if UpperCase(VarName)='CDATE' then Value:=CDate; if UpperCase(VarName)='KOD_SETUP' then Value:=KodSetupToPeriod(DSetPrint['KOD_SETUP'],4); if UpperCase(VarName)='DATE_BEG' then Value:=DateToStr(form.EditDateBeg.date); if UpperCase(VarName)='DATE_END' then Value:=DateToStr(form.EditDateEnd.date); end; end.
unit uTefDial; interface uses Windows, SysUtils, Classes, Dialogs, IniFiles, Forms, uTEFTypes; const REQUEST_FILE : array[0..1] of String = ('C:\TEF_DIAL\REQ\IntPos.001', 'C:\HiperTEF\REQ\IntPos.001'); TEMP_FILE : array[0..1] of String = ('C:\TEF_DIAL\REQ\IntPos.tmp', 'C:\HiperTEF\REQ\IntPos.tmp'); STATUS_FILE : array[0..1] of String = ('C:\TEF_DIAL\RESP\IntPos.sts', 'C:\HiperTEF\RESP\IntPos.sts'); RESPONSE_FILE : array[0..1] of String = ('C:\TEF_DIAL\RESP\IntPos.001', 'C:\HiperTEF\RESP\IntPos.001'); ACTIVATION_FILE : array[0..1] of String = ('C:\TEF_DIAL\RESP\ativo.001', 'C:\HiperTEF\RESP\ativo.001'); PERSISTENCE_FILE: String = 'C:\temp\Persist.ini'; Moedas : array[0..1] of String = ('Real', 'Dolar'); LINHAS_AVANCO = 4; type TRequestType = (rtATV, rtADM, rtCHQ, rtCRT, rtCNC, rtCNF, rtNCN); TTEFPending = class; TTEFParcela = class Vencimento: TDateTime; Valor: Double; NSUParcela: String; end; TTEFDial = class(TComponent) private FRetorno: Boolean; FValorAprovado: Double; FValorTotal: Double; FIDMoeda: Integer; FTempoEspera: Byte; FNSU: String; FCupomVinculado: String; FImagemCupom: TStringList; FRequisicaoAtual: TRequestType; FTextoEspOperador: String; FTextoEspCliente: String; FAprovada: Boolean; FTemCupom: Boolean; FOnPrint: TTEFPrintEvent; FIdentificacao: LongInt; FDataTransacao: String; FHoraTransacao: String; FNomeRede: String; FFinalizacao: String; FOnDialog: TTEFDialMessageEvent; FTempoMensagem: Byte; FMutex: Cardinal; FWorking: Boolean; FAutorizacao: String; FFormaPagamento: String; FPendingList: TList; { Private declarations } IniPersistence : TIniFile; FOnNeedOpenVinculado: TTEFNeedOpenPrintVinculado; FOnNeedCloseVinculado: TTEFNeedClosePrint; FOnNeedCloseGerencial: TTEFNeedClosePrint; FOnNeedOpenGerencial: TTEFNeedOpenPrint; FOnNeedPrintLineGerencial: TTEFNeedPrintLine; FOnNeedPrintLineVinculado: TTEFNeedPrintLine; FVias: Integer; FLinhaVazia: String; FOnTryAgainDialog: TTEFTryAgainDialog; FRequisicao: String; FBloqueiaTeclado: Boolean; FTipoTransacao: String; FNParcelas: Integer; FParcelas: TList; FOnStatusPrinter: TTEFStatusPrinter; FOnPerguntaCupom: TTEFPerguntaCupom; FCodigoFiscal: String; FIDMeioPag: Integer; FTEFDIALType: Integer; FIDPreSale: Integer; procedure InicializaVariaveis; function FloatToTEFFloat(Valor: Double): String; function VerificaStatus: Boolean; function ExtractFieldInt(Campo: String): Integer; function ExtractFieldStr(Campo: String): String; function GetRequestStr(ATRequestType: TRequestType): String; function AguardaArquivo(NomeArquivo: String; Infinito: Boolean = False): Boolean; function FazTransacao(ARequestType: TRequestType): Boolean; function VerificaRetorno: Boolean; function LeituraRetorno: Boolean; procedure AddPending; procedure ClearPendingList; procedure RemovePending(ANSU: String; Save: Boolean = True); function GetPendingByNSU(ANSU: String): Integer; procedure SetPendingConfirmed(ANSU: String); function DoOnNeedCloseGerencial: Boolean; function DoOnNeedCloseVinculado: Boolean; function DoOnNeedOpenGerencial: Boolean; function DoOnNeedOpenVinculado: Boolean; function DoOnNeedPrintLineGerencial(LineToPrint: String): Boolean; function DoOnNeedPrintLineVinculado(LineToPrint: String): Boolean; procedure DoOnStatusPrinter(var Online: Boolean); function PrintTEFVinculado(var VinculadoAberto: Boolean): Boolean; function LinhaNaoNula(S: String): String; procedure SetTEFToPending(Index: Integer); function PrintTEFGerencial(var VinculadoAberto, GerencialAberto: Boolean): Boolean; function DoOnTryAgainDialog: Boolean; procedure RemoveAllPendings(Save: Boolean = True); procedure ReadAllPendings; function AvancaLinhasVinculado(Count: Integer): Boolean; function AvancaLinhasGerencial(Count: Integer): Boolean; function CancelamentoSimples: Boolean; procedure RemoveRelactiveNSUs(NNSU: String); procedure DescarregaParaReserva; procedure DeleteTEFFiles; function GetParcelas(Index: Integer): TTEFParcela; function AddParcela(AVencimento: TDateTime; AValor: Double; ANSUParcela: String): Integer; function TEFDateToDateTime(S: String): TDateTime; function TestaResposta: Boolean; protected { Protected declarations } public { Public declarations } property Aprovada: Boolean read FAprovada; property Autorizacao: String read FAutorizacao; property CodFiscal: String read FCodigoFiscal write FCodigoFiscal; property DataTransacao: String read FDataTransacao write FDataTransacao; property HoraTransacao: String read FHoraTransacao write FHoraTransacao; property Finalizacao: String read FFinalizacao write FFinalizacao; property IDMoeda: Integer read FIDMoeda write FIDMoeda default 0; property IDMeioPag: Integer read FIDMeioPag write FIDMeioPag; property Identificacao: LongInt read FIdentificacao write FIdentificacao; property IDPreSale: Integer read FIDPreSale write FIDPreSale; property ImagemCupom: TStringList read FImagemCupom; property FormaPagamento: String read FFormaPagamento write FFormaPagamento; property NomeRede: String read FNomeRede write FNomeRede; property NParcelas: Integer read FNParcelas; property NSU: String read FNSU write FNSU; property Retorno: Boolean read FRetorno; property TemCupom: Boolean read FTemCupom; property TextoEspOperador: String read FTextoEspOperador; property TextoEspCliente: String read FTextoEspCliente; property ValorAprovado: Double read FValorAprovado write FValorAprovado; property Mutex: Cardinal read FMutex; property PendingList: TList read FPendingList write FPendingList; property Parcelas[Index: Integer]: TTEFParcela read GetParcelas; property Requisicao: String read FRequisicao; property TipoTransacao: String read FTipoTransacao; constructor Create(AOwner: TComponent);override; destructor Destroy;override; function Ativacao(Exibir: Boolean = True): Boolean; function FazRequisicao(RequestType: TRequestType; PendingOK: Boolean = True): Boolean; function GeraIdentificacao : String; function VerificaAtivacao: Boolean; function VendaCartao: Boolean; function VendaCheque: Boolean; function ConfirmaTransacao: Boolean; function Cancelamento: Boolean; function Administracao: Boolean; function ResolvePendencias: Boolean; function ConfirmacaoSimples: Boolean; function ImprimeTudo: Boolean; function TemPendencia: Boolean; published { Published declarations } property BloqueiaTeclado: Boolean read FBloqueiaTeclado write FBloqueiaTeclado default True; property CupomVinculado: String read FCupomVinculado write FCupomVinculado; property OnPrint: TTEFPrintEvent read FOnPrint write FOnPrint; property RequisicaoAtual: TRequestType read FRequisicaoAtual write FRequisicaoAtual; property LinhaVazia: String read FLinhaVazia write FLinhaVazia; property TempoEspera: Byte read FTempoEspera write FTempoEspera default 7; property TempoMensagem: Byte read FTempoMensagem write FTempoMensagem default 5; property ValorTotal: Double read FValorTotal write FValorTotal; property Vias: Integer read FVias write FVias default 2; property TEFDIALType: Integer read FTEFDIALType write FTEFDIALType; property OnDialog: TTEFDialMessageEvent read FOnDialog write FOnDialog; property OnNeedOpenVinculado: TTEFNeedOpenPrintVinculado read FOnNeedOpenVinculado write FOnNeedOpenVinculado; property OnNeedOpenGerencial: TTEFNeedOpenPrint read FOnNeedOpenGerencial write FOnNeedOpenGerencial; property OnNeedCloseVinculado: TTEFNeedClosePrint read FOnNeedCloseVinculado write FOnNeedCloseVinculado; property OnNeedCloseGerencial: TTEFNeedClosePrint read FOnNeedCloseGerencial write FOnNeedCloseGerencial; property OnNeedPrintLineGerencial: TTEFNeedPrintLine read FOnNeedPrintLineGerencial write FOnNeedPrintLineGerencial; property OnNeedPrintLineVinculado: TTEFNeedPrintLine read FOnNeedPrintLineVinculado write FOnNeedPrintLineVinculado; property OnTryAgainDialog: TTEFTryAgainDialog read FOnTryAgainDialog write FOnTryAgainDialog; property OnStatusPrinter: TTEFStatusPrinter read FOnStatusPrinter write FOnStatusPrinter; property OnPerguntaCupom: TTEFPerguntaCupom read FOnPerguntaCupom write FOnPerguntaCupom; end; TTEFPending = class private FValorTotal: Double; FNomeRede: String; FHoraTransacao: String; FNSU: String; FFormaPagamento: String; FDataTransacao: String; FImagemCupom: TStringList; FConfirmed: Boolean; FCupomVinculado: String; FValorAprovado: Double; FRequisicao: String; FFinalizacao: String; FTEFDIALType: Integer; FIDPreSale: Integer; public constructor Create; destructor Destroy; override; property DataTransacao: String read FDataTransacao write FDataTransacao; property HoraTransacao: String read FHoraTransacao write FHoraTransacao; property ImagemCupom: TStringList read FImagemCupom write FImagemCupom; property FormaPagamento: String read FFormaPagamento write FFormaPagamento; property NomeRede: String read FNomeRede write FNomeRede; property NSU: String read FNSU write FNSU; property ValorTotal: Double read FValorTotal write FValorTotal; property Confirmed: Boolean read FConfirmed write FConfirmed; property CupomVinculado: String read FCupomVinculado write FCupomVinculado; property ValorAprovado: Double read FValorAprovado write FValorAprovado; property Requisicao: String read FRequisicao write FRequisicao; property Finalizacao: String read FFinalizacao write FFinalizacao; property TEFDIALType: Integer read FTEFDIALType write FTEFDIALType; property IDPreSale: Integer read FIDPreSale write FIDPreSale; end; procedure Register; procedure BlockInput(Block: LongBool);stdcall;external 'USER32.DLL'; implementation procedure Register; begin RegisterComponents('NewPower', [TTEFDial]); end; constructor TTEFDial.Create(AOwner: TComponent); begin inherited Create(AOwner); InicializaVariaveis; if not (csDesigning in ComponentState) then FMutex := CreateMutex(nil, False, PChar(Self.Name)) end; destructor TTEFDial.Destroy; begin if not (csDesigning in ComponentState) then begin ClearPendingList; FreeAndNil(FPendingList); FreeAndNil(FImagemCupom); FreeAndNil(FParcelas); end; inherited Destroy; end; procedure TTEFDial.InicializaVariaveis; begin FTextoEspOperador := ''; FTextoEspCliente := ''; FAprovada := False; FTemCupom := False; FWorking := False; FBloqueiaTeclado := True; FTempoEspera := 7; FTempoMensagem := 5; FLinhaVazia := ''; FVias := 2; FRequisicao := ''; FCodigoFiscal := ''; FTEFDIALType := 0; if not (csDesigning in ComponentState) then begin if not DirectoryExists(ExtractFilePath(PERSISTENCE_FILE)) then ForceDirectories(ExtractFilePath(PERSISTENCE_FILE)); IniPersistence := TIniFile.Create(PERSISTENCE_FILE); FPendingList := TList.Create; FImagemCupom := TStringList.Create; FParcelas := TList.Create; end; end; function TTEFDial.TEFDateToDateTime(S: String): TDateTime; var Dia, Mes, Ano: Word; begin Dia := StrToInt(Copy(S, 1, 2)); Mes := StrToInt(Copy(S, 3, 2)); Ano := StrToInt(Copy(S, 5, 4)); Result := EncodeDate(Ano, Mes, Dia); end; function TTEFDial.FloatToTEFFloat(Valor: Double): String; begin Result := StringReplace(FormatFloat('0.00', Valor), DecimalSeparator, '', [rfReplaceAll]); end; function TTEFDial.GeraIdentificacao: String; begin Result := FormatDateTime('hhnnss', NOW) + FormatDateTime('zzzz', NOW); end; function TTEFDial.GetRequestStr(ATRequestType: TRequestType): String; begin case ATRequestType of rtATV: Result := 'ATV'; rtADM: Result := 'ADM'; rtCHQ: Result := 'CHQ'; rtCRT: Result := 'CRT'; rtCNC: Result := 'CNC'; rtCNF: Result := 'CNF'; rtNCN: Result := 'NCN'; else Result := ''; end; end; function TTEFDial.ExtractFieldStr(Campo: String): String; begin Result := Campo; Delete(Result, 1, 10); end; function TTEFDial.ExtractFieldInt(Campo: String): Integer; begin Result := StrToInt(ExtractFieldStr(Campo)); end; function TTEFDial.AguardaArquivo(NomeArquivo: String; Infinito: Boolean = False): Boolean; var HoraInicio, HoraFim : Cardinal; begin Result := False; HoraFim := 0; try if not Infinito then begin HoraInicio := GetTickCount; HoraFim := HoraInicio + (FTempoEspera * 1000); end; repeat Result := FileExists(NomeArquivo); Sleep(0); until Result or ((not Infinito) and (GetTickCount >= HoraFim)); except end; end; function TTEFDial.VerificaAtivacao: Boolean; var AFValorTotal: Double; AFNomeRede: String; AFHoraTransacao: String; AFNSU: String; AFFormaPagamento: String; AFDataTransacao: String; //AFImagemCupom: TStringList; //AFConfirmed: Boolean; AFCupomVinculado: String; AFValorAprovado: Double; AFRequisicao: String; AFRequisicaoAtual: TRequestType; AFIdentificacao: LongInt; AFTextoEspCliente :String; AFTextoEspOperador :String; AFFinalizacao: String; AFCodigoFiscal: String; AFIDMeioPag: Integer; AFTEFDIALType: Integer; begin {if FRequisicaoAtual = rtATV then begin Result := True; Exit; end;} Result := False; AFTextoEspCliente := FTextoEspCliente; AFTextoEspOperador := FTextoEspOperador; AFIdentificacao := FIdentificacao; AFRequisicaoAtual:= FRequisicaoAtual; AFValorTotal := FValorTotal; AFNomeRede := FNomeRede; AFHoraTransacao := FHoraTransacao; AFNSU := FNSU; AFFormaPagamento := FFormaPagamento; AFDataTransacao := FDataTransacao; AFCupomVinculado := FCupomVinculado; AFValorAprovado := FValorAprovado; AFRequisicao := FRequisicao; AFFinalizacao := FFinalizacao; AFCodigoFiscal := FCodigoFiscal; AFIDMeioPag := FIDMeioPag; AFTEFDIALType := FTEFDIALType; if FazRequisicao(rtATV) then begin FTextoEspOperador := ''; Result := VerificaStatus; end; FTextoEspCliente := AFTextoEspCliente; FTextoEspOperador := AFTextoEspOperador; FIdentificacao := AFIdentificacao; FRequisicaoAtual:= AFRequisicaoAtual; FValorTotal := AFValorTotal; FNomeRede := AFNomeRede; FHoraTransacao := AFHoraTransacao; FNSU := AFNSU; FFormaPagamento := AFFormaPagamento; FDataTransacao := AFDataTransacao; FCupomVinculado := AFCupomVinculado; FValorAprovado := AFValorAprovado; FRequisicao := AFRequisicao; FFinalizacao := AFFinalizacao; FCodigoFiscal := AFCodigoFiscal; FIDMeioPag := AFIDMeioPag; FTEFDIALType := AFTEFDIALType; if not Result then if Assigned(FOnDialog) then FOnDialog(Self, mtInatividade); end; function TTEFDial.FazRequisicao(RequestType: TRequestType; PendingOK: Boolean = True): Boolean; var ReqFile : TextFile; Verificado : Boolean; procedure GravaCampo(Field, FieldValue : String); begin WriteLn(ReqFile, Format('%S = %S', [Field, FieldValue])); end; begin FRequisicaoAtual := RequestType; Result := True; Verificado := (FRequisicaoAtual = rtATV); if not Verificado then Verificado := VerificaAtivacao; if Verificado then try DeleteTEFFiles; AssignFile(ReqFile, TEMP_FILE[FTEFDialType]); Rewrite(ReqFile); try FIdentificacao := StrToInt(GeraIdentificacao); if not (FRequisicaoAtual in [rtCNF, rtNCN]) then FRequisicao := GetRequestStr(FRequisicaoAtual); GravaCampo('000-000', GetRequestStr(FRequisicaoAtual)); GravaCampo('001-000', FormatFloat('0000000000', FIdentificacao)); case FRequisicaoAtual of rtATV: begin end; rtCRT: begin GravaCampo('002-000', FCupomVinculado); GravaCampo('003-000', FloatToTEFFloat(FValorTotal)); //GravaCampo('004-000', Moedas[FIDMoeda]); end; rtCHQ: begin GravaCampo('003-000', FloatToTEFFloat(FValorTotal)); end; rtCNF: begin GravaCampo('003-000', FloatToTEFFloat(FValorAprovado)); GravaCampo('010-000', FNomeRede); GravaCampo('012-000', FNSU); GravaCampo('027-000', Finalizacao); end; rtCNC: begin GravaCampo('003-000', FloatToTEFFloat(FValorAprovado)); GravaCampo('010-000', FNomeRede); GravaCampo('012-000', FNSU); GravaCampo('022-000', FDataTransacao); GravaCampo('023-000', FHoraTransacao); end; rtNCN: begin GravaCampo('010-000', FNomeRede); GravaCampo('012-000', FNSU); GravaCampo('027-000', Finalizacao); end; rtADM: begin // Os campos necessários já encontram se gravados end; else raise Exception.Create('Tipo de transação não implementado.'); end; GravaCampo('777-777', 'Teste Hipercard'); GravaCampo('999-999', '0'); Flush(ReqFile); finally CloseFile(ReqFile); end; if not (CopyFile(PChar(TEMP_FILE[FTEFDialType]), PChar(REQUEST_FILE[FTEFDialType]), False) and DeleteFile(TEMP_FILE[FTEFDialType])) then Result := False; except Result := False; end else Result := False; if Result and (FRequisicaoAtual in [rtCNF, rtNCN]) then begin //DeleteFile(RESPONSE_FILE); case FRequisicaoAtual Of rtCNF: SetPendingConfirmed(FRequisicao + FNSU); rtNCN: RemovePending(FRequisicao + FNSU); end; if PendingOK then RemovePending(FRequisicao + FNSU); end; FRetorno := Result; end; function TTEFDial.VerificaStatus: Boolean; var StatusFile : TextFile; IsIDOK, IsRequestOK: Boolean; Campo: String; begin try IsIDOK := False; IsRequestOK := False; // HOMOLOGA if FRequisicaoAtual <> rtATV then FTextoEspOperador := ''; if not AguardaArquivo(STATUS_FILE[FTEFDialType], FRequisicaoAtual <> rtATV) then begin Result := False; //ShowMessage('Gerenciador Padrão não está ativo'); end else begin AssignFile(StatusFile, STATUS_FILE[FTEFDialType]); Reset(StatusFile); try while not EOF(StatusFile) do begin Readln(StatusFile, Campo); if Copy(Campo, 1, 7) = '999-999' then Break; if (Copy(Campo, 1, 7) = '001-000') and (ExtractFieldInt(Campo) = FIdentificacao) then IsIDOK := True; if (Copy(Campo, 1, 7) = '000-000') and (ExtractFieldStr(Campo) = GetRequestStr(FRequisicaoAtual)) then IsRequestOK := True; if (Copy(Campo, 1, 7) = '030-000') and (ExtractFieldStr(Campo) <> '') then FTextoEspOperador := ExtractFieldStr(Campo); Sleep(0); end; Result := IsIDOK and IsRequestOK; finally CloseFile(StatusFile); {if FRequisicaoAtual = rtCNF then} //DeleteFile(STATUS_FILE); end; end; except Result := False; end; if Result and (FTextoEspOperador <> '') then if Assigned(FOnDialog) then FOnDialog(Self); FRetorno := Result; end; function TTEFDial.VerificaRetorno: Boolean; var bCerto: Boolean; begin Result := False; try repeat AguardaArquivo(RESPONSE_FILE[FTEFDialType], True); bCerto := TestaResposta; if not bCerto then DeleteFile(RESPONSE_FILE[FTEFDialType]); until bCerto; DescarregaParaReserva; if not LeituraRetorno then Exit; if FAprovada then begin Result := True; if (FTextoEspOperador <> '') then if FTemCupom then begin if Assigned(FOnDialog) then FOnDialog(Self, mtOperador, False); end else if Assigned(FOnDialog) then FOnDialog(Self); end else begin if Assigned(FOnDialog) then FOnDialog(Self); end; except Result := False; end; FRetorno := Result; end; function TTEFDial.TestaResposta: Boolean; var ResFile : TextFile; Campo: String; begin Result := False; AssignFile(ResFile, RESPONSE_FILE[FTEFDialType]); Reset(ResFile); try while not EOF(ResFile) do begin Readln(ResFile, Campo); if Copy(Campo, 1, 7) = '999-999' then Break; if Copy(Campo, 1, 7) = '001-000' then begin if (ExtractFieldInt(Campo) = FIdentificacao) then Result := True; Break; end; Sleep(0); end; finally CloseFile(ResFile); end; end; function TTEFDial.LeituraRetorno: Boolean; var ResFile : TextFile; Campo, sLinha : String; stlCampos : TStringList; I, QtdLinhas : Integer; {ADataParcela: TDateTime; AValorParcela: Double; ANSUParcela: String;} begin try AssignFile(ResFile, RESPONSE_FILE[FTEFDialType]); stlCampos := TStringList.Create; try stlCampos.Duplicates := dupIgnore; stlCampos.NameValueSeparator := '='; // Lê o arquivo e alimenta a lista Reset(ResFile); try while not EOF(ResFile) do begin Readln(ResFile, Campo); if Copy(Campo, 1, 7) = '999-999' then Break; stlCampos.Add(Copy(Campo, 1, 7) + '=' + ExtractFieldStr(Campo)); Sleep(0); end; Flush(ResFile); finally CloseFile(ResFile); end; // Trata os campos Recebidos, preenchendo as propriedades if Trim(stlCampos.Values['003-000']) <> '' then FValorAprovado := StrToIntDef(stlCampos.Values['003-000'], 0) / 100; FAprovada := Trim(stlCampos.Values['009-000']) = '0'; FNomeRede := stlCampos.Values['010-000']; FTipoTransacao := stlCampos.Values['011-000']; FNSU := stlCampos.Values['012-000']; FAutorizacao := stlCampos.Values['013-000']; FNParcelas := StrToIntDef(stlCampos.Values['018-000'], 0); FDataTransacao := stlCampos.Values['022-000']; FHoraTransacao := stlCampos.Values['023-000']; FFinalizacao := stlCampos.Values['027-000']; FTextoEspOperador := stlCampos.Values['030-000']; FTextoEspCliente := stlCampos.Values['031-000']; QtdLinhas := StrToIntDef(stlCampos.Values['028-000'], 0); FTemCupom := QtdLinhas > 0; // Preenche a imagem do cupom FImagemCupom.Clear; for I := 1 to QtdLinhas do begin sLinha := Trim(stlCampos.Values['029-'+FormatFloat('000', I)]); // Adicionado para resolver o problema Visa da Mara - Inicio sLinha := Copy(sLinha, 2, Length(sLinha) - 2); if Trim(sLinha) = '' then sLinha := ''; {FImagemCupom.Add(Copy(sLinha, 2, Length(sLinha) - 2));} FImagemCupom.Add(sLinha); // Adicionado para resolver o problema Visa da Mara - Fim Sleep(0); end; // Descomentar esse código para funcionar com parcelamento { FParcelas.Clear; if FNParcelas = 0 then begin AddParcela(TEFDateToDateTime(FDataTransacao), FValorAprovado, FNSU); end else for I := 1 to NParcelas do begin ADataParcela := TEFDateToDateTime(Trim(stlCampos.Values['019-'+FormatFloat('000', I)])); AValorParcela := StrToIntDef(Trim(stlCampos.Values['020-'+FormatFloat('000', I)]), 0) / 100; ANSUParcela := Trim(stlCampos.Values['021-'+FormatFloat('000', I)]); AddParcela(ADataParcela, AValorParcela, ANSUParcela); Sleep(0); end; } if FTemCupom then begin AddPending; end; finally stlCampos.Free; DeleteFile(REQUEST_FILE[FTEFDialType]); end; Result := True; except Result := False; end; end; function TTEFDial.AddParcela(AVencimento: TDateTime; AValor: Double; ANSUParcela: String): Integer; var TEFParcela: TTEFParcela; begin TEFParcela := TTEFParcela.Create; with TEFParcela do begin Vencimento := AVencimento; Valor := AValor; NSUParcela := ANSUParcela; end; Result := FParcelas.Add(TEFParcela); end; procedure TTEFDial.AddPending; var TEFPending : TTEFPending; Chave: String; begin TEFPending := TTEFPending.Create; Chave := FRequisicao + FNSU; if not IniPersistence.SectionExists(Chave) then begin IniPersistence.WriteString(Chave, 'NSU', FNSU); IniPersistence.WriteString(Chave, 'DataTransacao', FDataTransacao); IniPersistence.WriteString(Chave, 'HoraTransacao', FHoraTransacao); IniPersistence.WriteString(Chave, 'FormaPagamento', FFormaPagamento); IniPersistence.WriteString(Chave, 'NomeRede', FNomeRede); IniPersistence.WriteFloat(Chave, 'ValorTotal', FValorTotal); IniPersistence.WriteFloat(Chave, 'ValorAprovado', FValorAprovado); IniPersistence.WriteString(Chave, 'CupomVinculado', FCupomVinculado); IniPersistence.WriteString(Chave, 'Requisicao', FRequisicao); IniPersistence.WriteBool(Chave, 'Confirmed', False); IniPersistence.WriteString(Chave, 'Finalizacao', FFinalizacao); IniPersistence.WriteInteger(Chave, 'TEFDIALType', FTEFDIALType); end; TEFPending.DataTransacao := FDataTransacao; TEFPending.HoraTransacao := FHoraTransacao; TEFPending.FormaPagamento := FFormaPagamento; TEFPending.NomeRede := FNomeRede; TEFPending.NSU := FNSU; TEFPending.Requisicao := FRequisicao; TEFPending.ValorTotal := FValorTotal; TEFPending.CupomVinculado := FCupomVinculado; TEFPending.Finalizacao := FFinalizacao; TEFPending.Confirmed := False; TEFPending.ValorAprovado := FValorAprovado; TEFPending.ValorTotal := FValorTotal; TEFPending.TEFDIALType := FTEFDIALType; TEFPending.FImagemCupom.Clear; TEFPending.FImagemCupom.AddStrings(Self.FImagemCupom); FPendingList.Add(TEFPending); end; procedure TTEFDial.ClearPendingList; begin while FPendingList.Count > 0 do begin TTEFPending(FPendingList[0]).Free; FPendingList[0] := nil; FPendingList.Delete(0); end; end; function TTEFDial.GetPendingByNSU(ANSU: String): Integer; var I : Integer; begin Result := -1; for I := 0 to FPendingList.Count - 1 do begin if FPendingList[I] <> nil then if (TTEFPending(FPendingList[I]).FRequisicao + TTEFPending(FPendingList[I]).NSU = ANSU) then begin Result := I; Break; end; end; end; procedure TTEFDial.RemovePending(ANSU: String; Save: Boolean = True); var iPending: Integer; begin if Save and IniPersistence.SectionExists(ANSU) then IniPersistence.EraseSection(ANSU); iPending := GetPendingByNSU(ANSU); if iPending >= 0 then begin TTEFPending(FPendingList[iPending]).Free; FPendingList[iPending] := nil; FPendingList.Delete(iPending); FPendingList.Pack; end; end; procedure TTEFDial.SetPendingConfirmed(ANSU: String); var iPending: Integer; begin iPending := GetPendingByNSU(ANSU); if iPending >= 0 then begin if IniPersistence.SectionExists(ANSU) then IniPersistence.WriteBool(ANSU, 'Confirmed', True); TTEFPending(FPendingList[iPending]).Confirmed := True; end; end; procedure TTEFDial.SetTEFToPending(Index: Integer); var TEFPending : TTEFPending; begin TEFPending := TTEFPending(FPendingList[Index]); FValorTotal := TEFPending.ValorTotal; FValorAprovado := TEFPending.ValorAprovado; FNomeRede := TEFPending.NomeRede; FHoraTransacao := TEFPending.HoraTransacao; FNSU := TEFPending.NSU; FFormaPagamento := TEFPending.FormaPagamento; FDataTransacao := TEFPending.DataTransacao; FCupomVinculado := TEFPending.CupomVinculado; FRequisicao := TEFPending.Requisicao; FFinalizacao := TEFPending.Finalizacao; FTEFDIALType := TEFPending.TEFDIALType; IDPreSale := TEFPending.IDPreSale; FImagemCupom.Clear; FImagemCupom.AddStrings(TEFPending.FImagemCupom); FAprovada := True; FTemCupom := True; end; procedure TTEFDial.RemoveAllPendings(Save: Boolean = True); var TEFPending: TTEFPending; begin while FPendingList.Count > 0 do begin TEFPending := TTEFPending(FPendingList[0]); RemovePending(TEFPending.Requisicao + TEFPending.NSU, Save); end; FPendingList.Clear; end; procedure TTEFDial.ReadAllPendings; var stlSessions: TStringList; I: Integer; TEFPending: TTEFPending; begin RemoveAllPendings(False); stlSessions := TStringList.Create; try IniPersistence.ReadSections(stlSessions); for I := 0 to stlSessions.Count - 1 do begin TEFPending := TTEFPending.Create; TEFPending.FNSU := IniPersistence.ReadString(stlSessions[I], 'NSU', ''); TEFPending.FDataTransacao := IniPersistence.ReadString(stlSessions[I], 'DataTransacao', ''); TEFPending.FHoraTransacao := IniPersistence.ReadString(stlSessions[I], 'HoraTransacao', ''); TEFPending.FFormaPagamento := IniPersistence.ReadString(stlSessions[I], 'FormaPagamento', ''); TEFPending.FNomeRede := IniPersistence.ReadString(stlSessions[I], 'NomeRede', ''); TEFPending.FValorTotal := IniPersistence.ReadFloat(stlSessions[I], 'ValorTotal', 0); TEFPending.FValorAprovado := IniPersistence.ReadFloat(stlSessions[I], 'ValorAprovado', 0); TEFPending.FCupomVinculado := IniPersistence.ReadString(stlSessions[I], 'CupomVinculado', ''); TEFPending.FConfirmed := IniPersistence.ReadBool(stlSessions[I], 'Confirmed', False); TEFPending.FRequisicao := IniPersistence.ReadString(stlSessions[I], 'Requisicao', ''); TEFPending.FFinalizacao := IniPersistence.ReadString(stlSessions[I], 'Finalizacao', ''); TEFPending.FTEFDIALType := IniPersistence.ReadInteger(stlSessions[I], 'TEFDIALType', 0); FPendingList.Add(TEFPending); end; finally stlSessions.Free; end; end; function TTEFDial.FazTransacao(ARequestType: TRequestType): Boolean; var Printed : Boolean; begin Result := False; if FWorking then Exit; FWorking := True; try if not VerificaAtivacao then Exit; if FazRequisicao(ARequestType) then if VerificaStatus then if VerificaRetorno then begin if FAprovada and FTemCupom then begin Printed := ImprimeTudo; Result := Printed; if Result then DeleteTEFFiles; end else Printed := True; if (not (ARequestType in [rtCNF, rtNCN])) and ((ARequestType = rtADM) and (FTemCupom or (StrToInt(FTipoTransacao) <> 0)) or (ARequestType <> rtADM)) then begin // HOMOLOGACAO // Loop para verificar ativação while not VerificaAtivacao do begin Sleep(7000); end; if (Printed) then begin FazRequisicao(rtCNF); Result := VerificaStatus; end else begin FazRequisicao(rtNCN); VerificaStatus; if Assigned(FOnDialog) then FOnDialog(Self, mtPendencia, True); end; end; end; finally FWorking := False; end; end; function TTEFDial.VendaCheque: Boolean; begin Result := False; if FWorking then Exit; FWorking := True; try if not VerificaAtivacao then Exit; //if FazRequisicao(rtCRT) then if FazRequisicao(rtCHQ) then if VerificaStatus then if VerificaRetorno then Result := FAprovada; finally FWorking := False; end; FRetorno := Result; end; function TTEFDial.VendaCartao: Boolean; begin Result := False; if FWorking then Exit; FWorking := True; try if not VerificaAtivacao then Exit; if FazRequisicao(rtCRT) then if VerificaStatus then if VerificaRetorno then Result := FAprovada; finally FWorking := False; end; FRetorno := Result; end; procedure TTEFDial.RemoveRelactiveNSUs(NNSU: String); var iPending: Integer; begin iPending := GetPendingByNSU('CRT' + NNSU); if iPending >= 0 then RemovePending('CRT' + NNSU); end; function TTEFDial.Cancelamento: Boolean; var sNSU: String; begin sNSU := FNSU; Result := FazTransacao(rtCNC); if Result then RemoveRelactiveNSUs(sNSU); DeleteTEFFiles; end; function TTEFDial.Administracao: Boolean; begin FValorAprovado := 0; FValorTotal := 0; Result := FazTransacao(rtADM); DeleteTEFFiles; end; function TTEFDial.ImprimeTudo: Boolean; var VinculadoAberto, GerencialAberto, Printed, TryAgain, NeedVinculado: Boolean; begin Result := False; TryAgain := True; Printed := False; VinculadoAberto := False; GerencialAberto := False; try NeedVinculado := not (FRequisicaoAtual in [rtCNC, rtADM]); //DoOnNeedCloseVinculado; //DoOnNeedCloseGerencial; // Imprime vinculado se precisar if NeedVinculado then Printed := PrintTEFVinculado(VinculadoAberto); if NeedVinculado and (not Printed) then // Se precisava de vinculado e não foi impresso, pergunto se o usuário // Deseja continuar, antes de abrir o gerencial begin TryAgain := DoOnTryAgainDialog; if not TryAgain then Exit; end; if not Printed then repeat Printed := PrintTEFGerencial(VinculadoAberto, GerencialAberto); if not Printed then TryAgain := DoOnTryAgainDialog; until Printed or (not TryAgain); if not Printed then begin if VinculadoAberto then DoOnNeedCloseVinculado; if GerencialAberto then DoOnNeedCloseGerencial; end; finally Result := Printed; end; end; function TTEFDial.ConfirmaTransacao: Boolean; var Printed: Boolean; begin Result := False; Printed := ImprimeTudo; if Printed then begin while not VerificaAtivacao do Sleep(7000); if ConfirmacaoSimples then begin //DeleteTEFFiles; RemoveAllPendings; Result := True; end; end else repeat until ResolvePendencias; end; function TTEFDial.Ativacao(Exibir: Boolean = True): Boolean; begin Result := VerificaAtivacao; if Result Then if Exibir then if Assigned(FOnDialog) then FOnDialog(Self, mtAtividade, True); DeleteTEFFiles; end; function TTEFDial.ResolvePendencias: Boolean; begin Result := True; try ReadAllPendings; if FPendingList.Count = 0 then Exit; // RE-PRE-HOMOLOGACAO (* // HOMOLOGACAO // Loop para verificar ativação while not VerificaAtivacao do begin Sleep(7000); end; *) ReadAllPendings; if FPendingList.Count > 0 then begin if not TTEFPending(FPendingList[FPendingList.Count - 1]).FConfirmed then begin SetTEFToPending(FPendingList.Count - 1); Result := CancelamentoSimples; // HOMOLOGACAO if Assigned(FOnDialog) then FOnDialog(Self, mtPendencia, True); if not Result then Exit; end; end; //for I := 0 to FPendingList.Count - 1 do while FPendingList.Count > 0 do begin // HOMOLOGACAO // Loop para verificar ativação while not VerificaAtivacao do begin Sleep(7000); end; if TTEFPending(FPendingList[FPendingList.Count-1]).FConfirmed then begin SetTEFToPending(FPendingList.Count-1); Result := Cancelamento; if not Result then Exit; end; end; except Result := False; end; end; function TTEFDial.ConfirmacaoSimples: Boolean; begin Result := FazRequisicao(rtCNF, False); if Result then Result := VerificaStatus; DeleteTEFFiles; Sleep(2000); end; function TTEFDial.CancelamentoSimples: Boolean; begin while not VerificaAtivacao do Sleep(7000); Result := FazRequisicao(rtNCN); if Result then Result := VerificaStatus; DeleteTEFFiles; Sleep(2000); end; function TTEFDial.PrintTEFVinculado(var VinculadoAberto: Boolean): Boolean; var Printed: Boolean; iTefs, iVias, iLinhas : Integer; begin Result := False; VinculadoAberto := False; Printed := False; BlockInput(FBloqueiaTeclado); try try for iTefs := 0 to FPendingList.Count - 1 do begin SetTEFToPending(iTefs); if not VinculadoAberto then begin VinculadoAberto := DoOnNeedOpenVinculado; Printed := VinculadoAberto; end; if Printed then for iVias := 1 to FVias do begin for iLinhas := 0 to FImagemCupom.Count - 1 do begin DoOnStatusPrinter(Printed); if not Printed then Exit; Printed := DoOnNeedPrintLineVinculado(FImagemCupom[iLinhas]); if not Printed then Exit; end; // Imprime linhas vazias para separar os cupons if iVias <> FVias then begin Printed := AvancaLinhasVinculado(LINHAS_AVANCO); if not Printed then Exit; Sleep(FTempoMensagem * 1000); end; end else Exit; end; finally if VinculadoAberto then begin Sleep(2000); VinculadoAberto := not DoOnNeedCloseVinculado; if Printed then Printed := not VinculadoAberto; end; Result := Printed; end; finally BlockInput(False); end; end; function TTEFDial.PrintTEFGerencial(var VinculadoAberto, GerencialAberto: Boolean): Boolean; var Printed: Boolean; iTefs, iVias, iLinhas : Integer; begin Result := False; BlockInput(FBloqueiaTeclado); try {if VinculadoAberto then begin} { VinculadoAberto := not DoOnNeedCloseVinculado; } DoOnNeedCloseVinculado; VinculadoAberto := False; if VinculadoAberto then Exit; {end;} {if GerencialAberto then begin} //GerencialAberto := not DoOnNeedCloseVinculado; After Homo {GerencialAberto := not DoOnNeedCloseGerencial;} DoOnNeedCloseGerencial; GerencialAberto := False; if GerencialAberto then Exit; {end;} Printed := False; try for iTefs := 0 to FPendingList.Count - 1 do begin SetTEFToPending(iTefs); //if not VinculadoAberto then After Homo if not GerencialAberto then begin GerencialAberto := DoOnNeedOpenGerencial; Printed := GerencialAberto; end; if Printed then begin for iVias := 1 to FVias do begin for iLinhas := 0 to FImagemCupom.Count - 1 do begin DoOnStatusPrinter(Printed); if not Printed then Exit; Printed := DoOnNeedPrintLineGerencial(FImagemCupom[iLinhas]); if not Printed then Exit; end; // Imprime linhas vazias para separar os cupons if iVias <> FVias then begin Printed := AvancaLinhasGerencial(LINHAS_AVANCO); if not Printed then Exit; Sleep(FTempoMensagem * 1000); end; end; end else Exit; end; finally if GerencialAberto then begin Sleep(2000); GerencialAberto := not DoOnNeedCloseGerencial; if Printed then Printed := not GerencialAberto; end; Result := Printed; end; finally BlockInput(False); end; end; function TTEFDial.DoOnNeedOpenVinculado: Boolean; var VinculadoInfo: TVinculadoInfo; begin if Assigned(FOnNeedOpenVinculado) then begin VinculadoInfo := TVinculadoInfo.Create; try VinculadoInfo.CupomVinculado := Self.CupomVinculado; VinculadoInfo.FormaPagamento := Self.FormaPagamento; VinculadoInfo.IDMeioPag := Self.IDMeioPag; VinculadoInfo.ValorAprovado := Self.ValorAprovado; FOnNeedOpenVinculado(Self, VinculadoInfo, Result); finally VinculadoInfo.Free; end; end else Result := False; end; function TTEFDial.DoOnNeedOpenGerencial: Boolean; begin if Assigned(FOnNeedOpenGerencial) then FOnNeedOpenGerencial(Self, Result) else Result := False; end; function TTEFDial.DoOnNeedCloseVinculado: Boolean; begin Sleep(0); if Assigned(FOnNeedCloseVinculado) then FOnNeedCloseVinculado(Self, Result) else Result := False; Sleep(0); end; function TTEFDial.DoOnNeedCloseGerencial: Boolean; begin Sleep(0); if Assigned(FOnNeedCloseGerencial) then FOnNeedCloseGerencial(Self, Result) else Result := False; Sleep(0); end; function TTEFDial.DoOnNeedPrintLineGerencial(LineToPrint: String): Boolean; begin Sleep(0); if Assigned(FOnNeedPrintLineGerencial) then FOnNeedPrintLineGerencial(Self, LinhaNaoNula(LineToPrint), Result) else Result := False; Sleep(0); end; function TTEFDial.DoOnNeedPrintLineVinculado(LineToPrint: String): Boolean; begin if Assigned(FOnNeedPrintLineVinculado) then FOnNeedPrintLineVinculado(Self, LinhaNaoNula(LineToPrint), Result) else Result := False; Sleep(0); end; function TTEFDial.AvancaLinhasVinculado(Count: Integer) : Boolean; var I : Integer; begin Result := False; for I := 1 to Count do begin Result := DoOnNeedPrintLineVinculado(' '); if not Result then Break; end; end; function TTEFDial.AvancaLinhasGerencial(Count: Integer) : Boolean; var I : Integer; begin Result := False; for I := 1 to Count do begin DoOnStatusPrinter(Result); if not Result then Break; Result := DoOnNeedPrintLineGerencial(' '); if not Result then Break; end; end; function TTEFDial.DoOnTryAgainDialog: Boolean; begin if Assigned(FOnTryAgainDialog) then FOnTryAgainDialog(Self, Result) else Result := False; end; function TTEFDial.LinhaNaoNula(S: String): String; begin if S = '' then Result := FLinhaVazia else Result := S; end; { TTEFPending } constructor TTEFPending.Create; begin FImagemCupom := TStringList.Create; inherited Create; end; destructor TTEFPending.Destroy; begin FreeAndNil(FImagemCupom); inherited Destroy; end; function TTEFDial.TemPendencia: Boolean; begin Result := FPendingList.Count > 0; end; procedure TTEFDial.DescarregaParaReserva; var fHandle : LongInt; iRet: Boolean; RESERVED_FILE: String; begin RESERVED_FILE := ExtractFilePath(Application.ExeName) + 'INTPOS.001'; if FileExists(RESERVED_FILE) then DeleteFile(RESERVED_FILE); iRet := False; { Depois do arquivo Intpos.001 retornar da operadora copiar para o diretório de reserva } CopyFile(Pchar(RESPONSE_FILE[FTEFDialType]), Pchar(RESERVED_FILE), iRet); { Cria-se um Handle } fHandle := CreateFile('INTPOS.001',GENERIC_WRITE,0, nil, OPEN_ALWAYS,FILE_FLAG_NO_BUFFERING,0); { Descarrega o arquivo com essa função } FlushFileBuffers(fHandle); { Fecha o Handle } CloseHandle(fHandle); end; procedure TTEFDial.DeleteTEFFiles; begin DeleteFile(TEMP_FILE[FTEFDialType]); DeleteFile(REQUEST_FILE[FTEFDialType]); DeleteFile(STATUS_FILE[FTEFDialType]); DeleteFile(RESPONSE_FILE[FTEFDialType]); end; function TTEFDial.GetParcelas(Index: Integer): TTEFParcela; begin Result := FParcelas[Index]; end; procedure TTEFDial.DoOnStatusPrinter(var Online: Boolean); begin if Assigned(FOnStatusPrinter) then OnStatusPrinter(Self, Online) else Online := False; end; end.
unit Dmitry.Controls.WatermarkedEdit; interface uses System.SysUtils, System.Classes, Winapi.Windows, Winapi.Messages, Vcl.Controls, Vcl.StdCtrls, Vcl.Graphics, Vcl.Themes; type TWatermarkedEdit = class(TEdit) private { Private declarations } FWatermarkText: string; FText: string; FInnerMouse: Boolean; procedure SetWatermarkText(const Value: string); protected { Protected declarations } procedure WndProc(var Message: TMessage); override; procedure CMMouseLeave(var Message: TWMNoParams); message CM_MOUSELEAVE; procedure CMMouseEnter(var Message: TWMNoParams); message CM_MOUSEENTER; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure WmSetFocus(var Message: TMessage); message WM_SETFOCUS; procedure WmKillFocus(var Message: TMessage); message WM_KILLFOCUS; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property WatermarkText: string read FWatermarkText write SetWatermarkText; property Text; end; procedure Register; implementation procedure Register; begin RegisterComponents('Dm', [TWatermarkedEdit]); end; function ColorDiv2(Color1, Color2: TColor): TColor; begin Result := RGB((GetRValue(Color1) + GetRValue(Color2)) div 2, (GetGValue(Color1) + GetGValue(Color2)) div 2, (GetBValue(Color1) + GetBValue(Color2)) div 2); end; { TWatermarkedEdit } procedure TWatermarkedEdit.CMMouseEnter(var Message: TWMNoParams); begin FInnerMouse := True; inherited; end; procedure TWatermarkedEdit.CMMouseLeave(var Message: TWMNoParams); begin FInnerMouse := False; inherited; end; procedure TWatermarkedEdit.CMTextChanged(var Message: TMessage); begin FText := Text; inherited; end; constructor TWatermarkedEdit.Create(AOwner: TComponent); begin inherited; FInnerMouse := False; end; procedure TWatermarkedEdit.SetWatermarkText(const Value: string); begin FWatermarkText := Value; if HandleAllocated and not (csReadingState in ControlState) then Invalidate; end; procedure TWatermarkedEdit.WmKillFocus(var Message: TMessage); begin PostMessage(Handle, WM_PAINT, 0, 0); inherited; end; procedure TWatermarkedEdit.WmSetFocus(var Message: TMessage); begin PostMessage(Handle, WM_PAINT, 0, 0); inherited; end; procedure TWatermarkedEdit.WndProc(var Message: TMessage); var RcItem: TRect; DC: HDC; TC, C, FC: TColor; PS: TPaintStruct; Hf, OldFont: HFont; BrushInfo: TagLOGBRUSH; Brush: HBrush; begin if {not Focused and} (Message.Msg <> WM_GETTEXT) and Visible and (FText = '') then begin if (Message.Msg = WM_PAINT) or (Message.Msg = WM_ERASEBKGND) then begin rcItem := Rect(1, 1, Width, Height); DC := BeginPaint(Handle, PS); if DC = 0 then Exit; try if StyleServices.Enabled and not (Color <> clWindow) then begin C := StyleServices.GetStyleColor(scEdit); FC := StyleServices.GetStyleFontColor(sfEditBoxTextNormal); end else begin C := Color; FC := Font.Color; end; TC := ColorDiv2(ColorToRGB(C), ColorToRGB(FC)); if not Enabled then TC := ColorDiv2(ColorToRGB(C), ColorToRGB(TC)); SetTextColor(DC, TC); brushInfo.lbStyle := BS_SOLID; brushInfo.lbColor := ColorToRGB(C); Brush := CreateBrushIndirect(brushInfo); FillRect(DC, Rect(0, 0, Width, Height), Brush); hf := CreateFont(Font.Height, 0, 0,0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_TT_ONLY_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_DONTCARE or DEFAULT_PITCH, PChar(Font.Name)); oldFont := SelectObject(DC, hf); SetBkColor(DC, ColorToRGB(C)); DrawText(DC, PChar(FWatermarkText), Length(FWatermarkText), rcItem, DT_TOP); SelectObject(DC, oldFont); if(hf > 0) then DeleteObject(hf); if(Brush > 0) then DeleteObject(Brush); finally EndPaint(Handle, PS); end; Exit; end end; if (Message.Msg = WM_KEYDOWN) then PostMessage(Handle, CM_TEXTCHANGED, 0, 0); inherited; end; end.
unit UContasReceberController; interface uses Classes, SQLExpr, SysUtils, Generics.Collections, DBXJSON, DBXCommon, ConexaoBD, UUnidadeVO, UController, DBClient, DB, UContasReceberVO, UPessoasController, UCondominioController, UPlanoCOntasController, UCondominioVO, UPlanoContasVO, UHistoricoVO, ULancamentoContabilVO, UEmpresaTrab, UContaCorrenteVO; type TContasReceberController = class(TController<TContasReceberVO>) private public function ConsultarPorId(id: integer): TContasReceberVO; procedure ValidarDados(Objeto :TContasReceberVO);override; function Inserir(ContasReceber: TContasReceberVO): integer; function Excluir(ContasReceber: TContasReceberVO): boolean; function Alterar(ContasReceber: TContasReceberVO): boolean; function InserirBaixa (ContasReceber : TContasReceberVO) : integer; function RemoverBaixa (idContasReceber : integer) :integer; function InserirTitulosContaCorrente(ListaCReber:TObjectList<TContasReceberVO>):boolean; end; implementation uses UDao, Constantes, Vcl.Dialogs; function TContasReceberController.Alterar(ContasReceber: TContasReceberVO): boolean; var Lancamentos : TObjectList<TLancamentoContabilVO>; ContaCorrente : TObjectList<TContaCorrenteVO>; idContaUnidade, idContaDebito, idContaCredito : Integer; Lancamento : TLancamentoContabilVO; PlanoContasController : TPlanoContasCOntroller; ListaConta : TObjectList<TPlanoContasVO>; ContaPlano : TPlanoContasVO; Query : string; begin validarDados(ContasReceber); idContaUnidade := 0; try TDBExpress.IniciaTransacao; Result := TDAO.Alterar(ContasReceber); ContaCorrente := TDAO.Consultar<TContaCorrenteVO>(' idContasReceber = ' + IntToStr(ContasReceber.idContasReceber), '',0,true); if ContaCorrente.Count > 0 then begin ShowMessage('Titulo gerado pelo conta corrente não poderá ser alterado! '); end else begin Lancamentos:= TDAO.Consultar<TLancamentoContabilVO>(' LANCAMENTOCONTABIL.IDCONTASRECEBER = '+inttostr(ContasReceber.idContasReceber), '',0,true); if(Lancamentos.Count>0)then begin TDAO.Excluir(Lancamentos.First); end; if(ContasReceber.IdUnidade > 0)then begin PlanoContasController := TPlanoContasController.Create; Query := ' PlanoContas.idUnidade = ' +(IntTOsTR(ContasReceber.IdUnidade))+ ' and PlanoContas.idcondominio = '+ IntToStr(FormEmpresaTrab.CodigoEmpLogada); listaConta := PlanoContasController.Consultar(query); if (listaConta.Count > 0) then begin idContaUnidade:=listaConta[0].idPlanoContas; end; if ContasReceber.IdUnidade <> 0 then idContaDebito := idContaUnidade; if ContasReceber.IdConta <> 0 then idContaDebito := ContasReceber.IdConta; if ContasReceber.IdContraPartida <> 0 then idContaCredito := ContasReceber.IdContraPartida; Lancamento := TLancamentoContabilVo.Create; Lancamento.idcontadebito := idContaDebito; Lancamento.idContaCredito := idContaCredito; Lancamento.complemento := ContasReceber.DsComplemento; Lancamento.dtLcto := ContasReceber.DtCompetencia; Lancamento.VlValor := ContasReceber.VlValor; Lancamento.idContasReceber := ContasReceber.idContasReceber; Lancamento.idHistorico := ContasReceber.IdHistorico; TDao.Inserir(Lancamento); TDBExpress.ComitaTransacao; end; end; finally TDBExpress.RollBackTransacao; end; end; function TContasReceberController.ConsultarPorId(id: integer): TContasReceberVO; var P: TContasReceberVO; begin P := TDAO.ConsultarPorId<TContasReceberVO>(id); if (P <> nil) then begin p.CondominioVO := TDAO.ConsultarPorId<TCondominioVO>(P.IdCondominio); p.UnidadeVO := TDAO.ConsultarPorId<TUnidadeVO>(p.IdUnidade); p.PlanoContasContaVO := TDAO.ConsultarPorId<TPlanoContasVO>(P.IdConta); P.PlanoContasContraPartidaVO := TDao.ConsultarPorId<TPlanoContasVO>(P.IdContraPartida); p.HistoricoVO := TDao.ConsultarPorId<THistoricoVO>(P.IdHistorico); end; result := P; end; function TContasReceberController.Excluir(ContasReceber: TContasReceberVO): boolean; var Lancamento : TObjectList<TLancamentoContabilVO>; ContaCorrente : TObjectList<TContaCorrenteVO>; i : integer; begin try TDBExpress.IniciaTransacao; Lancamento:= TDAO.Consultar<TLancamentoContabilVO>(' LANCAMENTOCONTABIL.IDCONTASRECEBER = '+inttostr(ContasReceber.idContasReceber), '',0,true); ContaCorrente := TDAO.Consultar<TContaCorrenteVO>(' contacorrente.idContasReceber = ' + IntToStr(ContasReceber.idContasReceber), '',0,true); if(Lancamento.Count>0)then begin TDAO.Excluir(Lancamento.First); end; for I := 0 to ContaCorrente.Count - 1 do begin TDAO.Excluir(ContaCorrente[i]); end; Result := TDAO.Excluir(ContasReceber); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TContasReceberController.Inserir(ContasReceber: TContasReceberVO): integer; var contaPlano:TPlanoContasVO; Lancamento : TLancamentoContabilVO; listaConta :TObjectList<TPlanoContasVO>; Query : String; idContaUnidade,idcontadebito,idcontacredito:integer; PlanoContasController : TPlanoContasController; begin try idContaUnidade := 0; TDBExpress.IniciaTransacao; Result := TDAO.Inserir(ContasReceber); if(ContasReceber.IdUnidade > 0)then begin PlanoContasController := TPlanoContasController.Create; Query := ' PlanoContas.idUnidade = ' +(IntTOsTR(ContasReceber.IdUnidade) + ' and PlanoContas.idcondominio = '+ IntToStr(FormEmpresaTrab.CodigoEmpLogada)); listaConta := PlanoContasController.Consultar(query); if (listaConta.Count > 0) then begin idContaUnidade:=listaConta[0].idPlanoContas; end; end; if ContasReceber.IdUnidade > 0 then idContaDebito := idContaUnidade; if ContasReceber.IdConta > 0 then idContaDebito := ContasReceber.IdConta; if ContasReceber.IdContraPartida > 0 then idContaCredito := ContasReceber.IdContraPartida; Lancamento := TLancamentoContabilVo.Create; Lancamento.idcontadebito := idContaDebito; Lancamento.idContaCredito := idContaCredito; Lancamento.complemento := ContasReceber.DsComplemento; Lancamento.dtLcto := ContasReceber.DtCompetencia; Lancamento.VlValor := ContasReceber.VlValor; Lancamento.idContasReceber := result; Lancamento.idHistorico := ContasReceber.IdHistorico; TDao.Inserir(Lancamento); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TContasReceberController.InserirBaixa(ContasReceber: TContasReceberVO): integer; var Lancamentos : TObjectList<TLancamentoContabilVO>; i:integer; Lancamento, lctoDesconto, lctoJurosMulta : TLancamentoContabilVO; PlanoContasController : TPlanoContasController; query : string; listaConta : TObjectList<TPlanoContasVO>; valordebito : currency; begin TDBExpress.IniciaTransacao; try TDAO.Alterar(ContasReceber); Lancamentos:= TDAO.Consultar<TLancamentoContabilVO>(' LANCAMENTOCONTABIL.IDCONTASRECEBER = '+inttostr(ContasReceber.idContasReceber) + ' AND LANCAMENTOCONTABIL.IDBAIXA = '+inttostr(ContasReceber.idContasReceber), '',0,true); if(Lancamentos.Count>0)then begin for i:=0 to Lancamentos.Count-1 do begin TDAO.Excluir(Lancamentos[i]); end; end; Lancamento := TLancamentoContabilVo.Create; if(ContasReceber.IdUnidade>0)then begin PlanoContasController := TPlanoContasController.Create; Query := ' PlanoContas.idunidade = ' +(IntTOsTR(ContasReceber.idunidade) + ' and PlanoContas.idcondominio = '+ IntToStr(FormEmpresaTrab.CodigoEmpLogada)); listaConta := PlanoContasController.Consultar(query); if (listaConta.Count > 0) then begin Lancamento.idcontaCredito := listaConta[0].idPlanoContas; end; end else Lancamento.idcontaCredito := ContasReceber.idConta; Lancamento.dtLcto := ContasReceber.DtBaixa; Lancamento.VlValor := ContasReceber.VlBaixa; Lancamento.idContasReceber := ContasReceber.idContasReceber; Lancamento.idbaixa := ContasReceber.idContasReceber; Lancamento.idHistorico := ContasReceber.IdHistoricoBx; TDAO.Inserir(Lancamento); ValorDebito:= ContasReceber.VlBaixa; if((ContasReceber.VlDesconto>0))then begin LctoDesconto := TLancamentoContabilVo.Create; LctoDesconto.idContaDebito := FormEmpresaTrab.ctdescontop; LctoDesconto.dtLcto := ContasReceber.DtBaixa; LctoDesconto.VlValor := ContasReceber.vldesconto; LctoDesconto.idContasReceber := ContasReceber.idContasReceber; LctoDesconto.idBaixa:=ContasReceber.idContasReceber; ValorDebito := ValorDebito - ContasReceber.VlDesconto; TDao.Inserir(LctoDesconto); end ; if((ContasReceber.VlJuros>0))then begin lctoJurosMulta := TLancamentoContabilVo.Create; lctoJurosMulta.idContaCredito := FormEmpresaTrab.ctjurosp; lctoJurosMulta.dtLcto := ContasReceber.DtBaixa; lctoJurosMulta.VlValor := ContasReceber.vljuros; lctoJurosMulta.idContasReceber := ContasReceber.idContasReceber; lctoJurosMulta.idBaixa:=ContasReceber.idContasReceber; ValorDebito := ValorDebito + ContasReceber.VlJuros; TDao.Inserir(lctoJurosMulta); end; if((ContasReceber.VlMulta>0))then begin lctoJurosMulta := TLancamentoContabilVo.Create; lctoJurosMulta.idContaCredito := FormEmpresaTrab.ctmultap; lctoJurosMulta.dtLcto := ContasReceber.DtBaixa; lctoJurosMulta.VlValor := ContasReceber.vlmulta; lctoJurosMulta.idContasReceber := ContasReceber.idContasReceber; lctoJurosMulta.idBaixa:=ContasReceber.idContasReceber; ValorDebito := ValorDebito + ContasReceber.vlmulta; TDao.Inserir(lctoJurosMulta); end; lancamento := TLancamentoContabilVo.Create; Lancamento.dtLcto := ContasReceber.DtBaixa; Lancamento.VlValor := ValorDebito; lancamento.idContaDebito := ContasReceber.IdContaBaixa; Lancamento.idContasReceber := ContasReceber.idContasReceber; Lancamento.idbaixa := ContasReceber.idContasReceber; TDAO.Inserir(Lancamento); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TContasReceberController.InserirTitulosContaCorrente( ListaCReber: TObjectList<TContasReceberVO>): boolean; var i,x, idContaReceber:integer; begin TDBExpress.IniciaTransacao; try for i:=0 to ListaCReber.Count-1 do begin idContaReceber:=0; idContaREceber:= TDAO.Inserir(ListaCReber[i]); for x := 0 to listaCReber[i].ItensContaCorrente.Count-1 do begin listaCReber[i].ItensContaCorrente[x].idContasReceber:=idContaReceber; TDAO.Inserir(listaCReber[i].ItensContaCorrente[x]); end; end; TDBEXpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TContasReceberController.RemoverBaixa( idcontasReceber : integer): integer; var Lancamentos : TObjectList<TLancamentoContabilVO>; ContasReceber:TContasReceberVO; i:integer; begin TDBExpress.IniciaTransacao; try ContasReceber := nil; ContasReceber := self.ConsultarPorId(idContasReceber); ContasReceber.DtBaixa := 0; ContasReceber.VlBaixa := 0; ContasReceber.VlJuros := 0; ContasReceber.VlMulta := 0; ContasReceber.VlDesconto := 0; ContasReceber.IdHistoricoBx := 0; ContasReceber.IdContaBaixa := 0; ContasReceber.VlPago := 0; ContasReceber.FlBaixa := 'P'; TDAO.Alterar(ContasReceber); Lancamentos:= TDAO.Consultar<TLancamentoContabilVO>(' LANCAMENTOCONTABIL.IDCONTASRECEBER = '+inttostr(ContasReceber.idContasReceber) + ' AND LANCAMENTOCONTABIL.IDBAIXA = '+inttostr(ContasReceber.idContasReceber), '',0,true); if(Lancamentos.Count>0)then begin for i:=0 to Lancamentos.Count-1 do begin TDAO.Excluir(Lancamentos[i]); end; end; TDBEXpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; procedure TContasReceberController.ValidarDados(Objeto: TContasReceberVO); begin inherited; end; begin end.
unit spimulti; {$mode objfpc} interface uses Classes, Forms, SysUtils; function UsbAspMulti_EnableEDI(): integer; function UsbAspMulti_WriteReg(RegAddr: Word; RegData: byte): integer; function UsbAspMulti_ReadReg(RegAddr: Word; var RegData: byte): integer; function UsbAspMulti_Read(Addr: longword; var Data: byte): integer; function UsbAspMulti_ErasePage(Addr: longword): integer; function UsbAspMulti_WritePage(Addr: longword; var Data: array of byte): integer; function UsbAspMulti_Busy(): boolean; implementation uses Main; //Первая команда, после ресета, должна быть на частоте не более 8MHz //Write enable of EFCMD register,0xFEAC. function UsbAspMulti_EnableEDI(): integer; var Buff: array[0..4] of byte; begin Buff[0] := $40; Buff[1] := 0; Buff[2] := $FE; Buff[3] := $AD; Buff[4] := $08; result := AsProgrammer.Programmer.SPIWrite(1, 5, Buff); end; function UsbAspMulti_WriteReg(RegAddr: Word; RegData: byte): integer; var Buff: array[0..4] of byte; begin Buff[0] := $40; Buff[1] := 0; Buff[2] := hi(RegAddr); Buff[3] := lo(RegAddr); Buff[4] := RegData; result := AsProgrammer.Programmer.SPIWrite(1, 5, Buff); end; function UsbAspMulti_ReadReg(RegAddr: Word; var RegData: byte): integer; var Buff: array[0..4] of byte; ReadyStat: byte = 0; begin Buff[0] := $30; Buff[1] := 0; Buff[2] := hi(RegAddr); Buff[3] := lo(RegAddr); AsProgrammer.Programmer.SPIWrite(0, 4, Buff); //Ready repeat Application.ProcessMessages; if UserCancel then Exit; AsProgrammer.Programmer.SPIRead(0, 1, ReadyStat); until (ReadyStat = $50); result := AsProgrammer.Programmer.SPIRead(1, 1, regdata); end; function UsbAspMulti_Read(Addr: longword; var Data: byte): integer; begin UsbAspMulti_WriteReg($FEAA, lo(hi(Addr)) ); UsbAspMulti_WriteReg($FEA9, hi(lo(Addr)) ); UsbAspMulti_WriteReg($FEA8, lo(lo(Addr)) ); UsbAspMulti_WriteReg($FEAC, $03); Result := UsbAspMulti_ReadReg($FEAB, Data); end; //Page128 function UsbAspMulti_WritePage(Addr: longword; var Data: array of byte): integer; var i: integer; busy: boolean; begin UsbAspMulti_WriteReg($FEAA, lo(hi(Addr)) ); UsbAspMulti_WriteReg($FEA9, hi(lo(Addr)) ); //UsbAspMulti_WriteReg($FEA8, lo(lo(page)) ); UsbAspMulti_WriteReg($FEAC, $80); //clr buff for i:=0 to 127 do begin UsbAspMulti_WriteReg($FEA8, lo(lo(Addr)) + i ); UsbAspMulti_WriteReg($FEAB, Data[i]); UsbAspMulti_WriteReg($FEAC, $02); //latch page end; UsbAspMulti_WriteReg($FEAC, $70); //prog page end; function UsbAspMulti_ErasePage(Addr: longword): integer; begin UsbAspMulti_WriteReg($FEAA, lo(hi(Addr)) ); UsbAspMulti_WriteReg($FEA9, hi(lo(Addr)) ); UsbAspMulti_WriteReg($FEA8, lo(lo(Addr)) ); result := UsbAspMulti_WriteReg($FEAC, $20); end; function UsbAspMulti_Busy(): boolean; var sreg: byte = $FF; begin UsbAspMulti_ReadReg($FEAD, sreg); if (sreg and 2) = 0 then Result := False else Result := True; end; end.
// // Generated by JavaToPas v1.5 20171018 - 171149 //////////////////////////////////////////////////////////////////////////////// unit java.io.OutputStreamWriter; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, java.nio.charset.Charset; type JOutputStreamWriter = interface; JOutputStreamWriterClass = interface(JObjectClass) ['{D3453B8B-9E77-4F38-B6BD-D27C8B6E233C}'] function getEncoding : JString; cdecl; // ()Ljava/lang/String; A: $1 function init(&out : JOutputStream) : JOutputStreamWriter; cdecl; overload; // (Ljava/io/OutputStream;)V A: $1 function init(&out : JOutputStream; charsetName : JString) : JOutputStreamWriter; cdecl; overload;// (Ljava/io/OutputStream;Ljava/lang/String;)V A: $1 function init(&out : JOutputStream; cs : JCharset) : JOutputStreamWriter; cdecl; overload;// (Ljava/io/OutputStream;Ljava/nio/charset/Charset;)V A: $1 function init(&out : JOutputStream; enc : JCharsetEncoder) : JOutputStreamWriter; cdecl; overload;// (Ljava/io/OutputStream;Ljava/nio/charset/CharsetEncoder;)V A: $1 procedure &write(c : Integer) ; cdecl; overload; // (I)V A: $1 procedure &write(cbuf : TJavaArray<Char>; off : Integer; len : Integer) ; cdecl; overload;// ([CII)V A: $1 procedure &write(str : JString; off : Integer; len : Integer) ; cdecl; overload;// (Ljava/lang/String;II)V A: $1 procedure close ; cdecl; // ()V A: $1 procedure flush ; cdecl; // ()V A: $1 end; [JavaSignature('java/io/OutputStreamWriter')] JOutputStreamWriter = interface(JObject) ['{899533AE-5014-49F6-ACD6-154C9C667D3D}'] function getEncoding : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure &write(c : Integer) ; cdecl; overload; // (I)V A: $1 procedure &write(cbuf : TJavaArray<Char>; off : Integer; len : Integer) ; cdecl; overload;// ([CII)V A: $1 procedure &write(str : JString; off : Integer; len : Integer) ; cdecl; overload;// (Ljava/lang/String;II)V A: $1 procedure close ; cdecl; // ()V A: $1 procedure flush ; cdecl; // ()V A: $1 end; TJOutputStreamWriter = class(TJavaGenericImport<JOutputStreamWriterClass, JOutputStreamWriter>) end; implementation end.
unit AStarGlobals; interface uses Windows, Classes,{TStringList} FileCtrl, Sysutils{Filestuff}, GLUtils,//Strtofloatdef Dialogs{MessageDlg}, Shellapi,{ShellExecute} Forms,{App} Graphics{Graphics}; //const //x:type=value is like an initialized variable const // path-related constants //path is Checked Against the following: //They Are constant..this is Set to one of their values //path: Integer = 0; // replaced by pathStatus array //pathStatus constants notStarted: Integer = 0; notfinished: Integer = 0; //not used? found: Integer = 1; nonexistent: Integer = 2; tempStopped: Integer = 3; //not H claimedNode stopped: Integer = 3; //not H UpdatePath Targetunwalkable : Integer =4; RedirectFailed : Integer =5; //CheckRedirect returns these constants CheckRedirectSucceeded: Integer =1; CheckRedirectFailed: Integer = -1; //BlitzFindPath() mode constants Const normal: Integer = 0; randomMove: Integer = 1; PatrolMove: Integer = 2; //Not Implemented yet // walkability array constants onOpenList := onClosedList-1; onClosedList : Integer = 10; walkable: Integer = 0; unwalkable: Integer = 1; tempUnwalkable: Integer = 1; //tempUnwalkable := onClosedList-2; //PenalizeAdjacentPaths penalized: Integer = 1; //penalized := onClosedList-3; var mapWidth,mapHeight, tileSize, ImageWidth, ImageHeight:Integer; //Create needed arrays : SOME are Word to save memory //1 dimensional array holding ID# of open list items openList,//:array of Integer;//[mapWidth*mapHeight+2]; //1d array stores the x location of an item on the open list openX,//:array of Integer;//[mapWidth*mapHeight+2]; //1d array stores the y location of an item on the open list openY//:array of Integer;//[mapWidth*mapHeight+2]; //1d array to store F cost of a cell on the open list :array of Word; //Word is smaller than Integer walkability: array of array of Byte;//[mapWidth][mapHeight]; //These (_Cost) Must be Integer.. //they can be Negative?.. Straight Tiebreaker goes bonkers Fcost,//:array of Integer;//[mapWidth*mapHeight+2]; //1d array to store H cost of a cell on the open list Hcost:array of Integer;//[mapWidth*mapHeight+2]; //2d array to store G cost for each cell. Gcost: array of array of Integer;//[mapWidth+1][mapHeight+1]; //2 dimensional array used to record //whether a cell is on the open list or on the closed list. whichList,//: array of array of Integer;//[mapWidth+1][mapHeight+1]; //2d array to store parent of each cell (x) parentX,//: array of array of Integer;//[mapWidth+1][mapHeight+1]; //2d array to store parent of each cell (y) parentY//: array of array of Integer;//[mapWidth+1][mapHeight+1]; :array of array of Word; //Units : Blitz only MapAttribute,//:array of array of Integer; GCostData//:array of array of Integer; : array of array of Byte; //;array that holds info about adjacent units tempUnwalkability,//:array of array of Integer;//(mapWidth+1,mapHeight+1) nearByPath,//:array of array of Integer;//(mapWidth+1,mapHeight+1) //; array that stores claimed nodes claimedNode,//:array of array of Integer;//.unit(mapWidth+1,mapHeight+1) //SetLength in IdentifyIslands island:array of array of Word;//Integer;//(mapWidth+1,mapHeight+1) //Set by Program...Destroyed Setlength 0 in App Destroy MAGColorValueArray: Array of Array[1..2] of Integer; //THESE are DEMO ONLY : Units have their OWN //stores length of the found path for critter pathLength:array of Integer;//[numberPeople+1]; //stores current position along the chosen path for critter pathLocation:array of Integer;//[numberPeople+1]; //Path reading variables pathStatus:array of Integer;//[numberPeople+1]; xPath:array of Integer;//[numberPeople+1]; yPath:array of Integer;//[numberPeople+1]; //int* // [numberPeople+1] [xy pairs stored ] //Unit,X and Y Path Locations pathBank:array of array of Integer;//Setlength in FindPath //New stuff gGameStarted, gDiagonalBlockage:Boolean; gScreenCaptureNumber, gLoops, gInt1, gInt2:Integer; //global variables. //gPathCost:Integer;// PathCost:Integer;// savedClockTime:array [0..20]of Double; gLoopCount,savedClockCount :Integer; //gStartTime:=StartPrecisionTimer; gStartTime : Int64; //gLoopTime:=gLoopTime+StopPrecisionTimer(gStartTime); gLoopTime, //gGameTime:=gLoopTime*1000/gLoopCount; gGameTime:Double; //Mixed or Demo only? EnemyPositionsColor, EnemyUnitBaseColor, EnemyUnitGoalTargetColor:Integer; BaseStartColorArray, TargetGoalColorArray: Array [1..5]of Integer; //1 Enemy Base..Target .. 5 Bases, 5 Units Base..Target EnemystartXLoc,EnemystartYLoc, EnemytargetXLoc,EnemytargetYLoc:Integer; ActiveEnemyNumber:Integer; EnemyBaseXLocArray, EnemyBaseYLocArray: Array [1..5]of Integer; ActiveUnitNumber, NumberofUnits, NumberofUnitPeople:Integer; startXLocArray,startYLocArray, //Set seeker location targetXLocArray,targetYLocArray,//Set initial target location. speedArray : Array [1..5]of Integer; Type ProjectRecordData = record //IsEnemyPatrolActive, NumberofActiveUnits, NumberofActiveEnemy, NumberofActiveEnemyPatrol, RatioSizeMode, RatioSize, TileSizeMode, tileSize, HeightfieldSizeMode, HeightfieldSize, mapWidth,mapHeight, ImageSizeMode, ImageWidth, ImageHeight:Integer; GridLinesDisplayed, PathDisplayed, // UseTerrainValueAlpha, UseTurningpenalty,PenalizeAdjacentPaths ProcessNoGoIslands, ClaimedNodesDisplayed:Boolean; AdjacentPathPenaltyD, TerrainMagNoGoD, TerrainValueAlphaD, AverageTerrainD, TurningpenaltyD:Double; //Filenames HeightDataFile,ImageTextureFile,MapAttributesFile, ElevationFile, VegetationFile, SoilsFile, HydrologyFile, TransportFile, UrbanFile, NOGOFile, ObstaclesFile, InfluenceMapFile, GCostFile, MAGValuesFile, //ColorsFile, UnitsFile,TerrainFile:String; End; //Trunc(20*AdjacentPathPenaltyD) var ProjectRecord: ProjectRecordData; //pathBank1, pathBank2,:CurrentpathBank, Unit,[pathX pathY] UnitpathBank:Array[1..2]of Array of array of Integer;//Setlength in FindPath Type UnitRecord = record CurrentpathBank, pathStatus, pathLength, pathLocation, targetunit, unitCollidingWith:Integer; distanceToNextNode:Double; startNewPath:Boolean; //;used for delayed-action pathfinding //BaseColor,targetColor, {sprite, red, green, blue, selected,} xDistanceFromGroupCenter, yDistanceFromGroupCenter, actualAngleFromGroupCenter, assignedAngleFromGroupCenter:Integer; xPath, yPath, //;in pixels startXLoc, startYLoc, startZLoc,//xLoc, yLoc, targetX, targetY, targetZ:Integer; Md2WpnName,Md2WpnTextureName, Md2Name,Md2TextureName,FlagFile:String; TargetSize,ActorScale:Double; //;speed is in pixels/second ID, pathAI, OperatingOrders, SearchMode, TieBreakerMode, speed, Manueverability, armor, Members, Members1X, Members1Y, Members2X, Members2Y, Members3X, Members3Y,Members4X, Members4Y,Members5X, Members5Y :Integer; End; //5Units + 1 Enemy var UnitRecordArray: Array [1..6]of UnitRecord; (* Type unit Field ID, xLoc#, yLoc#, speed# ;speed is in pixels/second Field pathAI, pathStatus, pathLength, pathLocation Field pathBank, pathBank1, pathBank2 Field xPath#, yPath#, distanceToNextNode# ;in pixels Field targetX#, targetY#, target.unit, unitCollidingWith.unit Field startNewPath ;used for delayed-action pathfinding Field sprite, red, green, blue Field selected Field xDistanceFromGroupCenter#, yDistanceFromGroupCenter# Field actualAngleFromGroupCenter, assignedAngleFromGroupCenter End Type *) type PrefRecord = record //PMAGValuesFileName, PGCostFileName, PProjectDirectory: string[255]; PSplashScreenDisplayed, PAutoloadObstacleFile, PGridLinesDisplayed, PPathDisplayed:Boolean; PAProjectOptionsFormX,PAProjectOptionsFormY, PAStarFormX,PAStarFormY, PATerrainFormX,PATerrainFormY, PAStarAboutFormX,PAStarAboutFormY, PAGr32ViewerFormX,PAGr32ViewerFormY, PAProjectMapMakerFormX,PAProjectMapMakerFormY, PfrmLandscapeX,PfrmLandscapeY, PSearchMode, PTieBreakerMode, PAStarDataDisplayArrowsColor, PEnemyPositionsColor, PEnemyUnitBaseColor, PEnemyUnitGoalTargetColor, PBackGroundColor, PGridColor, PPathColor, PObstacleColor, PAstarMode,PImageSizeMode,PTileSizeMode:Integer; PActiveUnitNumber,PNumberofUnits,PNumberofUnitPeople, PmapWidth,PmapHeight:Integer; PtileSize, PImageWidth, PImageHeight:Integer; PBaseStartColorArray: Array [1..5]of Integer; PTargetGoalColorArray: Array [1..5]of Integer; end; PrefFile = file of PrefRecord; var PreRcd: PrefRecord; //Global 'temp' data AstarUnitsRunning, EditModeActive, LostinaLoop:Boolean; ProjectFilename:String; //POF file: Stored data ProgramPath:String; // MAGValuesFileName, GCostFileName, ProjectDirectory:String; SplashScreenDisplayed, AutoloadObstacleFile:Boolean; GridLinesDisplayed, PathDisplayed:Boolean; AProjectOptionsFormX,AProjectOptionsFormY, AStarFormX,AStarFormY, ATerrainFormX,ATerrainFormY, AStarAboutFormX,AStarAboutFormY, AGr32ViewerFormX,AGr32ViewerFormY, AProjectMapMakerFormX,AProjectMapMakerFormY, frmLandscapeX,frmLandscapeY:Integer; SearchMode, TieBreakerMode, AStarDataDisplayArrowsColor, GridColor, ObstacleColor, BackGroundColor, PathColor, AstarMode,ImageSizeMode,TileSizeMode:Integer; Procedure InitializePathfinder; Procedure EndPathfinder; function ExecuteFile(const FileName, Params, DefaultDir: string; ShowCmd: Integer): THandle; procedure LoadProjectFile(Filename:String); procedure LoadColorsFile(Filename:String); procedure LoadUnitsFile(Filename:String); procedure LoadTerrainFile(Filename:String); procedure ResetDefaults; procedure LoadGCostValues; procedure SaveGCostValues(mapWidth,mapHeight:Integer); procedure ResetMAGDefaults; procedure LoadMAGValues; procedure SaveMAGValues; procedure DoLoader; procedure SetPreferences; procedure DoSaver; procedure GetPreferences; implementation //--------------------------------------------------------------------------- // Name: InitializePathfinder // Desc: Allocates memory for the pathfinder. //-------------------------------------------------------------------------- Procedure InitializePathfinder; Begin //Create needed arrays SetLength(walkability,mapWidth,mapHeight);//[mapWidth][mapHeight]; SetLength(openList,mapWidth*mapHeight+2);//[mapWidth*mapHeight+2]; //whether a cell is on the open list or on the closed list. SetLength(openX,mapWidth*mapHeight+2);//[mapWidth*mapHeight+2]; SetLength(openY,mapWidth*mapHeight+2);//[mapWidth*mapHeight+2]; SetLength(whichList,mapWidth+1,mapHeight+1);//[mapWidth+1][mapHeight+1]; SetLength(parentX,mapWidth+1,mapHeight+1);//[mapWidth+1][mapHeight+1]; SetLength(parentY,mapWidth+1,mapHeight+1);//[mapWidth+1][mapHeight+1]; SetLength(Fcost,mapWidth*mapHeight+2);//[mapWidth*mapHeight+2]; SetLength(Hcost,mapWidth*mapHeight+2);//[mapWidth*mapHeight+2]; SetLength(Gcost,mapWidth+1,mapHeight+1);//[mapWidth+1][mapHeight+1]; //Demo only //Path reading variables // [numberPeople+1] [xy pairs] SetLength(pathBank,NumberofUnits+1); SetLength(pathLength,NumberofUnits+1);//[numberPeople+1]; SetLength(pathLocation,NumberofUnits+1);//[numberPeople+1]; SetLength(pathStatus,NumberofUnits+1);//[numberPeople+1]; SetLength(xPath,NumberofUnits+1);//[numberPeople+1]; SetLength(yPath,NumberofUnits+1);//[numberPeople+1]; end; //--------------------------------------------------------------------------- // Name: EndPathfinder // Desc: Frees memory used by the pathfinder. //--------------------------------------------------------------------------- Procedure EndPathfinder; Begin //Create needed arrays SetLength(walkability,0); SetLength(openList,0); SetLength(openX,0); SetLength(openY,0); SetLength(whichList,0); SetLength(parentX,0); SetLength(parentY,0); SetLength(Fcost,0); SetLength(Gcost,0); SetLength(Hcost,0); //for (int x = 0; x < numberPeople+1; x++) //Path reading variables for Demos SetLength(pathBank,0); SetLength(pathLength,0); SetLength(pathLocation,0); SetLength(pathStatus,0); SetLength(xPath,0); SetLength(yPath,0); //Should be zeroed by using Unit form SetLength(island,0); SetLength(claimedNode,0); SetLength(nearByPath,0); SetLength(tempUnwalkability,0); SetLength(GCostData,0); SetLength(MapAttribute,0); SetLength(UnitpathBank[1],0); SetLength(UnitpathBank[2],0); //UnitpathBank:Array[1..2]of Array of array of Integer;//Setlength in FindPath end; function ExecuteFile(const FileName, Params, DefaultDir: string; ShowCmd: Integer): THandle; var zFileName, zParams, zDir: array[0..255] of Char; begin Result := ShellExecute(Application.MainForm.Handle, nil, StrPCopy(zFileName, FileName), StrPCopy(zParams, Params), StrPCopy(zDir, DefaultDir), ShowCmd); end; procedure LoadProjectFile(Filename:String); var F: TextFile; S: string; Version:Integer; Const NoName='NoName'; Begin // Load Base data THEN THE SECTION FILENAMES: //Display Color,Units,Terrain File //(Each SECTION Loads their OWN stuff) AssignFile(F, FileName); Reset(F); Readln(F,S);If S='AStar Project File' then Begin Readln(F,S); Version:=Strtoint(S); //Read the Base Information Readln(F,S); ProjectRecord.HeightfieldSizeMode:=Strtoint(S); case ProjectRecord.HeightfieldSizeMode of 0:ProjectRecord.HeightfieldSize:=256; 1:ProjectRecord.HeightfieldSize:=512; 2:ProjectRecord.HeightfieldSize:=1024; end; Readln(F,S); ProjectRecord.RatioSizeMode:=Strtoint(S); case ProjectRecord.RatioSizeMode of 0:ProjectRecord.RatioSize:=1; 1:ProjectRecord.RatioSize:=2; 2:ProjectRecord.RatioSize:=4; 3:ProjectRecord.RatioSize:= 8; end; Readln(F,S); ProjectRecord.ImageSizeMode:=Strtoint(S); //Case into ImageWidth, ImageHeight case ProjectRecord.ImageSizeMode of 0:begin ProjectRecord.ImageWidth:=256; ProjectRecord.ImageHeight:=256; End; 1:begin ProjectRecord.ImageWidth:=512; ProjectRecord.ImageHeight:=512; End; 2:begin ProjectRecord.ImageWidth:=1024; ProjectRecord.ImageHeight:=1024; End; 3:begin ProjectRecord.ImageWidth:=2048; ProjectRecord.ImageHeight:=2048; End; 4:begin ProjectRecord.ImageWidth:=4096; ProjectRecord.ImageHeight:=4096; End; End;//case Readln(F,S); ProjectRecord.TileSizeMode:=Strtoint(S); //Case into tileSize case ProjectRecord.TileSizeMode of 0:begin ProjectRecord.tileSize:=32; End; 1:begin ProjectRecord.tileSize:=16; End; 2:begin ProjectRecord.tileSize:=8; End; 3:begin ProjectRecord.tileSize:=4; End; 4:begin ProjectRecord.tileSize:=2; End; 5:begin ProjectRecord.tileSize:=1; End; end; ProjectRecord.mapWidth := ProjectRecord.ImageWidth div ProjectRecord.tileSize; ProjectRecord.mapHeight := ProjectRecord.ImageWidth div ProjectRecord.tileSize; Readln(F,S); ProjectRecord.TerrainValueAlphaD :=StrtoFloatdef(S); Readln(F,S); ProjectRecord.AverageTerrainD:=StrtoFloatdef(S); Readln(F,S); ProjectRecord.TerrainMagNoGoD:=StrtoFloatdef(S); Readln(F,S); ProjectRecord.AdjacentPathPenaltyD:=StrtoFloatdef(S); Readln(F,S); ProjectRecord.TurningpenaltyD:=StrtoFloatdef(S); Readln(F,S); ProjectRecord.GridLinesDisplayed:= (S='True'); Readln(F,S); ProjectRecord.PathDisplayed:= (S='True'); Readln(F,S); ProjectRecord.ClaimedNodesDisplayed := (S='True'); Readln(F,S); ProjectRecord.ProcessNoGoIslands:= (S='True'); //Read the Section File Names {Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.ColorsFile:=S; If Length(S) > 0 then LoadColorsFile(S); } Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.UnitsFile:=S; If Length(S) > 0 then LoadUnitsFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.TerrainFile:=S; If Length(S) > 0 then LoadTerrainFile(S); //Future Proofing If Version > 1 then begin end; End else showmessage('Not AStar Project File'); CloseFile(F); End; procedure LoadColorsFile(Filename:String); var F: TextFile; S: string; Version:Integer; Begin AssignFile(F, FileName); Reset(F); Readln(F,S);If S='AStar Colors File' then Begin Readln(F,S); Version:=Strtoint(S); Readln(F,S); GridColor:=Strtoint(S); Readln(F,S); ObstacleColor:=Strtoint(S); Readln(F,S); BackGroundColor:=Strtoint(S); Readln(F,S); PathColor:=Strtoint(S); Readln(F,S); AStarDataDisplayArrowsColor:=Strtoint(S); Readln(F,S); BaseStartColorArray[1]:=Strtoint(S); Readln(F,S); BaseStartColorArray[2]:=Strtoint(S); Readln(F,S); BaseStartColorArray[3]:=Strtoint(S); Readln(F,S); BaseStartColorArray[4]:=Strtoint(S); Readln(F,S); BaseStartColorArray[5]:=Strtoint(S); Readln(F,S); TargetGoalColorArray[1]:=Strtoint(S); Readln(F,S); TargetGoalColorArray[2]:=Strtoint(S); Readln(F,S); TargetGoalColorArray[3]:=Strtoint(S); Readln(F,S); TargetGoalColorArray[4]:=Strtoint(S); Readln(F,S); TargetGoalColorArray[5]:=Strtoint(S); Readln(F,S); EnemyPositionsColor:=Strtoint(S); Readln(F,S); EnemyUnitBaseColor:=Strtoint(S); Readln(F,S); EnemyUnitGoalTargetColor:=Strtoint(S); //Future Proofing If Version > 1 then begin end; End; CloseFile(F); End; procedure LoadUnitsFile(Filename:String); var F: TextFile; S: string; Version:Integer; Const NoName='NoName'; Begin AssignFile(F, FileName); Reset(F); Readln(F,S);If S='AStar Units File' then Begin Readln(F,S); Version:=Strtoint(S); Readln(F,S); If (S='True') then ProjectRecord.NumberofActiveEnemyPatrol:=1 else ProjectRecord.NumberofActiveEnemyPatrol:=0; Readln(F,S); //NumberofUnits:=Strtoint(S); ProjectRecord.NumberofActiveUnits := ProjectRecord.NumberofActiveEnemyPatrol+Strtoint(S); //Unit1 Readln(F,S); UnitRecordArray[1].startXLoc:=Strtoint(S); Readln(F,S); UnitRecordArray[1].startYLoc:=Strtoint(S); Readln(F,S); UnitRecordArray[1].targetX:=Strtoint(S); Readln(F,S); UnitRecordArray[1].targetY:=Strtoint(S); Readln(F,S); UnitRecordArray[1].speed:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Manueverability:=Strtoint(S); Readln(F,S); UnitRecordArray[1].armor:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members1X:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members1Y:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members2X:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members2Y:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members3X:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members3Y:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members4X:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members4Y:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members5X:=Strtoint(S); Readln(F,S); UnitRecordArray[1].Members5Y:=Strtoint(S); Readln(F,S); UnitRecordArray[1].OperatingOrders:=Strtoint(S); Readln(F,S); UnitRecordArray[1].SearchMode:=Strtoint(S); Readln(F,S); UnitRecordArray[1].TieBreakerMode:=Strtoint(S); Readln(F,S); If (S= NoName) then S:=''; UnitRecordArray[1].FlagFile:=(S); Readln(F,S); If (S= NoName) then S:=''; UnitRecordArray[1].TargetSize:=StrtoFloatdef(S); Readln(F,S); If (S= NoName) then S:=''; UnitRecordArray[1].Md2Name:=(S); Readln(F,S); If (S= NoName) then S:=''; UnitRecordArray[1].Md2TextureName:=(S); Readln(F,S); UnitRecordArray[1].ActorScale:=StrtoFloatdef(S); Readln(F,S); If (S= NoName) then S:=''; UnitRecordArray[1].Md2WpnName:=(S); Readln(F,S); If (S= NoName) then S:=''; UnitRecordArray[1].Md2WpnTextureName:=(S); //This is ONLY Loaded by the Using Graphics //If Length(S) > 0 then Load; //Unit2 Readln(F,S); UnitRecordArray[2].startXLoc:=Strtoint(S); Readln(F,S); UnitRecordArray[2].startYLoc:=Strtoint(S); Readln(F,S); UnitRecordArray[2].targetX:=Strtoint(S); Readln(F,S); UnitRecordArray[2].targetY:=Strtoint(S); Readln(F,S); UnitRecordArray[2].speed:=Strtoint(S); Readln(F,S); UnitRecordArray[2].Manueverability:=Strtoint(S); // Unit2ManEdit.Text:=S; Readln(F,S); UnitRecordArray[2].armor:=Strtoint(S); // Unit2ArmorEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members:=Strtoint(S); // Unit2MEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members1X:=Strtoint(S); // Unit2M1XEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members1Y:=Strtoint(S); // Unit2M1YEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members2X:=Strtoint(S); // Unit2M2XEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members2Y:=Strtoint(S); // Unit2M2YEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members3X:=Strtoint(S); // Unit2M3XEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members3Y:=Strtoint(S); // Unit2M3YEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members4X:=Strtoint(S); // Unit2M4XEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members4Y:=Strtoint(S); // Unit2M4YEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members5X:=Strtoint(S); // Unit2M5XEdit.Text:=S; Readln(F,S); UnitRecordArray[2].Members5Y:=Strtoint(S); // Unit2M5YEdit.Text:=S; Readln(F,S); UnitRecordArray[2].OperatingOrders:=Strtoint(S); // Unit2OperatingOrdersRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[2].SearchMode:=Strtoint(S); // Unit2SearchRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[2].TieBreakerMode:=Strtoint(S); // Unit2TieBreakerRG.ItemIndex:=Strtoint(S); Readln(F,S); If (S= NoName) then S:=''; // FileAff2Edit.Text:=S; UnitRecordArray[2].FlagFile:=(S); Readln(F,S); If (S= NoName) then S:=''; // TargetSizeEdit2.Text:=S; UnitRecordArray[2].TargetSize:=StrtoFloatdef(S); Readln(F,S); If (S= NoName) then S:=''; // FileAmd2Edit.Text:=S; UnitRecordArray[2].Md2Name:=(S); Readln(F,S); If (S= NoName) then S:=''; // FileAjp2Edit.Text:=S; UnitRecordArray[2].Md2TextureName:=(S); Readln(F,S); UnitRecordArray[2].ActorScale:=StrtoFloatdef(S); // Unit2ActorScaleEdit.Text:=S; Readln(F,S); If (S= NoName) then S:=''; // WpnEdit2.Text:=S; UnitRecordArray[2].Md2WpnName:=(S); Readln(F,S); If (S= NoName) then S:=''; // WpnTextureEdit2.Text:=S; UnitRecordArray[2].Md2WpnTextureName:=(S); //This is ONLY Loaded by the Using Graphics //If Length(S) > 0 then Load; //Unit3 Readln(F,S); UnitRecordArray[3].startXLoc:=Strtoint(S); // Unit3StartXEdit.Text:=S; Readln(F,S); UnitRecordArray[3].startYLoc:=Strtoint(S); // Unit3StartYEdit.Text:=S; Readln(F,S); UnitRecordArray[3].targetX:=Strtoint(S); // Unit3TargetXEdit.Text:=S; Readln(F,S); UnitRecordArray[3].targetY:=Strtoint(S); /// Unit3TargetYEdit.Text:=S; Readln(F,S); UnitRecordArray[3].speed:=Strtoint(S); // Unit3SpeedEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Manueverability:=Strtoint(S); // Unit3ManEdit.Text:=S; Readln(F,S); UnitRecordArray[3].armor:=Strtoint(S); // Unit3ArmorEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members:=Strtoint(S); // Unit3MEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members1X:=Strtoint(S); // Unit3M1XEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members1Y:=Strtoint(S); // Unit3M1YEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members2X:=Strtoint(S); // Unit3M2XEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members2Y:=Strtoint(S); // Unit3M2YEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members3X:=Strtoint(S); // Unit3M3XEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members3Y:=Strtoint(S); // Unit3M3YEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members4X:=Strtoint(S); // Unit3M4XEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members4Y:=Strtoint(S); // Unit3M4YEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members5X:=Strtoint(S); // Unit3M5XEdit.Text:=S; Readln(F,S); UnitRecordArray[3].Members5Y:=Strtoint(S); // Unit3M5YEdit.Text:=S; Readln(F,S); UnitRecordArray[3].OperatingOrders:=Strtoint(S); // Unit3OperatingOrdersRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[3].SearchMode:=Strtoint(S); // Unit3SearchRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[3].TieBreakerMode:=Strtoint(S); // Unit3TieBreakerRG.ItemIndex:=Strtoint(S); Readln(F,S); If (S= NoName) then S:=''; // FileAff3Edit.Text:=S; UnitRecordArray[3].FlagFile:=(S); Readln(F,S); If (S= NoName) then S:=''; // TargetSizeEdit3.Text:=S; UnitRecordArray[3].TargetSize:=StrtoFloatdef(S); Readln(F,S); If (S= NoName) then S:=''; // FileAmd3Edit.Text:=S; UnitRecordArray[3].Md2Name:=(S); Readln(F,S); If (S= NoName) then S:=''; // FileAjp3Edit.Text:=S; UnitRecordArray[3].Md2TextureName:=(S); Readln(F,S); UnitRecordArray[3].ActorScale:=StrtoFloatdef(S); // Unit3ActorScaleEdit.Text:=S; Readln(F,S); If (S= NoName) then S:=''; // WpnEdit3.Text:=S; UnitRecordArray[3].Md2WpnName:=(S); Readln(F,S); If (S= NoName) then S:=''; // WpnTextureEdit3.Text:=S; UnitRecordArray[3].Md2WpnTextureName:=(S); //This is ONLY Loaded by the Using Graphics //If Length(S) > 0 then Load; //Unit4 Readln(F,S); UnitRecordArray[4].startXLoc:=Strtoint(S); // Unit4StartXEdit.Text:=S; Readln(F,S); UnitRecordArray[4].startYLoc:=Strtoint(S); // Unit4StartYEdit.Text:=S; Readln(F,S); UnitRecordArray[4].targetX:=Strtoint(S); // Unit4TargetXEdit.Text:=S; Readln(F,S); UnitRecordArray[4].targetY:=Strtoint(S); // Unit4TargetYEdit.Text:=S; Readln(F,S); UnitRecordArray[4].speed:=Strtoint(S); // Unit4SpeedEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Manueverability:=Strtoint(S); // Unit4ManEdit.Text:=S; Readln(F,S); UnitRecordArray[4].armor:=Strtoint(S); // Unit4ArmorEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members:=Strtoint(S); // Unit4MEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members1X:=Strtoint(S); // Unit4M1XEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members1Y:=Strtoint(S); // Unit4M1YEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members2X:=Strtoint(S); // Unit4M2XEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members2Y:=Strtoint(S); // Unit4M2YEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members3X:=Strtoint(S); // Unit4M3XEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members3Y:=Strtoint(S); // Unit4M3YEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members4X:=Strtoint(S); // Unit4M4XEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members4Y:=Strtoint(S); // Unit4M4YEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members5X:=Strtoint(S); // Unit4M5XEdit.Text:=S; Readln(F,S); UnitRecordArray[4].Members5Y:=Strtoint(S); // Unit4M5YEdit.Text:=S; Readln(F,S); UnitRecordArray[4].OperatingOrders:=Strtoint(S); // Unit4OperatingOrdersRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[4].SearchMode:=Strtoint(S); // Unit4SearchRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[4].TieBreakerMode:=Strtoint(S); // Unit4TieBreakerRG.ItemIndex:=Strtoint(S); Readln(F,S); If (S= NoName) then S:=''; // FileAff4Edit.Text:=S; UnitRecordArray[4].FlagFile:=(S); Readln(F,S); If (S= NoName) then S:=''; // TargetSizeEdit4.Text:=S; UnitRecordArray[4].TargetSize:=StrtoFloatdef(S); Readln(F,S); If (S= NoName) then S:=''; // FileAmd4Edit.Text:=S; UnitRecordArray[4].Md2Name:=(S); Readln(F,S); If (S= NoName) then S:=''; // FileAjp4Edit.Text:=S; UnitRecordArray[4].Md2TextureName:=(S); Readln(F,S); UnitRecordArray[4].ActorScale:=StrtoFloatdef(S); // Unit4ActorScaleEdit.Text:=S; Readln(F,S); If (S= NoName) then S:=''; // WpnEdit4.Text:=S; UnitRecordArray[4].Md2WpnName:=(S); Readln(F,S); If (S= NoName) then S:=''; // WpnTextureEdit4.Text:=S; UnitRecordArray[4].Md2WpnTextureName:=(S); //This is ONLY Loaded by the Using Graphics //If Length(S) > 0 then Load; //Unit5 Readln(F,S); UnitRecordArray[5].startXLoc:=Strtoint(S); // Unit5StartXEdit.Text:=S; Readln(F,S); UnitRecordArray[5].startYLoc:=Strtoint(S); // Unit5StartYEdit.Text:=S; Readln(F,S); UnitRecordArray[5].targetX:=Strtoint(S); // Unit5TargetXEdit.Text:=S; Readln(F,S); UnitRecordArray[5].targetY:=Strtoint(S); // Unit5TargetYEdit.Text:=S; Readln(F,S); UnitRecordArray[5].speed:=Strtoint(S); // Unit5SpeedEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Manueverability:=Strtoint(S); // Unit5ManEdit.Text:=S; Readln(F,S); UnitRecordArray[5].armor:=Strtoint(S); // Unit5ArmorEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members:=Strtoint(S); // Unit5MEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members1X:=Strtoint(S); // Unit5M1XEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members1Y:=Strtoint(S); // Unit5M1YEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members2X:=Strtoint(S); // Unit5M2XEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members2Y:=Strtoint(S); // Unit5M2YEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members3X:=Strtoint(S); // Unit5M3XEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members3Y:=Strtoint(S); // Unit5M3YEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members4X:=Strtoint(S); /// Unit5M4XEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members4Y:=Strtoint(S); // Unit5M4YEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members5X:=Strtoint(S); // Unit5M5XEdit.Text:=S; Readln(F,S); UnitRecordArray[5].Members5Y:=Strtoint(S); // Unit5M5YEdit.Text:=S; Readln(F,S); UnitRecordArray[5].OperatingOrders:=Strtoint(S); // Unit5OperatingOrdersRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[5].SearchMode:=Strtoint(S); // Unit5SearchRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[5].TieBreakerMode:=Strtoint(S); // Unit5TieBreakerRG.ItemIndex:=Strtoint(S); Readln(F,S); If (S= NoName) then S:=''; // FileAff5Edit.Text:=S; UnitRecordArray[5].FlagFile:=(S); Readln(F,S); If (S= NoName) then S:=''; // TargetSizeEdit5.Text:=S; UnitRecordArray[5].TargetSize:=StrtoFloatdef(S); Readln(F,S); If (S= NoName) then S:=''; // FileAmd5Edit.Text:=S; UnitRecordArray[5].Md2Name:=(S); Readln(F,S); If (S= NoName) then S:=''; // FileAjp5Edit.Text:=S; UnitRecordArray[5].Md2TextureName:=(S); Readln(F,S); UnitRecordArray[5].ActorScale:=StrtoFloatdef(S); // Unit5ActorScaleEdit.Text:=S; Readln(F,S); If (S= NoName) then S:=''; // WpnEdit5.Text:=S; UnitRecordArray[5].Md2WpnName:=(S); Readln(F,S); If (S= NoName) then S:=''; // WpnTextureEdit5.Text:=S; UnitRecordArray[5].Md2WpnTextureName:=(S); //This is ONLY Loaded by the Using Graphics //If Length(S) > 0 then Load; //Unit6 Enemy Readln(F,S); UnitRecordArray[6].startXLoc:=Strtoint(S); // Unit6StartXEdit.Text:=S; Readln(F,S); UnitRecordArray[6].startYLoc:=Strtoint(S); // Unit6StartYEdit.Text:=S; Readln(F,S); UnitRecordArray[6].targetX:=Strtoint(S); // Unit6TargetXEdit.Text:=S; Readln(F,S); UnitRecordArray[6].targetY:=Strtoint(S); // Unit6TargetYEdit.Text:=S; Readln(F,S); UnitRecordArray[6].speed:=Strtoint(S); // Unit6SpeedEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Manueverability:=Strtoint(S); // Unit6ManEdit.Text:=S; Readln(F,S); UnitRecordArray[6].armor:=Strtoint(S); // Unit6ArmorEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members:=Strtoint(S); // Unit6MEdit.Text:=S; ProjectRecord.NumberofActiveEnemy:= Strtoint(S); //ProjectRecord.NumberofActiveEnemy+ Readln(F,S); UnitRecordArray[6].Members1X:=Strtoint(S); // Unit6M1XEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members1Y:=Strtoint(S); // Unit6M1YEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members2X:=Strtoint(S); // Unit6M2XEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members2Y:=Strtoint(S); // Unit6M2YEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members3X:=Strtoint(S); // Unit6M3XEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members3Y:=Strtoint(S); // Unit6M3YEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members4X:=Strtoint(S); // Unit6M4XEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members4Y:=Strtoint(S); // Unit6M4YEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members5X:=Strtoint(S); // Unit6M5XEdit.Text:=S; Readln(F,S); UnitRecordArray[6].Members5Y:=Strtoint(S); // Unit6M5YEdit.Text:=S; Readln(F,S); UnitRecordArray[6].OperatingOrders:=Strtoint(S); // Unit6OperatingOrdersRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[6].SearchMode:=Strtoint(S); // Unit6SearchRG.ItemIndex:=Strtoint(S); Readln(F,S); UnitRecordArray[6].TieBreakerMode:=Strtoint(S); // Unit6TieBreakerRG.ItemIndex:=Strtoint(S); Readln(F,S); If (S= NoName) then S:=''; // FileAff6Edit.Text:=S; UnitRecordArray[6].FlagFile:=(S); Readln(F,S); If (S= NoName) then S:=''; // TargetSizeEdit6.Text:=S; UnitRecordArray[6].TargetSize:=StrtoFloatdef(S); Readln(F,S); If (S= NoName) then S:=''; // FileAmd6Edit.Text:=S; UnitRecordArray[6].Md2Name:=(S); Readln(F,S); If (S= NoName) then S:=''; // FileAjp6Edit.Text:=S; UnitRecordArray[6].Md2TextureName:=(S); Readln(F,S); UnitRecordArray[6].ActorScale:=StrtoFloatdef(S); // Unit6ActorScaleEdit.Text:=S; Readln(F,S); If (S= NoName) then S:=''; // WpnEdit6.Text:=S; UnitRecordArray[6].Md2WpnName:=(S); Readln(F,S); If (S= NoName) then S:=''; // WpnTextureEdit6.Text:=S; UnitRecordArray[6].Md2WpnTextureName:=(S); //This is ONLY Loaded by the Using Graphics //If Length(S) > 0 then Load; //Future Proofing If Version > 1 then begin end; End; CloseFile(F); End; procedure LoadTerrainFile(Filename:String); var F: TextFile; S: string; Version:Integer; Const NoName='NoName'; Begin AssignFile(F, FileName); Reset(F); Readln(F,S);If S='AStar Terrain File' then Begin Readln(F,S); Version:=Strtoint(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.HeightDataFile:=S; If Length(S) > 0 then ;//LoadImageFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.ImageTextureFile:=S; If Length(S) > 0 then ;//LoadImageFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.MapAttributesFile:=S; If Length(S) > 0 then ;// Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.ElevationFile:=S; If Length(S) > 0 then ;//LoadElevationFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.VegetationFile:=S; If Length(S) > 0 then ;//LoadVegetationFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.SoilsFile:=S; If Length(S) > 0 then ;//LoadSoilsFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.HydrologyFile:=S; If Length(S) > 0 then ;//LoadHydrologyFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.TransportFile:=S; If Length(S) > 0 then ;//LoadTransportFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.UrbanFile:=S; If Length(S) > 0 then ;//LoadUrbanFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.NOGOFile:=S; If Length(S) > 0 then ;//LoadNOGOFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.ObstaclesFile:=S; If Length(S) > 0 then ;//LoadObstaclesFile(S); Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.InfluenceMapFile:=S; If Length(S) > 0 then ;// Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.GCostFile:=S; If Length(S) > 0 then begin //GCostFileName:=S; LoadGCostValues;//LoadGCostFile(S); end; Readln(F,S); If (S= NoName) then S:=''; ProjectRecord.MAGValuesFile:=S; If Length(S) > 0 then begin //MAGValuesFileName:=S; LoadMAGValues;//LoadMAGValuesFile(S); end; //Future Proofing If Version > 1 then begin end; End; CloseFile(F); End; //This could be a file of integers, instead of Readln strings... procedure LoadGCostValues; var F: TextFile; S: string; Version,x,y,xi,yi,ii:Integer; Const NoName='NoName'; Begin AssignFile(F, ProjectRecord.GCostFile); Reset(F); Readln(F,S);If S='AStar GCost File' then Begin Readln(F,S); Version:=Strtoint(S); Readln(F,S); xi:=Strtoint(S); Readln(F,S); yi:=Strtoint(S); //SetLength(AttributeTileArray,mapWidth+1,mapHeight+1); SetLength(GCostData,xi+1,yi+1); For y:=0 to yi-1 do For x:=0 to xi-1 do begin Readln(F,S); ii:=Strtoint(S); GCostData[x][y] :=ii; end; //Future Proofing If Version > 1 then begin end; End; CloseFile(F); End; procedure SaveGCostValues(mapWidth,mapHeight:Integer); var F: TextFile; S: string; Version,x,y,ii:Integer; Const NoName='NoName'; Begin AssignFile(F, ProjectRecord.GCostFile); Rewrite(F); Writeln(F,'AStar GCost File'); Begin Version:=1; S:=Inttostr(Version); Writeln(F,S); S:=Inttostr(mapWidth); Writeln(F,S); S:=Inttostr(mapHeight); Writeln(F,S); For y:=0 to mapHeight-1 do For x:=0 to mapWidth-1 do begin ii:=GCostData[x][y]; S:=Inttostr(ii); Writeln(F,S); end; //Future Proofing If Version > 1 then begin end; End; CloseFile(F); End; procedure LoadMAGValues; var F: TextFile; S: string; Version,i,ii,iii:Integer; Const NoName='NoName'; Begin AssignFile(F, ProjectRecord.MAGValuesFile); Reset(F); Readln(F,S);If S='AStar MAG File' then Begin Readln(F,S); Version:=Strtoint(S); //OpenHeightDataEdit.Text:=S; // MAGValuesFileName SetLength(MAGColorValueArray,0); Readln(F,S); iii:=Strtoint(S); //showmessage(S); SetLength(MAGColorValueArray,iii); //MAGColorValueArray: Array of Array[1..2] of Integer; For I:=0 to iii-1 do begin Readln(F,S); ii:=Strtoint(S); MAGColorValueArray[I][1] :=ii; Readln(F,S); ii:=Strtoint(S); MAGColorValueArray[I][2] :=ii; end; //Future Proofing If Version > 1 then begin end; End; CloseFile(F); End; procedure SaveMAGValues; var F: TextFile; S: string; i,ii:Integer; Const NoName='NoName'; Begin // MAGValuesFileName SetLength(MAGColorValueArray,0); //showmessage(MAGValuesFileName); AssignFile(F, ProjectRecord.MAGValuesFile); Rewrite(F); writeln(F,'AStar MAG File'); S:=Inttostr(1); writeln(F,S); ii:= Length(MAGColorValueArray); S:=Inttostr(ii); writeln(F,S); //showmessage(s); For I:=0 to ii-1 do begin S:=Inttostr(MAGColorValueArray[I][1]); writeln(F,S); S:=Inttostr(MAGColorValueArray[I][2]); writeln(F,S); end; //Future Proofing //If Version > 1 then begin end; CloseFile(F); End; procedure ResetMAGDefaults; Begin SetLength(MAGColorValueArray,27); //0..26:27 //Transportation 0.4 MAGColorValueArray[0][1]:= RGB(0,0,0); MAGColorValueArray[0][2]:=30; //S-Bare MAGColorValueArray[1][1]:= RGB(175,0,0); MAGColorValueArray[1][2]:=5; //T-Hiway MAGColorValueArray[2][1]:= RGB(159,0,0); MAGColorValueArray[2][2]:=10; //T-Road MAGColorValueArray[3][1]:= RGB(150,0,0); MAGColorValueArray[3][2]:=20; //T-Street MAGColorValueArray[4][1]:= RGB(145,0,0); MAGColorValueArray[4][2]:=20; //T-Dirt Trail //Soils 5..12 Bare Ground is #0 MAGColorValueArray[5][1]:= RGB(160,175,160); MAGColorValueArray[5][2]:=40; //S-Bare MAGColorValueArray[6][1]:= RGB(207,239,207); //veg dead crops MAGColorValueArray[6][2]:=50; //S-Plowed field MAGColorValueArray[7][1]:= RGB(191,175,191); MAGColorValueArray[7][2]:=65; //S-Rocky Boulders MAGColorValueArray[8][1]:= RGB(191,175,91); MAGColorValueArray[8][2]:=75; //S-Muck MAGColorValueArray[9][1]:= RGB(91,175,91); MAGColorValueArray[9][2]:=85; //S-Swamp MAGColorValueArray[10][1]:= RGB(91,175,191); MAGColorValueArray[10][2]:=110; //S-Swamp Lake MAGColorValueArray[11][1]:= RGB(207,191,207); MAGColorValueArray[11][2]:=40; //S-Sand hard packed MAGColorValueArray[12][1]:= RGB(223,207,223); MAGColorValueArray[12][2]:=60; //S-Sand Dunes //Vegetation 13..17 MAGColorValueArray[13][1]:= RGB(254,191,0); MAGColorValueArray[13][2]:=45; // V-Grass MAGColorValueArray[14][1]:= RGB(127,159,127); MAGColorValueArray[14][2]:=50; //V-Mixed MAGColorValueArray[15][1]:= RGB(159,95,0); MAGColorValueArray[15][2]:=55; //V-Shrub MAGColorValueArray[16][1]:= RGB(0,255,0); MAGColorValueArray[16][2]:=65; //V-Forest MAGColorValueArray[17][1]:= RGB(0,111,0); MAGColorValueArray[17][2]:=80; //V-Jungle //Hydrology 18..23 MAGColorValueArray[18][1]:= RGB(0,254,254); MAGColorValueArray[18][2]:=65; //H-Stream (fordable) MAGColorValueArray[19][1]:= RGB(0,0,254); MAGColorValueArray[19][2]:=110; //H-River MAGColorValueArray[20][1]:= RGB(0,0,254); MAGColorValueArray[20][2]:=110; //H-Lake MAGColorValueArray[21][1]:= RGB(254,254,254); MAGColorValueArray[21][2]:=75; //H-Snow<1 ft MAGColorValueArray[22][1]:= RGB(207,207,207); MAGColorValueArray[22][2]:=110; //H-Snow>1 ft MAGColorValueArray[23][1]:= RGB(211,211,211); MAGColorValueArray[23][2]:=110; //H-Ice //Urban 24 25 MAGColorValueArray[24][1]:= RGB(225,0,0); MAGColorValueArray[24][2]:=65; //U-Housing MAGColorValueArray[25][1]:= RGB(254,0,0); MAGColorValueArray[25][2]:=75; //U-Urban areas //Obstacle Nogo 26 MAGColorValueArray[26][1]:= RGB(100,100,100); MAGColorValueArray[26][2]:=110; //O-NoGo areas End; {Reset Directories and all other defaults} procedure ResetDefaults; Begin ProjectDirectory:= ExtractFilePath(ParamStr(0))+'Projects'; //MAGValuesFileName ProjectRecord.MAGValuesFile:=ProjectDirectory+'\MagDefault.abf'; //showmessage(ProjectDirectory+'\MagDefault.abf'); ResetMAGDefaults; AProjectOptionsFormX:=200; AProjectOptionsFormY:=120; AStarFormX:=20; AStarFormY:=0; ATerrainFormX:=10; ATerrainFormY:=10; AGr32ViewerFormX:=10; AGr32ViewerFormY:=10; AStarAboutFormX:=280; AStarAboutFormY:=80; AProjectMapMakerFormX:=20; AProjectMapMakerFormY:=20; frmLandscapeX:=30; frmLandscapeY:=30; EditModeActive:=True; SplashScreenDisplayed:=True; AutoloadObstacleFile:=False; TileSizeMode:=0; tileSize := 50; ImageSizeMode:=0; ImageWidth:=650; ImageHeight:=500; mapWidth := 65;//80; mapHeight := 50;//60; SearchMode:=2; TieBreakerMode:=0; GridLinesDisplayed:=True; PathDisplayed:=True; AStarDataDisplayArrowsColor:=0; BackGroundColor:=clBlack; GridColor:=clBlue; ObstacleColor:=clBlue; PathColor:=clLime; EnemyPositionsColor:=clTeal; EnemyUnitBaseColor:=clFuchsia; EnemyUnitGoalTargetColor:=clFuchsia; BaseStartColorArray[1]:=clRed; TargetGoalColorArray[1]:=clRed; BaseStartColorArray[2]:=clYellow; TargetGoalColorArray[2]:=clYellow; BaseStartColorArray[3]:=clAqua; TargetGoalColorArray[3]:=clAqua; BaseStartColorArray[4]:=clLime; TargetGoalColorArray[4]:=clLime; BaseStartColorArray[5]:=clSilver; TargetGoalColorArray[5]:=clSilver; //Set Data Demo location AstarMode:=1; //pathfinderID is used TOO MUCH as Variable ActiveUnitNumber:=1; NumberofUnits := 1; startXLocArray[ActiveUnitNumber] := 3; startYLocArray[ActiveUnitNumber] := 6; //Set initial target location. This can //be changed by right-clicking on the map. targetXLocArray[ActiveUnitNumber] := 12; targetYLocArray[ActiveUnitNumber] := 6; speedArray[ActiveUnitNumber] := 5; End; procedure DoLoader; var P_File: PrefFile; var PathS: string; begin {} PathS := ExtractFilePath(ParamStr(0)) + 'AStar.pof'; if FileExists(PathS) then begin AssignFile(P_File, PathS); Reset(P_File); if IoResult <> 0 then ;//DoMessages(39984); Read(P_File, PreRcd); CloseFile(P_File); SetPreferences; end; //else DoMessages(39985); {ProjectRecord.MAGValuesFile :=ProjectDirectory+'\MagDefault.abf'; if FileExists(MAGValuesFileName) then LoadMAGValues else ResetMAGDefaults;} end; procedure SetPreferences; var i:Integer; begin {after loading} with PreRcd do begin // GCostFileName:=PGCostFileName; //ProjectRecord.MAGValuesFile:=PMAGValuesFileName; ProjectDirectory:=PProjectDirectory; AProjectOptionsFormX:=PAProjectOptionsFormX; AProjectOptionsFormY:=PAProjectOptionsFormY; AStarFormX:=PAStarFormX; AStarFormY:=PAStarFormY; ATerrainFormX:=PATerrainFormX; ATerrainFormY:=PATerrainFormY; AStarAboutFormX:=PAStarAboutFormX; AStarAboutFormY:=PAStarAboutFormY; AGr32ViewerFormX:=PAGr32ViewerFormX; AGr32ViewerFormY:=PAGr32ViewerFormY; AProjectMapMakerFormX:=PAProjectMapMakerFormX; AProjectMapMakerFormY:=PAProjectMapMakerFormY; frmLandscapeX:=PfrmLandscapeX; frmLandscapeY:=PfrmLandscapeY; SplashScreenDisplayed:=PSplashScreenDisplayed; AutoloadObstacleFile:=PAutoloadObstacleFile; GridLinesDisplayed:=PGridLinesDisplayed; PathDisplayed:=PPathDisplayed; SearchMode:=PSearchMode; TieBreakerMode:=PTieBreakerMode; AStarDataDisplayArrowsColor:=PAStarDataDisplayArrowsColor; BackGroundColor:=PBackGroundColor; GridColor:=PGridColor; PathColor:=PPathColor; ObstacleColor:=PObstacleColor; EnemyPositionsColor:=PEnemyPositionsColor; EnemyUnitBaseColor:=PEnemyUnitBaseColor; EnemyUnitGoalTargetColor:=PEnemyUnitGoalTargetColor; AstarMode:=PAstarMode; TileSizeMode:=PTileSizeMode; ImageSizeMode:=PImageSizeMode; ActiveUnitNumber:=PActiveUnitNumber; NumberofUnits:=PNumberofUnits; NumberofUnitPeople:=PNumberofUnitPeople; mapWidth:=PmapWidth; mapHeight:=PmapHeight; tileSize:=PtileSize; ImageWidth:=PImageWidth; ImageHeight:=PImageHeight; For i:=1 to 5 do BaseStartColorArray[i]:= PBaseStartColorArray[i]; For i:=1 to 5 do TargetGoalColorArray[i]:=PTargetGoalColorArray[i]; end; end; {---------------------------------------------------------------------} procedure DoSaver; var P_File: PrefFile; var PathS: string; begin PathS := ExtractFilePath(ParamStr(0)) + 'AStar.pof'; if (not FileExists(PathS)) then ;//DoMessages(14{39987}); GetPreferences; AssignFile(P_File, PathS); Rewrite(P_File); if IoResult <> 0 then begin //DoMessages(39986); end; //ProjectRecord.MAGValuesFile :=ProjectDirectory+'\MagDefault.abf'; write(P_File, PreRcd); CloseFile(P_File); //SaveMAGValues; end; {---------------------------------------------------------------------} procedure GetPreferences; var i:Integer; begin {before saving} with PreRcd do begin //PGCostFileName:=ProjectRecord.GCostFile; //PMAGValuesFileName:=ProjectRecord.MAGValuesFile; PProjectDirectory:=ProjectDirectory; PAProjectOptionsFormX:=AProjectOptionsFormX; PAProjectOptionsFormY:=AProjectOptionsFormY; PAStarFormX:=AStarFormX; PAStarFormY:=AStarFormY; PATerrainFormX:=ATerrainFormX; PATerrainFormY:=ATerrainFormY; PAStarAboutFormX:=AStarAboutFormX; PAStarAboutFormY:=AStarAboutFormY; PAGr32ViewerFormX:=AGr32ViewerFormX; PAGr32ViewerFormY:=AGr32ViewerFormY; PAProjectMapMakerFormX:=AProjectMapMakerFormX; PAProjectMapMakerFormY:=AProjectMapMakerFormY; PfrmLandscapeX:=frmLandscapeX; PfrmLandscapeY:=frmLandscapeY; PSplashScreenDisplayed:=SplashScreenDisplayed; PAutoloadObstacleFile:=AutoloadObstacleFile; PGridLinesDisplayed:=GridLinesDisplayed; PPathDisplayed:=PathDisplayed; PSearchMode:=SearchMode; PTieBreakerMode:=TieBreakerMode; PAStarDataDisplayArrowsColor:=AStarDataDisplayArrowsColor; PBackGroundColor:=BackGroundColor; PGridColor:=GridColor; PPathColor:=PathColor; PObstacleColor:=ObstacleColor; PEnemyPositionsColor:=EnemyPositionsColor; PEnemyUnitBaseColor:=EnemyUnitBaseColor; PEnemyUnitGoalTargetColor:=EnemyUnitGoalTargetColor; PAstarMode:=AstarMode; PTileSizeMode:=TileSizeMode; PImageSizeMode:=ImageSizeMode; PActiveUnitNumber:=ActiveUnitNumber; PNumberofUnits:=NumberofUnits; PNumberofUnitPeople:=NumberofUnitPeople; PmapWidth:=mapWidth; PmapHeight:=mapHeight; PtileSize:=tileSize; PImageWidth:=ImageWidth; PImageHeight:=ImageHeight; For i:=1 to 5 do PBaseStartColorArray[i]:= BaseStartColorArray[i]; For i:=1 to 5 do PTargetGoalColorArray[i]:=TargetGoalColorArray[i]; end; end; (* For i:=0 to 18 do AttributeColorArray[i]:=PAttributeColorArray[i]; For i:=0 to 18 do AttributeValueArray[i]:=PAttributeValueArray[i]; For i:=0 to 18 do AttributeColorArray[i]:=PAttributeColorArray[i]; For i:=0 to 18 do AttributeValueArray[i]:=PAttributeValueArray[i]; *) (*//Unit1 Read(F,S); UnitRecordArray[1].OperatingOrders:=Strtoint(S); :=Strtoint(S); Read(F,S); UnitRecordArray[1].SearchMode:=Strtoint(S); :=Strtoint(S); Read(F,S); UnitRecordArray[1].TieBreakerMode:=Strtoint(S); :=Strtoint(S); Read(F,S); If (S= NoName) then S:=''; FileAff1Edit.Text:=S; UnitRecordArray[1].FlagFile:=(S); //This is ONLY Loaded by the Using Graphics //If Length(S) > 0 then Load; *) end.
unit ExtendedReport; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, StdCtrls, ComCtrls, ToolWin, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Ibase,Menus, FIBDatabase, pFIBDatabase,DateUtils, FIBDataSet, pFIBDataSet,pFibStoredProc, ExtCtrls, Buttons,IB_Externals,RegUnit, cxCheckBox, cxTextEdit, Resources_unitb, GlobalSpr, cxGridBandedTableView, cxGridDBBandedTableView, cxContainer, cxDBEdit, cxProgressBar, cxDBProgressBar,FibQuery, UPrBar, cxMaskEdit, cxDropDownEdit, cxLookAndFeelPainters, cxButtons, cxSpinEdit, cxTimeEdit, cxCalendar, cxButtonEdit, frxClass, frxDBSet; type TfrmSmetaSpr = class(TForm) WorkDatabase: TpFIBDatabase; WriteTransaction: TpFIBTransaction; ReadTransaction: TpFIBTransaction; ReportDataSet: TpFIBDataSet; SmetaSource: TDataSource; cbMonthBeg: TcxComboBox; cbYearBeg: TcxComboBox; cxButtonEdit1: TcxButtonEdit; cbMonthEnd: TcxComboBox; cbYearEnd: TcxComboBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; cxDateEdit1: TcxDateEdit; cxTimeEdit1: TcxTimeEdit; cxButton1: TcxButton; cxButton2: TcxButton; frxDBDataset1: TfrxDBDataset; RestDataSet: TpFIBDataSet; frxDBDataset2: TfrxDBDataset; frxReport1: TfrxReport; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxButton1Click(Sender: TObject); procedure cxButton2Click(Sender: TObject); private { Private declarations } id_smeta : int64; smeta_kod : integer; smeta_title: string; function CheckData:Boolean; public INFINITY_DATE:TdateTime; ResultValue:Variant; { Public declarations } constructor Create(AOwner:TComponent; DBHandle:TISC_DB_HANDLE);reintroduce; end; implementation {$R *.dfm} constructor TfrmSmetaSpr.Create(AOwner: TComponent; DBHandle: TISC_DB_HANDLE); var i:Integer; begin inherited Create(AOwner); Self.WorkDatabase.Handle:=DBHAndle; ReadTransaction.StartTransaction; cxDateEdit1.Date:=Date; cxTimeEdit1.Time:=Time; cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_01)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_02)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_03)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_04)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_05)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_06)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_07)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_08)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_09)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_10)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_11)); cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_12)); for i:=0 to YEARS_COUNT do begin cbYearBeg.Properties.Items.Add(TRIM(IntToStr(BASE_YEAR+i))); end; cbMonthBeg.ItemIndex:=MonthOf(Date)-1; for i:=0 to cbYearBeg.Properties.Items.Count-1 do begin if pos(cbYearBeg.Properties.Items[i],IntToStr(YearOf(Date)))>0 then begin cbYearBeg.ItemIndex:=i; break; end; end; cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_01)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_02)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_03)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_04)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_05)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_06)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_07)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_08)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_09)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_10)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_11)); cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_12)); for i:=0 to YEARS_COUNT do begin cbYearEnd.Properties.Items.Add(TRIM(IntToStr(BASE_YEAR+i))); end; cbMonthEnd.ItemIndex:=MonthOf(IncMonth(Date,1))-1; for i:=0 to cbYearEnd.Properties.Items.Count-1 do begin if pos(cbYearEnd.Properties.Items[i],IntToStr(YearOf(IncMonth(Date,1))))>0 then begin cbYearEnd.ItemIndex:=i; break; end; end; end; procedure TfrmSmetaSpr.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TfrmSmetaSpr.cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var Res:Variant; begin Res:=GlobalSpr.GetSmets(self, WorkDatabase.Handle, Date, psmSmet); if VarArrayDimCount(Res)>0 then begin id_smeta :=VarAsType(Res[0],varInt64);; smeta_kod :=Res[3]; smeta_title:=VarToStr(Res[2]); cxButtonEdit1.Text:=VarToStr(Res[3])+' "'+VarToStr(Res[2])+'"'; cxButton1.Enabled:=true; end; end; procedure TfrmSmetaSpr.cxButton1Click(Sender: TObject); var DateBeg,DateEnd:TDateTime; begin if checkData then begin DateBeg:=StrToDate('01.'+IntToStr(cbMonthBeg.ItemIndex+1)+'.'+cbYearBeg.Properties.Items[cbYearBeg.ItemIndex]); DateEnd:=StrToDate('01.'+IntToStr(cbMonthEnd.ItemIndex+1)+'.'+cbYearEnd.Properties.Items[cbYearEnd.ItemIndex]); Screen.Cursor:=crHourGlass; if RestDataSet.Active then RestDataSet.Close; RestDataSet.SelectSQL.Text:=' SELECT * FROM BU_GET_BUDGET_FVALUES_RESTS('+IntToStr(id_smeta)+' ,'+ ''''+DateToStr(DateBeg)+''''+','+ ''''+DateToStr(DateEnd)+''''+')'; RestDataSet.Open; If ReportDataSet.Active then ReportDataSet.Close; ReportDataSet.SelectSQL.Text:=' SELECT * FROM BU_GET_BUDGET_FVALUES('+IntToStr(id_smeta)+' ,'+ ''''+DateToStr(DateBeg)+''''+','+ ''''+DateToStr(DateEnd)+''''+') ORDER BY PROFIT_FLAG DESC, SHOW_POSITION, SHOW_NUM'; frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Budgeting\ExtendedReport.fr3',true); frxReport1.Variables['TITLE']:=''''+IntToStr(smeta_kod)+' "'+smeta_title+'"('+DateToStr(DateBeg)+'-'+DateToStr(DateEnd)+')'+''''; frxReport1.Variables['DATE_DATA']:=Date; frxReport1.PrepareReport(true); Screen.Cursor:=crDefault; frxReport1.ShowPreparedReport; end else ShowMessage('Не можна сформувати звіт, бо бюджет має внутрішні бюджети в заданому періоді!'); end; procedure TfrmSmetaSpr.cxButton2Click(Sender: TObject); begin Close; end; function TfrmSmetaSpr.CheckData: Boolean; var CheckStoredProc:TpFibStoredProc; DateBeg,DateEnd:TDateTime; Res:Boolean; begin DateBeg:=StrToDate('01.'+IntToStr(cbMonthBeg.ItemIndex+1)+'.'+cbYearBeg.Properties.Items[cbYearBeg.ItemIndex]); DateEnd:=StrToDate('01.'+IntToStr(cbMonthEnd.ItemIndex+1)+'.'+cbYearEnd.Properties.Items[cbYearEnd.ItemIndex]); CheckStoredProc :=TpFibStoredProc.Create(self); CheckStoredProc.Database :=WorkDatabase; CheckStoredProc.Transaction:=ReadTransaction; CheckStoredProc.StoredProcName:='BU_GET_BUDGET_FVALUES_CHECK'; CheckStoredProc.Prepare; CheckStoredProc.ParamByName('ID_SM').Value :=id_smeta; CheckStoredProc.ParamByName('DATE_BEG').Value:=DateBeg; CheckStoredProc.ParamByName('DATE_END').Value:=DateEnd; CheckStoredProc.ExecProc; Res:=Boolean(CheckStoredProc.ParamByName('RESULT').AsInteger); CheckStoredProc.Close; CheckStoredProc.Free; Result:=Res; end; end.
unit UDPrintOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32; type TCrpePrintOptionsDlg = class(TForm) pnlPrintOptions: TPanel; lblCopies: TLabel; lblOutputFileName: TLabel; rgPages: TRadioGroup; editStopPage1: TEdit; editStartPage2: TEdit; editStopPage2: TEdit; cbCollation: TCheckBox; editOutputFileName: TEdit; btnOk: TButton; btnCancel: TButton; btnClear: TButton; btnPrompt: TButton; editCopies: TEdit; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure editCopiesChange(Sender: TObject); procedure cbCollationClick(Sender: TObject); procedure rgPagesClick(Sender: TObject); procedure editOutputFileNameChange(Sender: TObject); procedure btnPromptClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure UpdatePrintOptions; procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure editStartPage2Change(Sender: TObject); procedure editStopPage2Change(Sender: TObject); procedure editStopPage1Change(Sender: TObject); procedure InitializeControls(OnOff: boolean); private { Private declarations } public { Public declarations } Cr : TCrpe; rCollation : Boolean; rCopies : Word; rOutputFileName : string; rStartPage : Word; rStopPage : Word; end; var CrpePrintOptionsDlg: TCrpePrintOptionsDlg; bPrintOptions : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.FormCreate(Sender: TObject); begin bPrintOptions := True; LoadFormPos(Self); btnOk.Tag := 1; btnCancel.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.FormShow(Sender: TObject); begin {Store PrintOptions settings} rCollation := Cr.PrintOptions.Collation; rCopies := Cr.PrintOptions.Copies; rOutputFileName := Cr.PrintOptions.OutputFileName; rStartPage := Cr.PrintOptions.StartPage; rStopPage := Cr.PrintOptions.StopPage; UpdatePrintOptions; end; {------------------------------------------------------------------------------} { UpdatePrintOptions procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.UpdatePrintOptions; var OnOff : boolean; begin {Enable/Disable controls} OnOff := not IsStrEmpty(Cr.ReportName); InitializeControls(OnOff); {Update list box} if OnOff = True then begin {Copies} editCopies.Text := IntToStr(Cr.PrintOptions.Copies); {Start/Stop Page} rgPages.OnClick := nil; if Cr.PrintOptions.StartPage = 1 then begin if Cr.PrintOptions.StopPage = 1 then rgPages.ItemIndex := 1 else if Cr.PrintOptions.StopPage = 65535 then rgPages.ItemIndex := 0 else begin rgPages.ItemIndex := 2; editStopPage1.Text := IntToStr(Cr.PrintOptions.StopPage); end; end else if Cr.PrintOptions.StartPage > 1 then begin rgPages.ItemIndex := 3; editStartPage2.Text := IntToStr(Cr.PrintOptions.StartPage); editStopPage2.Text := IntToStr(Cr.PrintOptions.StopPage); end else rgPages.ItemIndex := 0; rgPages.OnClick := rgPagesClick; {Collation} cbCollation.Checked := Cr.PrintOptions.Collation; {OutputFileName} editOutputFileName.Text := Cr.PrintOptions.OutputFileName; end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { rgPagesClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.rgPagesClick(Sender: TObject); var nPage : integer; begin case rgPages.ItemIndex of {All} 0: begin Cr.PrintOptions.StartPage := 1; Cr.PrintOptions.StopPage := 65535; end; {First Page} 1: begin Cr.PrintOptions.StartPage := 1; Cr.PrintOptions.StopPage := 1; end; {Page 1 to ...} 2: begin Cr.PrintOptions.StartPage := 1; if IsNumeric(editStopPage1.Text) then nPage := StrToInt(editStopPage1.Text) else begin editStopPage1.Text := '0'; nPage := 0; end; Cr.PrintOptions.StopPage := nPage; end; {Page ... to ...} 3: begin {StartPage} if IsNumeric(editStartPage2.Text) then nPage := StrToInt(editStartPage2.Text) else begin editStartPage2.Text := '0'; nPage := 0; end; Cr.PrintOptions.StartPage := nPage; {StopPage} if IsNumeric(editStopPage2.Text) then nPage := StrToInt(editStopPage2.Text) else begin editStopPage2.Text := '0'; nPage := 0; end; Cr.PrintOptions.StopPage := nPage; end; end; end; {------------------------------------------------------------------------------} { editCopiesChange procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.editCopiesChange(Sender: TObject); begin if IsNumeric(editCopies.Text) then Cr.PrintOptions.Copies := StrToInt(editCopies.Text); end; {------------------------------------------------------------------------------} { cbCollationClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.cbCollationClick(Sender: TObject); begin Cr.PrintOptions.Collation := cbCollation.Checked; end; {------------------------------------------------------------------------------} { editStopPage2Change procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.editStopPage1Change(Sender: TObject); begin if IsNumeric(editStopPage1.Text) then Cr.PrintOptions.StopPage := StrToInt(editStopPage1.Text); end; {------------------------------------------------------------------------------} { editStartPage2Change procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.editStartPage2Change(Sender: TObject); begin if IsNumeric(editStartPage2.Text) then Cr.PrintOptions.StartPage := StrToInt(editStartPage2.Text); end; {------------------------------------------------------------------------------} { editStopPage2Change procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.editStopPage2Change(Sender: TObject); begin if IsNumeric(editStopPage2.Text) then Cr.PrintOptions.StopPage := StrToInt(editStopPage2.Text); end; {------------------------------------------------------------------------------} { editOutputFileNameChange procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.editOutputFileNameChange(Sender: TObject); begin Cr.PrintOptions.OutputFileName := editOutputFileName.Text; end; {------------------------------------------------------------------------------} { btnPromptClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.btnPromptClick(Sender: TObject); begin Cr.PrintOptions.Prompt; end; {------------------------------------------------------------------------------} { btnClearClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.btnClearClick(Sender: TObject); begin Cr.PrintOptions.Clear; UpdatePrintOptions; end; {------------------------------------------------------------------------------} { btnOkClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { btnCancelClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose procedure } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult = mrCancel then begin {Restore Original Settings} Cr.PrintOptions.Collation := rCollation; Cr.PrintOptions.Copies := rCopies; Cr.PrintOptions.OutputFileName := rOutputFileName; Cr.PrintOptions.StartPage := rStartPage; Cr.PrintOptions.StopPage := rStopPage; end; bPrintOptions := False; Release; end; end.
(* Category: SWAG Title: 16/32 BIT CRC ROUTINES Original name: 0003.PAS Description: 16 BIT CRC Author: GREG VIGNEAULT Date: 05-28-93 13:35 *) { The following is a Turbo/Quick Pascal Implementation of calculating the XModem Type of 16-bit cyclic redundancy checking (CRC). Is there a preference For the language of the next CRC-16 example (80x86 Assembly, BASIC, or C) ? } (*******************************************************************) Program TPCRC16; { Compiler: TurboPascal 4.0+ & QuickPascal 1.0+ } { Turbo Pascal 16-bit Cyclic Redundancy Checking (CRC) a.la. XModem } { Greg Vigneault, Box 7169, Station A, toronto, Canada M5W 1X8. } Const Beep = #7; { ASCII bell tone } Type bArray = Array [1..$4000] of Byte; { define buffer } bPointer = ^bArray; { Pointer to buffer } Var DataPtr : bPointer; { Pointer to data } fName : String; { File name } fHandle : File; { File handle } BytesIn : Word; { For counting data } CRC16 : Integer; { running CRC-16 } {-------------------------------------------------------------------} Procedure WriteHex( raw : Integer ); { display hexadecimal value } Var ch : Char; shft : Byte; begin if (raw = 0) then Write('0') { if zero } else begin shft := 16; { bit count } Repeat { isolate each hex nibble, and convert to ASCII } DEC( shft, 4 ); { shift by nibble } ch := CHR( raw SHR shft and $F or orD('0') ); {0..9 } if (ch > '9') then inC( ch, 7 ); {A..F } Write( ch ); { display the digit } Until (shft = 0); end; end {WriteHex}; {-------------------------------------------------------------------} Function UpdateCRC16(CRC : Integer; { CRC-16 to update } InBuf : bPointer; { Pointer to data } InLen : Integer) :Integer; { data count } Var Bit, ByteCount : Integer; Carry : Boolean; { catch overflow } begin For ByteCount := 1 to InLen do { all data Bytes } For Bit := 7 doWNto 0 do begin { 8 bits per Byte } Carry := CRC and $8000 <> 0; { shift overlow? } CRC := CRC SHL 1 or InBuf^[ByteCount] SHR Bit and 1; if Carry then CRC := CRC xor $1021; { apply polynomial } end; { For Bit & ByteCount } { all Bytes & bits } UpdateCRC16 := CRC; { updated CRC-16 } end {UpdateCRC16}; {-------------------------------------------------------------------} begin { check For memory } { if ( MaxAvail < Sizeof(bArray) ) then begin WriteLn( 'not enough memory!', Beep ); Halt(1); end; } if (ParamCount <> 1) then begin { File name input? } WriteLn( 'Use TPCRC16 <fName>', Beep );; Halt(2); end; fName := ParamStr(1); { get File name } Assign( fHandle, fName ); { open the File } {$i-} Reset( fHandle, 1 ); {$i+} { open succeeded? } if (IoResult <> 0) then begin { if not ... } WriteLn( 'File access ERRor', Beep ); Halt(3); end; New( DataPtr ); { allocate memory } CRC16 := 0; { initialize CRC-16 } Repeat BlockRead( fHandle, DataPtr^[1], Sizeof(bArray), BytesIn ); CRC16 := UpdateCRC16( CRC16, DataPtr, BytesIn ); Until (BytesIn <> Sizeof(bArray)) or Eof(fHandle); Close( fHandle ); { close input File } DataPtr^[1] := 0; DataPtr^[2] := 0; { insert two nulls } CRC16 := UpdateCRC16( CRC16, DataPtr, 2 ); { For final calc } Dispose( DataPtr ); { release memory } Write( 'The CRC-16 of File ', fName, ' is $' ); WriteHex( CRC16 ); WriteLn; end {TPCRCXMO}. (*********************************************************************) 
unit txNodes; interface uses txDefs, txCache; type TLocationNodeDisplayItem=(ghLink,ghIcon,ghTypeName,ghName,ghTitle,ghListItemSelect,ghFrameListClass); TLocationNodeDisplayItems=set of TLocationNodeDisplayItem; TLocationNode=class(TItemCacheNode) private it:TtxItemType; pid,id,icon:integer; typename,name:string; public constructor Create(ItemType:TtxItemType; QueryID:integer); function GetHTML(Display:TLocationNodeDisplayItems; var ParentID:integer):WideString; function GetListItemSelectHTML(var ParentID:integer):WideString; end; const ghFull:TLocationNodeDisplayItems=[ghLink,ghIcon,ghTypeName,ghName]; implementation uses SysUtils, xxm, txSession, DataLank; { TLocationNode } constructor TLocationNode.Create(ItemType:TtxItemType;QueryID:integer); var qr:TQueryResult; sql:UTF8String; begin inherited Create; it:=ItemType; if it=itObj then sql:='SELECT Obj.id, Obj.pid, ObjType.icon, ObjType.name AS typename, Obj.name FROM Obj INNER JOIN ObjType ON ObjType.id=Obj.objtype_id WHERE Obj.id=?' else sql:='SELECT * FROM '+txItemTypeTable[ItemType]+' WHERE id=?'; qr:=TQueryResult.Create(Session.DbCon,sql,[QueryID]); try id:=qr.GetInt('id'); pid:=qr.GetInt('pid'); icon:=qr.GetInt('icon'); if it=itObj then typename:=qr.GetStr('typename'); name:=qr.GetStr('name'); finally qr.Free; end; end; function TLocationNode.GetHTML(Display:TLocationNodeDisplayItems; var ParentID:integer):WideString; begin ParentID:=pid; Result:=''; if ghLink in Display then begin Result:=Result+'<a href="Item.xxm?x='+txItemTypeKey[it]+IntToStr(id)+'"'; if ghListItemSelect in Display then Result:=Result+' onclick="return listitem_select(event,'+IntToStr(id)+');"'; if ghTitle in Display then Result:=Result+' title="'+HTMLEncode(name)+'"'; if ghTypeName in Display then Result:=Result+' title="'+HTMLEncode(typename)+'"'; if ghFrameListClass in Display then Result:=Result+' class="fli fli'+IntToStr(id)+'"'; Result:=Result+'>'; end; if ghIcon in Display then Result:=Result+txImg(icon); if ghName in Display then Result:=Result+'&nbsp;'+HTMLEncode(name); if ghLink in Display then Result:=Result+'</a>'; end; function TLocationNode.GetListItemSelectHTML(var ParentID:integer):WideString; begin ParentID:=pid; Result:='<a href="Item.xxm?x=i'+IntToStr(id)+'" onclick="return listitem_select(event,'+IntToStr(id)+');" title="'+HTMLEncode(name)+'" class="fli fli'+IntToStr(id)+'">'+txImg(icon)+'</a>'; end; end.
// vim: set syntax=delphi: const // path from lumbridge spawn to wizard tower, goes past lumby church, the coffin, and father urhney on the way MAIN_PATH_RAW = [[864, 503], [900, 503], [914, 526], [910, 556], [914, 570], [936, 575], [946, 595], [943, 622], [934, 652], [923, 681], [914, 705], [903, 732], [876, 748], [830, 752], [795, 745], [759, 754], [716, 763], [677, 755], [645, 737], [605, 728], [598, 699], [584, 675], [573, 642], [550, 607], [539, 558], [510, 534], [473, 530], [430, 534], [424, 579], [424, 613], [423, 655], [422, 697]]; type TPositions = record Coffin, CoffinDoor, FatherAereck, FatherAereckDoor, FatherUrhney, FatherUrhneyDoor, LumbridgeSpawn, WizardBasementAltar, WizardBasementDoor, WizardBasementLadder, WizardTowerInsideDoor, WizardTowerOutsideDoor: TPoint; end; var P: TPositions; MainPath: Array of TPoint; WebPath: TWebGraph; procedure InitWebPath(); var rawNode: Array of Int64; p: TPoint; i: Integer = -1; begin for RawNode in MAIN_PATH_RAW do begin p := Point(rawNode[0], rawNode[1]); WebPath.AddNode(p, i); Inc(i); end; end; // initialization begin P.Coffin := Point(967, 607); P.CoffinDoor := Point(956, 605); P.FatherAereck := Point(944, 538); P.FatherAereckDoor := Point(944, 514); P.FatherUrhney := Point(558, 675); P.FatherUrhneyDoor := Point(558, 686); P.LumbridgeSpawn := Point(864, 503); P.WizardBasementAltar := Point(214, 168); // basement map P.WizardBasementDoor := Point(180, 199); // basement map P.WizardBasementLadder := Point(158, 130); // basement map P.WizardTowerInsideDoor := Point(398, 728); P.WizardTowerOutsideDoor := Point(406, 710); InitWebPath(); WebPath.AddNode(P.Coffin, -1); WebPath.AddNode(P.CoffinDoor, -1); WebPath.AddNode(P.FatherAereck, -1); WebPath.AddNode(P.FatherAereckDoor, -1); WebPath.AddNode(P.FatherUrhney, -1); WebPath.AddNode(P.FatherUrhneyDoor, -1); WebPath.AddNode(P.LumbridgeSpawn, -1); WebPath.AddNode(P.WizardTowerInsideDoor, -1); WebPath.AddNode(P.WizardTowerOutsideDoor, -1); RSW_Graph := WebPath; end;
unit EdictWriter; { Функции, связанные с записью в формат EDICT. Все варианты формата более-менее похожи, и происходят из JMDict, поэтому данные передаются им в одинаковой форме, однако младшие форматы их немного упрощают. } //{$DEFINE ICONV_EDICT1} { EDICT2/JMDict поддерживает любые юникод-символы в теле статьи. Однако EDICT1 официально позволяет только US-ASCII (а мы расширяем это до CP1251). По умолчанию мы плюём на это требование и выводим в EDICT1 идентичные данные, но ICONV_EDICT1 заставляет пробовать их преобразовать, а также проверять, что в статье нет символов, не умещающихся в этой кодировке. На практике это страшно неудобно, т.к. iconv не умеет ни нормально транслитеровать большинство не умеющающихся символов, ни отбрасывать символы ударения в русском, и поэтому очень много статей оказываются выброшены. } interface uses SysUtils, StreamUtils, JWBIO{$IFDEF ICONV_EDICT1}, iconv{$ENDIF}; {$IFDEF FPC} type UnicodeString = WideString; {$ENDIF} const MaxKanji = 8; MaxKana = 8; MaxGlosses = 48; MaxXrefs = 12; //бывало и 12 MaxAnts = 1; MaxLsources = 1; MaxSenses = 32; //Если будет нехватать - повышайте type EEdictWriterException = class(Exception); type TEdictKanjiEntry = record k: string; inf: string; //markers for <ke_pri> pop: boolean; // см. заметку procedure Reset; end; PEdictKanjiEntry = ^TEdictKanjiEntry; TEdictKanaEntry = record k: string; inf: string; //markers for <re_pri> AllKanji: boolean; //true, если кана годится для всех кандзи в статье Kanji: array[0..MaxKanji-1] of integer; //kanji references Kanji_used: integer; pop: boolean; //см. заметку procedure Reset; procedure AddKanjiRef(ref: integer); end; PEdictKanaEntry = ^TEdictKanaEntry; { О поле POP в кане и кандзи: JMDict для каны и для кандзи хранит пометки <pri>, отмечающие вхождение слова в разные индексы популярности вроде WORDFREQ. При экспорте в EDICT слова, имеющие пометки news1, ichi1, gai1 и spec1, получают пометку (P) - либо ко всей записи, либо к кане, либо к кандзи (см. ниже). Поскольку нам проверять все эти индексы не с руки, и получаем мы уже готовую информацию (P или не P), мы храним только метку POP, по которой пишем в JMDict метку spec1 (особая метка для выбранных вручную популярных слов). Если наш JMDict будут импортировать в главный, метки <pri> там проставят самостоятельно. } TEdictLSource = record lang: string; //язык оригинала expr: string; //слово в языке оригинала, от которого произошло значение procedure Reset; end; PEdictLSource = ^TEdictLSource; TEdictXref = record tp: string; val: string; procedure Reset; end; PEdictXref = ^TEdictXref; { Также интересны: gloss g_gend -- в файле нет -- поддерживается? example -- в файле нет -- даже формат неясен } TEdictSenseEntry = record glosses: array[0..MaxGlosses-1] of string; glosses_used: integer; xrefs: array[0..MaxXrefs-1] of TEdictXref; //ссылка на связанную запись <xref>[кана или кандзи]</xref> -- EDICT2: (See [кана или кандзи]) xrefs_used: integer; ants: array[0..MaxAnts-1] of string; //ссылки на антонимы <ant>[кана или кандзи]</ant> -- EDICT2: (ant: [кана или кандзи]) ants_used: integer; lsources: array[0..MaxLsources] of TEdictLSource; //язык-источник, напр. <lsource xml:lang=ru>собака</lsource>SOBAKA -- EDICT2: (ru: собака) lsources_used: integer; //также может быть: <lsource xml:lang="lat"/> //Теги. Заполняются через запятую, как в EDICT2. //В готовом виде: -- JMDict: &n; &uk; -- EDICT2: (n) (uk) t_pos: string; //part of speech -- EDICT2: (n,adj-no) t_field: string; //field of application -- EDICT2: {math} t_dial: string; //dialect -- EDICT2: (ksb:) t_misc: string; //прочее -- EDICT2: (uk) procedure Reset; procedure AddGloss(const val: string); function AddXref(const tp, val: string): PEdictXref; procedure AddAnt(const val: string); function AddLsource(const lang, expr: string): PEdictLSource; procedure AddTPos(const tag: string); procedure AddTField(const tag: string); procedure AddTDial(const tag: string); procedure AddTMisc(const tag: string); end; PEdictSenseEntry = ^TEdictSenseEntry; TEdictArticle = record ref: string; kanji: array[0..MaxKanji-1] of TEdictKanjiEntry; kanji_used: integer; kana: array[0..MaxKana-1] of TEdictKanaEntry; kana_used: integer; senses: array[0..MaxSenses-1] of TEdictSenseEntry; senses_used: integer; procedure Reset; function AddKanji: PEdictKanjiEntry; function AddKana: PEdictKanaEntry; function AddSense: PEdictSenseEntry; end; PEdictArticle = ^TEdictArticle; type TArticleWriter = class protected outp: TStreamEncoder; FOwnsEncoder: boolean; FAddedRecords: integer; procedure StartFile; virtual; procedure FinalizeFile; virtual; public constructor Create(const filename: string); overload; constructor Create(AEncoder: TStreamEncoder; AOwnsEncoder: boolean = false); overload; destructor Destroy; override; procedure Print(art: PEdictArticle); overload; virtual; abstract; property AddedRecords: integer read FAddedRecords; end; type TPopStats = record AllKanjiPop: boolean; AllKanaPop: boolean; HasPop: boolean; end; function GetPopStats(art: PEdictArticle): TPopStats; function EdictBuildArticleBody(wr: TArticleWriter; art: PEdictArticle): string; type TEdict1Writer = class(TArticleWriter) protected {$IFDEF ICONV_EDICT1} conv: iconv_t; {$ENDIF} procedure Print2(art: PEdictArticle; const kanji, kana: integer; const body: string); public constructor Create(const filename: string); destructor Destroy; override; procedure Print(art: PEdictArticle); override; end; type TEdict2Writer = class(TArticleWriter) protected function KanaToStr(art: PEdictArticle; idx: integer): string; public procedure Print(art: PEdictArticle); override; end; type TJmDictWriter = class(TArticleWriter) protected procedure StartFile; override; procedure FinalizeFile; override; procedure PrintTags(const tag_name, tag_vals: string); public procedure Print(art: PEdictArticle); override; end; implementation uses Classes; { Article } procedure TEdictKanjiEntry.Reset; begin k := ''; inf := ''; pop := false; end; procedure TEdictKanaEntry.Reset; begin k := ''; inf := ''; AllKanji := false; kanji_used := 0; pop := false; end; procedure TEdictKanaEntry.AddKanjiRef(ref: integer); begin if Kanji_used >= Length(Kanji) then raise EEdictWriterException.Create('EdictKanaEntry: Cannot add one more kana'); Kanji[Kanji_used] := ref; Inc(Kanji_used); end; procedure TEdictLSource.Reset; begin lang:=''; expr:=''; end; procedure TEdictXref.Reset; begin tp := ''; val := ''; end; procedure TEdictSenseEntry.Reset; begin glosses_used := 0; xrefs_used := 0; ants_used := 0; lsources_used := 0; t_pos := ''; t_field := ''; t_dial := ''; t_misc := ''; end; procedure TEdictSenseEntry.AddGloss(const val: string); begin if glosses_used >= Length(glosses) then raise EEdictWriterException.Create('EdictSenseEntry: Cannot add one more gloss'); if val='' then exit; //пустые не добавляем glosses[glosses_used] := val; Inc(glosses_used); end; function TEdictSenseEntry.AddXref(const tp, val: string): PEdictXref; begin if xrefs_used >= Length(xrefs) then raise EEdictWriterException.Create('EdictSenseEntry: Cannot add one more xref'); Result := @xrefs[xrefs_used]; Result^.Reset; Result^.tp := tp; Result^.val := val;; Inc(xrefs_used); end; procedure TEdictSenseEntry.AddAnt(const val: string); begin if ants_used >= Length(ants) then raise EEdictWriterException.Create('EdictSenseEntry: Cannot add one more ant'); ants[ants_used] := val; Inc(ants_used); end; function TEdictSenseEntry.AddLsource(const lang, expr: string): PEdictLSource; begin if lsources_used >= Length(lsources) then raise EEdictWriterException.Create('EdictSenseEntry: Cannot add one more lsources'); Result := @lsources[lsources_used]; Result^.Reset; Result^.lang := lang; Result^.expr := expr; Inc(lsources_used); end; procedure TEdictSenseEntry.AddTPos(const tag: string); begin if t_pos<>'' then t_pos := t_pos+','+tag else t_pos := tag; end; procedure TEdictSenseEntry.AddTField(const tag: string); begin if t_field<>'' then t_field := t_field+','+tag else t_field := tag; end; procedure TEdictSenseEntry.AddTDial(const tag: string); begin if t_dial<>'' then t_dial := t_dial+','+tag else t_dial := tag; end; procedure TEdictSenseEntry.AddTMisc(const tag: string); begin if t_misc<>'' then t_misc := t_misc+','+tag else t_misc := tag; end; procedure TEdictArticle.Reset; begin ref := ''; kanji_used := 0; kana_used := 0; senses_used := 0; end; function TEdictArticle.AddKanji: PEdictKanjiEntry; begin if kanji_used >= Length(kanji) then raise EEdictWriterException.Create('EdictArticle: Cannot add one more kanji'); Result := @kanji[kanji_used]; Result^.Reset; Inc(kanji_used); end; function TEdictArticle.AddKana: PEdictKanaEntry; begin if kana_used >= Length(kana) then raise EEdictWriterException.Create('EdictArticle: Cannot add one more kana'); Result := @kana[kana_used]; Result^.Reset; Inc(kana_used); end; function TEdictArticle.AddSense: PEdictSenseEntry; begin if senses_used >= Length(senses) then raise EEdictWriterException.Create('EdictArticle: Cannot add one more sense'); Result := @senses[senses_used]; Result^.Reset; Inc(senses_used); end; { ArticleWriter } constructor TArticleWriter.Create(const filename: string); var AOutp: TStreamEncoder; begin AOutp := CreateTextFile(filename, TUTF16Encoding); AOutp.WriteBom; Create(AOutp, {OwnsEncoder=}true); end; constructor TArticleWriter.Create(AEncoder: TStreamEncoder; AOwnsEncoder: boolean = false); begin inherited Create; outp := AEncoder; FOwnsEncoder := AOwnsEncoder; FAddedRecords := 0; StartFile; end; destructor TArticleWriter.Destroy; begin FinalizeFile; FreeAndNil(outp); inherited; end; procedure TArticleWriter.StartFile; begin end; procedure TArticleWriter.FinalizeFile; begin outp.Flush; end; { Утилиты } function GetPopStats(art: PEdictArticle): TPopStats; var i: integer; begin Result.HasPop := false; Result.AllKanjiPop := true; for i := 0 to art.kanji_used - 1 do if art.kanji[i].pop then Result.HasPop := true else Result.AllKanjiPop := false; Result.AllKanaPop := true; for i := 0 to art.kana_used - 1 do if art.kana[i].pop then Result.HasPop := true else Result.AllKanaPop := false; end; //Составляет тело статьи. function EdictBuildArticleBody(wr: TArticleWriter; art: PEdictArticle): string; var i, j: integer; se: PEdictSenseEntry; se_ln: string; xr_ref, xr_ant: string; expr: string; Edict1: boolean; begin Result := ''; Edict1 := wr is TEdict1Writer; for i := 0 to art.senses_used - 1 do begin se := @art.senses[i]; se_ln := ''; if se.t_pos<>'' then se_ln := '('+se.t_pos+') '; if art.senses_used>1 then se_ln := '('+IntToStr(i+1)+') '; //после грам. тегов -- так сделано в английском EDICT2 if se.t_field<>'' then se_ln := '{'+se.t_field+'} '; if se.t_dial<>'' then se_ln := '('+se.t_dial+') '; if se.t_misc<>'' then se_ln := '('+se.t_misc+') '; if not Edict1 then begin //Ref xr_ref := ''; for j := 0 to se.xrefs_used - 1 do xr_ref := xr_ref + se.xrefs[j].val + ','; if xr_ref<>'' then se_ln := se_ln + '(See '+copy(xr_ref,1,Length(xr_ref)-1)+') '; //ant xr_ant := ''; for j := 0 to se.ants_used - 1 do xr_ant := xr_ant + se.ants[j] + ','; if xr_ant<>'' then se_ln := se_ln + '(ant: '+copy(xr_ant,1,Length(xr_ant)-1)+') '; end; //языки-источники включаем даже в EDICT1, хотя там expr должно быть транслитом! for j := 0 to se.lsources_used - 1 do begin {$IFDEF ICONV_EDICT1} if Edict1 then try expr := UnicodeString(iconv2(TEdict1Writer(wr).conv conv,se.lsources[j].expr)) except on E: EIConvError do expr := ''; //cannot convert! end else {$ENDIF} expr := se.lsources[j].expr; se_ln := se_ln + '('+se.lsources[j].lang+':'+expr+') '; //sic! даже когда expr==''. так в едикте end; if se.glosses_used>0 then begin se_ln := se_ln + se.glosses[0]; for j := 1 to se.glosses_used - 1 do se_ln := se_ln + '/' + se.glosses[j]; end; if se_ln<>'' then //пустые значения (напр. только ссылки, и ничего не вошло) не добавляем Result := Result + '/' + se_ln; end; {$IFDEF ICONV_EDICT1} //По условию, все символы в поле "значение" Едикта-1 должны входить в US-ASCII. //В нашем случае допустимо также CP1251, поскольку словарь русский, но не больше. //Конвертируем и проверяем, будет ли ошибка. //Вообще-то, мы должны были отфильтровать это ещё раньше, но на всякий случай. if Edict1 then try iconv2(conv,Result); except on E: EIConvError do raise EParsingException.Create('Invalid target codepage symbols in article body'); end; {$ENDIF} end; { EDICT1 } constructor TEdict1Writer.Create(const filename: string); begin inherited; {$IFDEF ICONV_EDICT1} conv := iconv_open('CP1251//TRANSLIT', 'UTF-16LE'); if conv=iconv_t(-1) then raise Exception.Create('Cannot initialize iconv'); {$ENDIF} end; destructor TEdict1Writer.Destroy; begin {$IFDEF ICONV_EDICT1} iconv_close(conv); {$ENDIF} inherited; end; procedure TEdict1Writer.Print(art: PEdictArticle); var i, j: integer; body: string; begin //Генерируем тело статьи body := EdictBuildArticleBody(Self, art); if body='' then exit; //статья пустая -- видимо, ничто в ней не годилось для EDICT1 //Печатаем все варианты for i := 0 to art.kana_used - 1 do if art.kanji_used<=0 then begin Print2(art, -1, i, body); end else if art.kana[i].AllKanji then begin for j := 0 to art.kanji_used - 1 do Print2(art, j, i, body); end else begin for j := 0 to art.kana[i].Kanji_used - 1 do Print2(art, art.kana[i].Kanji[j], i, body); end; end; procedure TEdict1Writer.Print2(art: PEdictArticle; const kanji, kana: integer; const body: string); var ln: string; k_flags: string; begin if kanji>=0 then begin ln := art.kanji[kanji].k; if kana>=0 then ln := ln + ' [' + art.kana[kana].k + ']'; end else //kana must be set ln := art.kana[kana].k; //В EDICT1 флаги каны и кандзи пишутся перед первым вхождением sense k_flags := ''; if (kanji>=0) and (art.kanji[kanji].inf<>'') then k_flags := k_flags + '('+art.kanji[kanji].inf+') '; if (kana>=0) and (art.kana[kana].inf<>'') then k_flags := k_flags + '('+art.kana[kana].inf+') '; if k_flags<>'' then begin ln := ln + ' /'+k_flags; if body<>'' then ln := ln + ' ' + copy(body,2,Length(body)-1); //пропускаем стартовый '/' end else ln := ln + ' ' + body; if ((kanji>=0) and art.kanji[kanji].pop) or ((kana>=0) and art.kana[kana].pop) then ln := ln + '/(P)'; outp.WriteLn(ln+'/'); Inc(FAddedRecords); end; { EDICT2 } //Генерирует запись вида кана(кандзи,кандзи) для каны #idx из статьи art function TEdict2Writer.KanaToStr(art: PEdictArticle; idx: integer): string; var i: integer; begin Result := art.kana[idx].k; if art.kana[idx].AllKanji then exit; if art.kanji_used<=0 then exit; //на всякий случай, хотя тогда должен стоять AllKanji, наверное? { Вообще-то говоря, у каны может не быть отсылок на кандзи, и в таком случае единственный способ доступно это записать: кандзи1;кандзи2;КАНА2[кана1(кандзи1,кандзи2);КАНА2(КАНА2)] То есть, объявить кану отдельной записью. Это будет логично. Вариант хуже - написать кану с пустыми скобками: КАНА2() На это мало кто рассчитывает, и вообще, что это значит? Для какой записи это чтение? Однако по факту EDICT в таких случаях пишет кану так, как будто она годится для всех записей: кандзи1;кандзи2[кана1;КАНА2] Это ошибка, но раз так делает EDICT, мы поступим так же. } if art.kana[idx].Kanji_used<=0 then exit; Result := Result + '(' + art.kanji[art.kana[idx].Kanji[0]].k; for i := 1 to art.kana[idx].Kanji_used - 1 do Result := Result + ',' + art.kanji[art.kana[idx].Kanji[i]].k; Result := Result + ')'; end; procedure TEdict2Writer.Print(art: PEdictArticle); var ln: string; i: integer; s_kanji: string; s_kana: string; PopStats: TPopStats; begin PopStats := GetPopStats(art); //кандзи1;кандзи2;кандзи3 if art.kanji_used=0 then s_kanji := '' else begin s_kanji := art.kanji[0].k; if art.kanji[0].pop and not PopStats.AllKanjiPop then s_kanji := s_kanji + '(P)'; for i := 1 to art.kanji_used - 1 do begin s_kanji := s_kanji + ';' + art.kanji[i].k; if art.kanji[i].pop and not PopStats.AllKanjiPop then s_kanji := s_kanji + '(P)'; end; end; //кана1;кана2(кандзи1;кандзи2);кана3(кандзи2;кандзи3) if art.kana_used=0 then s_kana := '' else begin s_kana := KanaToStr(art, 0); if art.kana[0].pop and not PopStats.AllKanaPop then s_kana := s_kana + '(P)'; for i := 1 to art.kana_used - 1 do begin s_kana := s_kana + ';' + KanaToStr(art, i); if art.kana[i].pop and not PopStats.AllKanaPop then s_kana := s_kana + '(P)'; end; end; if s_kanji='' then begin s_kanji := s_kana; //исключение: "кана1 /(статья) /" end else if s_kana<>'' then s_kanji := s_kanji + ' [' + s_kana + ']'; s_kana := ''; //Теперь в s_kanji полный заголовок //Собираем в ln значения ln := EdictBuildArticleBody(Self, art); if PopStats.HasPop then ln := ln + '/(P)'; if art.ref<>'' then ln := ln + '/EntL'+art.ref; outp.WriteLn(s_kanji+' '+ln+'/'); Inc(FAddedRecords); end; { JMDict } procedure TJMDictWriter.StartFile; begin inherited; outp.WriteLn('<!-- JMdict created: '+FormatDatetime('yyyy-mm-dd', now())+' -->'); outp.WriteLn('<JMdict>'); end; procedure TJMDictWriter.FinalizeFile; begin outp.WriteLn('</JMdict>'); inherited; end; //Получает строку вида "val1,val2" и печатает набор тегов // <tag_name>val1</tag_name> // <tag_name>val2</tag_name> procedure TJMDictWriter.PrintTags(const tag_name, tag_vals: string); var tmp: string; t_pos: integer; begin tmp := tag_vals; t_pos := pos(tmp, ','); while t_pos>0 do begin outp.WriteLn('<'+tag_name+'>&'+copy(tmp,1,t_pos-1)+';</'+tag_name+'>'); //каждый тег отдельно tmp := copy(tmp,t_pos+1,Length(tmp)-t_pos); t_pos := pos(tmp, ','); end; if tmp<>'' then outp.WriteLn('<'+tag_name+'>&'+tmp+';</'+tag_name+'>'); end; procedure TJMDictWriter.Print(art: PEdictArticle); var i,j: integer; se: PEdictSenseEntry; begin outp.WriteLn('<entry>'); if art.ref<>'' then outp.WriteLn('<ent_seq>'+art.ref+'</ent_seq>'); for i := 0 to art.kanji_used - 1 do begin outp.WriteLn('<k_ele>'); outp.WriteLn('<keb>'+art.kanji[i].k+'</keb>'); if art.kanji[i].inf<>'' then PrintTags('ke_inf', art.kanji[i].inf); if art.kanji[i].pop then outp.WriteLn('<ke_pri>spec1</ke_pri>'); outp.WriteLn('</k_ele>'); end; for i := 0 to art.kana_used - 1 do begin outp.WriteLn('<r_ele>'); outp.WriteLn('<reb>'+art.kana[i].k+'</reb>'); if art.kana[i].inf<>'' then PrintTags('re_inf', art.kana[i].inf); if not art.kana[i].AllKanji then begin if art.kana[i].Kanji_used<=0 then outp.WriteLn('<re_nokanji/>') else for j := 0 to art.kana[i].Kanji_used - 1 do outp.WriteLn('<re_restr>'+art.kanji[art.kana[i].Kanji[j]].k+'</re_restr>'); if art.kana[i].pop then outp.WriteLn('<re_pri>spec1</re_pri>'); end; outp.WriteLn('</r_ele>'); end; for i := 0 to art.senses_used - 1 do begin outp.WriteLn('<sense>'); se := @art.senses[i]; for j := 0 to se.xrefs_used - 1 do if se.xrefs[j].tp='' then outp.WriteLn('<xref>'+se.xrefs[j].val+'</xref>') else outp.WriteLn('<xref type="'+se.xrefs[j].tp+'">'+se.xrefs[j].val+'</xref>'); for j := 0 to se.ants_used - 1 do outp.WriteLn('<ant>'+se.ants[j]+'</ant>'); for j := 0 to se.lsources_used - 1 do if se.lsources[j].expr='' then outp.WriteLn('<lsource xml:lang='+se.lsources[j].lang+'/>') else outp.WriteLn('<lsource xml:lang='+se.lsources[j].lang+'>'+se.lsources[j].expr+'</ant>'); if se.t_pos<>'' then PrintTags('pos', se.t_pos); if se.t_field<>'' then PrintTags('field', se.t_pos); if se.t_dial<>'' then PrintTags('dial', se.t_pos); if se.t_misc<>'' then PrintTags('misc', se.t_pos); for j := 0 to se.glosses_used - 1 do outp.WriteLn('<gloss xml:lang="rus">'+se.glosses[j]+'</gloss>'); //note the gloss xml:lang attribute outp.WriteLn('</sense>'); end; outp.WriteLn('</entry>'); Inc(FAddedRecords); end; end.
unit uDMThread; interface uses SysUtils, Classes, DB, DBClient, Forms; const ADV_BITMAP = 0; ADV_JPG = 1; ADV_VIDEO = 2; ADV_FLASH = 3; ADV_WEB = 4; ADV_BITMAP_EXT = 'Bitmap|*.bmp'; ADV_JPG_EXT = 'JPG|*.jpg'; ADV_VIDEO_EXT = 'Video|*.mpg|all|*.*'; ADV_FLASH_EXT = 'Flash File|*.swf'; ADV_WEB_EXT = 'HTML|*.html|ASP|*.asp'; SVR = 'Settings'; SVR_IP = 'IP'; SVR_PORT = 'Port'; SVR_LANGUAGE = 'Language'; type TDMThread = class(TDataModule) cdsAdvertising: TClientDataSet; cdsAdvertisingDescription: TStringField; cdsAdvertisingFileName: TStringField; cdsAdvertisingStartDate: TDateTimeField; cdsAdvertisingEndDate: TDateTimeField; cdsAdvertisingDaysOfWeek: TStringField; cdsAdvertisingDaysOfWeekString: TStringField; cdsAdvertisingType: TIntegerField; cdsAdvertisingTypeString: TStringField; cdsAdvertisingDuration: TIntegerField; cdsAdvertisingVideoControl: TBooleanField; cdsAdvertisingDisplayDescription: TBooleanField; cdsAdvertisingHours: TStringField; cdsCrossSaleItem: TClientDataSet; cdsCrossSaleItemID: TIntegerField; cdsCrossSaleItemModelNum: TStringField; cdsCrossSaleItemModelCategory: TStringField; cdsCrossSaleItemModelSubCategory: TStringField; cdsCrossSaleItemModelGroup: TStringField; cdsCrossSaleItemFileName: TStringField; cdsCrossSaleItemFileType: TIntegerField; cdsCrossSaleItemDuration: TIntegerField; cdsCrossSaleItemCrossDescription: TStringField; cdsCrossSaleItemCrossSalePrice: TCurrencyField; cdsCrossSaleItemHistory: TClientDataSet; cdsCrossSaleItemHistoryModel: TStringField; cdsCrossSaleItemHistoryRegister: TStringField; cdsCrossSaleItemHistoryItemDate: TDateTimeField; cdsAdvertisingID: TIntegerField; procedure cdsAdvertisingCalcFields(DataSet: TDataSet); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } FLocalPath: String; procedure LoadAdvertising; procedure LoadCrossSaleItem; procedure LoadCrossSaleItemHistory; procedure OpenAdvertising; procedure OpenCrossSaleItem; procedure OpenCrossSaleItemHistory; procedure CloseAdvertising; procedure CloseCrossSaleItem; procedure CloseCrossSaleItemHistory; public { Public declarations } procedure LoadAdvertiseStream(AStream: TStream); procedure LoadCrossSaleItemHistoryStream(AStream: TStream); procedure LoadCrossSaleItemStream(AStream: TStream); end; var DMThread: TDMThread; implementation {$R *.dfm} procedure TDMThread.cdsAdvertisingCalcFields(DataSet: TDataSet); var FWeekDays : String; begin FWeekDays := ''; if Pos('1,', cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Monday; '; if Pos('2,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Tuesday; '; if Pos('3,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Wednesday; '; if Pos('4,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Thursday; '; if Pos('5,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Friday; '; if Pos('6,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Saturday; '; if Pos('7,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Sunday; '; cdsAdvertisingDaysOfWeekString.AsString := FWeekDays; case cdsAdvertisingType.AsInteger of ADV_BITMAP : cdsAdvertisingTypeString.AsString := 'Bitmap'; ADV_JPG : cdsAdvertisingTypeString.AsString := 'JPG'; ADV_VIDEO : cdsAdvertisingTypeString.AsString := 'Video'; ADV_FLASH : cdsAdvertisingTypeString.AsString := 'Flash'; ADV_WEB : cdsAdvertisingTypeString.AsString := 'Website'; end; end; procedure TDMThread.DataModuleCreate(Sender: TObject); begin FLocalPath := ExtractFilePath(Application.ExeName); (* OpenCrossSaleItem; OpenCrossSaleItemHistory; OpenAdvertising; LoadAdvertising; *) end; procedure TDMThread.DataModuleDestroy(Sender: TObject); begin CloseAdvertising; CloseCrossSaleItem; CloseCrossSaleItemHistory; end; procedure TDMThread.OpenCrossSaleItem; begin cdsCrossSaleItem.Close; LoadCrossSaleItem; end; procedure TDMThread.OpenCrossSaleItemHistory; begin cdsCrossSaleItemHistory.Close; LoadCrossSaleItemHistory; end; procedure TDMThread.OpenAdvertising; begin cdsAdvertising.Close; LoadAdvertising; end; procedure TDMThread.LoadCrossSaleItem; begin if FileExists(FLocalPath + 'SVR_CrossSaleItem.xml') then cdsCrossSaleItem.LoadFromFile(FLocalPath + 'SVR_CrossSaleItem.xml'); end; procedure TDMThread.LoadCrossSaleItemHistory; begin if FileExists(FLocalPath + 'SVR_CrossSaleItemHistory.xml') then cdsCrossSaleItemHistory.LoadFromFile(FLocalPath + 'SVR_CrossSaleItemHistory.xml'); end; procedure TDMThread.LoadAdvertising; begin if FileExists(FLocalPath + 'SVR_Advertising.xml') then cdsAdvertising.LoadFromFile(FLocalPath + 'SVR_Advertising.xml'); end; procedure TDMThread.CloseAdvertising; begin cdsAdvertising.Close; end; procedure TDMThread.CloseCrossSaleItem; begin cdsCrossSaleItem.Close; end; procedure TDMThread.CloseCrossSaleItemHistory; begin cdsCrossSaleItemHistory.Close; end; procedure TDMThread.LoadCrossSaleItemStream(AStream: TStream); begin AStream.Seek(0, soFromBeginning); CloseCrossSaleItem; OpenCrossSaleItem; cdsCrossSaleItem.SaveToStream(AStream, dfXMLUTF8); end; procedure TDMThread.LoadCrossSaleItemHistoryStream(AStream: TStream); begin AStream.Seek(0, soFromBeginning); CloseCrossSaleItemHistory; OpenCrossSaleItemHistory; cdsCrossSaleItemHistory.SaveToStream(AStream, dfXMLUTF8); end; procedure TDMThread.LoadAdvertiseStream(AStream: TStream); begin AStream.Seek(0, soFromBeginning); CloseAdvertising; OpenAdvertising; cdsAdvertising.SaveToStream(AStream, dfXMLUTF8); end; end.
unit OOPClasses; interface Uses Windows; Type //declaracao de novos tipos para mostrar como se declarao novos tipo no Delphi. TIconType = (itInformation, itWarning, itStop, itQuestion); TOperationType = (otSoma, otSubtracao, otMultplicacao, otDivisao); //essa declaracao é a mesma coisa que {TOOPClass = Class(TObject)} //o Delphi Subentende que estamos descendendo de TObject. TOOPClass = Class Private //metodo encapsulado pela Classe TOOPClass. {Somente poderemos utilizar este metodo dentro desta Classe.} procedure ChooseIconMessage(const BodyMsg, CaptionMsg : String; const IconType : TIconType); //--------------------------------- // Seção Privada à TOOPClass. // //--------------------------------- Protected //metodo protegido, somente os descendentes poderao utilizar este metodo. procedure ChooseOperation(const X, Y : Extended; Operation : TOperationType); virtual; //--------------------------------- // Seção Protegida // //--------------------------------- Public procedure ShowMessageEx(const stBodyMsg, stCaptionMsg : String; const itIconType : TIconType); //--------------------------------- // Seção Publica // //--------------------------------- Published //--------------------------------- // Seção Publicada // //--------------------------------- end;//TOOPClass. //classe descendente de TOOPClass, com isso ela herda quase tudo da classe ancestral. TOOPClassDescendente = Class(TOOPClass) Private //--------------------------------- // Seção Privada à TOOPClass. // //--------------------------------- Protected //--------------------------------- // Seção Protegida // //--------------------------------- Public procedure ChooseOperation(const X, Y: Extended; Operation: TOperationType); override; //--------------------------------- // Seção Publica // //--------------------------------- Published //--------------------------------- // Seção Publicada // //--------------------------------- end;//TOOPClassDescendente implementation uses SysUtils; { TOOPClass } procedure TOOPClass.ChooseIconMessage(const BodyMsg : String; const CaptionMsg : String; const IconType: TIconType); begin case IconType of itInformation : MessageBox(0, PChar(BodyMsg), PChar(CaptionMsg), MB_ICONINFORMATION); itWarning : MessageBox(0, PChar(BodyMsg), PChar(CaptionMsg), MB_ICONWARNING); itStop : MessageBox(0, PChar(BodyMsg), PChar(CaptionMsg), MB_ICONSTOP); itQuestion : MessageBox(0, PChar(BodyMsg), PChar(CaptionMsg), MB_ICONQUESTION); end;//case. end; procedure TOOPClass.ChooseOperation(const X, Y: Extended; Operation: TOperationType); var Result : Extended; begin //incializando o variavel. Result := 0; //escolha a operacao... case Operation of otSoma : Result := X + Y; otSubtracao : Result := X - Y; otMultplicacao: Result := X * Y; otDivisao : Result := X / Y; end;//case. //exiba o resultado da operacao. MessageBox(0, PChar(FloatToStr(Result)), 'ChooseOperation', MB_ICONINFORMATION); end; //function. procedure TOOPClass.ShowMessageEx(const stBodyMsg, stCaptionMsg: String; const itIconType: TIconType); begin ChooseIconMessage(stBodyMsg, stCaptionMsg, itIconType); end;// { inherited; { TOOPClassDescendente } procedure TOOPClassDescendente.ChooseOperation(const X, Y: Extended; Operation: TOperationType); begin //herdamos a codificacao do metodo ancestral.... inherited; //exibimos uma mensagem, que sera somente executada no final //da execucao do metodo ancestral. ShowMessageEx('Completamos a Operacao com Sucesso.' +#13+#10+ 'Está Messagem é da Classe Ancestral [ TOOPClass ]...', 'TOOPClassDescendente', itInformation); end; end.
unit uListOfSubjects; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst, Buttons, ExtCtrls; type TfmListOfSubjects = class(TForm) Panel1: TPanel; Label1: TLabel; clbListOfSubjects: TCheckListBox; bbSelAllSubjects: TBitBtn; Label2: TLabel; Label3: TLabel; bbOk: TBitBtn; bbCancel: TBitBtn; bbDelSelAllSubjects: TBitBtn; procedure FormShow(Sender: TObject); procedure bbSelAllSubjectsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure clbListOfSubjectsClick(Sender: TObject); procedure bbDelSelAllSubjectsClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fmListOfSubjects: TfmListOfSubjects; implementation uses uEditorCodes; {$R *.dfm} procedure TfmListOfSubjects.FormShow(Sender: TObject); var i: Integer; begin clbListOfSubjects.Clear; for i := 0 to High(fmEditorCodes.SubjectsFromFile) do clbListOfSubjects.Items.Add(fmEditorCodes.SubjectsFromFile[i]); bbDelSelAllSubjects.Enabled := False; bbSelAllSubjects.Enabled := True; end; procedure TfmListOfSubjects.bbSelAllSubjectsClick(Sender: TObject); var i: Integer; begin for i := 0 to clbListOfSubjects.Count - 1 do clbListOfSubjects.Checked[i] := True; bbDelSelAllSubjects.Enabled := True; bbSelAllSubjects.Enabled := False; end; procedure TfmListOfSubjects.FormCreate(Sender: TObject); begin Self.Left := fmEditorCodes.Left + (fmEditorCodes.Width - Self.Width) div 2; Self.Top := fmEditorCodes.Height div 2; end; procedure TfmListOfSubjects.clbListOfSubjectsClick(Sender: TObject); var i: Integer; begin clbListOfSubjects.Tag := 0; for i := 0 to clbListOfSubjects.Count - 1 do if clbListOfSubjects.Checked[i] then clbListOfSubjects.Tag := clbListOfSubjects.Tag + 1; if clbListOfSubjects.Tag = clbListOfSubjects.Count then begin bbDelSelAllSubjects.Enabled := True; bbSelAllSubjects.Enabled := False; end // if clbListOfSubjects.Tag = clbListOfSu else if clbListOfSubjects.Tag = 0 then begin bbDelSelAllSubjects.Enabled := False; bbSelAllSubjects.Enabled := True; end // if clbListOfSubjects.Tag = clbListOfSubjects.Count else begin bbDelSelAllSubjects.Enabled := True; bbSelAllSubjects.Enabled := True; end; end; procedure TfmListOfSubjects.bbDelSelAllSubjectsClick(Sender: TObject); var i: Integer; begin for i := 0 to clbListOfSubjects.Count - 1 do clbListOfSubjects.Checked[i] := False; bbDelSelAllSubjects.Enabled := False; bbSelAllSubjects.Enabled := True; end; end.
unit TwoDPointQueue; interface type P2DPosition = ^T2DPosition; T2DPosition = record x,y : integer; Next : P2DPosition; end; C2DPointQueue = class private Start,Last,Active : P2DPosition; procedure Reset; public // Constructors and Destructors constructor Create; destructor Destroy; override; // Add procedure Add (x,y : integer); procedure Delete; // Delete procedure Clear; // Gets function GetPosition (var x,y : integer): boolean; function GetX: integer; function GetY: integer; function IsEmpty: boolean; function IsActive(_Elem: P2DPosition): boolean; function IsEndOfQueue: boolean; function GetFirstElement: P2DPosition; procedure GetNextElement(var _Elem: P2DPosition); function GetActive: P2DPosition; // Misc procedure GoToNextElement; procedure GoToFirstElement; procedure GoToLastElement; end; implementation constructor C2DPointQueue.Create; begin Reset; end; destructor C2DPointQueue.Destroy; begin Clear; inherited Destroy; end; procedure C2DPointQueue.Reset; begin Start := nil; Last := nil; Active := nil; end; // Add procedure C2DPointQueue.Add (x,y : integer); var NewPosition : P2DPosition; begin New(NewPosition); NewPosition^.x := x; NewPosition^.y := y; NewPosition^.Next := nil; if Start <> nil then begin Last^.Next := NewPosition; end else begin Start := NewPosition; Active := Start; end; Last := NewPosition; end; // Delete procedure C2DPointQueue.Delete; var Previous : P2DPosition; begin if Active <> nil then begin Previous := Start; if Active = Start then begin Start := Start^.Next; Previous := Start; end else begin while Previous^.Next <> Active do begin Previous := Previous^.Next; end; Previous^.Next := Active^.Next; if Active = Last then begin Last := Previous; end; end; Dispose(Active); Active := Previous; end; end; procedure C2DPointQueue.Clear; var Garbage : P2DPosition; begin Active := Start; while Active <> nil do begin Garbage := Active; Active := Active^.Next; dispose(Garbage); end; end; // Gets function C2DPointQueue.GetPosition (var x,y : integer): boolean; begin if Active <> nil then begin x := Active^.x; y := Active^.y; Result := true; end else begin Result := false; end; end; function C2DPointQueue.GetX: integer; begin Result := 0; if Active <> nil then begin Result := Active^.x; end; end; function C2DPointQueue.GetY: integer; begin Result := 0; if Active <> nil then begin Result := Active^.y; end; end; function C2DPointQueue.IsEmpty: boolean; begin Result := (Start = nil); end; function C2DPointQueue.IsActive(_Elem: P2DPosition): boolean; begin Result := (_Elem = Active); end; function C2DPointQueue.GetFirstElement: P2DPosition; begin Result := Start; end; function C2DPointQueue.GetActive: P2DPosition; begin Result := Active; end; procedure C2DPointQueue.GetNextElement(var _Elem: P2DPosition); begin if _Elem <> nil then begin _Elem := _Elem^.Next; end; end; // Misc procedure C2DPointQueue.GoToNextElement; begin if Active <> nil then begin Active := Active^.Next; end end; procedure C2DPointQueue.GoToFirstElement; begin Active := Start; end; procedure C2DPointQueue.GoToLastElement; begin Active := Last; end; function C2DPointQueue.IsEndOfQueue: boolean; begin Result := Active = Last; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TForm1 = class(TForm) Panel1: TPanel; Button1: TButton; Memo1: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private function AufWelchemMonitorIstDieForm: Integer; public end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var i1: Integer; begin Memo1.Clear; for i1 := 0 to Screen.MonitorCount -1 do begin Memo1.Lines.Add('Monitor ' + IntToStr(i1+1)); Memo1.Lines.Add('Left = ' + IntToStr(Screen.Monitors[i1].Left)); Memo1.Lines.Add('Width = ' + IntToStr(Screen.Monitors[i1].Width)); Memo1.Lines.Add('Top = ' + IntToStr(Screen.Monitors[i1].Top)); Memo1.Lines.Add('Height = ' + IntToStr(Screen.Monitors[i1].Height)); Memo1.Lines.Add(''); end; end; procedure TForm1.Button2Click(Sender: TObject); begin // Caption := 'Die Form ist auf dem ' + IntToStr(AufWelchemMonitorIstDieForm)+ '. Monitor'; end; function TForm1.AufWelchemMonitorIstDieForm: Integer; var i1: Integer; Von: Integer; Bis: Integer; FormPos: Integer; begin Result := 0; FormPos := trunc(Left + (Width div 2)); if FormPos < 0 then begin Result := 1; exit; end; for i1 := 0 to Screen.MonitorCount -1 do begin Von := Screen.Monitors[i1].Left; Bis := Von + Screen.Monitors[i1].Width; if (FormPos >= Von) and (FormPos <= Bis) then begin Result := i1+1; exit; end; end; end; end.
unit UnPrincipal; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl, FMX.Layouts, System.Actions, FMX.ActnList, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.Effects; type TfrmPrincipal = class(TForm) tbItemMenu: TTabItem; tbItemApoio: TTabItem; tbctrlPrincipal: TTabControl; lytPrincipal: TLayout; Layout1: TLayout; actAcoes: TActionList; actMudarAba: TChangeTabAction; lytMenu: TGridLayout; lytSuperior: TLayout; lytInferior: TLayout; lytBotao1: TLayout; rndBotao1: TRoundRect; imgBotao1: TImage; lytRotulo1: TLayout; lblTituloBtn1: TLabel; lblDescricaoBtn1: TLabel; ShadowEffect1: TShadowEffect; Layout2: TLayout; RoundRect1: TRoundRect; imgCadForn: TImage; Layout3: TLayout; lblTituloBtn2: TLabel; ShadowEffect2: TShadowEffect; Label2: TLabel; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure imgBotao1Click(Sender: TObject); private { Private declarations } FActiveForm : TForm; public { Public declarations } procedure MudarAba(ATabItem: TTabItem; Sender: TObject); procedure AbrirForm(AFormClass: TComponentClass); end; var frmPrincipal: TfrmPrincipal; implementation {$R *.fmx} procedure TfrmPrincipal.AbrirForm(AFormClass: TComponentClass); var LayoutBase, BotaoMenu: TComponent; begin if Assigned(FActiveForm) then begin if FActiveForm.ClassType = AFormClass then exit else begin FActiveForm.DisposeOf; //Não usar Free //Free passa pelo GarbageCollector isso pode demorar DisponseOf Limpa direto FActiveForm := nil; end; end; Application.CreateForm(AFormClass, FActiveForm); //encontra o LayoutBase no form a ser exibido para adicionar ao FrmPrincipal LayoutBase := FActiveForm.FindComponent('lytBase'); if Assigned(LayoutBase) then lytPrincipal.AddObject(TLayout(LayoutBase)); //enccontra o Botão de controle de Menu no form a ser exibido para //associá-lo ao Multiview do frmPrincipal //Caso tenha menu....modelo abaixo: //BotaoMenu := FActiveForm.FindComponent('btnMenu'); //if Assigned(BotaoMenu) then // mlvMenu.MasterButton := TControl(BotaoMenu); end; procedure TfrmPrincipal.Button1Click(Sender: TObject); begin MudarAba(tbItemApoio); end; procedure TfrmPrincipal.FormCreate(Sender: TObject); begin tbctrlPrincipal.ActiveTab := tbItemMenu; tbctrlPrincipal.TabPosition := TTabPosition.None; //Para as TABs nao aparecer na execucao end; procedure TfrmPrincipal.imgBotao1Click(Sender: TObject); begin //AbrirForm(TfrmClientes); //Carrego o próximo form //MudarAba(tbItemApoio, Sender); //Mudar aba do menu para o apoio end; procedure TfrmPrincipal.MudarAba(ATabItem: TTabItem; Sender: TObject); begin actMudarAba.Tab := ATabItem; actMudarAba.ExecuteTarget(Sender); end; end.
unit GLD3dsFile; interface uses Classes, GL, GLDTypes, GLDClasses, GLD3dsAtmosphere, GLD3dsBackground, GLD3dsCamera, GLD3dsChunk, GLD3dsIo, GLD3dsLight, GLD3dsMaterial, GLD3dsMesh, GLD3dsNode, GLD3dsQuat, GLD3dsShadow, GLD3dsTcb, GLD3dsTracks, GLD3dsTypes, GLD3dsViewport; type TGLD3dsFile = class(TGLDSysClass) private FMeshVersion: GLuint; FKeyfRevision: GLushort; FName: string; FMasterScale: GLfloat; FConstructionPlane: TGLDVector4fClass; FAmbient: TGLDColor4fClass; FShadow: TGLD3dsShadow; FBackground: TGLD3dsBackground; FAtmosphere: TGLD3dsAtmosphere; FViewport: TGLD3dsViewport; FViewportKeyf: TGLD3dsViewport; FFrames: GLuint; FSegmentFrom: GLuint; FSegmentTo: GLuint; FCurrentFrame: GLuint; FMaterials: TGLD3dsMaterialList; FMeshes: TGLD3dsMeshList; FCameras: TGLD3dsCameraList; FLights: TGLD3dsLightList; FNodes: TGLD3dsNodeList; procedure SetMeshVersion(Value: GLuint); procedure SetKeyfRevision(Value: GLushort); procedure SetName(Value: string); procedure SetMasterScale(Value: GLfloat); procedure SetConstructionPlane(Value: TGLDVector4fClass); procedure SetAmbient(Value: TGLDColor4fClass); procedure SetShadow(Value: TGLD3dsShadow); procedure SetBackground(Value: TGLD3dsBackground); procedure SetAtmosphere(Value: TGLD3dsAtmosphere); procedure SetViewport(Value: TGLD3dsViewport); procedure SetViewportKeyf(Value: TGLD3dsViewport); procedure SetFrames(Value: GLuint); procedure SetSegmentFrom(Value: GLuint); procedure SetSegmentTo(Value: GLuint); procedure SetCurrentFrame(Value: GLuint); procedure SetMaterials(Value: TGLD3dsMaterialList); procedure SetMeshes(Value: TGLD3dsMeshList); procedure SetCameras(Value: TGLD3dsCameraList); procedure SetLights(Value: TGLD3dsLightList); procedure SetNodes(Value: TGLD3dsNodeList); function NamedObjectRead(Stream: TStream): GLboolean; function AmbientRead(Stream: TStream): GLboolean; function MDataRead(Stream: TStream): GLboolean; function KFDataRead(Stream: TStream): GLboolean; protected procedure SetOnChange(Value: TNotifyEvent); override; public constructor Create(AOwner: TPersistent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function SysClassType: TGLDSysClassType; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; function Read(Stream: TStream): GLboolean; function ReadFromFile(const FileName: string): GLboolean; published property MeshVersion: GLuint read FMeshVersion write SetMeshVersion; property KeyfRevision: GLushort read FKeyfRevision write SetKeyfRevision; property Name: string read FName write SetName; property MasterScale: GLfloat read FMasterScale write SetMasterScale; property ConstructionPlane: TGLDVector4fClass read FConstructionPlane write SetConstructionPlane; property Ambient: TGLDColor4fClass read FAmbient write SetAmbient; property Shadow: TGLD3dsShadow read FShadow write SetShadow; property Background: TGLD3dsBackground read FBackground write SetBackground; property Atmosphere: TGLD3dsAtmosphere read FAtmosphere write SetAtmosphere; property Viewport: TGLD3dsViewport read FViewport write SetViewport; property ViewportKeyf: TGLD3dsViewport read FViewportKeyf write SetViewportKeyf; property Frames: GLuint read FFrames write SetFrames; property SegmentFrom: GLuint read FSegmentFrom write SetSegmentFrom; property SegmentTo: GLuint read FSegmentTo write SetSegmentTo; property CurrentFrame: GLuint read FCurrentFrame write SetCurrentFrame; property Materials: TGLD3dsMaterialList read FMaterials write SetMaterials; property Meshes: TGLD3dsMeshList read FMeshes write SetMeshes; property Cameras: TGLD3dsCameraList read FCameras write SetCameras; property Lights: TGLD3dsLightList read FLights write SetLights; property Nodes: TGLD3dsNodeList read FNodes write SetNodes; end; implementation uses SysUtils; constructor TGLD3dsFile.Create(AOwner: TPersistent); begin inherited Create(AOwner); FMeshVersion := 0; FKeyfRevision := 0; FName := ''; FMasterScale := 1; FConstructionPlane := TGLDVector4fClass.Create(Self); FAmbient := TGLDColor4fClass.Create(Self); FShadow := TGLD3dsShadow.Create(Self); FBackground := TGLD3dsBackground.Create(Self); FAtmosphere := TGLD3dsAtmosphere.Create(Self); FViewport := TGLD3dsViewport.Create(Self); FViewportKeyf := TGLD3dsViewport.Create(Self); FFrames := 0; FSegmentFrom := 0; FSegmentTo := 0; FCurrentFrame := 0; FMaterials := TGLD3dsMaterialList.Create(Self); FMeshes := TGLD3dsMeshList.Create(Self); FCameras := TGLD3dsCameraList.Create(Self); FLights := TGLD3dsLightList.Create(Self); FNodes := TGLD3dsNodeList.Create(Self); end; destructor TGLD3dsFile.Destroy; begin FConstructionPlane.Free; FAmbient.Free; FShadow.Free; FBackground.Free; FAtmosphere.Free; FViewport.Free; FViewportKeyf.Free; FMaterials.Free; FMeshes.Free; FCameras.Free; FLights.Free; FNodes.Free; inherited Destroy; end; procedure TGLD3dsFile.Assign(Source: TPersistent); begin if (Source = nil) or (Source = Self) then Exit; if not (Source is TGLD3dsFile) then Exit; FMeshVersion := TGLD3dsFile(Source).FMeshVersion; FKeyfRevision := TGLD3dsFile(Source).FKeyfRevision; FName := TGLD3dsFile(Source).FName; FMasterScale := TGLD3dsFile(Source).FMasterScale; FConstructionPlane.Assign(TGLD3dsFile(Source).FConstructionPlane); FAmbient.Assign(TGLD3dsFile(Source).FAmbient); FShadow.Assign(TGLD3dsFile(Source).FShadow); FBackground.Assign(TGLD3dsFile(Source).FBackground); FAtmosphere.Assign(TGLD3dsFile(Source).FAtmosphere); FViewport.Assign(TGLD3dsFile(Source).FViewport); FViewportKeyf.Assign(TGLD3dsFile(Source).FViewportKeyf); FFrames := TGLD3dsFile(Source).FMeshVersion; FSegmentFrom := TGLD3dsFile(Source).FSegmentFrom; FSegmentTo := TGLD3dsFile(Source).FSegmentTo; FCurrentFrame := TGLD3dsFile(Source).FCurrentFrame; FMaterials.Assign(TGLD3dsFile(Source).FMaterials); FMeshes.Assign(TGLD3dsFile(Source).FMeshes); FCameras.Assign(TGLD3dsFile(Source).FCameras); FLights.Assign(TGLD3dsFile(Source).FLights); FNodes.Assign(TGLD3dsFile(Source).FNodes); end; class function TGLD3dsFile.SysClassType: TGLDSysClassType; begin Result := GLD_SYSCLASS_3DS_FILE; end; procedure TGLD3dsFile.LoadFromStream(Stream: TStream); begin Stream.Read(FMeshVersion, SizeOf(GLuint)); Stream.Read(FKeyfRevision, SizeOf(GLushort)); GLDXLoadStringFromStream(Stream, FName); Stream.Read(FMasterScale, SizeOf(GLfloat)); Stream.Read(FConstructionPlane.GetPointer^, SizeOf(TGLDVector3f)); FAmbient.LoadFromStream(Stream); FShadow.LoadFromStream(Stream); FBackground.LoadFromStream(Stream); FAtmosphere.LoadFromStream(Stream); FViewport.LoadFromStream(Stream); FViewportKeyf.LoadFromStream(Stream); Stream.Read(FFrames, SizeOf(GLuint)); Stream.Read(FSegmentFrom, SizeOf(GLuint)); Stream.Read(FSegmentTo, SizeOf(GLuint)); Stream.Read(FCurrentFrame, SizeOf(GLuint)); FMaterials.LoadFromStream(Stream); FMeshes.LoadFromStream(Stream); FCameras.LoadFromStream(Stream); FLights.LoadFromStream(Stream); FNodes.LoadFromStream(Stream); end; procedure TGLD3dsFile.SaveToStream(Stream: TStream); begin Stream.Write(FMeshVersion, SizeOf(GLuint)); Stream.Write(FKeyfRevision, SizeOf(GLushort)); GLDXSaveStringToStream(Stream, FName); Stream.Write(FMasterScale, SizeOf(GLfloat)); Stream.Write(FConstructionPlane.GetPointer^, SizeOf(TGLDVector3f)); FAmbient.SaveToStream(Stream); FShadow.SaveToStream(Stream); FBackground.SaveToStream(Stream); FAtmosphere.SaveToStream(Stream); FViewport.SaveToStream(Stream); FViewportKeyf.SaveToStream(Stream); Stream.Write(FFrames, SizeOf(GLuint)); Stream.Write(FSegmentFrom, SizeOf(GLuint)); Stream.Write(FSegmentTo, SizeOf(GLuint)); Stream.Write(FCurrentFrame, SizeOf(GLuint)); FMaterials.SaveToStream(Stream); FMeshes.SaveToStream(Stream); FCameras.SaveToStream(Stream); FLights.SaveToStream(Stream); FNodes.SaveToStream(Stream); end; function TGLD3dsFile.NamedObjectRead(Stream: TStream): GLboolean; var C: TGLD3dsChunk; Name: string; begin Result := False; if not GLD3dsChunkReadStart(C, GLD3DS_NAMED_OBJECT, Stream) then Exit; Name := GLD3dsIoReadString(Stream); repeat GLD3dsChunkRead(C, Stream); case C.Chunk of GLD3DS_N_TRI_OBJECT: begin if FMeshes.CreateNew = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FMeshes.Last.Read(Stream) then Exit; FMeshes.Last.Name := Name; end; GLD3DS_N_CAMERA: begin if FCameras.CreateNew = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FCameras.Last.Read(Stream) then Exit; end; GLD3DS_N_DIRECT_LIGHT: begin if FLights.CreateNew = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FLights.Last.Read(Stream) then Exit; end; else begin GLD3dsChunkReadReset(Stream); C.Chunk := 0; end; end; until C.Chunk = 0; Result := True; end; function TGLD3dsFile.AmbientRead(Stream: TStream): GLboolean; var C: TGLD3dsChunk; HaveLin: GLboolean; begin HaveLin := False; Result := False; if not GLD3dsChunkReadStart(C, GLD3DS_AMBIENT_LIGHT, Stream) then Exit; repeat GLD3dsChunkRead(C, Stream); case C.Chunk of GLD3DS_LIN_COLOR_F: begin Stream.Read(FAmbient.GetPointer^, SizeOf(TGLDColor3f)); HaveLin := True; end; GLD3DS_COLOR_F: begin if not HaveLin then begin Stream.Read(FAmbient.GetPointer^, SizeOf(TGLDColor3f)); end; end; else begin GLD3dsChunkReadReset(Stream); C.Chunk := 0; end; end; until C.Chunk = 0; Result := True; end; function TGLD3dsFile.MDataRead(Stream: TStream): GLboolean; var C: TGLD3dsChunk; i: GLuint; begin Result := False; if not GLD3dsChunkReadStart(C, GLD3DS_MDATA, Stream) then Exit; repeat GLD3dsChunkRead(C, Stream); case C.Chunk of GLD3DS_MESH_VERSION: begin FMeshVersion := GLD3dsIoReadIntd(Stream); end; GLD3DS_MASTER_SCALE: begin FMasterScale := GLD3dsIoReadFloat(Stream); end; GLD3DS_SHADOW_MAP_SIZE, GLD3DS_LO_SHADOW_BIAS, GLD3DS_HI_SHADOW_BIAS, GLD3DS_SHADOW_SAMPLES, GLD3DS_SHADOW_RANGE, GLD3DS_SHADOW_FILTER, GLD3DS_RAY_BIAS: begin GLD3dsChunkReadReset(Stream); if not FShadow.Read(Stream) then Exit; end; GLD3DS_VIEWPORT_LAYOUT, GLD3DS_DEFAULT_VIEW: begin GLD3dsChunkReadReset(Stream); if not FViewport.Read(Stream) then Exit; end; GLD3DS_O_CONSTS: begin Stream.Read(FConstructionPlane.GetPointer^, SizeOf(TGLDVector3f)); end; GLD3DS_AMBIENT_LIGHT: begin GLD3dsChunkReadReset(Stream); if not AmbientRead(Stream) then Exit; end; GLD3DS_BIT_MAP, GLD3DS_SOLID_BGND, GLD3DS_V_GRADIENT, GLD3DS_USE_BIT_MAP, GLD3DS_USE_SOLID_BGND, GLD3DS_USE_V_GRADIENT: begin GLD3dsChunkReadReset(Stream); if not FBackground.Read(Stream) then Exit; end; GLD3DS_FOG, GLD3DS_LAYER_FOG, GLD3DS_DISTANCE_CUE, GLD3DS_USE_FOG, GLD3DS_USE_LAYER_FOG, GLD3DS_USE_DISTANCE_CUE: begin GLD3dsChunkReadReset(Stream); if not FAtmosphere.Read(Stream) then Exit; end; GLD3DS_MAT_ENTRY: begin if FMaterials.CreateNew = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FMaterials.Last.Read(Stream) then Exit; end; GLD3DS_NAMED_OBJECT: begin GLD3dsChunkReadReset(Stream); if not NamedObjectRead(Stream) then Exit; end; else begin GLD3dsChunkReadReset(Stream); C.Chunk := 0; end; end; until C.Chunk = 0; Result := True; end; function TGLD3dsFile.KFDataRead(Stream: TStream): GLboolean; var C: TGLD3dsChunk; begin Result := False; if not GLD3dsChunkReadStart(C, GLD3DS_KFDATA, Stream) then Exit; repeat GLD3dsChunkRead(C, Stream); case C.Chunk of GLD3DS_KFHDR: begin FKeyfRevision := GLD3dsIoReadWord(Stream); FName := GLD3dsIoReadString(Stream); FFrames := GLD3dsIoReadIntd(Stream); end; GLD3DS_KFSEG: begin FSegmentFrom := GLD3dsIoReadIntd(Stream); FSegmentTo := GLD3dsIoReadIntd(Stream); end; GLD3DS_KFCURTIME: begin FCurrentFrame := GLD3dsIoReadIntd(Stream); end; GLD3DS_VIEWPORT_LAYOUT, GLD3DS_DEFAULT_VIEW: begin GLD3dsChunkReadReset(Stream); if not FViewportKeyf.Read(Stream) then Exit; end; GLD3DS_AMBIENT_NODE_TAG: begin if FNodes.CreateNew(GLD3DS_AMBIENT_NODE) = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FNodes.Last.Read(Stream) then Exit; end; GLD3DS_OBJECT_NODE_TAG: begin if FNodes.CreateNew(GLD3DS_OBJECT_NODE) = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FNodes.Last.Read(Stream) then Exit; end; GLD3DS_CAMERA_NODE_TAG: begin if FNodes.CreateNew(GLD3DS_CAMERA_NODE) = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FNodes.Last.Read(Stream) then Exit; end; GLD3DS_TARGET_NODE_TAG: begin if FNodes.CreateNew(GLD3DS_TARGET_NODE) = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FNodes.Last.Read(Stream) then Exit; end; GLD3DS_LIGHT_NODE_TAG, GLD3DS_SPOTLIGHT_NODE_TAG: begin if FNodes.CreateNew(GLD3DS_LIGHT_NODE) = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FNodes.Last.Read(Stream) then Exit; end; GLD3DS_L_TARGET_NODE_TAG: begin if FNodes.CreateNew(GLD3DS_SPOT_NODE) = 0 then Exit; GLD3dsChunkReadReset(Stream); if not FNodes.Last.Read(Stream) then Exit; end; else begin GLD3dsChunkReadReset(Stream); C.Chunk := 0; end; end; until C.Chunk = 0; Result := True; end; function TGLD3dsFile.Read(Stream: TStream): GLboolean; var C: TGLD3dsChunk; begin Result := False; GLD3dsChunkRead(C, Stream); case C.Chunk of GLD3DS_MDATA: begin GLD3dsChunkReadReset(Stream); if not MDataRead(Stream) then Exit; end; GLD3DS_M3DMAGIC, GLD3DS_MLIBMAGIC, GLD3DS_CMAGIC: begin repeat GLD3dsChunkRead(C, Stream); case C.Chunk of GLD3DS_M3D_VERSION: begin FMeshVersion := GLD3dsIoReadDword(Stream); end; GLD3DS_MDATA: begin GLD3dsChunkReadReset(Stream); if not MDataRead(Stream) then Exit; end; GLD3DS_KFDATA: begin GLD3dsChunkReadReset(Stream); if not KFDataRead(Stream) then Exit; end; else begin GLD3dsChunkReadReset(Stream); C.Chunk := 0; end; end; until C.Chunk = 0; end; end; Result := True; end; function TGLD3dsFile.ReadFromFile(const FileName: string): GLboolean; var FileStream: TFileStream; begin Result := False; if not FileExists(FileName) then Exit; try FileStream := TFileStream.Create(FileName, fmOpenRead); try Result := Read(FileStream); except Result := False; end; finally FileStream.Free; end; end; procedure TGLD3dsFile.SetOnChange(Value: TNotifyEvent); begin inherited SetOnChange(Value); FConstructionPlane.OnChange := FOnChange; FAmbient.OnChange := FOnChange; FShadow.OnChange := FOnChange; FBackground.OnChange := FOnChange; FAtmosphere.OnChange := FOnChange; FViewport.OnChange := FOnChange; FViewportKeyf.OnChange := FOnChange; FMaterials.OnChange := FOnChange; FMeshes.OnChange := FOnChange; FCameras.OnChange := FOnChange; FLights.OnChange := FOnChange; FNodes.OnChange := FOnChange; end; procedure TGLD3dsFile.SetMeshVersion(Value: GLuint); begin if FMeshVersion = Value then Exit; FMeshVersion := Value; Change; end; procedure TGLD3dsFile.SetKeyfRevision(Value: GLushort); begin if FKeyfRevision = Value then Exit; FKeyfRevision := Value; Change; end; procedure TGLD3dsFile.SetName(Value: string); begin if FName = Value then Exit; FName := Value; Change; end; procedure TGLD3dsFile.SetMasterScale(Value: GLfloat); begin if FMasterScale = Value then Exit; FMasterScale := Value; Change; end; procedure TGLD3dsFile.SetConstructionPlane(Value: TGLDVector4fClass); begin FConstructionPlane.Assign(Value); end; procedure TGLD3dsFile.SetAmbient(Value: TGLDColor4fClass); begin FAmbient.Assign(Value); end; procedure TGLD3dsFile.SetShadow(Value: TGLD3dsShadow); begin FShadow.Assign(Value); end; procedure TGLD3dsFile.SetBackground(Value: TGLD3dsBackground); begin FBackground.Assign(Value); end; procedure TGLD3dsFile.SetAtmosphere(Value: TGLD3dsAtmosphere); begin FAtmosphere.Assign(Value); end; procedure TGLD3dsFile.SetViewport(Value: TGLD3dsViewport); begin FViewport.Assign(Value); end; procedure TGLD3dsFile.SetViewportKeyf(Value: TGLD3dsViewport); begin FViewportKeyF.Assign(Value); end; procedure TGLD3dsFile.SetFrames(Value: GLuint); begin if FFrames = Value then Exit; FFrames := Value; Change; end; procedure TGLD3dsFile.SetSegmentFrom(Value: GLuint); begin if FSegmentFrom = Value then Exit; FSegmentFrom := Value; Change; end; procedure TGLD3dsFile.SetSegmentTo(Value: GLuint); begin if FSegmentTo = Value then Exit; FSegmentTo := Value; Change; end; procedure TGLD3dsFile.SetCurrentFrame(Value: GLuint); begin if FCurrentFrame = Value then Exit; FCurrentFrame := Value; Change; end; procedure TGLD3dsFile.SetMaterials(Value: TGLD3dsMaterialList); begin FMaterials.Assign(Value); end; procedure TGLD3dsFile.SetMeshes(Value: TGLD3dsMeshList); begin FMeshes.Assign(Value); end; procedure TGLD3dsFile.SetCameras(Value: TGLD3dsCameraList); begin FCameras.Assign(Value); end; procedure TGLD3dsFile.SetLights(Value: TGLD3dsLightList); begin FLights.Assign(Value); end; procedure TGLD3dsFile.SetNodes(Value: TGLD3dsNodeList); begin FNodes.Assign(Value); end; end.
unit TextureGeneratorBase; interface uses GLConstants, BasicMathsTypes, BasicDataTypes, Windows, Graphics, BasicFunctions, SysUtils, Math3d, TriangleFiller, ImageRGBAByteData, ImageGreyByteData, ImageRGBByteData, Abstract2DImageData, LOD; type CTextureGeneratorBase = class protected FLOD: TLOD; FSize: integer; FMaterialID: integer; FTextureID: integer; // Painting procedures function GetHeightPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer): TBitmap; procedure FixBilinearBorders(var _Bitmap: TBitmap; var _AlphaMap: TByteMap); overload; procedure FixBilinearBorders(var _ImageData: TAbstract2DImageData); overload; function GenerateHeightMapBuffer(const _DiffuseMap: TAbstract2DImageData): T2DImageGreyByteData; public // Constructors and Destructors constructor Create(var _LOD: TLOD); overload; virtual; constructor Create(var _LOD: TLOD; _Size, _MaterialID, _TextureID: integer); overload; virtual; destructor Destroy; override; procedure Initialize; procedure Reset; procedure Clear; // Execute procedure Execute; virtual; abstract; // Generate Textures step by step procedure SetupFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Size: integer); overload; procedure SetupFrameBuffer(var _Buffer: T2DFrameBuffer; _Size: integer); overload; procedure PaintMeshDiffuseTexture(const _Faces: auint32; const _VertsColours: TAVector4f; const _TexCoords: TAVector2f; _VerticesPerFace: integer; var _Buffer: TAbstract2DImageData; var _WeightBuffer: TAbstract2DImageData); procedure PaintMeshNormalMapTexture(const _Faces: auint32; const _VertsNormals: TAVector3f; const _TexCoords: TAVector2f; _VerticesPerFace: integer; var _Buffer: TAbstract2DImageData; var _WeightBuffer: TAbstract2DImageData); procedure PaintMeshBumpMapTexture(const _Faces: auint32; const _VertsNormals: TAVector3f; const _TexCoords: TAVector2f; _VerticesPerFace: integer; var _Buffer: TAbstract2DImageData; const _DiffuseMap: TAbstract2DImageData); procedure PaintMeshNCMDiffuseTexture(const _Faces: auint32; const _VertsColours: TAVector4f; const _TexCoords: TAVector2f; _VerticesPerFace: integer; var _Buffer: TAbstract2DImageData; var _WeightBuffer: TAbstract2DImageData); procedure DisposeFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer); overload; procedure DisposeFrameBuffer(var _Buffer: T2DFrameBuffer); overload; function GetColouredBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _AlphaMap: TByteMap): TBitmap; function GetColouredImageDataFromBuffer(var _Buffer, _WeightBuffer: TAbstract2DImageData): TAbstract2DImageData; function GetPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer): TBitmap; overload; function GetPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _AlphaMap: TByteMap): TBitmap; overload; function GetPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _AlphaMap: TByteMap): TBitmap; overload; function GetPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer): TBitmap; overload; function GetPositionedImageDataFromBuffer(const _Buffer, _WeightBuffer: TAbstract2DImageData): TAbstract2DImageData; function GetBumpMapTexture(const _DiffuseMap: TAbstract2DImageData; _Scale: single = C_BUMP_DEFAULTSCALE): TAbstract2DImageData; end; implementation uses Math; constructor CTextureGeneratorBase.Create(var _LOD: TLOD; _Size, _MaterialID, _TextureID: integer); begin FLOD := _LOD; FSize := _Size; FMaterialID := _MaterialID; FTextureID := _TextureID; Initialize; end; constructor CTextureGeneratorBase.Create(var _LOD: TLOD); begin FLOD := _LOD; FSize := 1024; FTextureID := 0; if FLOD <> nil then begin if High(FLOD.Mesh) >= 0 then begin FSize := FLOD.Mesh[0].GetTextureSize(0,FLOD.Mesh[0].Materials[0].GetTextureID(C_TTP_DIFFUSE)); FTextureID := FLOD.Mesh[0].GetNextTextureID(0); end; end; FMaterialID := 0; Initialize; end; destructor CTextureGeneratorBase.Destroy; begin Clear; inherited Destroy; end; procedure CTextureGeneratorBase.Initialize; begin // do nothing end; procedure CTextureGeneratorBase.Clear; begin // do nothing end; procedure CTextureGeneratorBase.Reset; begin Clear; Initialize; end; // Painting procedures procedure CTextureGeneratorBase.SetupFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Size: integer); var x,y : integer; begin SetLength(_Buffer,_Size,_Size); SetLength(_WeightBuffer,_Size,_Size); for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer) to High(_Buffer) do begin _Buffer[x,y].X := 0; _Buffer[x,y].Y := 0; _Buffer[x,y].Z := 0; _Buffer[x,y].W := 0; _WeightBuffer[x,y] := 0; end; end; end; procedure CTextureGeneratorBase.SetupFrameBuffer(var _Buffer: T2DFrameBuffer; _Size: integer); var x,y : integer; begin SetLength(_Buffer,_Size,_Size); for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer) to High(_Buffer) do begin _Buffer[x,y].X := 0; _Buffer[x,y].Y := 0; _Buffer[x,y].Z := 0; _Buffer[x,y].W := 0; end; end; end; procedure CTextureGeneratorBase.DisposeFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer); var x : integer; begin for x := Low(_Buffer) to High(_Buffer) do begin SetLength(_Buffer[x],0); SetLength(_WeightBuffer[x],0); end; SetLength(_Buffer,0); SetLength(_WeightBuffer,0); end; procedure CTextureGeneratorBase.DisposeFrameBuffer(var _Buffer: T2DFrameBuffer); var x : integer; begin for x := Low(_Buffer) to High(_Buffer) do begin SetLength(_Buffer[x],0); end; SetLength(_Buffer,0); end; function CTextureGeneratorBase.GetColouredBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _AlphaMap: TByteMap): TBitmap; var x,y,i,j,counter : integer; begin Result := TBitmap.Create; Result.PixelFormat := pf32Bit; Result.Transparent := false; Result.Width := High(_Buffer)+1; Result.Height := High(_Buffer)+1; SetLength(_AlphaMap,Result.Width,Result.Width); // First pass for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer[x]) to High(_Buffer[x]) do begin if _WeightBuffer[x,y] > 0 then begin if ((_Buffer[x,y].X / _WeightBuffer[x,y]) < 0) then _Buffer[x,y].X := 0; //_Buffer[x,y].X * -1; if (abs(_Buffer[x,y].X / _WeightBuffer[x,y]) > 1) then _Buffer[x,y].X := _WeightBuffer[x,y]; if ((_Buffer[x,y].Y / _WeightBuffer[x,y]) < 0) then _Buffer[x,y].Y := 0; //_Buffer[x,y].Y * -1; if (abs(_Buffer[x,y].Y / _WeightBuffer[x,y]) > 1) then _Buffer[x,y].Y := _WeightBuffer[x,y]; if ((_Buffer[x,y].Z / _WeightBuffer[x,y]) < 0) then _Buffer[x,y].Z := 0; //_Buffer[x,y].Z * -1; if (abs(_Buffer[x,y].Z / _WeightBuffer[x,y]) > 1) then _Buffer[x,y].Z := _WeightBuffer[x,y]; if ((_Buffer[x,y].W / _WeightBuffer[x,y]) < 0) then _Buffer[x,y].W := 0; //_Buffer[x,y].W * -1; if (abs(_Buffer[x,y].W / _WeightBuffer[x,y]) > 1) then _Buffer[x,y].W := _WeightBuffer[x,y]; _Buffer[x,y].X := _Buffer[x,y].X / _WeightBuffer[x,y]; _Buffer[x,y].Y := _Buffer[x,y].Y / _WeightBuffer[x,y]; _Buffer[x,y].Z := _Buffer[x,y].Z / _WeightBuffer[x,y]; //Result.Canvas.Pixels[x,Result.Height - y] := RGB(Trunc((_Buffer[x,y].X / _WeightBuffer[x,y]) * 255),Trunc((_Buffer[x,y].Y / _WeightBuffer[x,y]) * 255),Trunc((_Buffer[x,y].Z / _WeightBuffer[x,y]) * 255)); _AlphaMap[x,Result.Height - y] := Trunc(((_Buffer[x,y].W / _WeightBuffer[x,y])) * 255); _WeightBuffer[x,y] := 1; end else begin //Result.Canvas.Pixels[x,Result.Height - y] := 0;//$888888; _Buffer[x,y].X := 0; _Buffer[x,y].Y := 0; _Buffer[x,y].Z := 0; _AlphaMap[x,Result.Height - y] := C_TRP_INVISIBLE; end; end; end; // Second pass for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer[x]) to High(_Buffer[x]) do begin if _WeightBuffer[x,y] > 0 then begin Result.Canvas.Pixels[x,Result.Height - y] := RGB(Trunc(_Buffer[x,y].X * 255),Trunc(_Buffer[x,y].Y * 255),Trunc(_Buffer[x,y].Z * 255)); end else begin counter := 0; for i := max(0, x - 1) to min(High(_Buffer), x + 1) do for j := max(0, y - 1) to min(High(_Buffer[x]), y + 1) do begin if _WeightBuffer[i, j] = 1 then begin _Buffer[x,y].X := _Buffer[x,y].X + _Buffer[i,j].X; _Buffer[x,y].Y := _Buffer[x,y].Y + _Buffer[i,j].Y; _Buffer[x,y].Z := _Buffer[x,y].Z + _Buffer[i,j].Z; inc(counter); end; end; if counter > 0 then begin _Buffer[x,y].X := _Buffer[x,y].X / counter; _Buffer[x,y].Y := _Buffer[x,y].Y / counter; _Buffer[x,y].Z := _Buffer[x,y].Z / counter; _AlphaMap[x,Result.Height - y] := C_TRP_RGB_OPAQUE; Result.Canvas.Pixels[x,Result.Height - y] := RGB(Trunc(_Buffer[x,y].X * 255),Trunc(_Buffer[x,y].Y * 255),Trunc(_Buffer[x,y].Z * 255)); end; end; end; end; // FixBilinearBorders(Result,_AlphaMap); end; function CTextureGeneratorBase.GetColouredImageDataFromBuffer(var _Buffer, _WeightBuffer: TAbstract2DImageData): TAbstract2DImageData; var x, y, i, j, counter : integer; begin Result := T2DImageRGBAByteData.Create(_Buffer.XSize,_Buffer.YSize); // First pass for x := 0 to _Buffer.MaxX do begin for y := 0 to _Buffer.MaxY do begin if _WeightBuffer.Red[x,y] > 0 then begin if ((_Buffer.Red[x,y] / _WeightBuffer.Red[x,y]) < 0) then _Buffer.Red[x,y] := 0; if (abs(_Buffer.Red[x,y] / _WeightBuffer.Red[x,y]) > 1) then _Buffer.Red[x,y] := _WeightBuffer.Red[x,y]; if ((_Buffer.Green[x,y] / _WeightBuffer.Red[x,y]) < 0) then _Buffer.Green[x,y] := 0; if (abs(_Buffer.Green[x,y] / _WeightBuffer.Red[x,y]) > 1) then _Buffer.Green[x,y] := _WeightBuffer.Red[x,y]; if ((_Buffer.Blue[x,y] / _WeightBuffer.Red[x,y]) < 0) then _Buffer.Blue[x,y] := 0; if (abs(_Buffer.Blue[x,y] / _WeightBuffer.Red[x,y]) > 1) then _Buffer.Blue[x,y] := _WeightBuffer.Red[x,y]; if ((_Buffer.Alpha[x,y] / _WeightBuffer.Red[x,y]) < 0) then _Buffer.Alpha[x,y] := 0; if (abs(_Buffer.Alpha[x,y] / _WeightBuffer.Red[x,y]) > 1) then _Buffer.Alpha[x,y] := _WeightBuffer.Red[x,y]; _Buffer.Red[x, y] := (_Buffer.Red[x,y] / _WeightBuffer.Red[x,y]); _Buffer.Green[x, y] := (_Buffer.Green[x,y] / _WeightBuffer.Red[x,y]); _Buffer.Blue[x, y] := (_Buffer.Blue[x,y] / _WeightBuffer.Red[x,y]); Result.Alpha[x,Result.YSize - y] := (_Buffer.Alpha[x,y] / _WeightBuffer.Red[x,y]) * 255; _WeightBuffer.Red[x,y] := 1; end else begin Result.Red[x,Result.YSize - y] := 0;//$888888; Result.Green[x,Result.YSize - y] := 0;//$888888; Result.Blue[x,Result.YSize - y] := 0;//$888888; Result.Alpha[x,Result.YSize - y] := C_TRP_INVISIBLE; end; end; end; // Second pass for x := 0 to _Buffer.MaxX do begin for y := 0 to _Buffer.MaxY do begin if _WeightBuffer.Red[x,y] > 0 then begin Result.Red[x,Result.YSize - y] := _Buffer.Red[x,y] * 255; Result.Green[x,Result.YSize - y] := _Buffer.Green[x,y] * 255; Result.Blue[x,Result.YSize - y] := _Buffer.Blue[x,y] * 255; end else begin counter := 0; for i := max(0, x - 1) to min(_Buffer.MaxX, x + 1) do for j := max(0, y - 1) to min(_Buffer.MaxY, y + 1) do begin if _WeightBuffer.Red[i, j] = 1 then begin _Buffer.Red[x,y] := _Buffer.Red[x,y] + _Buffer.Red[i,j]; _Buffer.Green[x,y] := _Buffer.Green[x,y] + _Buffer.Green[i,j]; _Buffer.Blue[x,y] := _Buffer.Blue[x,y] + _Buffer.Blue[i,j]; inc(counter); end; end; if counter > 0 then begin _Buffer.Red[x,y] := _Buffer.Red[x,y] / counter; _Buffer.Green[x,y] := _Buffer.Green[x,y] / counter; _Buffer.Blue[x,y] := _Buffer.Blue[x,y] / counter; Result.Red[x,Result.YSize - y] := _Buffer.Red[x,y] * 255; Result.Green[x,Result.YSize - y] := _Buffer.Green[x,y] * 255; Result.Blue[x,Result.YSize - y] := _Buffer.Blue[x,y] * 255; Result.Alpha[x,Result.YSize - y] := C_TRP_RGB_OPAQUE; end; end; end; end; // FixBilinearBorders(Result); end; function CTextureGeneratorBase.GetPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer): TBitmap; var x,y : integer; Normal: TVector3f; begin Result := TBitmap.Create; Result.PixelFormat := pf32Bit; Result.Width := High(_Buffer)+1; Result.Height := High(_Buffer)+1; for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer[x]) to High(_Buffer[x]) do begin if _WeightBuffer[x,y] > 0 then begin Normal.X := _Buffer[x,y].X / _WeightBuffer[x,y]; Normal.Y := _Buffer[x,y].Y / _WeightBuffer[x,y]; Normal.Z := _Buffer[x,y].Z / _WeightBuffer[x,y]; if abs(Normal.X) + abs(Normal.Y) + abs(Normal.Z) = 0 then Normal.Z := 1; Normalize(Normal); Result.Canvas.Pixels[x,Result.Height - y] := RGB(Round((1 + Normal.X) * 127.5),Round((1 + Normal.Y) * 127.5),Round((1 + Normal.Z) * 127.5)); end else begin Result.Canvas.Pixels[x,Result.Height - y] := 0; end; end; end; end; function CTextureGeneratorBase.GetPositionedImageDataFromBuffer(const _Buffer, _WeightBuffer: TAbstract2DImageData): TAbstract2DImageData; var x,y : integer; Normal: TVector3f; begin Result := T2DImageRGBByteData.Create(_Buffer.XSize,_Buffer.YSize); for x := 0 to _Buffer.MaxX do begin for y := 0 to _Buffer.MaxY do begin if _WeightBuffer.Red[x,y] > 0 then begin Normal.X := _Buffer.Red[x,y] / _WeightBuffer.Red[x,y]; Normal.Y := _Buffer.Green[x,y] / _WeightBuffer.Red[x,y]; Normal.Z := _Buffer.Blue[x,y] / _WeightBuffer.Red[x,y]; if abs(Normal.X) + abs(Normal.Y) + abs(Normal.Z) = 0 then Normal.Z := 1; Normalize(Normal); Result.Red[x,Result.YSize - y] := Round((1 + Normal.X) * 127.5); Result.Green[x,Result.YSize - y] := Round((1 + Normal.Y) * 127.5); Result.Blue[x,Result.YSize - y] := Round((1 + Normal.Z) * 127.5); end else begin Result.Red[x,Result.YSize - y] := 0; Result.Green[x,Result.YSize - y] := 0; Result.Blue[x,Result.YSize - y] := 0; end; end; end; end; function CTextureGeneratorBase.GetPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _AlphaMap: TByteMap): TBitmap; var x,y : integer; Normal: TVector3f; begin Result := TBitmap.Create; Result.PixelFormat := pf32Bit; Result.Width := High(_Buffer)+1; Result.Height := High(_Buffer)+1; for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer[x]) to High(_Buffer[x]) do begin if _WeightBuffer[x,y] > 0 then begin Normal.X := _Buffer[x,y].X / _WeightBuffer[x,y]; Normal.Y := _Buffer[x,y].Y / _WeightBuffer[x,y]; Normal.Z := _Buffer[x,y].Z / _WeightBuffer[x,y]; if abs(Normal.X) + abs(Normal.Y) + abs(Normal.Z) = 0 then Normal.Z := 1; Normalize(Normal); Result.Canvas.Pixels[x,Result.Height - y] := RGB(Round((1 + Normal.X) * 127.5),Round((1 + Normal.Y) * 127.5),Round((1 + Normal.Z) * 127.5)); end else begin Result.Canvas.Pixels[x,Result.Height - y] := 0; end; end; end; end; function CTextureGeneratorBase.GetPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _AlphaMap: TByteMap): TBitmap; var x,y : integer; Normal: TVector3f; begin Result := TBitmap.Create; Result.PixelFormat := pf32Bit; Result.Width := High(_Buffer)+1; Result.Height := High(_Buffer)+1; SetLength(_AlphaMap,Result.Width,Result.Width); for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer[x]) to High(_Buffer[x]) do begin Normal.X := _Buffer[x,y].X; Normal.Y := _Buffer[x,y].Y; Normal.Z := _Buffer[x,y].Z; if (abs(Normal.X) + abs(Normal.Y) + abs(Normal.Z) = 0) then Normal.Z := 1; Normalize(Normal); Result.Canvas.Pixels[x,Result.Height - y] := RGB(Round((1 + Normal.X) * 127.5),Round((1 + Normal.Y) * 127.5),Round((1 + Normal.Z) * 127.5)); _AlphaMap[x,Result.Height - y] := C_TRP_OPAQUE; end; end; end; function CTextureGeneratorBase.GetPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer): TBitmap; var x,y : integer; Normal: TVector3f; begin Result := TBitmap.Create; Result.PixelFormat := pf32Bit; Result.Width := High(_Buffer)+1; Result.Height := High(_Buffer)+1; for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer[x]) to High(_Buffer[x]) do begin Normal.X := _Buffer[x,y].X; Normal.Y := _Buffer[x,y].Y; Normal.Z := _Buffer[x,y].Z; if (abs(Normal.X) + abs(Normal.Y) + abs(Normal.Z) = 0) then Normal.Z := 1; Normalize(Normal); Result.Canvas.Pixels[x,Result.Height - y] := RGB(Round((1 + Normal.X) * 127.5),Round((1 + Normal.Y) * 127.5),Round((1 + Normal.Z) * 127.5)); end; end; end; function CTextureGeneratorBase.GetHeightPositionedBitmapFromFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer): TBitmap; var x,y : integer; begin Result := TBitmap.Create; Result.PixelFormat := pf32Bit; Result.Width := High(_Buffer)+1; Result.Height := High(_Buffer)+1; for x := Low(_Buffer) to High(_Buffer) do begin for y := Low(_Buffer[x]) to High(_Buffer[x]) do begin if _WeightBuffer[x,y] > 0 then begin Result.Canvas.Pixels[x,Result.Height - y] := RGBA(Round((1 + (_Buffer[x,y].X / _WeightBuffer[x,y])) * 127.5),Round((1 + (_Buffer[x,y].Y / _WeightBuffer[x,y])) * 127.5),Round((1 + (_Buffer[x,y].Z / _WeightBuffer[x,y])) * 127.5),Round((_Buffer[x,y].W / _WeightBuffer[x,y]) * 255)); end else begin Result.Canvas.Pixels[x,Result.Height - y] := 0; end; end; end; end; function CTextureGeneratorBase.GenerateHeightMapBuffer(const _DiffuseMap: TAbstract2DImageData): T2DImageGreyByteData; var x,y,Size : integer; r,g,b: real; begin // Build height map and visited map Size := _DiffuseMap.XSize; Result := T2DImageGreyByteData.Create(Size,Size); for x := 0 to Result.MaxX do begin for y := 0 to Result.MaxY do begin r := _DiffuseMap.Red[x,y] / 255; g := _DiffuseMap.Green[x,y] / 255; b := _DiffuseMap.Blue[x,y] / 255; // Convert to YIQ Result.Red[x,y] := Round((1 - (0.299 * r) + (0.587 * g) + (0.114 * b)) * 255) and $FF; end; end; end; procedure CTextureGeneratorBase.PaintMeshDiffuseTexture(const _Faces: auint32; const _VertsColours: TAVector4f; const _TexCoords: TAVector2f; _VerticesPerFace: integer; var _Buffer: TAbstract2DImageData; var _WeightBuffer: TAbstract2DImageData); var i,LastFace : cardinal; Filler: CTriangleFiller; begin LastFace := ((High(_Faces)+1) div _VerticesPerFace) - 1; Filler := CTriangleFiller.Create; for i := 0 to LastFace do begin Filler.PaintTriangle(_Buffer,_WeightBuffer,_TexCoords[_Faces[(i * _VerticesPerFace)]],_TexCoords[_Faces[(i * _VerticesPerFace)+1]],_TexCoords[_Faces[(i * _VerticesPerFace)+2]],_VertsColours[_Faces[(i * _VerticesPerFace)]],_VertsColours[_Faces[(i * _VerticesPerFace)+1]],_VertsColours[_Faces[(i * _VerticesPerFace)+2]]); end; Filler.Free; end; procedure CTextureGeneratorBase.PaintMeshNCMDiffuseTexture(const _Faces: auint32; const _VertsColours: TAVector4f; const _TexCoords: TAVector2f; _VerticesPerFace: integer; var _Buffer: TAbstract2DImageData; var _WeightBuffer: TAbstract2DImageData); var i,LastFace : cardinal; Filler: CTriangleFiller; begin LastFace := ((High(_Faces)+1) div _VerticesPerFace) - 1; Filler := CTriangleFiller.Create; for i := 0 to LastFace do begin Filler.PaintTriangleNCM(_Buffer,_WeightBuffer,_TexCoords[_Faces[(i * _VerticesPerFace)]],_TexCoords[_Faces[(i * _VerticesPerFace)+1]],_TexCoords[_Faces[(i * _VerticesPerFace)+2]],_VertsColours[_Faces[(i * _VerticesPerFace)]],_VertsColours[_Faces[(i * _VerticesPerFace)+1]],_VertsColours[_Faces[(i * _VerticesPerFace)+2]]); end; Filler.Free; end; procedure CTextureGeneratorBase.PaintMeshNormalMapTexture(const _Faces: auint32; const _VertsNormals: TAVector3f; const _TexCoords: TAVector2f; _VerticesPerFace: integer; var _Buffer: TAbstract2DImageData; var _WeightBuffer: TAbstract2DImageData); var i,LastFace : cardinal; Filler: CTriangleFiller; begin LastFace := ((High(_Faces)+1) div _VerticesPerFace) - 1; Filler := CTriangleFiller.Create; for i := 0 to LastFace do begin Filler.PaintTriangle(_Buffer,_WeightBuffer,_TexCoords[_Faces[(i * _VerticesPerFace)]],_TexCoords[_Faces[(i * _VerticesPerFace)+1]],_TexCoords[_Faces[(i * _VerticesPerFace)+2]],_VertsNormals[_Faces[(i * _VerticesPerFace)]],_VertsNormals[_Faces[(i * _VerticesPerFace)+1]],_VertsNormals[_Faces[(i * _VerticesPerFace)+2]]); end; Filler.Free; end; // This is the original attempt painting faces. procedure CTextureGeneratorBase.PaintMeshBumpMapTexture(const _Faces: auint32; const _VertsNormals: TAVector3f; const _TexCoords: TAVector2f; _VerticesPerFace: integer; var _Buffer: TAbstract2DImageData; const _DiffuseMap: TAbstract2DImageData); var HeightMap : TAbstract2DImageData; Face : integer; Filler: CTriangleFiller; begin // Build height map and visited map Filler := CTriangleFiller.Create; HeightMap := GenerateHeightMapBuffer(_DiffuseMap); // Now, we'll check each face. Face := 0; while Face < High(_Faces) do begin // Paint the face here. Filler.PaintFlatTriangleFromHeightMap(_Buffer,HeightMap,_TexCoords[_Faces[Face]],_TexCoords[_Faces[Face+1]],_TexCoords[_Faces[Face+2]]); // Go to next face. inc(Face,_VerticesPerFace); end; HeightMap.Free; Filler.Free; end; // This is the latest attempt as a simple image processsing operation. function CTextureGeneratorBase.GetBumpMapTexture(const _DiffuseMap: TAbstract2DImageData; _Scale: single): TAbstract2DImageData; var HeightMap : TAbstract2DImageData; x,y,Size : integer; Filler: CTriangleFiller; begin // Build height map and visited map Filler := CTriangleFiller.Create; HeightMap := GenerateHeightMapBuffer(_DiffuseMap); HeightMap.ScaleBy(_Scale / 255); Size := HeightMap.XSize; Result := T2DImageRGBByteData.Create(Size,Size); // Now, we'll check each face. for x := 0 to HeightMap.MaxX do for y := 0 to HeightMap.MaxY do begin Filler.PaintBumpValueAtFrameBuffer(Result,HeightMap,X,Y,Size); end; HeightMap.Free; Filler.Free; end; // This procedure fixes white/black borders in the edge of each partition. procedure CTextureGeneratorBase.FixBilinearBorders(var _Bitmap: TBitmap; var _AlphaMap: TByteMap); var x,y,i,k,mini,maxi,mink,maxk,r,g,b,ri,gi,bi,sum : integer; AlphaMapBackup: TByteMap; begin SetLength(AlphaMapBackup,High(_AlphaMap)+1,High(_AlphaMap)+1); for x := Low(_AlphaMap) to High(_AlphaMap) do begin for y := Low(_AlphaMap[x]) to High(_AlphaMap[x]) do begin AlphaMapBackup[x,y] := _AlphaMap[x,y]; end; end; for x := Low(_AlphaMap) to High(_AlphaMap) do begin for y := Low(_AlphaMap[x]) to High(_AlphaMap[x]) do begin if AlphaMapBackup[x,y] = C_TRP_RGB_INVISIBLE then begin mini := x - 1; if mini < 0 then mini := 0; maxi := x + 1; if maxi > High(_AlphaMap) then maxi := High(_AlphaMap); mink := y - 1; if mink < 0 then mink := 0; maxk := y + 1; if maxk > High(_AlphaMap) then maxk := High(_AlphaMap); r := 0; g := 0; b := 0; sum := 0; for i := mini to maxi do for k := mink to maxk do begin if AlphaMapBackup[i,k] <> C_TRP_RGB_INVISIBLE then begin ri := GetRValue(_Bitmap.Canvas.Pixels[i,k]); gi := GetGValue(_Bitmap.Canvas.Pixels[i,k]); bi := GetBValue(_Bitmap.Canvas.Pixels[i,k]); r := r + ri; g := g + gi; b := b + bi; inc(sum); end; end; if (r + g + b) > 0 then _AlphaMap[x,y] := C_TRP_RGB_OPAQUE; if sum > 0 then _Bitmap.Canvas.Pixels[x,y] := RGB(r div sum, g div sum, b div sum); end; end; end; // Free memory for i := Low(_AlphaMap) to High(_AlphaMap) do begin SetLength(AlphaMapBackup[i],0); end; SetLength(AlphaMapBackup,0); end; procedure CTextureGeneratorBase.FixBilinearBorders(var _ImageData: TAbstract2DImageData); var x,y,i,k,mini,maxi,mink,maxk,r,g,b,ri,gi,bi,sum : integer; AlphaMapBackup: TByteMap; begin SetLength(AlphaMapBackup,_ImageData.XSize,_ImageData.YSize); for x := 0 to _ImageData.MaxX do begin for y := 0 to _ImageData.MaxY do begin AlphaMapBackup[x,y] := Trunc(_ImageData.Alpha[x,y]); end; end; for x := 0 to _ImageData.MaxX do begin for y := 0 to _ImageData.MaxY do begin if AlphaMapBackup[x,y] = C_TRP_RGB_INVISIBLE then begin mini := x - 1; if mini < 0 then mini := 0; maxi := x + 1; if maxi > _ImageData.MaxX then maxi := _ImageData.MaxX; mink := y - 1; if mink < 0 then mink := 0; maxk := y + 1; if maxk > _ImageData.MaxY then maxk := _ImageData.MaxY; r := 0; g := 0; b := 0; sum := 0; for i := mini to maxi do for k := mink to maxk do begin if AlphaMapBackup[i,k] <> C_TRP_RGB_INVISIBLE then begin ri := Trunc(_ImageData.Red[i,k]); gi := Trunc(_ImageData.Green[i,k]); bi := Trunc(_ImageData.Blue[i,k]); r := r + ri; g := g + gi; b := b + bi; inc(sum); end; end; if (r + g + b) > 0 then _ImageData.Alpha[x,y] := C_TRP_RGB_OPAQUE; if sum > 0 then begin _ImageData.Red[x,y] := r div sum; _ImageData.Green[x,y] := g div sum; _ImageData.Blue[x,y] := b div sum; end; end; end; end; // Free memory for i := Low(AlphaMapBackup) to High(AlphaMapBackup) do begin SetLength(AlphaMapBackup[i],0); end; SetLength(AlphaMapBackup,0); end; end.
unit CommunityModel; interface uses connection, Ragna, System.JSON, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.ConsoleUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, Horse, System.SysUtils, Dataset.serialize, System.Classes, System.NetEncoding, Soap.EncdDecd; function save(communitJson: string ): TFDQuery; function update(id: integer; communitJson: string ): TFDQuery; function delete(id: integer ): boolean; function findAll(page: integer; limit: integer; findName:string; findValue: string; var tot_page: integer): TFDQuery; overload; function findAll(): TFDQuery; overload; function findAll(findName:string; findValue: string): TFDQuery; overload; function findByPK(id: integer): TFDQuery; implementation function save(communitJson: string ): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Community = DMConnection.Comunidades; var jsonObj := TJSONObject .ParseJSONValue(TEncoding.UTF8.GetBytes(communitJson), 0) as TJSONObject; Community.New(jsonObj).OpenUp; Result := Community; end; function findAll(findName:string; findValue: string): TFDQuery; overload; begin DMConnection := TDMConnection.Create(DMConnection); const Community = DMConnection.Comunidades; Community .where(findName).Equals(findValue) .Order(Community.FieldByName('nome_comunidade')) .OpenUp; Result := Community; end; function findAll(): TFDQuery; overload; begin DMConnection := TDMConnection.Create(DMConnection); const Community = DMConnection.Comunidades; Community .Order(Community.FieldByName('nome_comunidade')) .OpenUp; Result := Community; end; function update(id: integer; communitJson: string ): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Community = DMConnection.Comunidades; var jsonObj := TJSONObject .ParseJSONValue(TEncoding.UTF8.GetBytes(communitJson), 0) as TJSONObject; Community.where('id').Equals(id).OpenUp; Community.MergeFromJSONObject(jsonObj); Result := Community; end; function delete(id: integer ): boolean; begin DMConnection := TDMConnection.Create(DMConnection); const Community = DMConnection.comunidades; try Community.Remove(Community.FieldByName('id'), id).OpenUp; result:= true; except on E:Exception do result:= false; end; end; function findAll(page: integer; limit: integer; findName:string; findValue: string; var tot_page: integer): TFDQuery; overload; begin DMConnection := TDMConnection.Create(DMConnection); const Community = DMConnection.Comunidades_Regiao; Community.Close; Community.SQL.Clear; Community.SQL.Add('select '); Community.SQL.Add('c.*,'); Community.SQL.Add('r.nome_regiao'); Community.SQL.Add('from '); Community.SQL.Add('comunidades c inner join'); Community.SQL.Add('regioes_atendimento r on'); Community.SQL.Add('r.id = c.id_regiao'); var filtered := false; var tot := false; if ((findName <> '') and (findValue <> '')) then begin Community.SQL.Add(' where '); Community.SQL.Add( findName +' like ' + QuotedStr('%' + findValue + '%')); Community.Open; filtered := true; tot := Trunc((Community.RowsAffected/limit)) < (Community.RowsAffected/limit); if tot then tot_page := Trunc(Community.RowsAffected/limit) + 1 else tot_page := Trunc(Community.RowsAffected/limit); Community.close; end; if not filtered then begin tot := Trunc((Community.OpenUp.RowsAffected/limit)) < (Community.OpenUp.RowsAffected/limit); if tot then tot_page := Trunc(Community.OpenUp.RowsAffected/limit) + 1 else tot_page := Trunc(Community.OpenUp.RowsAffected/limit); end; var initial := page - 1; initial := initial * limit; Community.SQL.Add('ORDER BY '); Community.SQL.Add('c.id OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY;'); Community.ParamByName('offset').AsInteger := initial; Community.ParamByName('limit').AsInteger := limit; Community.Open; Result := Community; end; function findByPK(id: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Community = DMConnection.Comunidades; Community.where('id').equals(id).openUp; result := Community; end; end.
{ THIS UNIT IS TO BE THE SINGLETON TO WHICH THE TITLE OF THIS PROJECT REFERS. I CALL IT SERVICES, BECAUSE THE MOST COMMON USAGE FOR A SINGLETON FOR MYSELF IS TO HAVE A CENTRALIZED SERVICES SINGLETON THAT THE APPLICATION TALKS TO TO RESOLVE THINGS LIKE CONTAINER, LOGGER, ETC. } unit Services; interface uses Windows //Critical Section ; type TServices = class private fSingletonResource : string; function GetSingletonResource: string; procedure SetSingletonResource(const Value: string); //protected public property SingletonResource: string read GetSingletonResource write SetSingletonResource; class function Ton() : TServices; //published end; implementation var //CRITICAL SECTION TO BE USED TO GAIN ACCESS TO SINGLETON //THIS IS FASTER THAN A MUTEX, BUT A MUTEX WOULD BE NECESSARY IF WE WERE //NEEDING ACCESS ACROSS MULTIPLE PROCESSES _CriticalSectionSingleton : TRTLCriticalSection; //CRITICAL SECTION TO BE USED TO GAIN ACCESS TO A SPECIFIC RESOURCE //IN THE SINGLETON. EACH RESOURCE WOULD HAVE ITS OWN CRITICAL SECTION _CriticalSectionResource : TRTLCriticalSection; //ACTUAL INSTANCE OF SERVICES SINGLETON _Instance : TServices; { TServices } function TServices.GetSingletonResource: string; begin Result := ''; try EnterCriticalSection(_CriticalSectionResource); Result := fSingletonResource; finally LeaveCriticalSection(_CriticalSectionResource); end; end; procedure TServices.SetSingletonResource(const Value: string); begin try EnterCriticalSection(_CriticalSectionResource); fSingletonResource := Value; finally LeaveCriticalSection(_CriticalSectionResource); end; end; {$REGION 'Singleton.Ton'} class function TServices.Ton: TServices; begin Result := nil; EnterCriticalSection(_CriticalSectionSingleton); try if _Instance = nil then begin _Instance := TServices.Create(); end; Result := _Instance; finally LeaveCriticalSection(_CriticalSectionSingleton); end; Result := _Instance; end; {$ENDREGION} initialization InitializeCriticalSection(_CriticalSectionSingleton); InitializeCriticalSection(_CriticalSectionResource); finalization DeleteCriticalSection(_CriticalSectionSingleton); DeleteCriticalSection(_CriticalSectionResource); end.
unit UFilter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, ExtCtrls, StdCtrls, Graphics, UMetaData; type TEvent = Procedure of Object; { TFilterPanel } TFilterPanel = class(TPanel) NameComboBox: TComboBox; SignComboBox: TComboBox; CancelButton: TButton; DeleteButton: TButton; ExecuteButton: TButton; ValueEdit: TEdit; procedure CreateFilter(ATag, ANum: Integer; AParent: TScrollBox); function CreateComboBox(ALeft: Integer): TCombobox; function CreateEdit: TEdit; function CreateButton(ALeft: Integer; ACaption: String): TButton; procedure ExecuteFilter(Sender: TObject); procedure ChangeValue(Sender: TObject); procedure CancelFilter(Sender: TObject); public AQueryEvent: TEvent; end; { TFilterListBox } TFilterListBox = class(TScrollBox) procedure AddFilterButtonClick(Sender: TObject); procedure CancelFiltersButtonClick(Sender: TObject); procedure DeleteFilter(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DeleteFiltersButtonClick(Sender: TObject); procedure ExecuteFiltersButtonClick(Sender: TObject); public FilterPanels: array of TFilterPanel; QueryEvent: TEvent; end; const NumberOfSigns = 6; const indent = 37; implementation { TFilterListBox } procedure TFilterListBox.DeleteFiltersButtonClick(Sender: TObject); var i: Integer; begin for i := 0 to High(FilterPanels) do DeleteFilter((FilterPanels[0].DeleteButton as TObject), mbLeft, [], 0, 0); SetLength(FilterPanels, 0); end; procedure TFilterListBox.ExecuteFiltersButtonClick(Sender: TObject); var i: Integer; begin for i := 0 to High(FilterPanels) do FilterPanels[i].ExecuteFilter(Sender);; end; procedure TFilterListBox.AddFilterButtonClick(Sender: TObject); var i: Integer; begin SetLength(FilterPanels, Length(FilterPanels) + 1); FilterPanels[High(FilterPanels)] := TFilterPanel.Create(Self); With FilterPanels[High(FilterPanels)] do begin CreateFilter(Self.Tag, High(FilterPanels), Self); DeleteButton.OnMouseUp := @DeleteFilter; AQueryEvent := QueryEvent; end; end; procedure TFilterListBox.CancelFiltersButtonClick(Sender: TObject); var i: Integer; begin for i := 0 to High(FilterPanels) do FilterPanels[i].CancelFilter(Sender); end; procedure TFilterListBox.DeleteFilter(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var ATag, i: Integer; begin ATag := (Sender as TButton).Parent.Tag; With FilterPanels[ATag] do CancelFilter(Sender); FreeAndNil(FilterPanels[ATag]); for i := ATag to High(FilterPanels) - 1 do begin FilterPanels[i] := FilterPanels[i + 1]; With FilterPanels[i] do begin Top := Top - indent; Tag := Tag - 1; end; end; SetLength(FilterPanels, Length(FilterPanels) - 1); end; { TFilterPanel } procedure TFilterPanel.CreateFilter(ATag, ANum: Integer; AParent: TScrollBox); var i: Integer; Signs: array[0..NumberOfSigns] of string = ('<', '>', '=', '<=', '>=', 'Начинается с', 'Включает'); begin Visible := True; Height := 32; Width := 592; Top := 5 + indent * ANum; Left := 10; Tag := ANum; Parent := AParent; Color := clRed; NameComboBox := CreateComboBox(6); With NameComboBox, Tables.TablesInf[ATag] do begin for i := 0 to High(Columns) do if (Columns[i].Visible) or (Columns[i].ReferenceColumnCaption <> '') then if Columns[i].ReferenceColumnCaption <> '' then Items.Add(Columns[i].ReferenceColumnCaption) else Items.Add(Columns[i].Caption); ItemIndex := 0; end; SignComboBox := CreateComboBox(120); With SignComboBox do begin for i := 0 to NumberOfSigns do Items.Add(Signs[i]); ItemIndex := 0; end; ValueEdit := CreateEdit; ExecuteButton := CreateButton(352, 'Применить'); ExecuteButton.OnClick := @ExecuteFilter; CancelButton := CreateButton(432, 'Отменить'); CancelButton.OnClick := @CancelFilter; DeleteButton := CreateButton(512, 'Удалить'); end; procedure TFilterPanel.CancelFilter(Sender: TObject); begin Color := clRed; ExecuteButton.Enabled := True; AQueryEvent; end; procedure TFilterPanel.ChangeValue(Sender: TObject); begin Color := clRed; ExecuteButton.Enabled := True; end; procedure TFilterPanel.ExecuteFilter(Sender: TObject); begin ExecuteButton.Enabled := False; AQueryEvent; Color := clGreen; end; function TFilterPanel.CreateComboBox(ALeft: Integer): TCombobox; begin Result := TComboBox.Create(Self); With Result do begin Visible := True; Left := ALeft; Top := 6; Width := 113; Height := 23; ReadOnly := True; Style := csDropDownList; Parent := Self; OnChange := @ChangeValue; end; end; function TFilterPanel.CreateEdit: TEdit; begin Result := TEdit.Create(Self); With Result do begin Visible := True; Left := 240; Top := 6; Width := 103; Height := 23; Parent := Self; OnChange := @ChangeValue; end; end; function TFilterPanel.CreateButton(ALeft: Integer; ACaption: String): TButton; begin Result := TButton.Create(Self); With Result do begin Visible := True; Left := ALeft; Top := 6; Width := 75; Height := 25; Caption := ACaption; Parent := Self; end; end; end.
unit MeshCurvatureMeasure; interface uses BasicMathsTypes, NeighborDetector; const CMCM_CONVEX = 0; CMCM_CONCAVE = 1; CMCM_SADDLE = 2; CMCM_PART_OF_EDGE = 3; CMCM_PART_OF_FACE = 4; type TMeshCurvatureMeasure = class public // Get a curvature measure. function GetVertexCurvatureAngle(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): single; function GetVertexCurvatureLength(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): single; function GetVertexAngleSum(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): single; function GetVertexAngleSumFactor(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): single; overload; function GetVertexAngleSumFactor(_Factor: single): single; overload; // Just check if it is convex, concave or something else. function GetVertexClassification(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): integer; function IsVertexConvex(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): boolean; function IsVertexConcave(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): boolean; function IsVertexUseful(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): boolean; end; implementation uses Math3d, Math, BasicFunctions; function TMeshCurvatureMeasure.GetVertexCurvatureAngle(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): single; const C_DEFAULT = 999999; var v : integer; Direction: TVector3f; DotResult: single; begin Result := C_DEFAULT; v := _NeighborDetector.GetNeighborFromID(_ID); while v <> -1 do begin Direction := SubtractVector(_Vertices[v],_Vertices[_ID]); Normalize(Direction); DotResult := DotProduct(_VertexNormals[_ID],Direction); if DotResult <> 0 then begin if Abs(DotResult) < Result then begin if (Result <> C_DEFAULT) and ((Result * DotResult) > 0) then begin Result := DotResult; end else if (Result <> C_DEFAULT) then begin Result := 0; exit; end else begin Result := DotResult; end; end; end else if DotResult = 0 then begin Result := 0; exit; end; v := _NeighborDetector.GetNextNeighbor; end; if Result = C_DEFAULT then Result := 0; end; function TMeshCurvatureMeasure.GetVertexCurvatureLength(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): single; const C_DEFAULT = 999999; var v : integer; Direction: TVector3f; DotResult,PreviousDotResult,Length: single; begin PreviousDotResult := C_DEFAULT; Result := C_DEFAULT; v := _NeighborDetector.GetNeighborFromID(_ID); while v <> -1 do begin Direction := SubtractVector(_Vertices[v],_Vertices[_ID]); Length := GetVectorLength(Direction); Normalize(Direction); DotResult := DotProduct(_VertexNormals[_ID],Direction); if DotResult <> 0 then begin Length := Length * DotResult; if Abs(Length) < Abs(Result) then begin if (PreviousDotResult <> C_DEFAULT) and ((PreviousDotResult * DotResult) > 0) then begin PreviousDotResult := DotResult; Result := Length; end else if (PreviousDotResult <> C_DEFAULT) then begin Result := 0; exit; end else begin PreviousDotResult := DotResult; Result := Length; end; end; end else if DotResult = 0 then begin Result := 0; exit; end; v := _NeighborDetector.GetNextNeighbor; end; if Result = C_DEFAULT then Result := 0; end; // Requires star ordered C_NEIGHBTYPE_VERTEX_VERTEX _NeighborDetector. function TMeshCurvatureMeasure.GetVertexAngleSum(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): single; const C_DEFAULT = 999999; var v,vNext,firstV : integer; Direction,DirectionNext: TVector3f; DotResult: single; begin Result := 0; v := _NeighborDetector.GetNeighborFromID(_ID); if v <> -1 then begin vNext := _NeighborDetector.GetNextNeighbor; firstV := v; while vNext <> -1 do begin Direction := SubtractVector(_Vertices[v],_Vertices[_ID]); Normalize(Direction); DirectionNext := SubtractVector(_Vertices[vNext],_Vertices[_ID]); Normalize(DirectionNext); DotResult := DotProduct(Direction,DirectionNext); Result := Result + arccos(DotResult); v := vNext; vNext := _NeighborDetector.GetNextNeighbor; end; if v <> firstV then begin Direction := SubtractVector(_Vertices[firstV],_Vertices[_ID]); Normalize(Direction); DotResult := DotProduct(Direction,DirectionNext); Result := Result + arccos(DotResult); end; end; end; function TMeshCurvatureMeasure.GetVertexAngleSumFactor(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): single; const C_2PI = 2 * pi; begin Result := epsilon((GetVertexAngleSum(_ID, _Vertices, _VertexNormals, _NeighborDetector) / C_2PI) - 1) + 1; end; function TMeshCurvatureMeasure.GetVertexAngleSumFactor(_Factor: single): single; const C_2PI = 2 * pi; begin Result := epsilon((_Factor / C_2PI) - 1) + 1; end; function TMeshCurvatureMeasure.GetVertexClassification(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): integer; var v,zeroCounter : integer; Direction: TVector3f; DotResult: single; begin Result := -1; zeroCounter := 0; v := _NeighborDetector.GetNeighborFromID(_ID); while v <> -1 do begin Direction := SubtractVector(_Vertices[v],_Vertices[_ID]); Normalize(Direction); DotResult := DotProduct(_VertexNormals[_ID],Direction); if DotResult > 0 then begin if Result = -1 then begin Result := CMCM_CONCAVE; // Pretend that it is concave. end else if Result = CMCM_CONVEX then begin Result := CMCM_SADDLE; // Pretend that it is a saddle point. end; end else if DotResult = 0 then begin if zeroCounter > 1 then begin Result := CMCM_PART_OF_FACE; exit; end else begin Result := CMCM_PART_OF_EDGE; // Pretend that it is part of an edge. inc(zeroCounter); end; end else begin if Result = -1 then begin Result := CMCM_CONVEX; // Pretend that it is convex. end else if Result = CMCM_CONCAVE then begin Result := CMCM_SADDLE; // Pretend that it is a saddle point. end; end; v := _NeighborDetector.GetNextNeighbor; end; end; // New Discrete 'Laplacian' Operator (not really laplacian) function TMeshCurvatureMeasure.IsVertexConvex(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): boolean; var v : integer; Direction: TVector3f; DotResult: single; begin v := _NeighborDetector.GetNeighborFromID(_ID); while v <> -1 do begin Direction := SubtractVector(_Vertices[v],_Vertices[_ID]); Normalize(Direction); DotResult := DotProduct(_VertexNormals[_ID],Direction); if DotResult <= 0 then begin Result := false; // it is concave. exit; end; v := _NeighborDetector.GetNextNeighbor; end; Result := true; // if all angles are smaller than 90', it's convex. end; function TMeshCurvatureMeasure.IsVertexConcave(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): boolean; var v : integer; Direction: TVector3f; DotResult: single; begin v := _NeighborDetector.GetNeighborFromID(_ID); while v <> -1 do begin Direction := SubtractVector(_Vertices[v],_Vertices[_ID]); Normalize(Direction); DotResult := DotProduct(_VertexNormals[_ID],Direction); if DotResult >= 0 then begin Result := false; // it is convex. exit; end; v := _NeighborDetector.GetNextNeighbor; end; Result := true; // if all angles are higher than 90', it's concave. end; function TMeshCurvatureMeasure.IsVertexUseful(_ID: integer; const _Vertices, _VertexNormals: TAVector3f; const _NeighborDetector : TNeighborDetector): boolean; var v : integer; Direction: TVector3f; DotResult: single; begin v := _NeighborDetector.GetNeighborFromID(_ID); while v <> -1 do begin Direction := SubtractVector(_Vertices[v],_Vertices[_ID]); Normalize(Direction); DotResult := DotProduct(_VertexNormals[_ID],Direction); if DotResult = 0 then begin Result := false; // it is either part of an edge or face. Not useful. exit; end; v := _NeighborDetector.GetNextNeighbor; end; Result := true; end; end.
unit IntegerList; interface uses CustomList; type // Custom list of integers TIntegerList = class(TBaseList) private function Get(Index: Integer): Integer; public procedure Add(item : Integer); overload; procedure Add(index: Integer; item : Integer); overload; //function Get(Index: Integer): Variant; function First : Integer; function Last : Integer; property Items[Index: Integer]: Integer read Get; default; end; implementation uses Variants, SysUtils; { TIntegerList } procedure TIntegerList.Add(item: Integer); begin inherited Add(item); end; procedure TIntegerList.Add(index, item: Integer); begin inherited Add(index, item); end; function TIntegerList.First: Integer; var variantValue : Variant; begin variantValue := inherited First; if variantValue = Null then begin raise Exception.Create('Invalid index'); Exit; end; Result := Integer(variantValue); end; function TIntegerList.Get(Index: Integer): Integer; var variantValue : Variant; begin variantValue := inherited Get(index); if variantValue = Null then begin raise Exception.Create('Invalid index'); Exit; end; Result := Integer(variantValue); end; function TIntegerList.Last: Integer; var variantValue : Variant; begin variantValue := inherited Last; if variantValue = Null then begin raise Exception.Create('Invalid index'); Exit; end; Result := Integer(variantValue); end; end.
unit Progress; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TProgressDlg = class(TForm) lblFileName: TLabel; txtFileName: TLabel; lblCount: TLabel; txtCount: TLabel; btnCancel: TButton; aniFindFile: TAnimate; procedure FormShow(Sender: TObject); procedure btnCancelClick(Sender: TObject); private { Private 宣言 } FAll, FCount: Integer; FStop: Boolean; public { Public 宣言 } procedure InitCount; procedure SetFileName(Name: String); procedure AddCount; property Stop: Boolean read FStop; end; var ProgressDlg: TProgressDlg; implementation {$R *.dfm} uses FileCtrl, ShellApi, StrUtils, Utils; procedure TProgressDlg.InitCount; begin FAll := 0; FCount := 0; FStop := False; end; procedure TProgressDlg.SetFileName(Name: String); begin FAll := FAll + 1; txtFileName.Caption := MinimizeName(Name, txtFileName.Canvas, txtFileName.Width); txtCount.Caption := Format('%d/%d', [FCount, FAll]); Refresh; end; procedure TProgressDlg.AddCount; begin FCount := FCount + 1; txtCount.Caption := Format('%d/%d', [FCount, FAll]); txtCount.Refresh; end; procedure TProgressDlg.FormShow(Sender: TObject); begin ShowWindow(Application.Handle, SW_HIDE); { タスクバーにアイコンを表示させない } end; procedure TProgressDlg.btnCancelClick(Sender: TObject); begin FStop := True; end; end.
namespace proholz.xsdparser; interface type XsdElementVisitor = public class(XsdAnnotatedElementsVisitor) private // * // * The {@link XsdElement} instance which owns this {@link XsdElementVisitor} instance. This way this visitor instance // * can perform changes in the {@link XsdElement} object. // // var owner: XsdElement; public constructor(aowner: XsdElement); method visit(element: XsdComplexType); override; method visit(element: XsdSimpleType); override; end; implementation constructor XsdElementVisitor(aowner: XsdElement); begin inherited constructor(aowner); self.owner := aowner; end; method XsdElementVisitor.visit(element: XsdComplexType); begin inherited visit(element); owner.setComplexType(ReferenceBase.createFromXsd(element)); end; method XsdElementVisitor.visit(element: XsdSimpleType); begin inherited visit(element); owner.setSimpleType(ReferenceBase.createFromXsd(element)); end; end.
unit DSA.Sorts.BubbleSort; interface uses System.SysUtils, DSA.Interfaces.Comparer, DSA.Utils; type TBubbleSort<T> = class private type TArr_T = TArray<T>; ICmp_T = IComparer<T>; public class procedure Sort(var arr: TArr_T; cmp: ICmp_T); end; procedure Main; implementation uses DSA.Sorts.InsertionSort, DSA.Sorts.SelectionSort; type TSelectionSort_int = TSelectionSort<integer>; TInsertionSort_int = TInsertionSort<integer>; TBubbleSort_int = TBubbleSort<integer>; procedure Main; var sourceArr, targetArr: TArray_int; n: integer; selectionSort_int: TSelectionSort_int; InsertionSort_int: TInsertionSort_int; BubbleSort_int: TBubbleSort_int; begin n := 20000; with TSortTestHelper_int.Create do begin sourceArr := GenerateNearlyOrderedArray(n, 1000); BubbleSort_int := TBubbleSort_int.Create; targetArr := CopyArray(sourceArr); TestSort('BubbleSort'#9#9, targetArr, BubbleSort_int.Sort); BubbleSort_int.Free; selectionSort_int := TSelectionSort_int.Create; targetArr := CopyArray(sourceArr); TestSort('SelectionSort'#9#9, targetArr, selectionSort_int.Sort); selectionSort_int.Free; InsertionSort_int := TInsertionSort_int.Create; targetArr := CopyArray(sourceArr); TestSort('InsertionSort'#9#9, targetArr, InsertionSort_int.Sort); targetArr := CopyArray(sourceArr); TestSort('InsertionSort_Adv'#9, targetArr, InsertionSort_int.Sort_Adv); InsertionSort_int.Free; end; end; { TBubbleSort<T> } class procedure TBubbleSort<T>.Sort(var arr: TArr_T; cmp: ICmp_T); var temp: T; unSorted: boolean; n: integer; i: integer; j: integer; bool: integer; begin unSorted := True; n := Length(arr); j := 1; while unSorted do begin unSorted := False; Inc(j); for i := 0 to n - j do begin bool := cmp.Compare(arr[i], arr[i + 1]); if bool > 0 then begin temp := arr[i]; arr[i] := arr[i + 1]; arr[i + 1] := temp; unSorted := True; end; end; end; end; end.
unit profile; interface uses Classes, timez; type TProfile = class public constructor Create(wMin: word; wMax: word); procedure AddValue(wCanal: word; eValue: extended; ti: times); function GetResult(sName: string): TStringList; private wItemMin: word; wItemMax: word; end; implementation uses SysUtils, Math, support, realz; const ITEMS = 512; type canal_t = record energy: array [0 .. ITEMS - 1] of extended; end; half_t = record value: canal_t; flag: boolean; nan: boolean; end; day_t = record halfs: array [0 .. 47] of half_t; value: canal_t; flag: boolean; nan: boolean; end; month_t = record days: array [1 .. 31] of day_t; value: canal_t; flag: boolean; nan: boolean; end; var year: array [1 .. 12] of month_t; constructor TProfile.Create(wMin: word; wMax: word); var c: word; d, h, m: byte; begin wItemMin := wMin; wItemMax := wMax; for c := 0 to ITEMS - 1 do begin for m := 1 to 12 do begin year[m].flag := false; year[m].nan := false; year[m].value.energy[c] := 0; for d := 1 to 31 do begin year[m].days[d].flag := false; year[m].days[d].nan := false; year[m].days[d].value.energy[c] := 0; for h := 0 to 47 do begin year[m].days[d].halfs[h].flag := false; year[m].days[d].halfs[h].nan := false; year[m].days[d].halfs[h].value.energy[c] := 0; end; end; end; end; end; procedure TProfile.AddValue(wCanal: word; eValue: extended; ti: times); var d, h, m: byte; nan: boolean; begin h := ti.bHour * 2 + ti.bMinute div 30; d := ti.bDay; m := ti.bMonth; if IsNaN(eValue) then begin nan := true; eValue := 0; end else nan := false; year[m].flag := true; year[m].nan := year[m].nan or nan; year[m].value.energy[wCanal] := year[m].value.energy[wCanal] + eValue; year[m].days[d].flag := true; year[m].days[d].nan := year[m].days[d].nan or nan; year[m].days[d].value.energy[wCanal] := year[m].days[d].value.energy[wCanal] + eValue; year[m].days[d].halfs[h].flag := true; year[m].days[d].halfs[h].nan := year[m].days[d].halfs[h].nan or nan; year[m].days[d].halfs[h].value.energy[wCanal] := year[m].days[d].halfs[h].value.energy[wCanal] + eValue; end; function TProfile.GetResult(sName: string): TStringList; var c: word; d, h, m: byte; s, z: string; begin Result := TStringList.Create; Result.Add(''); for m := 1 to 12 do begin for d := 1 to 31 do begin if year[m].days[d].flag then begin Result.Add(''); s := PackStrR('', GetColWidth); for c := wItemMin to wItemMax do s := s + PackStrR(sName + IntToStr(c), GetColWidth); Result.Add(s); s := PackLine(GetColWidth); for c := wItemMin to wItemMax do s := s + PackLine(GetColWidth); Result.Add(s); s := PackStrR('сутки ' + Int2Str(d, 2) + '.' + Int2Str(m, 2), GetColWidth); Result.Add(s); for h := 0 to 47 do begin s := PackStrR(Int2Str(h div 2, 2) + '.' + Int2Str((h mod 2) * 30, 2), GetColWidth); if (year[m].days[d].halfs[h].flag) then for c := wItemMin to wItemMax do begin if year[m].days[d].halfs[h].nan then z := PackStrR('?', GetColWidth) else z := Float2StrR(year[m].days[d].halfs[h].value.energy[c]); s := s + z; end; Result.Add(s); end; end; end; end; Result.Add(''); for m := 1 to 12 do begin if year[m].flag then Result.Add(PackStrR('месяц ' + IntToStr(m), GetColWidth)); for d := 1 to 31 do begin if year[m].days[d].flag then begin s := PackStrR('сутки ' + Int2Str(d, 2) + '.' + Int2Str(m, 2), GetColWidth); for c := wItemMin to wItemMax do begin if year[m].days[d].nan then z := ' ?' else z := ''; s := s + PackStrR(Float2Str(year[m].days[d].value.energy[c]) + z, GetColWidth); end; Result.Add(s); end; end; end; Result.Add(''); for m := 1 to 12 do begin if year[m].flag then begin s := PackStrR('месяц ' + IntToStr(m), GetColWidth); for c := wItemMin to wItemMax do begin if year[m].nan then z := ' ?' else z := ''; s := s + PackStrR(Float2Str(year[m].value.energy[c]) + z, GetColWidth); end; Result.Add(s); end; end; end; end.
unit Antlr.Runtime.Tests; interface uses Classes, SysUtils, TestFramework, Antlr.Runtime; type // Test methods for class IANTLRStringStream TestANTLRStringStream = class(TTestCase) strict private const NL = #13#10; GRAMMARSTR = '' + 'parser grammar p;' + NL + 'prog : WHILE ID LCURLY (assign)* RCURLY EOF;' + NL + 'assign : ID ASSIGN expr SEMI ;' + NL + 'expr : INT | FLOAT | ID ;' + NL; public procedure SetUp; override; procedure TearDown; override; published procedure TestSizeOnEmptyANTLRStringStream; procedure TestSizeOnANTLRStringStream; procedure TestConsumeOnANTLRStringStream; procedure TestResetOnANTLRStringStream; procedure TestSubstringOnANTLRStringStream; end; implementation { TestANTLRStringStream } procedure TestANTLRStringStream.SetUp; begin end; procedure TestANTLRStringStream.TearDown; begin end; procedure TestANTLRStringStream.TestConsumeOnANTLRStringStream; var Stream: IANTLRStringStream; begin Stream := TANTLRStringStream.Create('One'#13#10'Two'); CheckEquals(0, Stream.Index); CheckEquals(0, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // O CheckEquals(1, Stream.Index); CheckEquals(1, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // n CheckEquals(2, Stream.Index); CheckEquals(2, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // e CheckEquals(3, Stream.Index); CheckEquals(3, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // #13 CheckEquals(4, Stream.Index); CheckEquals(4, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // #10 CheckEquals(5, Stream.Index); CheckEquals(0, Stream.CharPositionInLine); CheckEquals(2, Stream.Line); Stream.Consume; // T CheckEquals(6, Stream.Index); CheckEquals(1, Stream.CharPositionInLine); CheckEquals(2, Stream.Line); Stream.Consume; // w CheckEquals(7, Stream.Index); CheckEquals(2, Stream.CharPositionInLine); CheckEquals(2, Stream.Line); Stream.Consume; // o CheckEquals(8, Stream.Index); CheckEquals(3, Stream.CharPositionInLine); CheckEquals(2, Stream.Line); Stream.Consume; // EOF CheckEquals(8, Stream.Index); CheckEquals(3, Stream.CharPositionInLine); CheckEquals(2, Stream.Line); Stream.Consume; // EOF CheckEquals(8, Stream.Index); CheckEquals(3, Stream.CharPositionInLine); CheckEquals(2, Stream.Line); end; procedure TestANTLRStringStream.TestResetOnANTLRStringStream; var Stream: IANTLRStringStream; begin Stream := TANTLRStringStream.Create('One'#13#10'Two'); CheckEquals(0, Stream.Index); CheckEquals(0, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // O Stream.Consume; // n CheckEquals(Ord('e'), Stream.LA(1)); CheckEquals(2, Stream.Index); Stream.Reset; CheckEquals(Ord('O'), Stream.LA(1)); CheckEquals(0, Stream.Index); CheckEquals(0, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // O CheckEquals(Ord('n'), Stream.LA(1)); CheckEquals(1, Stream.Index); CheckEquals(1, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // n CheckEquals(Ord('e'), Stream.LA(1)); CheckEquals(2, Stream.Index); CheckEquals(2, Stream.CharPositionInLine); CheckEquals(1, Stream.Line); Stream.Consume; // n end; procedure TestANTLRStringStream.TestSizeOnANTLRStringStream; var S1, S2, S3: IANTLRStringStream; begin S1 := TANTLRStringStream.Create('lexer'#13#10); CheckEquals(7, S1.Size); S2 := TANTLRStringStream.Create(GRAMMARSTR); CheckEquals(Length(GRAMMARSTR), S2.Size); S3 := TANTLRStringStream.Create('grammar P;'); CheckEquals(10, S3.Size); end; procedure TestANTLRStringStream.TestSizeOnEmptyANTLRStringStream; var S1: IANTLRStringStream; begin S1 := TANTLRStringStream.Create(''); CheckEquals(0, S1.Size); CheckEquals(0, S1.Index); end; procedure TestANTLRStringStream.TestSubstringOnANTLRStringStream; var Stream: IANTLRStringStream; begin Stream := TANTLRStringStream.Create('One'#13#10'Two'#13#10'Three'); CheckEquals('Two', Stream.Substring(5, 7)); CheckEquals('One', Stream.Substring(0, 2)); CheckEquals('Three', Stream.Substring(10, 14)); Stream.Consume; CheckEquals('Two', Stream.Substring(5, 7)); CheckEquals('One', Stream.Substring(0, 2)); CheckEquals('Three', Stream.Substring(10, 14)); end; initialization // Register any test cases with the test runner RegisterTest(TestANTLRStringStream.Suite); end.
unit uDemoForm; interface {$R uDemoForm.res} {$MESSAGE 'TODO - Constraints'} uses Windows, Types, apiGUI, apiObjects, apiWrappersGUI, apiMenu; const NullRect: TRect = (Left: 0; Top: 0; Right: 0; Bottom: 0); type { TDemoForm } TDemoForm = class(TInterfacedObject, IAIMPUIChangeEvents, IAIMPUIKeyboardEvents, IAIMPUIMouseEvents, IAIMPUIMouseWheelEvents, IAIMPUIPageControlEvents, IAIMPUIFormEvents) private FSkipMouseEvents: Boolean; // Custom Handlers procedure HandlerAddCustom(const Sender: IUnknown); procedure HandlerAddFiles(const Sender: IUnknown); procedure HandlerAddFolders(const Sender: IUnknown); procedure HandlerCloseButton(const Sender: IUnknown); procedure HandlerCustomDrawSlider(const Sender: IUnknown; DC: HDC; const R: TRect); procedure HandlerEditButton(const Sender: IUnknown); procedure HandlerSkipMouseEvents(const Sender: IUnknown); // IAIMPUIChangeEvents procedure OnChanged(Sender: IInterface); stdcall; // IAIMPUIKeyboardEvents procedure OnEnter(Sender: IInterface); stdcall; procedure OnExit(Sender: IInterface); stdcall; procedure OnKeyDown(Sender: IInterface; var Key: Word; Modifiers: Word); stdcall; procedure OnKeyPress(Sender: IInterface; var Key: Char); stdcall; procedure OnKeyUp(Sender: IInterface; var Key: Word; Modifiers: Word); stdcall; // IAIMPUIMouseEvents procedure OnMouseDoubleClick(Sender: IInterface; Button: TAIMPUIMouseButton; X, Y: Integer; Modifiers: Word); stdcall; procedure OnMouseDown(Sender: IInterface; Button: TAIMPUIMouseButton; X, Y: Integer; Modifiers: Word); stdcall; procedure OnMouseMove(Sender: IInterface; X, Y: Integer; Modifiers: Word); stdcall; procedure OnMouseUp(Sender: IInterface; Button: TAIMPUIMouseButton; X, Y: Integer; Modifiers: Word); stdcall; procedure OnMouseLeave(Sender: IInterface); stdcall; // IAIMPUIMouseWheelEvents function OnMouseWheel(Sender: IInterface; WheelDelta: Integer; X, Y: Integer; Modifiers: Word): LongBool; stdcall; // IAIMPUIPageControlEvents procedure OnActivated(Sender: IAIMPUIPageControl; Page: IAIMPUITabSheet); overload; stdcall; procedure OnActivating(Sender: IAIMPUIPageControl; Page: IAIMPUITabSheet; var Allow: LongBool); stdcall; // IAIMPUIFormEvents procedure OnActivated(Sender: IAIMPUIForm); overload; stdcall; procedure OnCloseQuery(Sender: IAIMPUIForm; var CanClose: LongBool); stdcall; procedure OnCreated(Sender: IAIMPUIForm); stdcall; procedure OnDeactivated(Sender: IAIMPUIForm); stdcall; procedure OnDestroyed(Sender: IAIMPUIForm); stdcall; procedure OnLocalize(Sender: IAIMPUIForm); stdcall; procedure OnShortCut(Sender: IAIMPUIForm; Key: Word; Modifiers: Word; var Handled: LongBool); stdcall; protected FForm: IAIMPUIForm; FImages: IAIMPUIImageList; FLog: IAIMPUITreeList; FService: IAIMPServiceUI; FTreeList: IAIMPUITreeList; procedure AddPathToTreeList(const Name, ParentFolder, Notes: string; AImageIndex: Integer); procedure Log(const Sender: IUnknown; const S: string); protected procedure CreateBottomBar(AParent: IAIMPUIWinControl); procedure CreateControls(AParent: IAIMPUIWinControl); procedure CreateLog(AParent: IAIMPUIWinControl); procedure CreatePageControl(AParent: IAIMPUIWinControl); procedure CreateBBCBox(AParent: IAIMPUIWinControl); procedure CreateEditors(AParent: IAIMPUIWinControl); procedure CreateGraphics(AParent: IAIMPUIWinControl); procedure CreateGroups(AParent: IAIMPUIWinControl); procedure CreateIndicators(AParent: IAIMPUIWinControl); procedure CreateTreeList(AParent: IAIMPUIWinControl); public constructor Create(AService: IAIMPServiceUI); function ShowModal: Integer; end; implementation uses apiWrappers, SysUtils; const ButtonNames: array[TAIMPUIMouseButton] of string = ('LMB', 'RMB', 'MMB'); function CenterRect(const ABounds: TRect; AWidth, AHeight: Integer): TRect; begin Result.Left := (ABounds.Left + ABounds.Right - AWidth) div 2; Result.Top := (ABounds.Top + ABounds.Bottom - AHeight) div 2; Result.Right := Result.Left + AWidth; Result.Bottom := Result.Top + AHeight; end; { TDemoForm } constructor TDemoForm.Create(AService: IAIMPServiceUI); var ABounds: TRect; begin FService := AService; FSkipMouseEvents := True; CheckResult(AService.CreateForm(0, 0, MakeString('DemoForm'), Self, FForm)); CheckResult(FForm.SetValueAsInt32(AIMPUI_FORM_PROPID_CLOSEBYESCAPE, 1)); // Center the Form on screen SystemParametersInfo(SPI_GETWORKAREA, 0, ABounds, 0); CheckResult(FForm.SetPlacement(TAIMPUIControlPlacement.Create(CenterRect(ABounds, 1024, 600)))); // Create ImageList for children controls CheckResult(AService.CreateObject(FForm, nil, IAIMPUIImageList, FImages)); CheckResult(FImages.LoadFromResource(HInstance, 'IMAGES', 'PNG')); // Create children controls CreateControls(FForm); end; procedure TDemoForm.CreateControls(AParent: IAIMPUIWinControl); begin CreateBottomBar(AParent); CreateLog(AParent); CreatePageControl(AParent); end; procedure TDemoForm.CreateBottomBar(AParent: IAIMPUIWinControl); var AButton: IAIMPUIButton; APanel: IAIMPUIWinControl; begin // Create the panel for Bar CheckResult(FService.CreateControl(FForm, AParent, nil, nil, IID_IAIMPUIPanel, APanel)); CheckResult(APanel.SetPlacement(TAIMPUIControlPlacement.Create(ualBottom, Bounds(0, MaxWord, 0, 28)))); CheckResult(APanel.SetValueAsInt32(AIMPUI_PANEL_PROPID_BORDERS, 0)); // Create the Button CheckResult(FService.CreateControl(FForm, APanel, MakeString('B1'), TAIMPUINotifyEventAdapter.Create(HandlerCloseButton), IID_IAIMPUIButton, AButton)); CheckResult(AButton.SetPlacement(TAIMPUIControlPlacement.Create(ualRight, 0))); CheckResult(AButton.SetPlacementConstraints(TAIMPUIControlPlacementConstraints.Create(100, 25, 100, 25))); end; procedure TDemoForm.CreateLog(AParent: IAIMPUIWinControl); var AColumn: IAIMPUITreeListColumn; AControl: IAIMPUIControl; APanel: IAIMPUIWinControl; begin CheckResult(FService.CreateControl(FForm, AParent, nil, nil, IID_IAIMPUIPanel, APanel)); CheckResult(APanel.SetPlacement(TAIMPUIControlPlacement.Create(ualLeft, 400, Rect(6, 6, 0, 0)))); CheckResult(APanel.SetValueAsInt32(AIMPUI_PANEL_PROPID_BORDERS, 0)); // The Treelist control will be used for loging all events CheckResult(FService.CreateControl(FForm, APanel, MakeString('Log'), Self, IAIMPUITreeList, FLog)); CheckResult(FLog.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, 0, NullRect))); CheckResult(FLog.SetValueAsInt32(AIMPUI_TL_PROPID_COLUMN_AUTOWIDTH, 1)); CheckResult(FLog.AddColumn(IAIMPUITreeListColumn, AColumn)); // Create the Sender column CheckResult(AColumn.SetValueAsInt32(AIMPUI_TL_COLUMN_PROPID_CAN_RESIZE, 0)); CheckResult(FLog.AddColumn(IAIMPUITreeListColumn, AColumn)); // Create the Action column // Create the SkipMouseEvents option CheckResult(FService.CreateControl(FForm, APanel, MakeString('cbSkipMouseEvents'), TAIMPUINotifyEventAdapter.Create(HandlerSkipMouseEvents), IAIMPUICheckBox, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualBottom, 0, Rect(0, 6, 0, 0)))); CheckResult(AControl.SetValueAsInt32(AIMPUI_CHECKBOX_PROPID_STATE, Ord(FSkipMouseEvents))); // Create the splitter CheckResult(FService.CreateControl(FForm, AParent, nil, Self, IAIMPUISplitter, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualLeft, 3, NullRect))); CheckResult(AControl.SetValueAsObject(AIMPUI_SPLITTER_PROPID_CONTROL, APanel)); end; procedure TDemoForm.CreatePageControl(AParent: IAIMPUIWinControl); var APageControl: IAIMPUIPageControl; ATabSheet: IAIMPUITabSheet; begin // Create the PageControl CheckResult(FService.CreateControl(FForm, AParent, MakeString('PageControl'), Self, IAIMPUIPageControl, APageControl)); CheckResult(APageControl.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, 0, Rect(6, 6, 6, 0)))); // Create the TabSheet with editors CheckResult(APageControl.Add(MakeString('tsEditors'), ATabSheet)); CreateEditors(ATabSheet); // Create the TabSheet with groups CheckResult(APageControl.Add(MakeString('tsGroups'), ATabSheet)); CreateGroups(ATabSheet); // Create the TabSheet with graphic objects CheckResult(APageControl.Add(MakeString('tsGraphics'), ATabSheet)); CreateGraphics(ATabSheet); // Create the TabSheet with sliders and progress bars CheckResult(APageControl.Add(MakeString('tsIndicators'), ATabSheet)); CreateIndicators(ATabSheet); // Create the TabSheet with BBCode Box CheckResult(APageControl.Add(MakeString('tsBBC'), ATabSheet)); CreateBBCBox(ATabSheet); // Create the TabSheet with TreeList CheckResult(APageControl.Add(MakeString('tsTreeList'), ATabSheet)); CreateTreeList(ATabSheet); end; procedure TDemoForm.CreateBBCBox(AParent: IAIMPUIWinControl); const BBCText = 'Today, on the 9th birthday of AIMP project, we are pleased ' + 'to announce the launch of a public beta testing of two major ' + 'version of our products - [url=http://www.aimp.ru/index.php?do=features]AIMP v4[/url] and ' + '[url=http://www.aimp.ru/index.php?do=features&os=android]AIMP for Android v2[/url]' + #13#10 + #13#10 + '[b]Warning![/b]' + #13#10 + 'Note that both version are [u]test[/u], they [u]may contains a lot of bugs[/u]!'; var AControl: IAIMPUIWinControl; begin CheckResult(FService.CreateControl(FForm, AParent, MakeString('bbcBox'), Self, IAIMPUIBBCBox, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, 0))); CheckResult(AControl.SetValueAsObject(AIMPUI_BBCBOX_PROPID_TEXT, MakeString(BBCText))); CheckResult(AControl.SetValueAsInt32(AIMPUI_BBCBOX_PROPID_TRANSPARENT, 1)); CheckResult(AControl.SetValueAsInt32(AIMPUI_BBCBOX_PROPID_BORDERS, 0)); end; procedure TDemoForm.CreateEditors(AParent: IAIMPUIWinControl); var AComboBox: IAIMPUIBaseComboBox; AControl: IAIMPUIWinControl; AEdit: IAIMPUIEdit; AEditButton: IAIMPUIEditButton; ALeftSidePane: IAIMPUIWinControl; I: Integer; begin CheckResult(FService.CreateControl(FForm, AParent, MakeString('pnlLeftSide'), Self, IAIMPUIPanel, ALeftSidePane)); CheckResult(ALeftSidePane.SetPlacement(TAIMPUIControlPlacement.Create(ualLeft, 300, NullRect))); CheckResult(ALeftSidePane.SetValueAsInt32(AIMPUI_PANEL_PROPID_TRANSPARENT, 1)); CheckResult(ALeftSidePane.SetValueAsInt32(AIMPUI_PANEL_PROPID_BORDERS, 0)); // Create the ButtonedEdit CheckResult(FService.CreateControl(FForm, ALeftSidePane, MakeString('edText'), Self, IAIMPUIEdit, AEdit)); CheckResult(AEdit.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(AEdit.SetValueAsObject(AIMPUI_BUTTONEDEDIT_PROPID_BUTTONSIMAGES, FImages)); CheckResult(AEdit.AddButton(TAIMPUINotifyEventAdapter.Create(HandlerEditButton), AEditButton)); CheckResult(AEditButton.SetValueAsInt32(AIMPUI_EDITBUTTON_PROPID_WIDTH, 50)); CheckResult(AEdit.AddButton(TAIMPUINotifyEventAdapter.Create(HandlerEditButton), AEditButton)); CheckResult(AEditButton.SetValueAsInt32(AIMPUI_EDITBUTTON_PROPID_IMAGEINDEX, 6)); // Create ComboBox CheckResult(FService.CreateControl(FForm, ALeftSidePane, MakeString('cbbSimple'), Self, IAIMPUIComboBox, AComboBox)); CheckResult(AComboBox.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(AComboBox.SetValueAsInt32(AIMPUI_COMBOBOX_PROPID_STYLE, 1)); for I := 0 to 2 do CheckResult(AComboBox.Add(nil, 0)); // Create CheckComboBox CheckResult(FService.CreateControl(FForm, ALeftSidePane, MakeString('ccbCheck'), Self, IAIMPUICheckComboBox, AComboBox)); CheckResult(AComboBox.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); for I := 0 to 2 do CheckResult(AComboBox.Add(MakeString('Check' + IntToStr(I + 1)), Ord(I = 1))); // 2nd item will be checked // Create ImageComboBox CheckResult(FService.CreateControl(FForm, ALeftSidePane, MakeString('icbImages'), Self, IAIMPUIImageComboBox, AComboBox)); CheckResult(AComboBox.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(AComboBox.SetValueAsObject(AIMPUI_IMAGECOMBOBOX_PROPID_IMAGELIST, FImages)); for I := 0 to 5 do CheckResult(AComboBox.Add(MakeString('Image ' + IntToStr(I + 1)), I)); // Create SpinEdit CheckResult(FService.CreateControl(FForm, ALeftSidePane, MakeString('seSpin'), Self, IAIMPUISpinEdit, AControl)); CheckResult(AControl.SetValueAsObject(AIMPUI_SPINEDIT_PROPID_DISPLAYMASK, MakeString('Delta: %s px'))); CheckResult(AControl.SetValueAsInt32(AIMPUI_SPINEDIT_PROPID_INCREMENT, 2)); CheckResult(AControl.SetValueAsInt32(AIMPUI_SPINEDIT_PROPID_MAXVALUE, 6)); CheckResult(AControl.SetValueAsInt32(AIMPUI_SPINEDIT_PROPID_MINVALUE, -2)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualBottom, 0))); // Create TimeEdit CheckResult(FService.CreateControl(FForm, ALeftSidePane, MakeString('teTime'), Self, IAIMPUITimeEdit, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualBottom, 0))); // Create Memo CheckResult(FService.CreateControl(FForm, AParent, MakeString('edMemo'), Self, IAIMPUIMemo, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, 0))); end; procedure TDemoForm.CreateGraphics(AParent: IAIMPUIWinControl); function CreateLabel(const AName: UnicodeString; AParent: IAIMPUIWinControl): IAIMPUIControl; begin CheckResult(FService.CreateControl(FForm, AParent, MakeString(AName), Self, IAIMPUILabel, Result)); CheckResult(Result.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(Result.SetValueAsInt32(AIMPUI_LABEL_PROPID_AUTOSIZE, 1)); end; function CreateImage(const ResName: UnicodeString; AParent: IAIMPUIWinControl; AAlignment: TAIMPUIControlAlignment): IAIMPUIControl; var AImage: IAIMPImage2; AImageSize: TSize; begin CoreCreateObject(IAIMPImage2, AImage); AImage.LoadFromFile(MakeString('B:\asdadasdas')); CheckResult(AImage.LoadFromResource(HInstance, PWideChar(ResName), 'PNG')); CheckResult(AImage.GetSize(AImageSize)); CheckResult(FService.CreateControl(FForm, AParent, nil, Self, IAIMPUIImage, Result)); CheckResult(Result.SetPlacement(TAIMPUIControlPlacement.Create(AAlignment, Bounds(0, 0, AImageSize.cx, AImageSize.cy)))); CheckResult(Result.SetValueAsObject(AIMPUI_IMAGE_PROPID_IMAGE, AImage)); end; var AControl: IAIMPUIControl; AContainer: IAIMPUIWinControl; begin // Create the description label CheckResult(CreateLabel('lbDescription', AParent).SetValueAsInt32(AIMPUI_LABEL_PROPID_LINE, 1)); // Create the ScrollBox with large image CheckResult(FService.CreateControl(FForm, AParent, nil, Self, IAIMPUIScrollBox, AContainer)); CheckResult(AContainer.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, 0))); CreateImage('PREVIEW', AContainer, ualNone); // Create the left side panel CheckResult(FService.CreateControl(FForm, AParent, nil, Self, IAIMPUIPanel, AContainer)); CheckResult(AContainer.SetPlacement(TAIMPUIControlPlacement.Create(ualLeft, 150, NullRect))); CheckResult(AContainer.SetValueAsInt32(AIMPUI_PANEL_PROPID_TRANSPARENT, 1)); CheckResult(AContainer.SetValueAsInt32(AIMPUI_PANEL_PROPID_BORDERS, 0)); // Create the image AControl := CreateImage('LOGO', AContainer, ualTop); CheckResult(AControl.SetValueAsInt32(AIMPUI_IMAGE_PROPID_IMAGESTRETCHMODE, AIMP_IMAGE_DRAW_STRETCHMODE_FIT)); // Create labels AControl := CreateLabel('lbRAT', AContainer); CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTALIGN, 1)); // Right CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTCOLOR, $FF0000)); //Blue CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTSTYLE, AIMPUI_FLAGS_FONT_STRIKEOUT)); AControl := CreateLabel('lbCT', AContainer); CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTALIGN, 2)); // Center CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTCOLOR, $00AA00)); // Green CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTSTYLE, AIMPUI_FLAGS_FONT_BOLD)); AControl := CreateLabel('lbLAT', AContainer); CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTCOLOR, $0000FF)); // Red CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTSTYLE, AIMPUI_FLAGS_FONT_ITALIC)); AControl := CreateLabel('lbWEB', AContainer); CheckResult(AControl.SetValueAsInt32(AIMPUI_LABEL_PROPID_TEXTALIGN, 2)); // Center CheckResult(AControl.SetValueAsObject(AIMPUI_LABEL_PROPID_URL, MakeString('http://aimp.ru'))); //Blue // Create the separator line CheckResult(FService.CreateControl(FForm, AContainer, nil, Self, IAIMPUIBevel, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 2))); CheckResult(AControl.SetValueAsInt32(AIMPUI_BEVEL_PROPID_BORDERS, AIMPUI_FLAGS_BORDER_TOP)); end; procedure TDemoForm.CreateGroups(AParent: IAIMPUIWinControl); var AChildControl: IAIMPUIWinControl; AControl: IAIMPUIWinControl; begin // Create the Category CheckResult(FService.CreateControl(FForm, AParent, MakeString('catMain'), Self, IID_IAIMPUICategory, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, 0))); AParent := AControl; // It will be a parent for all other groups // Create the GroupBox CheckResult(FService.CreateControl(FForm, AParent, MakeString('gbSimple'), Self, IID_IAIMPUIGroupBox, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 200))); CheckResult(AControl.SetValueAsInt32(AIMPUI_GROUPBOX_PROPID_AUTOSIZE, 1)); // Create the CheckBoxes and place them at GroupBox CheckResult(FService.CreateControl(FForm, AControl, MakeString('cbItem1'), Self, IID_IAIMPUICheckBox, AChildControl)); CheckResult(AChildControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(FService.CreateControl(FForm, AControl, MakeString('cbItem2'), Self, IID_IAIMPUICheckBox, AChildControl)); CheckResult(AChildControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); // Create the Validation Label CheckResult(FService.CreateControl(FForm, AControl, MakeString('vlWarning'), Self, IID_IAIMPUIValidationLabel, AChildControl)); CheckResult(AChildControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(AChildControl.SetValueAsInt32(AIMPUI_VALIDATIONLABEL_PROPID_GLYPH, 0)); // Create the GroupBox with check mark CheckResult(FService.CreateControl(FForm, AParent, MakeString('gbChecked'), Self, IID_IAIMPUIGroupBox, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 200))); CheckResult(AControl.SetValueAsInt32(AIMPUI_GROUPBOX_PROPID_AUTOSIZE, 1)); CheckResult(AControl.SetValueAsInt32(AIMPUI_GROUPBOX_PROPID_CHECKMODE, 2)); // Create the RadioBoxes and place them at GroupBox CheckResult(FService.CreateControl(FForm, AControl, MakeString('rbItem1'), Self, IID_IAIMPUIRadioBox, AChildControl)); CheckResult(AChildControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(FService.CreateControl(FForm, AControl, MakeString('rbItem2'), Self, IID_IAIMPUIRadioBox, AChildControl)); CheckResult(AChildControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); // Create the Validation Label CheckResult(FService.CreateControl(FForm, AControl, MakeString('vlWarning2'), Self, IID_IAIMPUIValidationLabel, AChildControl)); CheckResult(AChildControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(AChildControl.SetValueAsInt32(AIMPUI_VALIDATIONLABEL_PROPID_GLYPH, 2)); end; procedure TDemoForm.CreateIndicators(AParent: IAIMPUIWinControl); var AControl: IAIMPUIWinControl; begin CheckResult(FService.CreateControl(FForm, AParent, MakeString('pbProgress'), Self, IAIMPUIProgressBar, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(AControl.SetValueAsInt32(AIMPUI_PROGRESSBAR_PROPID_MAX, 100)); CheckResult(AControl.SetValueAsInt32(AIMPUI_PROGRESSBAR_PROPID_MIN, 10)); CheckResult(AControl.SetValueAsInt32(AIMPUI_PROGRESSBAR_PROPID_PROGRESS, 50)); CheckResult(FService.CreateControl(FForm, AParent, MakeString('pbIndeterminate'), Self, IAIMPUIProgressBar, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 0))); CheckResult(AControl.SetValueAsInt32(AIMPUI_PROGRESSBAR_PROPID_INDETERMINATE, 1)); CheckResult(FService.CreateControl(FForm, AParent, MakeString('slSlider'), Self, IAIMPUISlider, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 30))); CheckResult(AControl.SetValueAsInt32(AIMPUI_SLIDER_PROPID_HORIZONTAL, 1)); CheckResult(AControl.SetValueAsInt32(AIMPUI_SLIDER_PROPID_PAGESIZE, 10)); CheckResult(AControl.SetValueAsInt32(AIMPUI_SLIDER_PROPID_TRANSPARENT, 1)); CheckResult(FService.CreateControl(FForm, AParent, MakeString('slCustomDrawSlider'), TAIMPUIDrawEventAdapter.Create(HandlerCustomDrawSlider, Self), IAIMPUISlider, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualLeft, 30, Rect(30, 30, 30, 30)))); CheckResult(AControl.SetValueAsInt32(AIMPUI_SLIDER_PROPID_PAGESIZE, 10)); CheckResult(AControl.SetValueAsInt32(AIMPUI_SLIDER_PROPID_TRANSPARENT, 1)); end; procedure TDemoForm.CreateTreeList(AParent: IAIMPUIWinControl); procedure AddMenuItem(ADropDownMenu: IAIMPUIPopupMenu; const ID: string; EventHandler: TAIMPUINotifyEvent; Default: Boolean = False); var AMenuItem: IAIMPUIMenuItem; begin CheckResult(ADropDownMenu.Add(MakeString(ID), AMenuItem)); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT, TAIMPUINotifyEventAdapter.Create(EventHandler))); CheckResult(AMenuItem.SetValueAsInt32(AIMP_MENUITEM_PROPID_DEFAULT, Ord(Default))); end; var AColumn: IAIMPUITreeList; AControl: IAIMPUIWinControl; ADropDownMenu: IAIMPUIPopupMenu; begin // Create the TreeList CheckResult(FService.CreateControl(FForm, AParent, MakeString('tlPaths'), Self, IAIMPUITreeList, FTreeList)); CheckResult(FTreeList.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, 0))); CheckResult(FTreeList.SetValueAsInt32(AIMPUI_TL_PROPID_CHECKBOXES, 1)); CheckResult(FTreeList.SetValueAsObject(AIMPUI_TL_PROPID_NODE_IMAGES, FImages)); CheckResult(FTreeList.AddColumn(IAIMPUITreeListColumn, AColumn)); CheckResult(FTreeList.AddColumn(IAIMPUITreeListColumn, AColumn)); CheckResult(AColumn.SetValueAsInt32(AIMPUI_TL_COLUMN_PROPID_WIDTH, 300)); CheckResult(FTreeList.AddColumn(IAIMPUITreeListColumn, AColumn)); CheckResult(AColumn.SetValueAsInt32(AIMPUI_TL_COLUMN_PROPID_WIDTH, 300)); // Create panel for buttons CheckResult(FService.CreateControl(FForm, AParent, MakeString('pnlTreeListButtonsBar'), Self, IAIMPUIPanel, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualBottom, 31, NullRect))); CheckResult(AControl.SetValueAsInt32(AIMPUI_PANEL_PROPID_TRANSPARENT, 1)); CheckResult(AControl.SetValueAsInt32(AIMPUI_PANEL_PROPID_BORDERS, 0)); AParent := AControl; // Create the drop down menu CheckResult(FService.CreateObject(FForm, nil, IAIMPUIPopupMenu, ADropDownMenu)); AddMenuItem(ADropDownMenu, 'ru.aimp.guidemo.addcustom', HandlerAddCustom, True); AddMenuItem(ADropDownMenu, 'ru.aimp.guidemo.addfolders', HandlerAddFolders); AddMenuItem(ADropDownMenu, 'ru.aimp.guidemo.addfiles', HandlerAddFiles); // Create button with drop down menu CheckResult(FService.CreateControl(FForm, AParent, MakeString('btnAdd'), TAIMPUINotifyEventAdapter.Create(HandlerAddCustom, Self), IAIMPUIButton, AControl)); CheckResult(AControl.SetPlacement(TAIMPUIControlPlacement.Create(ualLeft, 96))); CheckResult(AControl.SetValueAsInt32(AIMPUI_BUTTON_PROPID_STYLE, AIMPUI_FLAGS_BUTTON_STYLE_DROPDOWNBUTTON)); CheckResult(AControl.SetValueAsObject(AIMPUI_BUTTON_PROPID_DROPDOWNMENU, ADropDownMenu)); end; procedure TDemoForm.AddPathToTreeList(const Name, ParentFolder, Notes: string; AImageIndex: Integer); var ANode: IAIMPUITreeListNode; ARootNode: IAIMPUITreeListNode; begin // Query RootNode CheckResult(FTreeList.GetRootNode(IID_IAIMPUITreeListNode, ARootNode)); // Add entry CheckResult(ARootNode.Add(ANode)); CheckResult(ANode.SetValueAsInt32(AIMPUI_TL_NODE_PROPID_IMAGEINDEX, AImageIndex)); CheckResult(ANode.SetValue(0, MakeString(Name))); CheckResult(ANode.SetValue(1, MakeString(ParentFolder))); CheckResult(ANode.SetValue(2, MakeString(Notes))); end; procedure TDemoForm.Log(const Sender: IUnknown; const S: string); var AIntf: IAIMPUIControl; AName: IAIMPString; ANode: IAIMPUITreeListNode; ARootNode: IAIMPUITreeListNode; begin AName := nil; if Supports(Sender, IAIMPUIControl, AIntf) then CheckResult(AIntf.GetValueAsObject(AIMPUI_CONTROL_PROPID_NAME, IID_IAIMPString, AName)); // Query RootNode CheckResult(FLog.GetRootNode(IID_IAIMPUITreeListNode, ARootNode)); // Add entry to log CheckResult(ARootNode.Add(ANode)); CheckResult(ANode.SetValue(0, AName)); CheckResult(ANode.SetValue(1, MakeString(S))); // Focus the entry CheckResult(FLog.SetFocused(ANode)); end; procedure TDemoForm.HandlerAddCustom(const Sender: IInterface); var ADialog: IAIMPUIInputDialog; ATextForValues: IAIMPObjectList; AValues: array [0..2] of OleVariant; begin CoreCreateObject(IAIMPObjectList, ATextForValues); CheckResult(ATextForValues.Add(LangLoadStringEx('InputBox\L1'))); CheckResult(ATextForValues.Add(LangLoadStringEx('InputBox\L2'))); CheckResult(ATextForValues.Add(LangLoadStringEx('InputBox\L3'))); CheckResult(FService.QueryInterface(IAIMPUIInputDialog, ADialog)); if Succeeded(ADialog.Execute2(FForm.GetHandle, LangLoadStringEx('InputBox\Caption'), nil, ATextForValues, @AValues[0], Length(AValues))) then AddPathToTreeList(AValues[0], AValues[1], AValues[2], 9); end; procedure TDemoForm.HandlerAddFiles(const Sender: IInterface); var ADialog: IAIMPUIFileDialogs; APath: string; APathInf: IAIMPString; ASelection: IAIMPObjectList; I: Integer; begin CheckResult(FService.QueryInterface(IAIMPUIFileDialogs, ADialog)); if Succeeded(ADialog.ExecuteOpenDialog2(FForm.GetHandle, nil, MakeString('All Files|*.*'), ASelection)) then begin for I := 0 to ASelection.GetCount - 1 do if Succeeded(ASelection.GetObject(I, IAIMPString, APathInf)) then begin APath := IAIMPStringToString(APathInf); AddPathToTreeList(ExtractFileName(APath), ExtractFilePath(APath), 'Just a file', 7); end; end; end; procedure TDemoForm.HandlerAddFolders(const Sender: IInterface); var ADialog: IAIMPUIBrowseFolderDialog; APath: string; APathInf: IAIMPString; ASelection: IAIMPObjectList; I: Integer; begin CheckResult(FService.QueryInterface(IAIMPUIBrowseFolderDialog, ADialog)); if Succeeded(ADialog.Execute(FForm.GetHandle, AIMPUI_FLAGS_BROWSEFOLDER_MULTISELECT, nil, ASelection)) then begin for I := 0 to ASelection.GetCount - 1 do if Succeeded(ASelection.GetObject(I, IAIMPString, APathInf)) then begin APath := IAIMPStringToString(APathInf); AddPathToTreeList(ExtractFileName(ExtractFileDir(APath)), ExtractFilePath(ExtractFileDir(APath)), 'Just a folder', 8); end; end; end; procedure TDemoForm.HandlerCloseButton(const Sender: IUnknown); begin FForm.Close; end; procedure TDemoForm.HandlerCustomDrawSlider(const Sender: IInterface; DC: HDC; const R: TRect); var ABrush: HBRUSH; AValue: Integer; begin // Get value and convert it to Byte range CheckResult((Sender as IAIMPUISlider).GetValueAsInt32(AIMPUI_SLIDER_PROPID_VALUE, AValue)); AValue := MulDiv(MaxByte, AValue, 100); // Fill the background ABrush := CreateSolidBrush(RGB(MaxByte - AValue, AValue, 0)); FillRect(DC, R, ABrush); DeleteObject(ABrush); // Draw the rectanble for track bar FrameRect(DC, R, GetStockObject(BLACK_BRUSH)); end; procedure TDemoForm.HandlerEditButton(const Sender: IInterface); var ADialog: IAIMPUIMessageDialog; AIndex: Integer; begin CheckResult((Sender as IAIMPUIEditButton).GetValueAsInt32(AIMPUI_EDITBUTTON_PROPID_INDEX, AIndex)); CheckResult(FService.QueryInterface(IAIMPUIMessageDialog, ADialog)); CheckResult(ADialog.Execute(FForm.GetHandle, MakeString(''), MakeString(Format('EditButton%d clicked!', [AIndex])), MB_ICONINFORMATION)); end; procedure TDemoForm.HandlerSkipMouseEvents(const Sender: IInterface); var AState: Integer; begin CheckResult((Sender as IAIMPUICheckBox).GetValueAsInt32(AIMPUI_CHECKBOX_PROPID_STATE, AState)); FSkipMouseEvents := AState = 1; end; procedure TDemoForm.OnChanged(Sender: IInterface); begin Log(Sender, 'Changed'); end; procedure TDemoForm.OnEnter(Sender: IInterface); begin Log(Sender, 'OnEnter'); end; procedure TDemoForm.OnExit(Sender: IInterface); begin Log(Sender, 'OnExit'); end; procedure TDemoForm.OnKeyDown(Sender: IInterface; var Key: Word; Modifiers: Word); begin Log(Sender, Format('OnKeyDown(%d, %d)', [Key, Modifiers])); end; procedure TDemoForm.OnKeyPress(Sender: IInterface; var Key: Char); begin Log(Sender, Format('OnKeyPress(%s)', [Key])); end; procedure TDemoForm.OnKeyUp(Sender: IInterface; var Key: Word; Modifiers: Word); begin Log(Sender, Format('OnKeyUp(%d, %d)', [Key, Modifiers])); end; procedure TDemoForm.OnMouseDoubleClick(Sender: IInterface; Button: TAIMPUIMouseButton; X, Y: Integer; Modifiers: Word); begin if not FSkipMouseEvents then Log(Sender, Format('Double click via %s at %d,%d (Mods: %d)', [ButtonNames[Button], X, Y, Modifiers])); end; procedure TDemoForm.OnMouseDown(Sender: IInterface; Button: TAIMPUIMouseButton; X, Y: Integer; Modifiers: Word); begin if not FSkipMouseEvents then Log(Sender, Format('Mouse down via %s at %d,%d (Mods: %d)', [ButtonNames[Button], X, Y, Modifiers])); end; procedure TDemoForm.OnMouseLeave(Sender: IInterface); begin // do nothing end; procedure TDemoForm.OnMouseMove(Sender: IInterface; X, Y: Integer; Modifiers: Word); begin if not FSkipMouseEvents then Log(Sender, Format('Mouse move at %d,%d (Mods: %d)', [X, Y, Modifiers])); end; procedure TDemoForm.OnMouseUp(Sender: IInterface; Button: TAIMPUIMouseButton; X, Y: Integer; Modifiers: Word); begin if not FSkipMouseEvents then Log(Sender, Format('Mouse up via %s at %d,%d (Mods: %d)', [ButtonNames[Button], X, Y, Modifiers])); end; function TDemoForm.OnMouseWheel(Sender: IInterface; WheelDelta, X, Y: Integer; Modifiers: Word): LongBool; begin if not FSkipMouseEvents then Log(Sender, Format('Mouse Wheel at %d,%d (Mods: %d, Delta: %d)', [X, Y, Modifiers, WheelDelta])); Result := False; // not handled, we just log the event end; procedure TDemoForm.OnShortCut(Sender: IAIMPUIForm; Key, Modifiers: Word; var Handled: LongBool); begin // do nothing end; function TDemoForm.ShowModal: Integer; begin Result := FForm.ShowModal; end; procedure TDemoForm.OnActivated(Sender: IAIMPUIPageControl; Page: IAIMPUITabSheet); begin Log(Sender, PropListGetStr(Page, AIMPUI_TABSHEET_PROPID_CAPTION) + ' was activated'); end; procedure TDemoForm.OnActivating(Sender: IAIMPUIPageControl; Page: IAIMPUITabSheet; var Allow: LongBool); begin Log(Sender, PropListGetStr(Page, AIMPUI_TABSHEET_PROPID_CAPTION) + ' is activating'); end; procedure TDemoForm.OnActivated(Sender: IAIMPUIForm); begin Log(Sender, 'OnActivated'); end; procedure TDemoForm.OnCloseQuery(Sender: IAIMPUIForm; var CanClose: LongBool); var ADialog: IAIMPUIMessageDialog; begin CheckResult(FService.QueryInterface(IAIMPUIMessageDialog, ADialog)); CanClose := ADialog.Execute(FForm.GetHandle, LangLoadStringEx('GUIDemo.MSG\1'), LangLoadStringEx('GUIDemo.MSG\2'), MB_ICONQUESTION or MB_OKCANCEL or MB_DEFBUTTON2) = ID_OK; end; procedure TDemoForm.OnCreated(Sender: IAIMPUIForm); begin // do nothing end; procedure TDemoForm.OnDeactivated(Sender: IAIMPUIForm); begin Log(Sender, 'OnDeactivated'); end; procedure TDemoForm.OnDestroyed(Sender: IAIMPUIForm); begin // Release all variables FLog := nil; FTreeList := nil; FImages := nil; FForm := nil; end; procedure TDemoForm.OnLocalize(Sender: IAIMPUIForm); begin Log(Sender, 'OnLocalize'); end; end.
{ ******************************************************* } { * {* uEpisode.pas {* Delphi Implementation of the Class Episode {* Generated by Enterprise Architect {* Created on: 09-févr.-2015 11:45:26 {* Original author: Labelleg OK {* {******************************************************* } unit xmltvdb.Episode; interface uses System.Generics.Collections, xmltvdb.TVDBSeries, xmltvdb.TVDBEpisode, xmltvdb.DateUtils; type IEpisode = interface ['{C857D0E2-372E-437A-8A9E-CE615E1FECE4}'] function addTVDBSeriesEpisodeNumbers(const seasonNumber: String; const episodeNumber: String): boolean; procedure clearRemoteIds; function getEpisode: Integer; function getLanguage: String; function getMultipartSeasonEpisodeNaming: String; function getOriginalAirDate: TDateTime; function GetOriginalStartAirDateTime: string; function getPaddedEpisodeNumber: String; function getPaddedSeasonNumber: String; // function getRemoteIds: TDictionary<String, String>; procedure getRemoteIds(out resultat: TDictionary<String, String>); function GetOriginalms_progid:string; function getSeason: Integer; function getSeries: ITVDBSeries; function getSeriesYear: String; function getTitle: String; function getTVDBId: String; function getXMLTVSeasonEpisodeAttribute: String; function hasEpisode: boolean; function hasOriginalAirDate: boolean; function hasRemoteId: boolean; function hasSeason: boolean; function hasSeries: boolean; function hasTitle: boolean; function hasTVDBid: boolean; function hasTVDBImage: boolean; function isMultiPart: boolean; procedure setEpisode(const e: Integer); procedure setHasTVDBImage(const hasTVDBImage: boolean); procedure setIMDBId(const imdbId: String); procedure setLanguage(const langCode: String); function setMatchingEpisodes(const episodes: TVDBEpisodeColl): boolean; procedure setMultipart(const multipart: boolean); procedure setMultipartSeasonEpisodeNaming(const seasonEpisodeNaming: String); procedure setOriginalAirDate(const dt: TDateTime); procedure setOriginalStartAirDateTime(const dt: string); procedure setSeason(const s: Integer); procedure setSeries(const series: ITVDBSeries); procedure setTitle(const title: String); procedure setZap2ItId(const zap2ItId: String); procedure SetOriginalms_progid(const ms_progid:string); function toString: String; end; TEpisode = class(TInterfacedObject, IEpisode) private Fepisode: Integer; FhasTVDBImage: boolean; // remote id's we can use to look up series Fimdbid: String; Flanguage: String; // for multi-part episodes (meaning this episode represents more than 1 tvdb episode) FmultiPart: boolean; ForiginalAirDate: TDateTime; FOriginalStartAirDateTime: string; Fseason: Integer; Fseries: ITVDBSeries; Ftitle: String; // remote id's we can use to look up series Fzap2itid: String; FmultiPartseasonEpisodeNaming: String; Fms_progid: string; function padNumber(const num: Integer): String; public constructor Create(const series: ITVDBSeries); overload; destructor Destroy; override; function addTVDBSeriesEpisodeNumbers(const seasonNumber: String; const episodeNumber: String): boolean; procedure clearRemoteIds; function getEpisode: Integer; function getLanguage: String; function getMultipartSeasonEpisodeNaming: String; function getOriginalAirDate: TDateTime; function GetOriginalStartAirDateTime: string; function getPaddedEpisodeNumber: String; function getPaddedSeasonNumber: String; function GetOriginalms_progid:string; // function getRemoteIds: TDictionary<String, String>; procedure getRemoteIds(out resultat: TDictionary<String, String>); function getSeason: Integer; function getSeries: ITVDBSeries; function getSeriesYear: String; function getTitle: String; function getTVDBId: String; // three numbers separated by dots, the first is the series or season, the second // the episode number within that series, and the third the part number, if the // programme is part of a two-parter. All these numbers are indexed from zero, // and they can be given in the form 'X/Y' to show series X out of Y series made, // or episode X out of Y episodes in this series, or part X of a Y-part episode. // If any of these aren't known they can be omitted. You can put spaces whereever // you like to make things easier to read. function getXMLTVSeasonEpisodeAttribute: String; function hasEpisode: boolean; function hasOriginalAirDate: boolean; function hasRemoteId: boolean; function hasSeason: boolean; function hasSeries: boolean; function hasTitle: boolean; function hasTVDBid: boolean; function hasTVDBImage: boolean; function isMultiPart: boolean; procedure setEpisode(const e: Integer); procedure setHasTVDBImage(const hasTVDBImage: boolean); procedure setIMDBId(const imdbId: String); procedure setLanguage(const langCode: String); function setMatchingEpisodes(const episodes: TVDBEpisodeColl): boolean; procedure setMultipart(const multipart: boolean); procedure setMultipartSeasonEpisodeNaming(const seasonEpisodeNaming: String); procedure setOriginalAirDate(const dt: TDateTime); procedure setOriginalStartAirDateTime(const dt: string); procedure setSeason(const s: Integer); procedure setSeries(const series: ITVDBSeries); procedure setTitle(const title: String); procedure setZap2ItId(const zap2ItId: String); procedure SetOriginalms_progid(const ms_progid:string); function toString: String; reintroduce; // constructor Create; overload; end; implementation uses System.Math, REST.Utils, CodeSiteLogging, System.SysUtils, uConts, xmltvdb.tvdb ; { implementation of Episode } function TEpisode.addTVDBSeriesEpisodeNumbers(const seasonNumber, episodeNumber: String): boolean; var s: Integer; e: Integer; begin Result := False; if TryStrToInt(seasonNumber, s) then begin if TryStrToInt(episodeNumber, e) then begin setSeason(s); setEpisode(e); Result := True; end; end; if not Result then begin CodeSite.SendWarning('Could not parse season episode numbers: S' + seasonNumber + 'E' + episodeNumber); end; end; procedure TEpisode.clearRemoteIds; begin Self.Fzap2itid := ''; Self.Fimdbid := ''; end; constructor TEpisode.Create(const series: ITVDBSeries); begin inherited Create; Fseason := -1; Fepisode := -1; Self.ForiginalAirDate.SetToNull; Fseries := TTVDBSeries.Create(series.GetseriesId, series.GetseriesName, series.getSeriesYear); end; destructor TEpisode.Destroy; begin Fseries:=nil; inherited Destroy; end; function TEpisode.getEpisode: Integer; begin Result := Fepisode; end; function TEpisode.getLanguage: String; begin Result := iif(Flanguage <> '', Flanguage, 'en'); // default english end; function TEpisode.getMultipartSeasonEpisodeNaming: String; begin Result := FmultiPartseasonEpisodeNaming; end; function TEpisode.getOriginalAirDate: TDateTime; begin Result := ForiginalAirDate; end; function TEpisode.GetOriginalms_progid: string; begin Result := Fms_progid; end; function TEpisode.GetOriginalStartAirDateTime: string; begin Result := FOriginalStartAirDateTime; end; function TEpisode.getPaddedEpisodeNumber: String; begin Result := padNumber(getEpisode); end; function TEpisode.getPaddedSeasonNumber: String; begin Result := padNumber(getSeason); end; procedure TEpisode.getRemoteIds(out resultat: TDictionary<String, String>); // var // ids: TDictionary<String, String>; begin // GetSeriesByRemoteID.php?imdbid=<imdbid>&language=<language>&zap2it=<zap2it> // ids := TDictionary<String, String>.Create; // LinkedHashMap<String,String> ids = new LinkedHashMap<>(); if Fzap2itid <> '' then begin resultat.Add(ZAP2IT_IDENTIFIER, Fzap2itid); end; if (Fimdbid <> '') then begin resultat.Add(IMDB_IDENTIFIER, Fimdbid); end; // Result := ids; end; function TEpisode.getSeason: Integer; begin Result := Fseason; end; function TEpisode.getSeries: ITVDBSeries; begin Result := Self.Fseries; end; function TEpisode.getSeriesYear: String; begin Result := iif(hasSeries(), Fseries.getSeriesYear, ''); end; function TEpisode.getTitle: String; begin Result := Ftitle; end; function TEpisode.getTVDBId: String; begin Result := iif(getSeries = nil, '', getSeries().GetseriesId); end; function TEpisode.getXMLTVSeasonEpisodeAttribute: String; begin // zero indexed // int e = getEpisode()-1; // int s = getSeason()-1; // final String part = "0/0";//not used, but needed to keep FTR parser happy // return s+"."+e+"."+part; Result := Format('%d.%d.0/0', [getEpisode - 1, getSeason - 1]); end; function TEpisode.hasEpisode: boolean; begin Result := (Fepisode <> -1); end; function TEpisode.hasOriginalAirDate: boolean; begin Result := not ForiginalAirDate.IsNull; end; function TEpisode.hasRemoteId: boolean; begin Result := (Fzap2itid <> '') or (Fimdbid <> ''); end; function TEpisode.hasSeason: boolean; begin Result := (Fseason <> -1); end; function TEpisode.hasSeries: boolean; begin Result := (Fseries <> nil); end; function TEpisode.hasTitle: boolean; begin Result := (Ftitle <> ''); end; function TEpisode.hasTVDBid: boolean; begin Result := (getTVDBId <> '-1'); end; function TEpisode.hasTVDBImage: boolean; begin Result := FhasTVDBImage; end; function TEpisode.isMultiPart: boolean; begin Result := FmultiPart; end; function TEpisode.padNumber(const num: Integer): String; begin if (num < 10) then begin Result := '0' + num.toString; end else begin Result := '' + num.toString; end; end; procedure TEpisode.setEpisode(const e: Integer); begin Self.Fepisode := e; end; procedure TEpisode.setHasTVDBImage(const hasTVDBImage: boolean); begin Self.FhasTVDBImage := hasTVDBImage; end; procedure TEpisode.setIMDBId(const imdbId: String); begin Self.Fimdbid := imdbId; end; procedure TEpisode.setLanguage(const langCode: String); begin Self.Flanguage := langCode; end; function TEpisode.setMatchingEpisodes(const episodes: TVDBEpisodeColl): boolean; var // ep: ITVDBEpisode; seasonEpisodeNaming: string; lastSeason: Integer; firstEpisode: ITVDBEpisode; nextEpisode: ITVDBEpisode; begin // ep:= TTVDBEpisode.Create(); if (episodes.isEmpty()) then begin CodeSite.SendWarning('No episodes passed in to setMatchingEpisodes()'); Result := False; exit; end; if (episodes.count = 1) then begin setMultipart(False); Result := addTVDBSeriesEpisodeNumbers(episodes[0].GetseasonNumber, episodes[0].GetepisodeNumber); end else // multipart begin setMultipart(True); seasonEpisodeNaming := ''; lastSeason := -1; firstEpisode := nil; for nextEpisode in episodes do begin if (firstEpisode = nil) then begin firstEpisode := nextEpisode; end; // check the season/episode numbers for integrity if (not addTVDBSeriesEpisodeNumbers(nextEpisode.GetseasonNumber, nextEpisode.GetepisodeNumber)) then begin CodeSite.SendError('Found a multi-part match on thetvdb.com, ' + 'but the season and episode numbers are invalid (' + nextEpisode.GetseasonNumber + '\' + nextEpisode.GetepisodeNumber + '\). Skipping and trying again later.'); Result := False; exit; end; if (getSeason() <> lastSeason) then begin seasonEpisodeNaming := seasonEpisodeNaming + 'S' + getPaddedSeasonNumber(); end; // always continue to add episode numbers seasonEpisodeNaming := seasonEpisodeNaming + 'E' + getPaddedEpisodeNumber(); lastSeason := getSeason(); end; CodeSite.SendFmtMsg('Video''s multipart (%d-part) season episodes were determined to be: %s', [episodes.count, seasonEpisodeNaming]); // CodeSite.SendMsg( 'Video''s multipart ('+episodes.Count.ToString+'-part) season episodes were determined to be: ' + seasonEpisodeNaming); setMultipartSeasonEpisodeNaming(seasonEpisodeNaming); // use the first episode's season/episode as the 'default' if we need just a single-episode number addTVDBSeriesEpisodeNumbers(firstEpisode.GetseasonNumber, firstEpisode.GetepisodeNumber); Result := True; end; end; procedure TEpisode.setMultipart(const multipart: boolean); begin Self.FmultiPart := multipart; end; procedure TEpisode.setMultipartSeasonEpisodeNaming(const seasonEpisodeNaming: String); begin Self.FmultiPartseasonEpisodeNaming := seasonEpisodeNaming; end; procedure TEpisode.setOriginalAirDate(const dt: TDateTime); begin Self.ForiginalAirDate := dt; end; procedure TEpisode.SetOriginalms_progid(const ms_progid: string); begin Self.Fms_progid := ms_progid; end; procedure TEpisode.setOriginalStartAirDateTime(const dt: string); begin Self.FOriginalStartAirDateTime := dt; end; procedure TEpisode.setSeason(const s: Integer); begin Self.Fseason := s; end; procedure TEpisode.setSeries(const series: ITVDBSeries); begin Self.Fseries.Assign( series); end; procedure TEpisode.setTitle(const title: String); begin Self.Ftitle := title; end; procedure TEpisode.setZap2ItId(const zap2ItId: String); begin Self.Fzap2itid := zap2ItId; end; function TEpisode.toString: String; begin Result := getSeries().toString + ': S' + getPaddedSeasonNumber() + 'E' + getPaddedEpisodeNumber() + ' - ' + getTitle() + iif(hasOriginalAirDate(), ' (' + TTVGeneral.dateToTVDBString(getOriginalAirDate) + ')', ''); end; end.
unit UnitListarDispositivos; interface uses StrUtils,Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, ExtCtrls, UnitMain, UnitConexao, sSkinProvider; type TFormListarDispositivos = class(TForm) StatusBar1: TStatusBar; tvDevices: TTreeView; Splitter1: TSplitter; lvAdvancedInfo: TListView; ilDevices: TImageList; sSkinProvider1: TsSkinProvider; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure lvAdvancedInfoCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure tvDevicesCompare(Sender: TObject; Node1, Node2: TTreeNode; Data: Integer; var Compare: Integer); procedure tvDevicesChange(Sender: TObject; Node: TTreeNode); private { Private declarations } Servidor: TConexaoNew; NomePC: string; LiberarForm: boolean; procedure WMCloseFree(var Message: TMessage); message WM_CLOSEFREE; procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA; procedure AtualizarStrings; procedure ListarTodosDispositivos(Lista: string); procedure ListarDispositivosExtras(TempStr: string); procedure InitImageList; procedure ReleaseImageList; function GetDeviceImageIndex(DeviceGUID: TGUID): Integer; procedure CreateParams(var Params : TCreateParams); override; public { Public declarations } procedure OnRead(Recebido: String; ConAux: TConexaoNew); overload; constructor Create(aOwner: TComponent; ConAux: TConexaoNew);overload; end; var FormListarDispositivos: TFormListarDispositivos; implementation {$R *.dfm} uses UnitConstantes, ListarDispositivos, SetupAPI, UnitStrings, CustomIniFiles, UnitCommonProcedures; //Here's the implementation of CreateParams procedure TFormListarDispositivos.CreateParams(var Params : TCreateParams); begin inherited CreateParams(Params); //Don't ever forget to do this!!! if FormMain.ControlCenter = True then Exit; Params.WndParent := GetDesktopWindow; end; procedure TFormListarDispositivos.WMAtualizarIdioma(var Message: TMessage); begin AtualizarStrings; end; procedure TFormListarDispositivos.WMCloseFree(var Message: TMessage); begin LiberarForm := True; Close; end; constructor TFormListarDispositivos.Create(aOwner: TComponent; ConAux: TConexaoNew); var TempStr: WideString; IniFile: TIniFile; begin inherited Create(aOwner); Servidor := ConAux; NomePC := Servidor.NomeDoServidor; TempStr := ExtractFilePath(ParamStr(0)) + 'Settings\'; ForceDirectories(TempStr); TempStr := TempStr + NomePC + '.ini'; if FileExists(TempStr) = True then try IniFile := TIniFile.Create(TempStr, IniFilePassword); Width := IniFile.ReadInteger('Devices', 'Width', Width); Height := IniFile.ReadInteger('Devices', 'Height', Height); Left := IniFile.ReadInteger('Devices', 'Left', Left); Top := IniFile.ReadInteger('Devices', 'Top', Top); tvDevices.Width := IniFile.ReadInteger('Devices', 'TV1', tvDevices.Width); lvAdvancedInfo.Column[0].Width := IniFile.ReadInteger('Devices', 'LV1_0', lvAdvancedInfo.Column[0].Width); lvAdvancedInfo.Column[1].Width := IniFile.ReadInteger('Devices', 'LV1_1', lvAdvancedInfo.Column[1].Width); IniFile.Free; except DeleteFile(TempStr); end; end; procedure TFormListarDispositivos.OnRead(Recebido: String; ConAux: TConexaoNew); var DeviceClassesCount, DevicesCount: string; begin if copy(recebido, 1, posex('|', recebido) - 1) = LISTADEDISPOSITIVOSPRONTA then begin delete(recebido, 1, posex('|', recebido)); DeviceClassesCount := copy(recebido, 1, posex('|', recebido) - 1); delete(recebido, 1, posex('|', recebido)); DevicesCount := copy(recebido, 1, posex('|', recebido) - 1); delete(recebido, 1, posex('|', recebido)); ListarTodosDispositivos(recebido); StatusBar1.Panels.Items[0].Text := traduzidos[400] + ': ' + DeviceClassesCount; StatusBar1.Panels.Items[1].Text := traduzidos[401] + ': ' + DevicesCount; tvDevices.Enabled := true; end else if copy(recebido, 1, posex('|', recebido) - 1) = LISTADEDISPOSITIVOSEXTRASPRONTA then begin delete(recebido, 1, posex('|', recebido)); ListarDispositivosExtras(recebido); tvDevices.Enabled := true; end else end; procedure TFormListarDispositivos.AtualizarStrings; begin lvAdvancedInfo.Columns.Items[0].Caption := traduzidos[402]; lvAdvancedInfo.Columns.Items[1].Caption := traduzidos[403]; end; procedure TFormListarDispositivos.ListarTodosDispositivos(Lista: string); var dwIndex: DWORD; DeviceInfoData: SP_DEVINFO_DATA; DeviceName, DeviceClassName: String; tvRoot: TTreeNode; ClassGUID: TGUID; DeviceClassesCount, DevicesCount: Integer; tempstr: string; begin tvDevices.Items.BeginUpdate; try while (length(Lista) > 2) and (Visible = True) do // tamanho #13#10 begin DeviceClassName := copy(Lista, 1, posex(SeparadorDevices, Lista) - 1); delete(Lista, 1, posex(SeparadorDevices, Lista) + length(SeparadorDevices) - 1); tvRoot := tvDevices.Items.Add(nil, DeviceClassName); TempStr := copy(Lista, 1, posex('##' + SeparadorDevices, Lista) - 1); delete(Lista, 1, posex('##' + SeparadorDevices, Lista) + 1); delete(Lista, 1, length(SeparadorDevices)); copymemory(@ClassGUID, @tempstr[1], sizeof(ClassGUID)); tvRoot.ImageIndex := GetDeviceImageIndex(ClassGUID); tvRoot.SelectedIndex := tvRoot.ImageIndex; tvRoot.StateIndex := strtoint(copy(Lista, 1, posex(SeparadorDevices, Lista) - 1)); delete(Lista, 1, posex(SeparadorDevices, Lista) + length(SeparadorDevices) - 1); delete(Lista, 1, 2); // #13#10 while posex('@@', Lista) = 1 do begin delete(Lista, 1, 2); // '@@' DeviceName := copy(Lista, 1, posex(SeparadorDevices, Lista) - 1); delete(Lista, 1, posex(SeparadorDevices, Lista) + length(SeparadorDevices) - 1); TempStr := copy(Lista, 1, posex('##' + SeparadorDevices, Lista) - 1); delete(Lista, 1, posex('##' + SeparadorDevices, Lista) + 1); delete(Lista, 1, length(SeparadorDevices)); copymemory(@DeviceInfoData.ClassGuid, @tempstr[1], sizeof(DeviceInfoData.ClassGuid)); dwIndex := strtoint(copy(Lista, 1, posex(SeparadorDevices, Lista) - 1)); delete(Lista, 1, posex(SeparadorDevices, Lista) + length(SeparadorDevices) - 1); delete(Lista, 1, 2); // #13#10 with tvDevices.Items.AddChild(tvRoot, DeviceName) do begin ImageIndex := GetDeviceImageIndex(DeviceInfoData.ClassGuid); SelectedIndex := ImageIndex; StateIndex := Integer(dwIndex); end; end; end; tvDevices.AlphaSort; finally tvDevices.Items.EndUpdate; end; end; procedure TFormListarDispositivos.ListarDispositivosExtras(TempStr: string); var ANode: TTreeNode; Item: TListItem; begin if lvAdvancedInfo.Items.Count > 0 then lvAdvancedInfo.Items.Clear; try lvAdvancedInfo.Items.BeginUpdate; while length(Tempstr) > 2 do begin Item := lvAdvancedInfo.Items.Add; Item.Caption := copy(TempStr, 1, posex(SeparadorDevices, Tempstr) - 1); delete(TempStr, 1, posex(SeparadorDevices, Tempstr) + length(SeparadorDevices) - 1); Item.SubItems.Add(copy(TempStr, 1, posex(SeparadorDevices, Tempstr) - 1)); delete(TempStr, 1, posex(SeparadorDevices, Tempstr) + length(SeparadorDevices) - 1); delete(TempStr, 1, 2); // #13#10 end; finally lvAdvancedInfo.Items.EndUpdate; end; end; function TFormListarDispositivos.GetDeviceImageIndex(DeviceGUID: TGUID): Integer; begin Result := -1; SetupDiGetClassImageIndex(ClassImageListData, DeviceGUID, Result); end; procedure TFormListarDispositivos.InitImageList; begin ZeroMemory(@ClassImageListData, SizeOf(TSPClassImageListData)); ClassImageListData.cbSize := SizeOf(TSPClassImageListData); if SetupDiGetClassImageList(ClassImageListData) then ilDevices.Handle := ClassImageListData.ImageList; end; procedure TFormListarDispositivos.ReleaseImageList; begin if not SetupDiDestroyClassImageList(ClassImageListData) then RaiseLastOSError; end; procedure TFormListarDispositivos.FormClose(Sender: TObject; var Action: TCloseAction); var TempStr: WideString; IniFile: TIniFile; begin if LiberarForm then Action := caFree; TempStr := ExtractFilePath(ParamStr(0)) + 'Settings\'; ForceDirectories(TempStr); TempStr := TempStr + NomePC + '.ini'; try IniFile := TIniFile.Create(TempStr, IniFilePassword); IniFile.WriteInteger('Devices', 'Width', Width); IniFile.WriteInteger('Devices', 'Height', Height); IniFile.WriteInteger('Devices', 'Left', Left); IniFile.WriteInteger('Devices', 'Top', Top); IniFile.WriteInteger('Devices', 'TV1', tvDevices.Width); IniFile.WriteInteger('Devices', 'LV1_0', lvAdvancedInfo.Column[0].Width); IniFile.WriteInteger('Devices', 'LV1_1', lvAdvancedInfo.Column[1].Width); IniFile.Free; except DeleteFile(TempStr); end; end; procedure TFormListarDispositivos.FormCreate(Sender: TObject); begin Self.Left := (screen.width - Self.width) div 2 ; Self.top := (screen.height - Self.height) div 2; if lvAdvancedInfo.Items.Count > 0 then lvAdvancedInfo.Items.Clear; InitImageList; end; procedure TFormListarDispositivos.FormShow(Sender: TObject); begin tvDevices.Enabled := true; if lvAdvancedInfo.Items.Count > 0 then lvAdvancedInfo.Items.Clear; tvDevices.Items.Clear; AtualizarStrings; StatusBar1.Panels.Items[0].Text := Traduzidos[205]; StatusBar1.Panels.Items[1].Text := Traduzidos[205]; sleep(10); Servidor.enviarString(LISTDEVICES + '|'); end; procedure TFormListarDispositivos.lvAdvancedInfoCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); begin Compare := CompareText(Item1.Caption, Item2.Caption); end; procedure TFormListarDispositivos.tvDevicesCompare(Sender: TObject; Node1, Node2: TTreeNode; Data: Integer; var Compare: Integer); begin Compare := CompareText(Node1.Text, Node2.Text); end; procedure TFormListarDispositivos.tvDevicesChange(Sender: TObject; Node: TTreeNode); var ANode: TTreeNode; begin ANode := tvDevices.Selected; if Assigned(ANode) then if ANode.StateIndex >= 0 then begin tvDevices.Enabled := false; Servidor.enviarString(LISTEXTRADEVICES + '|' + inttostr(ANode.StateIndex) + '|'); end; end; end.
unit scriptsfunc; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Variants, Dialogs, graphics, BaseHW, spi25, msgstr, PasCalc, pasfunc; procedure SetScriptFunctions(PC : TPasCalc); procedure SetScriptVars(); procedure RunScript(ScriptText: TStrings); function RunScriptFromFile(ScriptFile: string; Section: string): boolean; function ParseScriptText(Script: TStrings; SectionName: string; var ScriptText: TStrings ): Boolean; function GetScriptSectionsFromFile(ScriptFile: string): TStrings; implementation uses main, scriptedit; const _SPI_SPEED_MAX = 255; function GetScriptSectionsFromFile(ScriptFile: string): TStrings; var st, SectionName: string; i: integer; ScriptText: TStrings; begin if not FileExists(ScriptsPath+ScriptFile) then Exit; Result:= TStringList.Create; ScriptText:= TStringList.Create; ScriptText.LoadFromFile(ScriptsPath+ScriptFile); for i:= 0 to ScriptText.Count-1 do begin st := Trim(Upcase(ScriptText.Strings[i])); if Copy(st, 1, 2) = '{$' then begin SectionName := Trim(Copy(st, 3, pos('}', st)-3)); if SectionName <> '' then begin Result.Add(SectionName); end; end; end; end; {Возвращает текст выбранной секции Если секция не найдена возвращает false} function ParseScriptText(Script: TStrings; SectionName: string; var ScriptText: TStrings ): Boolean; var st: string; i: integer; s: boolean; begin Result := false; s:= false; for i:=0 to Script.Count-1 do begin st:= Script.Strings[i]; if s then begin if Trim(Copy(st, 1, 2)) = '{$' then break; ScriptText.Append(st); end else begin st:= StringReplace(st, ' ', '', [rfReplaceAll]); if Pos('{$' + Upcase(SectionName) + '}', Upcase(st)) <> 0 then //if Upcase(st) = '{$' + Upcase(SectionName) + '}' then begin s := true; Result := true; end; end; end; end; //Выполняет скрипт procedure RunScript(ScriptText: TStrings); var TimeCounter: TDateTime; begin LogPrint(TimeToStr(Time())); TimeCounter := Time(); MainForm.Log.Append(STR_USING_SCRIPT + CurrentICParam.Script); RomF.Clear; //Предопределяем переменные ScriptEngine.ClearVars; SyncUI_ICParam(); SetScriptVars(); MainForm.StatusBar.Panels.Items[2].Text := CurrentICParam.Name; ScriptEngine.Execute(ScriptText.Text); if ScriptEngine.ErrCode<>0 then begin if not ScriptEditForm.Visible then begin LogPrint(ScriptEngine.ErrMsg); LogPrint(ScriptEngine.ErrLine); end else begin ScriptLogPrint(ScriptEngine.ErrMsg); ScriptLogPrint(ScriptEngine.ErrLine); end; end; LogPrint(STR_TIME + TimeToStr(Time() - TimeCounter)); end; {Выполняет секцию скрипта из файла Если файл или секция отсутствует то возвращает false} function RunScriptFromFile(ScriptFile: string; Section: string): boolean; var ScriptText, ParsedScriptText: TStrings; begin if not FileExists(ScriptsPath+ScriptFile) then Exit(false); try ScriptText:= TStringList.Create; ParsedScriptText:= TStringList.Create; ScriptText.LoadFromFile(ScriptsPath+ScriptFile); if not ParseScriptText(ScriptText, Section, ParsedScriptText) then Exit(false); RunScript(ParsedScriptText); Result := true; finally ScriptText.Free; ParsedScriptText.Free; end; end; function VarIsString(V : TVar) : boolean; var t: integer; begin t := VarType(V.Value); Result := (t=varString) or (t=varOleStr); end; //------------------------------------------------------------------------------ {Script Delay(ms: WORD); Останавливает выполнение скрипта на ms миллисекунд } function Script_Delay(Sender:TObject; var A:TVarList): boolean; begin if A.Count < 1 then Exit(false); Sleep(TPVar(A.Items[0])^.Value); Result := true; end; {Script ShowMessage(text); Аналог ShowMessage} function Script_ShowMessage(Sender:TObject; var A:TVarList) : boolean; var s: string; begin if A.Count < 1 then Exit(false); s := TPVar(A.Items[0])^.Value; ShowMessage(s); Result := true; end; {Script InputBox(Captiontext, Prompttext, Defaulttext): value; Аналог InputBox} function Script_InputBox(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin if A.Count < 3 then Exit(false); R.Value := InputBox(TPVar(A.Items[0])^.Value, TPVar(A.Items[1])^.Value, TPVar(A.Items[2])^.Value); Result := true; end; {Script LogPrint(text); Выводит сообщение в лог Параметры: text текст сообщения} function Script_LogPrint(Sender:TObject; var A:TVarList) : boolean; var s: string; begin if A.Count < 1 then Exit(false); s := TPVar(A.Items[0])^.Value; LogPrint('Script: ' + s); Result := true; end; {Script CreateByteArray(size): variant; Создает массив с типом элементов varbyte} function Script_CreateByteArray(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin if A.Count < 1 then Exit(false); R.Value := VarArrayCreate([0, TPVar(A.Items[0])^.Value - 1], varByte); Result := true; end; {Script GetArrayItem(array, index): variant; Возвращает значение элемента массива} function Script_GetArrayItem(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin if (A.Count < 2) or (not VarIsArray(TPVar(A.Items[0])^.Value)) then Exit(false); R.Value := TPVar(A.Items[0])^.Value[TPVar(A.Items[1])^.Value]; Result := true; end; {Script SetArrayItem(array, index, value); Устанавливает значение элемента массива} function Script_SetArrayItem(Sender:TObject; var A:TVarList) : boolean; begin if (A.Count < 3) or (not VarIsArray(TPVar(A.Items[0])^.Value)) then Exit(false); TPVar(A.Items[0])^.Value[TPVar(A.Items[1])^.Value] := TPVar(A.Items[2])^.Value; Result := true; end; {Script IntToHex(value, digits): string; Аналог IntToHex} function Script_IntToHex(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin if A.Count < 2 then Exit(false); R.Value:= IntToHex(Int64(TPVar(A.Items[0])^.Value), TPVar(A.Items[1])^.Value); Result := true; end; {Script CHR(byte): char; Аналог CHR} function Script_CHR(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin if A.Count < 1 then Exit(false); R.Value:= CHR(TPVar(A.Items[0])^.Value); Result := true; end; {Script SPIEnterProgMode(speed): boolean; Инициализирует состояние пинов для SPI и устанавливает частоту SPI Если частота не установлена возвращает false Игнорируется для CH341} function Script_SPIEnterProgMode(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var speed: byte; begin if not OpenDevice() then Exit(false); if A.Count < 1 then Exit(false); speed := TPVar(A.Items[0])^.Value; if speed = _SPI_SPEED_MAX then speed := 13; if EnterProgMode25(SetSPISpeed(speed), MainForm.MenuSendAB.Checked) then R.Value := True else R.Value := False; Result := true; end; {Script SPIExitProgMode(); Отключает пины SPI} function Script_SPIExitProgMode(Sender:TObject; var A:TVarList) : boolean; begin ExitProgMode25; AsProgrammer.Programmer.DevClose; Result := true; end; {Script ProgressBar(inc, max, pos); Устанавливает состояние ProgressBar Параметры: inc насколько увиличить позицию Необязательные параметры: max максимальная позиция ProgressBar pos устанавливает конкретную позицию ProgressBar} function Script_ProgressBar(Sender:TObject; var A:TVarList) : boolean; begin if A.Count < 1 then Exit(false); MainForm.ProgressBar.Position := MainForm.ProgressBar.Position + TPVar(A.Items[0])^.Value; if A.Count > 1 then MainForm.ProgressBar.Max := TPVar(A.Items[1])^.Value; if A.Count > 2 then MainForm.ProgressBar.Position := TPVar(A.Items[2])^.Value; Result := true; end; {Script SPIRead(cs, size, buffer..): integer; Читает данные в буфер Параметры: cs если cs=1 отпускать Chip Select после чтения данных size размер данных в байтах buffer переменные для хранения данных или массив созданный CreateByteArray Возвращает количество прочитанных байт} function Script_SPIRead(Sender:TObject; var A:TVarList; var R: TVar) : boolean; var i, size, cs: integer; DataArr: array of byte; begin if A.Count < 3 then Exit(false); cs := TPVar(A.Items[0])^.Value; size := TPVar(A.Items[1])^.Value; SetLength(DataArr, size); R.Value := SPIRead(cs, size, DataArr[0]); //Если buffer массив if (VarIsArray(TPVar(A.Items[2])^.Value)) then for i := 0 to size-1 do begin TPVar(A.Items[2])^.Value[i] := DataArr[i]; end else for i := 0 to size-1 do begin TPVar(A.Items[i+2])^.Value := DataArr[i]; end; Result := true; end; {Script SPIWrite(cs, size, buffer..): integer; Записывает данные из буфера Параметры: cs если cs=1 отпускать Chip Select после записи данных size размер данных в байтах buffer переменные для хранения данных или массив созданный CreateByteArray Возвращает количество записанных байт} function Script_SPIWrite(Sender:TObject; var A:TVarList; var R: TVar) : boolean; var i, size, cs: integer; DataArr: array of byte; begin if A.Count < 3 then Exit(false); size := TPVar(A.Items[1])^.Value; cs := TPVar(A.Items[0])^.Value; SetLength(DataArr, size); //Если buffer массив if (VarIsArray(TPVar(A.Items[2])^.Value)) then for i := 0 to size-1 do begin DataArr[i] := TPVar(A.Items[2])^.Value[i]; end else for i := 0 to size-1 do begin DataArr[i] := TPVar(A.Items[i+2])^.Value; end; R.Value := SPIWrite(cs, size, DataArr); Result := true; end; {Script SPIReadToEditor(cs, size): integer; Читает данные в редактор Параметры: cs если cs=1 отпускать Chip Select после чтения данных size размер данных в байтах Возвращает количество прочитанных байт} function Script_SPIReadToEditor(Sender:TObject; var A:TVarList; var R: TVar) : boolean; var DataArr: array of byte; BufferLen: integer; begin if A.Count < 2 then Exit(false); BufferLen := TPVar(A.Items[1])^.Value; SetLength(DataArr, BufferLen); R.Value := SPIRead(TPVar(A.Items[0])^.Value, BufferLen, DataArr[0]); RomF.Clear; RomF.WriteBuffer(DataArr[0], BufferLen); RomF.Position := 0; try MainForm.MPHexEditorEx.InsertMode:= true; MainForm.MPHexEditorEx.NoSizeChange:= false; MainForm.MPHexEditorEx.ReadOnlyView:= true; MainForm.MPHexEditorEx.AppendBuffer(RomF.Memory , BufferLen); finally MainForm.MPHexEditorEx.ReadOnlyView:= false; MainForm.MPHexEditorEx.InsertMode:= MainForm.AllowInsertItem.Checked; MainForm.MPHexEditorEx.NoSizeChange:= not MainForm.AllowInsertItem.Checked; end; Result := true; end; {Script SPIWriteFromEditor(cs, size, position): integer; Записывает данные из редактора размером size с позиции position Параметры: cs если cs=1 отпускать Chip Select после записи данных size размер данных в байтах position позиция в редакторе Возвращает количество записанных байт} function Script_SPIWriteFromEditor(Sender:TObject; var A:TVarList; var R: TVar) : boolean; var DataArr: array of byte; BufferLen: integer; begin if A.Count < 3 then Exit(false); BufferLen := TPVar(A.Items[1])^.Value; SetLength(DataArr, BufferLen); RomF.Clear; MainForm.MPHexEditorEx.SaveToStream(RomF); RomF.Position := TPVar(A.Items[2])^.Value; RomF.ReadBuffer(DataArr[0], BufferLen); R.Value := SPIWrite(TPVar(A.Items[0])^.Value, BufferLen, DataArr); Result := true; end; //I2C--------------------------------------------------------------------------- {Script I2CEnterProgMode; Инициализирует состояние пинов} function Script_I2CEnterProgMode(Sender:TObject; var A:TVarList) : boolean; begin if not OpenDevice() then Exit(false); Asprogrammer.Programmer.I2CInit; Result := true; end; {Script I2cExitProgMode(); Отключает пины} function Script_I2CExitProgMode(Sender:TObject; var A:TVarList) : boolean; begin Asprogrammer.Programmer.I2CDeinit; AsProgrammer.Programmer.DevClose; Result := true; end; {Script I2CReadWrite(DevAddr, wsize, rsize, wbuffer.., rbuffer...): integer; Записывает данные из буфера Параметры: DevAddr адрес устройства size размер данных в байтах buffer переменные для хранения данных или массив созданный CreateByteArray Возвращает количество записанных + прочитанных байт} function Script_I2CReadWrite(Sender:TObject; var A:TVarList; var R: TVar) : boolean; var i, rsize, wsize: integer; WDataArr, RDataArr: array of byte; DevAddr: byte; begin if A.Count < 4 then Exit(false); DevAddr := TPVar(A.Items[0])^.Value; wsize := TPVar(A.Items[1])^.Value; if wsize < 1 then Exit(false); rsize := TPVar(A.Items[2])^.Value; SetLength(WDataArr, wsize); SetLength(RDataArr, rsize); //Если wbuffer массив if (VarIsArray(TPVar(A.Items[3])^.Value)) then for i := 0 to wsize-1 do begin WDataArr[i] := TPVar(A.Items[3])^.Value[i]; end else for i := 0 to wsize-1 do begin WDataArr[i] := TPVar(A.Items[i+3])^.Value; end; R.Value := AsProgrammer.Programmer.I2CReadWrite(DevAddr, wsize, WDataArr, rsize, RDataArr); if rsize < 1 then Exit(true); if (VarIsArray(TPVar(A.Items[3])^.Value)) then wsize := 1; //Если rbuffer массив if (VarIsArray(TPVar(A.Items[wsize+3])^.Value)) then for i := 0 to rsize-1 do begin TPVar(A.Items[wsize+3])^.Value[i] := RDataArr[i]; end else for i := 0 to rsize-1 do begin TPVar(A.Items[i+wsize+3])^.Value := RDataArr[i]; end; Result := true; end; {Script I2CStart; Используется вместе с I2CWriteByte, I2CReadByte } function Script_I2CStart(Sender:TObject) : boolean; begin AsProgrammer.Programmer.I2CStart; result := true; end; {Script I2CStop; Используется вместе с I2CWriteByte, I2CReadByte } function Script_I2CStop(Sender:TObject) : boolean; begin AsProgrammer.Programmer.I2CStop; result := true; end; {Script I2CWriteByte(data): boolean; Возвращает ack/nack Параметры: data байт данных для записи Возвращает ack/nack} function Script_I2CWriteByte(Sender:TObject; var A:TVarList; var R: TVar) : boolean; begin if A.Count < 1 then Exit(false); R.Value := AsProgrammer.Programmer.I2CWriteByte(TPVar(A.Items[0])^.Value); result := true; end; {Script I2CReadByte(ack: boolean): data; Возвращает байт данных Параметры: ack ack/nack Возвращает байт прочитаных данных} function Script_I2CReadByte(Sender:TObject; var A:TVarList; var R: TVar) : boolean; begin if A.Count < 1 then Exit(false); R.Value := AsProgrammer.Programmer.I2CReadByte(TPVar(A.Items[0])^.Value); result := true; end; {Script ReadToEditor(size, position, buffer...); Записывает данные из буфера в редактор Параметры: size размер данных в байтах position позиция в редакторе buffer переменные для хранения данных или массив созданный CreateByteArray} function Script_ReadToEditor(Sender:TObject; var A:TVarList) : boolean; var DataArr: array of byte; size, i: integer; begin if A.Count < 3 then Exit(false); size := TPVar(A.Items[0])^.Value; if size < 1 then Exit(false); if TPVar(A.Items[1])^.Value < 0 then Exit(false); SetLength(DataArr, size); //Если buffer массив if (VarIsArray(TPVar(A.Items[2])^.Value)) then for i := 0 to size-1 do begin DataArr[i] := TPVar(A.Items[2])^.Value[i]; end else for i := 0 to size-1 do begin DataArr[i] := TPVar(A.Items[i+2])^.Value; end; RomF.Clear; MainForm.MPHexEditorEx.SaveToStream(RomF); RomF.Position := TPVar(A.Items[1])^.Value; RomF.WriteBuffer(DataArr[0], size); RomF.Position := 0; MainForm.MPHexEditorEx.LoadFromStream(RomF); Result := true; end; {Script WriteFromEditor(size, position, buffer...); Записывает данные из редактора размером size с позиции position Параметры: size размер данных в байтах position позиция в редакторе buffer переменные для хранения данных или массив созданный CreateByteArray} function Script_WriteFromEditor(Sender:TObject; var A:TVarList) : boolean; var DataArr: array of byte; size, i: integer; begin if A.Count < 3 then Exit(false); size := TPVar(A.Items[0])^.Value; if size < 1 then Exit(false); SetLength(DataArr, size); RomF.Clear; MainForm.MPHexEditorEx.SaveToStream(RomF); RomF.Position := TPVar(A.Items[1])^.Value; RomF.ReadBuffer(DataArr[0], size); //Если buffer массив if (VarIsArray(TPVar(A.Items[2])^.Value)) then for i := 0 to size-1 do begin TPVar(A.Items[2])^.Value[i] := DataArr[i]; end else for i := 0 to size-1 do begin TPVar(A.Items[i+2])^.Value := DataArr[i]; end; Result := true; end; {Script GetEditorDataSize: Longword; Возвращает размер данных в редакторе } function Script_GetEditorDataSize(Sender:TObject; var A:TVarList; var R: TVar) : boolean; begin R.Value := MainForm.MPHexEditorEx.DataSize; result := true; end; //------------------------------------------------------------------------------ procedure SetScriptFunctions(PC : TPasCalc); begin PC.SetFunction('Delay', @Script_Delay); PC.SetFunction('ShowMessage', @Script_ShowMessage); PC.SetFunction('InputBox', @Script_InputBox); PC.SetFunction('LogPrint', @Script_LogPrint); PC.SetFunction('ProgressBar', @Script_ProgressBar); PC.SetFunction('IntToHex', @Script_IntToHex); PC.SetFunction('CHR', @Script_CHR); PC.SetFunction('ReadToEditor', @Script_ReadToEditor); PC.SetFunction('WriteFromEditor', @Script_WriteFromEditor); PC.SetFunction('GetEditorDataSize', @Script_GetEditorDataSize); PC.SetFunction('CreateByteArray', @Script_CreateByteArray); PC.SetFunction('GetArrayItem', @Script_GetArrayItem); PC.SetFunction('SetArrayItem', @Script_SetArrayItem); PC.SetFunction('SPIEnterProgMode', @Script_SPIEnterProgMode); PC.SetFunction('SPIExitProgMode', @Script_SPIExitProgMode); PC.SetFunction('SPIRead', @Script_SPIRead); PC.SetFunction('SPIWrite', @Script_SPIWrite); PC.SetFunction('SPIReadToEditor', @Script_SPIReadToEditor); PC.SetFunction('SPIWriteFromEditor', @Script_SPIWriteFromEditor); PC.SetFunction('I2CEnterProgMode', @Script_I2CEnterProgMode); PC.SetFunction('I2CExitProgMode', @Script_I2CExitProgMode); PC.SetFunction('I2CReadWrite', @Script_I2CReadWrite); PC.SetFunction('I2CStart', @Script_I2CStart); PC.SetFunction('I2CStop', @Script_I2CStop); PC.SetFunction('I2CWriteByte', @Script_I2CWriteByte); PC.SetFunction('I2CReadByte', @Script_I2CReadByte); SetFunctions(PC); end; procedure SetScriptVars(); begin ScriptEngine.SetValue('_IC_Name', CurrentICParam.Name); ScriptEngine.SetValue('_IC_Size', CurrentICParam.Size); ScriptEngine.SetValue('_IC_Page', CurrentICParam.Page); ScriptEngine.SetValue('_IC_SpiCmd', CurrentICParam.SpiCmd); ScriptEngine.SetValue('_IC_MWAddrLen', CurrentICParam.MWAddLen); ScriptEngine.SetValue('_IC_I2CAddrType', CurrentICParam.I2CAddrType); ScriptEngine.SetValue('_SPI_SPEED_MAX', _SPI_SPEED_MAX); end; end.
unit IsOddTest; interface uses DUnitX.TestFramework, uIntX; type [TestFixture] TIsOddTest = class(TObject) public [Test] procedure ShouldBeFalseForZero(); [Test] procedure ShouldBeFalseForEvenNumber(); [Test] procedure ShouldBeTrueForOddNumber(); end; implementation [Test] procedure TIsOddTest.ShouldBeFalseForZero(); var value: TIntX; result: Boolean; begin value := TIntX.Create(0); result := value.IsOdd; Assert.IsFalse(result); end; [Test] procedure TIsOddTest.ShouldBeFalseForEvenNumber(); var value: TIntX; result: Boolean; begin value := TIntX.Create(42); result := value.IsOdd; Assert.IsFalse(result); end; procedure TIsOddTest.ShouldBeTrueForOddNumber(); var value: TIntX; result: Boolean; begin value := TIntX.Create(57); result := value.IsOdd; Assert.IsTrue(result); end; initialization TDUnitX.RegisterTestFixture(TIsOddTest); end.
unit Validador.Core.Impl.ConversorXMLDataSet; interface implementation uses System.SysUtils, DB, System.Classes, Validador.DI, Validador.Core.ConversorXMLDataSet, Validador.Data.dbChangeXML, FireDac.Comp.Client, Validador.Data.FDDbChange, Xml.xmldom, Xml.XMLDoc, Xml.XMLIntf; type TConversorXMLDataSet = class(TInterfacedObject, IConversorXMLDataSet) private FXML: IXMLDocument; FDataSet: TFDDbChange; public procedure SetXML(const AXML: IXMLDocument); procedure SetDataSet(const ADataSet: TFDDbChange); procedure ConverterParaDataSet; procedure ConverterParaXML; procedure DataSetParaImportacao; end; procedure TConversorXMLDataSet.ConverterParaXML; var _script: IXMLScriptType; _havillan: IXMLHavillanType; begin FDataSet.DisableControls; try FDataSet.First; _havillan := Gethavillan(FXML); while not FDataSet.Eof do begin _script := _havillan.Add; Validador.Data.dbChangeXML.AtribuirNome(_script, FDataSet.Value.AsString, FDataSet.Nome.AsString); if not FDataSet.Versao.AsString.Trim.IsEmpty then _script.Version := FDataSet.Versao.AsString; if FDataSet.TemPos.AsBoolean then _script.X_has_pos := 'True'; if not FDataSet.Descricao.AsString.Trim.IsEmpty then _script.Description := FDataSet.Descricao.AsString; if not FDataSet.ZDescricao.AsString.Trim.IsEmpty then _script.Z_description := FDataSet.ZDescricao.AsString; if not FDataSet.Value.AsString.Trim.IsEmpty then _script.Text := FDataSet.Value.AsString; FDataSet.Next; end; finally FDataSet.EnableControls; end; end; procedure TConversorXMLDataSet.DataSetParaImportacao; var _filtro: string; _filtrado: boolean; _indexFieldNames: string; begin _filtro := FDataSet.Filter; _filtrado := FDataSet.Filtered; _indexFieldNames := FDataSet.IndexFieldNames; try FDataSet.Filter := 'IMPORTAR = True'; FDataSet.Filtered := True; FDataSet.IndexFieldNames := 'OrdemOriginal'; ConverterParaXML; finally FDataSet.IndexFieldNames := _indexFieldNames; FDataSet.Filtered := _filtrado; FDataSet.Filter := _filtro; end; end; procedure TConversorXMLDataSet.SetDataSet(const ADataSet: TFDDbChange); begin FDataSet := ADataSet; end; procedure TConversorXMLDataSet.SetXML(const AXML: IXMLDocument); begin FXML := AXML; end; procedure TConversorXMLDataSet.ConverterParaDataSet; var _havillan: IXMLHavillanType; _script: IXMLScriptType; i: integer; begin _havillan := Gethavillan(FXML); FDataSet.DisableControls; try for i := 0 to Pred(_havillan.Count) do begin _script := _havillan.Script[i]; if _script.A_name.Trim.IsEmpty and _script.Text.Trim.IsEmpty then Continue; FDataSet.Insert; FDataSet.OrdemOriginal.AsInteger := i; FDataSet.Versao.AsString := _script.Version; FDataSet.Descricao.AsString := _script.Description; FDataSet.ZDescricao.AsString := _script.Z_description; FDataSet.Nome.AsString := _script.A_name; FDataSet.TemPos.AsBoolean := _script.X_has_pos = 'True'; if not _script.Text.Trim.IsEmpty then begin FDataSet.Value.AsString := _script.Text; FDataSet.Nome.AsString := _script.Text; end; FDataSet.Post; end; finally FDataSet.First; FDataSet.EnableControls; end; end; initialization ContainerDI.RegisterType<TConversorXMLDataSet>.Implements<IConversorXMLDataSet>; ContainerDI.Build; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela de Encerramento do Exercício para o módulo Contabilidade The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (alberteije@gmail.com) @version 2.0 ******************************************************************************* } unit UContabilEncerramentoExercicio; {$MODE Delphi} interface uses BrookHTTPClient, BrookFCLHTTPClientBroker, BrookHTTPUtils, BrookUtils, FPJson, ZDataset, LCLIntf, LCLType, LMessages, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, ComCtrls, LabeledCtrls, rxdbgrid, rxtoolbar, DBCtrls, StrUtils, Math, Constantes, CheckLst, ActnList, ToolWin, db, BufDataset, Biblioteca, ULookup, VO, ContabilEncerramentoExeCabVO, ContabilEncerramentoExeCabController; type { TFContabilEncerramentoExercicio } TFContabilEncerramentoExercicio = class(TFTelaCadastro) CDSContabilEncerramentoExercicioDetalhe: TBufDataset; DSContabilEncerramentoExercicioDetalhe: TDataSource; PanelMestre: TPanel; PageControlItens: TPageControl; tsItens: TTabSheet; PanelItens: TPanel; GridDetalhe: TRxDbGrid; EditDataInicio: TLabeledDateEdit; EditDataInclusao: TLabeledDateEdit; EditMotivo: TLabeledEdit; EditDataFim: TLabeledDateEdit; procedure FormCreate(Sender: TObject); procedure GridDblClick(Sender: TObject); procedure BotaoConsultarClick(Sender: TObject); procedure BotaoSalvarClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; procedure LimparCampos; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; procedure ConfigurarLayoutTela; end; var FContabilEncerramentoExercicio: TFContabilEncerramentoExercicio; implementation uses UDataModule, ContabilEncerramentoExeDetVO; {$R *.lfm} {$REGION 'Controles Infra'} procedure TFContabilEncerramentoExercicio.BotaoConsultarClick(Sender: TObject); var RetornoConsulta: TZQuery; ListaCampos: TStringList; i: integer; begin inherited; if Sessao.Camadas = 2 then begin Filtro := MontaFiltro; CDSGrid.Close; CDSGrid.Open; ConfiguraGridFromVO(Grid, ClasseObjetoGridVO); ListaCampos := TStringList.Create; RetornoConsulta := TContabilEncerramentoExeCabController.Consulta(Filtro, IntToStr(Pagina)); RetornoConsulta.Active := True; RetornoConsulta.GetFieldNames(ListaCampos); RetornoConsulta.First; while not RetornoConsulta.EOF do begin CDSGrid.Append; for i := 0 to ListaCampos.Count - 1 do begin CDSGrid.FieldByName(ListaCampos[i]).Value := RetornoConsulta.FieldByName(ListaCampos[i]).Value; end; CDSGrid.Post; RetornoConsulta.Next; end; end; end; procedure TFContabilEncerramentoExercicio.BotaoSalvarClick(Sender: TObject); begin inherited; BotaoConsultarClick(Sender); end; procedure TFContabilEncerramentoExercicio.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TContabilEncerramentoExeCabVO; ObjetoController := TContabilEncerramentoExeCabController.Create; inherited; BotaoImprimir.Visible := False; MenuImprimir.Visible := False; ConfiguraCDSFromVO(CDSContabilEncerramentoExercicioDetalhe, TContabilEncerramentoExeDetVO); ConfiguraGridFromVO(GridDetalhe, TContabilEncerramentoExeDetVO); end; procedure TFContabilEncerramentoExercicio.LimparCampos; begin inherited; CDSContabilEncerramentoExercicioDetalhe.Close; CDSContabilEncerramentoExercicioDetalhe.Open; end; procedure TFContabilEncerramentoExercicio.ConfigurarLayoutTela; begin PanelEdits.Enabled := True; if StatusTela = stNavegandoEdits then begin PanelMestre.Enabled := False; PanelItens.Enabled := False; end else begin PanelMestre.Enabled := True; PanelItens.Enabled := True; end; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFContabilEncerramentoExercicio.DoInserir: Boolean; begin Result := inherited DoInserir; ConfigurarLayoutTela; if Result then begin EditMotivo.SetFocus; end; end; function TFContabilEncerramentoExercicio.DoEditar: Boolean; begin Result := inherited DoEditar; ConfigurarLayoutTela; if Result then begin EditMotivo.SetFocus; end; end; function TFContabilEncerramentoExercicio.DoExcluir: Boolean; begin if inherited DoExcluir then begin try Result := TContabilEncerramentoExeCabController.Exclui(IdRegistroSelecionado); except Result := False; end; end else begin Result := False; end; if Result then BotaoConsultar.Click; end; function TFContabilEncerramentoExercicio.DoSalvar: Boolean; var ContabilEncerramentoExercicioDetalhe: TContabilEncerramentoExeDetVO; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TContabilEncerramentoExeCabVO.Create; TContabilEncerramentoExeCabVO(ObjetoVO).IdEmpresa := Sessao.Empresa.Id; TContabilEncerramentoExeCabVO(ObjetoVO).Motivo := EditMotivo.Text; TContabilEncerramentoExeCabVO(ObjetoVO).DataInicio := EditDataInicio.Date; TContabilEncerramentoExeCabVO(ObjetoVO).DataFim := EditDataFim.Date; TContabilEncerramentoExeCabVO(ObjetoVO).DataInclusao := EditDataInclusao.Date; // Detalhes CDSContabilEncerramentoExercicioDetalhe.DisableControls; CDSContabilEncerramentoExercicioDetalhe.First; while not CDSContabilEncerramentoExercicioDetalhe.Eof do begin ContabilEncerramentoExercicioDetalhe := TContabilEncerramentoExeDetVO.Create; ContabilEncerramentoExercicioDetalhe.Id := CDSContabilEncerramentoExercicioDetalhe.FieldByName('ID').AsInteger; ContabilEncerramentoExercicioDetalhe.IdContabilEncerramentoExe := TContabilEncerramentoExeCabVO(ObjetoVO).Id; ContabilEncerramentoExercicioDetalhe.IdContabilConta := CDSContabilEncerramentoExercicioDetalhe.FieldByName('ID_CONTABIL_CONTA').AsInteger; ContabilEncerramentoExercicioDetalhe.SaldoAnterior := CDSContabilEncerramentoExercicioDetalhe.FieldByName('SALDO_ANTERIOR').AsFloat; ContabilEncerramentoExercicioDetalhe.ValorDebito := CDSContabilEncerramentoExercicioDetalhe.FieldByName('VALOR_DEBITO').AsFloat; ContabilEncerramentoExercicioDetalhe.ValorCredito := CDSContabilEncerramentoExercicioDetalhe.FieldByName('VALOR_CREDITO').AsFloat; ContabilEncerramentoExercicioDetalhe.Saldo := CDSContabilEncerramentoExercicioDetalhe.FieldByName('SALDO').AsFloat; TContabilEncerramentoExeCabVO(ObjetoVO).ListaContabilEncerramentoExeDetVO.Add(ContabilEncerramentoExercicioDetalhe); CDSContabilEncerramentoExercicioDetalhe.Next; end; CDSContabilEncerramentoExercicioDetalhe.EnableControls; if StatusTela = stInserindo then begin TContabilEncerramentoExeCabController.Insere(TContabilEncerramentoExeCabVO(ObjetoVO)); end else if StatusTela = stEditando then begin /// EXERCICIO: Verifique se tem como serializar as listas junto com o objeto para realizar a comparação //if TContabilEncerramentoExeCabVO(ObjetoVO).ToJSONString <> StringObjetoOld then //begin TContabilEncerramentoExeCabController.Altera(TContabilEncerramentoExeCabVO(ObjetoVO)); //end //else //Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFContabilEncerramentoExercicio.GridDblClick(Sender: TObject); begin inherited; ConfigurarLayoutTela; end; procedure TFContabilEncerramentoExercicio.GridParaEdits; var IdCabecalho: String; Current: TContabilEncerramentoExeDetVO; i:integer; begin inherited; if not CDSGrid.IsEmpty then begin IdCabecalho := IntToStr(IdRegistroSelecionado); ObjetoVO := TContabilEncerramentoExeCabController.ConsultaObjeto('ID=' + IdCabecalho); end; if Assigned(ObjetoVO) then begin EditMotivo.Text := TContabilEncerramentoExeCabVO(ObjetoVO).Motivo; EditDataInicio.Date := TContabilEncerramentoExeCabVO(ObjetoVO).DataInicio; EditDataFim.Date := TContabilEncerramentoExeCabVO(ObjetoVO).DataFim; EditDataInclusao.Date := TContabilEncerramentoExeCabVO(ObjetoVO).DataInclusao; // Detalhes for I := 0 to TContabilEncerramentoExeCabVO(ObjetoVO).ListaContabilEncerramentoExeDetVO.Count - 1 do begin Current := TContabilEncerramentoExeCabVO(ObjetoVO).ListaContabilEncerramentoExeDetVO[I]; CDSContabilEncerramentoExercicioDetalhe.Append; CDSContabilEncerramentoExercicioDetalhe.FieldByName('ID').AsInteger := Current.id; CDSContabilEncerramentoExercicioDetalhe.FieldByName('ID_CONTABIL_ENCERRAMENTO_EXE').AsInteger := Current.IdContabilEncerramentoExe; CDSContabilEncerramentoExercicioDetalhe.FieldByName('ID_CONTABIL_CONTA').AsInteger := Current.IdContabilConta; CDSContabilEncerramentoExercicioDetalhe.FieldByName('SALDO_ANTERIOR').AsFloat := Current.SaldoAnterior; CDSContabilEncerramentoExercicioDetalhe.FieldByName('VALOR_DEBITO').AsFloat := Current.ValorDebito; CDSContabilEncerramentoExercicioDetalhe.FieldByName('VALOR_CREDITO').AsFloat := Current.ValorCredito; CDSContabilEncerramentoExercicioDetalhe.FieldByName('SALDO').AsFloat := Current.Saldo; CDSContabilEncerramentoExercicioDetalhe.Post; end; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; ConfigurarLayoutTela; end; {$ENDREGION} /// EXERCICIO /// Implemente as rotinas automáticas no sistema end.
unit uAdr_DataModule; interface uses SysUtils, Classes, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery; type TAdrDM = class(TDataModule) pFIBDB_Adr: TpFIBDatabase; pFIBDS_SelectAdr: TpFIBDataSet; pFIBT_ReadAdr: TpFIBTransaction; pFIBT_WriteAdr: TpFIBTransaction; pFIBDS_SelectStreet: TpFIBDataSet; pFIBDS_SelectRegion: TpFIBDataSet; pFIBDS_SelectPlace: TpFIBDataSet; pFIBDS_SelectDistrict: TpFIBDataSet; pFIBDS_SelectRegionID_REGION: TFIBIntegerField; pFIBDS_SelectRegionNAME_REGION: TFIBStringField; pFIBDS_SelectDistrictID_DISTRICT: TFIBIntegerField; pFIBDS_SelectDistrictNAME_DISTRICT: TFIBStringField; pFIBDS_SelectPlaceID_PLACE: TFIBIntegerField; pFIBDS_SelectPlaceNAME_PLACE: TFIBStringField; pFIBDS_SelectPlaceIS_DISTRICT_CENTRE: TFIBStringField; pFIBDS_SelectPlaceIS_REGIONAL_CENTRE: TFIBStringField; pFIBDS_SelectPlaceIS_CAPITAL: TFIBStringField; pFIBDS_SelectStreetID_STREET: TFIBIntegerField; pFIBDS_SelectStreetNAME_STREET: TFIBStringField; pFIBDS_SelectAdrID_ADRESS: TFIBIntegerField; pFIBDS_SelectAdrZIPCODE: TFIBStringField; pFIBDS_SelectAdrID_CITY_AREA: TFIBIntegerField; pFIBDS_SelectAdrID_STREET: TFIBIntegerField; pFIBDS_SelectAdrKORPUS: TFIBStringField; pFIBDS_SelectAdrHOUSE: TFIBStringField; pFIBDS_SelectAdrFLAT: TFIBStringField; pFIBDS_SelectAdrDATE_BEG: TFIBDateField; pFIBDS_SelectAdrDATE_END: TFIBDateField; pFIBDS_SelectAdrSTREET_NAME: TFIBStringField; pFIBDS_SelectAdrPLACE_NAME: TFIBStringField; pFIBDS_SelectAdrCOUNTRY_NAME: TFIBStringField; pFIBDS_SelectAdrDISTRICT_NAME: TFIBStringField; pFIBDS_SelectAdrREGION_NAME: TFIBStringField; pFIBDS_SelectAdrID_ADR_PK: TFIBIntegerField; pFIBQ_Delete: TpFIBQuery; pFIBDS_SelectAdrCAREA_NAME: TFIBStringField; pFIBDS_SelectAdrFULL_NAME: TFIBStringField; pFIBDS_Id: TpFIBDataSet; pFIBDS_IdZIPCODE: TFIBStringField; pFIBDS_IdID_CITY_AREA: TFIBIntegerField; pFIBDS_IdID_STREET: TFIBIntegerField; pFIBDS_IdKORPUS: TFIBStringField; pFIBDS_IdHOUSE: TFIBStringField; pFIBDS_IdFLAT: TFIBStringField; pFIBDS_IdDATE_BEG: TFIBDateField; pFIBDS_IdDATE_END: TFIBDateField; pFIBDS_IdADRESS_NAME: TFIBStringField; pFIBDS_IdID_ADR_PK: TFIBIntegerField; pFIBDS_IdNAME_CITY_AREA: TFIBStringField; pFIBDS_Idfull_name: TStringField; pFIBDS_SelectCountry: TpFIBDataSet; pFIBDS_SelectCountryID_COUNTRY: TFIBIntegerField; pFIBDS_SelectCountryNAME_COUNTRY: TFIBStringField; procedure pFIBDS_SelectRegionAfterScroll(DataSet: TDataSet); procedure pFIBDS_SelectDistrictAfterScroll(DataSet: TDataSet); procedure pFIBDS_SelectPlaceAfterScroll(DataSet: TDataSet); procedure pFIBDS_SelectCountryAfterScroll(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; const C_Del_SQL='execute procedure ADR_COUNTRY_D(:where);'; D_Del_SQL='execute procedure ADR_DISTRICT_D(:where);'; R_Del_SQL='execute procedure ADR_REGION_D(:where);'; P_Del_SQL='execute procedure ADR_PLACE_D(:where);'; S_Del_SQL='execute procedure ADR_STREET_D(:where);'; A_Del_SQL='execute procedure ADR_ADRESS_MAIN_D(:where);'; Adr_Sel_SQL='select * from ADR_ADRESS_MAIN_S(:ActDate);'; procedure ShowInfo(DataSet: TDataSet); var AdrDM: TAdrDM; implementation uses Dialogs; {$R *.dfm} procedure ShowInfo(DataSet: TDataSet); var text: string; i:integer; begin text:=''; for i:=1 to DataSet.Fields.Count do text:=text+DataSet.Fields[i-1].FieldName+' : '+DataSet.Fields[i-1].DisplayText+#13; ShowMessage(text); end; procedure TAdrDM.pFIBDS_SelectRegionAfterScroll(DataSet: TDataSet); begin pFIBDS_SelectDistrict.Close; pFIBDS_SelectDistrict.ParamByName('id_region').AsVariant:=pFIBDS_SelectRegion['id_region']; pFIBDS_SelectDistrict.Open; end; procedure TAdrDM.pFIBDS_SelectDistrictAfterScroll(DataSet: TDataSet); begin pFIBDS_SelectPlace.Close; pFIBDS_SelectPlace.ParamByName('id_region').AsVariant:=pFIBDS_SelectRegion['id_region']; pFIBDS_SelectPlace.ParamByName('id_district').AsVariant:=pFIBDS_SelectDistrict['id_district']; pFIBDS_SelectPlace.Open; end; procedure TAdrDM.pFIBDS_SelectPlaceAfterScroll(DataSet: TDataSet); begin pFIBDS_SelectStreet.Close; pFIBDS_SelectStreet.ParamByName('id_place').AsVariant:=pFIBDS_SelectPlace['id_place']; pFIBDS_SelectStreet.Open; end; procedure TAdrDM.pFIBDS_SelectCountryAfterScroll(DataSet: TDataSet); begin pFIBDS_SelectRegion.Close; pFIBDS_SelectRegion.ParamByName('id_country').AsVariant:=pFIBDS_SelectCountry['id_country']; pFIBDS_SelectRegion.Open; end; end.
unit Dmitry.Controls.DmGradient; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs; type TDmGradient = class(TGraphicControl) private Fonmousedown: TNotifyEvent; Fcolorfrom: TColor; Fcolorto: TColor; FOrientarionHorizontal: Boolean; procedure Setcolorfrom(const Value: TColor); procedure Setcolorto(const Value: TColor); procedure Cmonmousedown(var message: TWMMouse); message WM_LBUTTONdown; procedure SetOrientarionHorizontal(const Value: Boolean); protected Procedure Paint; override; { Protected declarations } public Constructor Create(AOwner: TComponent); override; { Public declarations } published Property onmousedown: TNotifyEvent read Fonmousedown write Fonmousedown; Property Align; property ColorFrom: TColor read Fcolorfrom Write Setcolorfrom; property ColorTo: TColor read Fcolorto Write Setcolorto; property OrientarionHorizontal: Boolean read FOrientarionHorizontal write SetOrientarionHorizontal; { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('Dm', [TDmGradient]); end; { TGradient } constructor TDmGradient.Create(AOwner: TComponent); begin inherited Create(AOwner); Align := alNone; FOrientarionHorizontal := False; ColorFrom := $FF0000; ColorTo := $0; width := 100; height := 100; end; procedure TDmGradient.Paint; var R, G, B, R1, G1, B1, R2, G2, B2, i, RR1, GG1, BB1: Integer; RR, GG, BB: Boolean; Rect: TRect; begin if not FOrientarionHorizontal then begin with inherited Canvas do begin R1 := GetRvalue(ColorFrom); G1 := GetGvalue(ColorFrom); B1 := GetBvalue(ColorFrom); R2 := GetRvalue(ColorTo); G2 := GetGvalue(ColorTo); B2 := GetBvalue(ColorTo); If R1 - R2 >= 0 then RR := True else RR := False; If B1 - B2 >= 0 then BB := True else BB := False; If G1 - G2 >= 0 then GG := True else GG := False; RR1 := abs(R1 - R2); GG1 := abs(G1 - G2); BB1 := abs(B1 - B2); Rect.Left := 0; Rect.Right := width; For i := 0 to height do begin Rect.Top := i - 2; Rect.Bottom := i - 1; If not RR then R := R1 + Round((RR1 / height) * i) else R := R1 - Round((RR1 / height) * i); If not GG then G := G1 + Round((GG1 / height) * i) else G := G1 - Round((GG1 / height) * i); If not BB then B := B1 + Round((BB1 / height) * i) else B := B1 - Round((BB1 / height) * i); Brush.color := rgb(R, G, B); fillrect(Rect); end; end; end else begin with inherited Canvas do begin R1 := GetRvalue(ColorFrom); G1 := GetGvalue(ColorFrom); B1 := GetBvalue(ColorFrom); R2 := GetRvalue(ColorTo); G2 := GetGvalue(ColorTo); B2 := GetBvalue(ColorTo); if R1 - R2 >= 0 then RR := True else RR := False; if B1 - B2 >= 0 then BB := True else BB := False; if G1 - G2 >= 0 then GG := True else GG := False; RR1 := abs(R1 - R2); GG1 := abs(G1 - G2); BB1 := abs(B1 - B2); Rect.Top := 0; Rect.Bottom := height; // Rect.Left:=0; // Rect.Right:=width; for i := 0 to width do begin // Rect.Top:=i-2; // Rect.Bottom:=i-1; Rect.Left := i - 2; Rect.Right := i - 1; If not RR then R := R1 + Round((RR1 / width) * i) else R := R1 - Round((RR1 / width) * i); if not GG then G := G1 + Round((GG1 / width) * i) else G := G1 - Round((GG1 / width) * i); If not BB then B := B1 + Round((BB1 / width) * i) else B := B1 - Round((BB1 / width) * i); Brush.color := rgb(R, G, B); fillrect(Rect); end; end; end; end; procedure TDmGradient.Setcolorfrom(const Value: TColor); begin Fcolorfrom := Value; Invalidate; end; procedure TDmGradient.Setcolorto(const Value: TColor); begin Fcolorto := Value; Invalidate; end; procedure TDmGradient.Cmonmousedown(var message: TWMMouse); begin inherited; if Assigned(Fonmousedown) then Fonmousedown(Self); end; procedure TDmGradient.SetOrientarionHorizontal(const Value: Boolean); begin FOrientarionHorizontal := Value; end; end.
unit uTEFConsts; interface const TEF_NONE = 0; TEF_DIAL = 1; TEF_DEDICADO = 2; TEF_DIAL_XPRESS = 0; TEF_DIAL_HIPER = 1; TEF_DIAL_NAMES: array [0..1] of String = ('TEF Dial', 'TEF Hipercard'); TEF_PARCELAMENTO_LOJA = 1; TEF_PARCELAMENTO_ADM = 2; TEF_PAYMENTS: set of byte = [10..21, 23..58, 60..64, 70..99]; TEF_BANDEIRA_FININVEST = 32; implementation end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFTask; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefTaskOwn = class(TCefBaseRefCountedOwn, ICefTask) protected procedure Execute; virtual; public constructor Create; virtual; end; TCefTaskRef = class(TCefBaseRefCountedRef, ICefTask) protected procedure Execute; virtual; public class function UnWrap(data: Pointer): ICefTask; end; TCefFastTaskProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure; TCefFastTask = class(TCefTaskOwn) protected FMethod: TCefFastTaskProc; procedure Execute; override; public class procedure New(threadId: TCefThreadId; const method: TCefFastTaskProc); class procedure NewDelayed(threadId: TCefThreadId; Delay: Int64; const method: TCefFastTaskProc); constructor Create(const method: TCefFastTaskProc); reintroduce; end; TCefGetTextTask = class(TCefTaskOwn) protected FChromiumBrowser : TObject; FFrameName : ustring; FFrame : ICefFrame; FFrameIdentifier : int64; procedure Execute; override; public constructor Create(const aChromiumBrowser : TObject; const aFrameName : ustring); reintroduce; overload; constructor Create(const aChromiumBrowser : TObject; const aFrame : ICefFrame); reintroduce; overload; constructor Create(const aChromiumBrowser : TObject; const aFrameIdentifier : int64); reintroduce; overload; destructor Destroy; override; end; TCefGetHTMLTask = class(TCefGetTextTask) protected procedure Execute; override; end; TCefDeleteCookiesTask = class(TCefTaskOwn) protected FCallBack : ICefDeleteCookiesCallback; procedure Execute; override; public constructor Create(const aCallBack : ICefDeleteCookiesCallback); reintroduce; end; TCefUpdatePrefsTask = class(TCefTaskOwn) protected FChromiumBrowser : TObject; procedure Execute; override; public constructor Create(const aChromiumBrowser : TObject); reintroduce; end; TCefSavePrefsTask = class(TCefTaskOwn) protected FChromiumBrowser : TObject; procedure Execute; override; public constructor Create(const aChromiumBrowser : TObject); reintroduce; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFChromium, uCEFCookieManager; procedure cef_task_execute(self: PCefTask); stdcall; begin TCefTaskOwn(CefGetObject(self)).Execute(); end; constructor TCefTaskOwn.Create; begin inherited CreateData(SizeOf(TCefTask)); with PCefTask(FData)^ do execute := cef_task_execute; end; procedure TCefTaskOwn.Execute; begin // end; // TCefTaskRef procedure TCefTaskRef.Execute; begin PCefTask(FData).execute(FData); end; class function TCefTaskRef.UnWrap(data: Pointer): ICefTask; begin if data <> nil then Result := Create(data) as ICefTask else Result := nil; end; // TCefFastTask constructor TCefFastTask.Create(const method: TCefFastTaskProc); begin inherited Create; FMethod := method; end; procedure TCefFastTask.Execute; begin FMethod(); end; class procedure TCefFastTask.New(threadId: TCefThreadId; const method: TCefFastTaskProc); begin CefPostTask(threadId, Create(method)); end; class procedure TCefFastTask.NewDelayed(threadId: TCefThreadId; Delay: Int64; const method: TCefFastTaskProc); begin CefPostDelayedTask(threadId, Create(method), Delay); end; // TCefGetTextTask constructor TCefGetTextTask.Create(const aChromiumBrowser : TObject; const aFrameName : ustring); begin inherited Create; FChromiumBrowser := aChromiumBrowser; FFrameName := aFrameName; FFrame := nil; FFrameIdentifier := 0; end; constructor TCefGetTextTask.Create(const aChromiumBrowser : TObject; const aFrame : ICefFrame); begin inherited Create; FChromiumBrowser := aChromiumBrowser; FFrameName := ''; FFrame := aFrame; FFrameIdentifier := 0; end; constructor TCefGetTextTask.Create(const aChromiumBrowser : TObject; const aFrameIdentifier : int64); begin inherited Create; FChromiumBrowser := aChromiumBrowser; FFrameName := ''; FFrame := nil; FFrameIdentifier := aFrameIdentifier; end; destructor TCefGetTextTask.Destroy; begin FFrame := nil; inherited Destroy; end; procedure TCefGetTextTask.Execute; begin if (FChromiumBrowser <> nil) and (FChromiumBrowser is TChromium) then begin if (FFrame <> nil) then TChromium(FChromiumBrowser).Internal_GetText(FFrame) else if (FFrameIdentifier <> 0) then TChromium(FChromiumBrowser).Internal_GetText(FFrameIdentifier) else TChromium(FChromiumBrowser).Internal_GetText(FFrameName); end; end; // TCefGetHTMLTask procedure TCefGetHTMLTask.Execute; begin if (FChromiumBrowser <> nil) and (FChromiumBrowser is TChromium) then begin if (FFrame <> nil) then TChromium(FChromiumBrowser).Internal_GetHTML(FFrame) else if (FFrameIdentifier <> 0) then TChromium(FChromiumBrowser).Internal_GetHTML(FFrameIdentifier) else TChromium(FChromiumBrowser).Internal_GetHTML(FFrameName); end; end; // TCefDeleteCookiesTask constructor TCefDeleteCookiesTask.Create(const aCallBack : ICefDeleteCookiesCallback); begin inherited Create; FCallBack := aCallBack; end; procedure TCefDeleteCookiesTask.Execute; var CookieManager : ICefCookieManager; begin CookieManager := TCefCookieManagerRef.Global(nil); CookieManager.DeleteCookies('', '', FCallBack); end; // TCefUpdatePrefsTask constructor TCefUpdatePrefsTask.Create(const aChromiumBrowser : TObject); begin inherited Create; FChromiumBrowser := aChromiumBrowser; end; procedure TCefUpdatePrefsTask.Execute; begin if (FChromiumBrowser <> nil) and (FChromiumBrowser is TChromium) then TChromium(FChromiumBrowser).Internal_UpdatePreferences; end; // TCefSavePrefsTask constructor TCefSavePrefsTask.Create(const aChromiumBrowser : TObject); begin inherited Create; FChromiumBrowser := aChromiumBrowser; end; procedure TCefSavePrefsTask.Execute; begin if (FChromiumBrowser <> nil) and (FChromiumBrowser is TChromium) then TChromium(FChromiumBrowser).Internal_SavePreferences; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmColorComboBox Purpose : Standard Combobox with Colors being displayed. Both standard 16 and windows system colors. Date : 01-01-1999 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmColorComboBox; interface {$I CompilerDefines.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TColorSet = (csEndUser, csProgrammer); TrmColorComboBox = class(TCustomComboBox) private { Private declarations } fBoxRect : TRect; fColorSet : TColorSet; function GetColorIndex:TColor; procedure SetColorSet(value : TColorSet); protected { Protected declarations } procedure DrawItem(Index: Integer; WRect: TRect; State: TOwnerDrawState); override; procedure CreateWnd; override; public { Public declarations } constructor create(AOwner:TComponent); override; property ColorIndex:TColor read GetColorIndex; published { Published declarations } property ColorSet:TColorSet read fColorSet write SetColorSet default csEndUser; property OnChange; end; implementation const maxcolors = 43; DefaultColors = 18; ColorValues : array[0..42] of TColor = (clBlack, clMaroon, clGreen, clOlive, clNavy, clPurple, clTeal, clGray, clSilver, clRed, clLime, clYellow, clBlue, clFuchsia, clAqua, clLtGray, clDkGray, clWhite, clScrollBar, clBackground, clActiveCaption, clInactiveCaption, clMenu, clWindow, clWindowFrame, clMenuText, clWindowText, clCaptionText, clActiveBorder, clInactiveBorder, clAppWorkSpace, clHighlight, clHighlightText, clBtnFace, clBtnShadow, clGrayText, clBtnText, clInactiveCaptionText, clBtnHighlight, cl3DDkShadow, cl3DLight, clInfoText, clInfoBk); ColorStrings : array[0..42] of String = ('clBlack','clMaroon','clGreen','clOlive','clNavy','clPurple','clTeal','clGray', 'clSilver','clRed','clLime','clYellow','clBlue','clFuchsia','clAqua','clLtGray', 'clDkGray','clWhite','clScrollBar','clBackground','clActiveCaption','clInactiveCaption', 'clMenu','clWindow','clWindowFrame','clMenuText','clWindowText','clCaptionText', 'clActiveBorder','clInactiveBorder','clAppWorkSpace','clHighlight','clHighlightText', 'clBtnFace','clBtnShadow','clGrayText','clBtnText','clInactiveCaptionText','clBtnHighlight', 'cl3DDkShadow','cl3DLight','clInfoText','clInfoBk'); constructor TrmColorComboBox.create(AOwner:TComponent); begin inherited create(AOwner); style := csOwnerDrawFixed; ColorSet := csEndUser; end; function TrmColorComboBox.GetColorIndex:TColor; begin result := ColorValues[itemindex]; end; procedure TrmColorComboBox.DrawItem(Index: Integer; WRect: TRect; State: TOwnerDrawState); var fillcolor, textcolor : TColor; ColorName : string; begin if (odSelected in state) then begin fillcolor := clHighLight; TextColor := clHighLightText; end else begin fillcolor := clWindow; TextColor := clWindowText; end; fBoxRect := rect(WRect.Left + 2,WRect.Top + 2, WRect.Left + 15, WRect.Bottom - 2); with canvas do begin brush.color := FillColor; fillrect(WRect); brush.color := ColorValues[index]; fillrect(fboxrect); brush.color := clactiveborder; framerect(fboxrect); brush.color := fillColor; pen.color := TextColor; WRect.left := WRect.left + 17; colorname := ColorStrings[Index]; if ColorSet = csEndUser then delete(colorname,1,2); TextRect(WRect, Wrect.Left, WRect.Top, colorname); end; end; procedure TrmColorComboBox.SetColorSet(value : TColorSet); var loop:integer; begin fColorSet := value; if (not self.HandleAllocated) or (csdesigning in componentstate) then exit; items.clear; if ColorSet = csProgrammer then for loop := 0 to maxColors-1 do items.add(ColorStrings[loop]) else for loop := 0 to DefaultColors-1 do items.add(ColorStrings[loop]) end; procedure TrmColorComboBox.CreateWnd; var loop:integer; begin inherited; items.clear; if ColorSet = csProgrammer then for loop := 0 to maxColors-1 do items.add(ColorStrings[loop]) else for loop := 0 to DefaultColors-1 do items.add(ColorStrings[loop]) end; end.
unit PromoConfigClass; interface uses classes, sysUtils, dbClient, DB, uSystemConst; type TPromoConfig = class private fPromoMatrix: TClientDataset; fPromoStackMatrix: TClientDataset; fValidPromos: TClientDataset; procedure createPromoMatrix(); procedure loadPromoMatrix(); procedure createPromoStackMatrix(); procedure loadPromoStackMatrix(); constructor create(); public class function getPromoConfigSingleton(): TPromoConfig; function loadValidPromos(arg_datePromo: TDateTime): TClientDataset; end; implementation uses uDM; { TPromoConfig } constructor TPromoConfig.Create(); begin createPromoMatrix(); createPromoStackMatrix(); end; procedure TPromoConfig.createPromoMatrix(); begin try fPromoMatrix := TClientDataset.Create(nil); fPromoMatrix.FieldDefs.add('promoType', ftInteger, 0, true); fpromoMatrix.fieldDefs.add('discountPercent', ftBoolean, 0, true); fpromoMatrix.fieldDefs.add('discountAmount', ftBoolean, 0, true); fpromoMatrix.fieldDefs.add('discountQuantity', ftBoolean, 0 , true); fpromoMatrix.FieldDefs.add('discountSale', ftBoolean, 0, true); fPromoMatrix.CreateDataSet; loadPromoMatrix(); except on E: Exception do begin raise Exception.Create('Cannot create matrix of discounts ' + e.message); end; end; end; procedure TPromoConfig.createPromoStackMatrix(); begin try fPromoStackMatrix := TClientDataset.Create(nil); fPromoStackMatrix.FieldDefs.add('promoType', ftInteger, 0, true); fPromoStackMatrix.fieldDefs.add('discountPercent', ftBoolean, 0, true); fPromoStackMatrix.fieldDefs.add('discountAmount', ftBoolean, 0, true); fPromoStackMatrix.fieldDefs.add('discountQuantity', ftBoolean, 0 , true); fPromoStackMatrix.FieldDefs.add('discountSale', ftBoolean, 0, true); fPromoStackMatrix.CreateDataSet; loadPromoStackMatrix(); except on E: Exception do begin raise Exception.Create('Cannot create matrix of discounts ' + e.message); end; end; end; class function TPromoConfig.getPromoConfigSingleton: TPromoConfig; begin if (self = nil ) then result := TPromoConfig.create() else result := TPromoConfig(self); end; procedure TPromoConfig.loadPromoMatrix(); var i: Integer; begin i := 1; while ( i < 4 ) do begin fPromoMatrix.Insert; case i of 1: begin fPromoMatrix.FieldByName('promoType').Value := PROMO_SALE_TYPE; fPromoMatrix.fieldByName('discountPercent').value := true; fPromoMatrix.fieldByName('discountAmount').value := true; fPromoMatrix.fieldByName('discountQuantity').value := true; fPromoMatrix.fieldByName('discountSale').value := true; fPromoMatrix.Post; end; 2: begin fPromoMatrix.FieldByName('promoType').Value := PROMO_FREQBUYER_TYPE; fPromoMatrix.fieldByName('discountPercent').value := false; fPromoMatrix.fieldByName('discountAmount').value := false; fPromoMatrix.fieldByName('discountQuantity').value := true; fPromoMatrix.fieldByName('discountSale').value := false; fPromoMatrix.Post; end; 3: begin fPromoMatrix.FieldByName('promoType').Value := PROMO_COUPON_TYPE; fPromoMatrix.fieldByName('discountPercent').value := true; fPromoMatrix.fieldByName('discountAmount').value := true; fPromoMatrix.fieldByName('discountQuantity').value := true; fPromoMatrix.fieldByName('discountSale').value := true; fPromoMatrix.Post; end; 4: begin fPromoMatrix.FieldByName('promoType').Value := PROMO_LOYALTY_TYPE; fPromoMatrix.fieldByName('discountPercent').value := true; fPromoMatrix.fieldByName('discountAmount').value := true; fPromoMatrix.fieldByName('discountQuantity').value := true; fPromoMatrix.fieldByName('discountSale').value := true; fPromoMatrix.Post; end; end; inc(i); end; end; procedure TPromoConfig.loadPromoStackMatrix(); var i: Integer; begin i := 1; while ( i < 4 ) do begin fPromoMatrix.Insert; case i of 1: begin fPromoStackMatrix.FieldByName('promoType').Value := PROMO_SALE_TYPE; fPromoStackMatrix.fieldByName('discountPercent').value := false; fPromoStackMatrix.fieldByName('discountAmount').value := false; fPromoStackMatrix.fieldByName('discountQuantity').value := false; fPromoStackMatrix.fieldByName('discountSale').value := true; fPromoStackMatrix.Post; end; 2: begin fPromoStackMatrix.FieldByName('promoType').Value := PROMO_FREQBUYER_TYPE; fPromoStackMatrix.fieldByName('discountPercent').value := false; fPromoStackMatrix.fieldByName('discountAmount').value := false; fPromoStackMatrix.fieldByName('discountQuantity').value := true; fPromoStackMatrix.fieldByName('discountSale').value := false; fPromoStackMatrix.Post; end; 3: begin fPromoStackMatrix.FieldByName('promoType').Value := PROMO_COUPON_TYPE; fPromoStackMatrix.fieldByName('discountPercent').value := true; fPromoStackMatrix.fieldByName('discountAmount').value := true; fPromoStackMatrix.fieldByName('discountQuantity').value := true; fPromoStackMatrix.fieldByName('discountSale').value := true; fPromoStackMatrix.Post; end; 4: begin fPromoStackMatrix.FieldByName('promoType').Value := PROMO_LOYALTY_TYPE; fPromoStackMatrix.fieldByName('discountPercent').value := false; fPromoStackMatrix.fieldByName('discountAmount').value := false; fPromoStackMatrix.fieldByName('discountQuantity').value := false; fPromoStackMatrix.fieldByName('discountSale').value := true; fPromoStackMatrix.Post; end; end; inc(i); end; end; function TPromoConfig.loadValidPromos(arg_datePromo: TDateTime): TClientDataset; begin fValidPromos := dm.getPromoSettingsOnDate(arg_datePromo); result := fValidPromos; end; end.
unit MsgWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls; type TMsgForm = class(TForm) Memo: TMemo; MsgMain: TMainMenu; Messages1: TMenuItem; Clear1: TMenuItem; N1: TMenuItem; Hidethiswindow1: TMenuItem; procedure Clear1Click(Sender: TObject); procedure Hidethiswindow1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } MaxMsgs:Integer; Procedure SetMaxMsgs(n:Integer); public { Public declarations } Procedure AddMessage(const msg:String); Property MaxMessages:Integer read MaxMsgs write SetMaxMsgs; end; var MsgForm: TMsgForm; implementation {$R *.DFM} procedure TMsgForm.Clear1Click(Sender: TObject); begin Memo.Lines.Clear; end; procedure TMsgForm.Hidethiswindow1Click(Sender: TObject); begin Visible:=false; end; Procedure TMsgForm.SetMaxMsgs(n:Integer); begin MaxMsgs:=n; end; Procedure TMsgForm.AddMessage(const msg:String); var n:Integer; begin n:=Memo.Lines.Count; if n>=MaxMsgs then Memo.Lines.Delete(n-1); Memo.Lines.Insert(0,msg); end; procedure TMsgForm.FormCreate(Sender: TObject); begin MaxMessages:=1000; end; end.
unit ufrmDailySalesAnalysis; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterReport, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, Actions, ActnList, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, ComCtrls, dxCore, cxDateUtils, cxStyles, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxDropDownEdit, cxDBExtLookupComboBox, cxTextEdit, cxMaskEdit, cxCalendar, cxImageComboBox, cxCustomData, cxFilter, cxData; type TfrmDailySalesAnalysis = class(TfrmMasterReport) Panel2: TPanel; Label2: TLabel; dtStart: TcxDateEdit; dtEnd: TcxDateEdit; Label3: TLabel; cxGrid: TcxGrid; cxGridView: TcxGridDBTableView; cxlvMaster: TcxGridLevel; Label4: TLabel; cbGroup: TcxImageComboBox; procedure actExportExecute(Sender: TObject); procedure actPrintExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure LoadData; end; var frmDailySalesAnalysis: TfrmDailySalesAnalysis; implementation {$R *.dfm} uses uDMClient, uDMReport, uDXUtils, DateUtils; procedure TfrmDailySalesAnalysis.actExportExecute(Sender: TObject); begin inherited; cxGridView.ExportToXLS(); end; procedure TfrmDailySalesAnalysis.actPrintExecute(Sender: TObject); begin inherited; with DMReport do begin AddReportVariable('UserCetak', 'USER'); AddReportVariable('DateStart', FormatDateTime('dd/MM/yyyy', dtStart.Date)); AddReportVariable('DateEnd', FormatDateTime('dd/MM/yyyy', dtEnd.Date)); ExecuteReport('Reports\DSA', ReportClient.DSA_GetDSPrint(dtStart.Date, dtEnd.Date, cbGroup.EditValue),[]); end; end; procedure TfrmDailySalesAnalysis.actRefreshExecute(Sender: TObject); begin inherited; LoadData; end; procedure TfrmDailySalesAnalysis.FormCreate(Sender: TObject); begin inherited; dtStart.Date := Now(); dtEnd.Date := Now(); cbGroup.ItemIndex := 0; end; procedure TfrmDailySalesAnalysis.LoadData; begin cxGridView.LoadFromDS(DMReport.ReportClient.DSA_GetDS(dtStart.Date, dtEnd.Date, cbGroup.EditValue), Self); if Assigned(cxGridView.DataController.DataSource) then begin cxGridView.AutoFormatCurrency(',0.00;(,0.00)'); cxGridView.SetSummaryByColumns(['LastSales','LastSalesProcent', 'LastProfit','LastProfitProcent', 'AllSales','AllSalesProcent', 'AllProfit','AllProfitProcent']); cxGridView.ApplyBestFit(); end; end; end.
unit Pospolite.View.DOM.Document; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} interface uses Classes, SysUtils, Pospolite.View.Basics, Pospolite.View.CSS.Selector; type { TPLHTMLDocumentQueries } TPLHTMLDocumentQueries = class sealed public class function querySelectorFast(const AQuery: TPLString; AObject: TPLHTMLObject; const AFirstOnly: TPLBool): TPLHTMLObjects; class function querySelector(const AQuery: TPLString; AObject: TPLHTMLObject ): TPLHTMLObject; class function querySelectorAll(const AQuery: TPLString; AObject: TPLHTMLObject ): TPLHTMLObjects; inline; end; implementation { TPLHTMLDocumentQueries } class function TPLHTMLDocumentQueries.querySelectorFast( const AQuery: TPLString; AObject: TPLHTMLObject; const AFirstOnly: TPLBool ): TPLHTMLObjects; var sel: IPLCSSSelectors; s: TPLCSSSelector; i, j, id: SizeInt; ssp: TPLCSSSimpleSelectorPattern; tmp: IPLHTMLObjects; res: TPLBool; objp, obja: TPLHTMLObject; procedure TrySelect(a: TPLHTMLObject); var obj, applied: TPLHTMLObject; begin if not Assigned(a) then exit; if ssp.AppliesTo(a, applied) then tmp.Add(applied); for obj in a.Children do TrySelect(obj); end; begin Result := TPLHTMLObjects.Create(false); if not Assigned(AObject) then exit; tmp := TPLHTMLObjects.Create(false); sel := TPLCSSSelectorParser.ParseSelector(AQuery); for s in sel do begin // parsowanie od tyłu, jak to robi przeglądarka tmp.Clear; ssp := s.SimpleSelectors.Last; TrySelect(AObject); for i := 0 to tmp.Count-1 do begin res := true; objp := tmp[i]; for j := s.Combinators.Count-1 downto 0 do begin ssp := s.SimpleSelectors[j]; case s.Combinators[j].Value of scDescendant: begin objp := objp.Parent; res := false; while Assigned(objp) do begin if ssp.AppliesTo(objp, obja) then begin res := true; objp := obja; break; end else objp := objp.Parent; end; end; scChild: begin objp := objp.Parent; if ssp.AppliesTo(objp, obja) then begin objp := obja; break; end else res := false; end; scAdjascentSibling: begin obja := objp.Parent; id := objp.GetIDFromParent; if id > 0 then begin id -= 1; // omijanie zwykłego tekstu while (id >= 0) and (obja.Children[id].Name = 'internal_text_object') do id -= 1; res := (id >= 0) and ssp.AppliesTo(obja.Children[id], objp); end else res := false; end; scGeneralSibling: begin obja := objp.Parent; id := objp.GetIDFromParent; if id > 0 then begin id -= 1; while (id >= 0) and not ssp.AppliesTo(objp.Parent.Children[id], obja) do id -= 1; res := id >= 0; if res then objp := obja; end else res := false; end; scUndefined: res := false; end; if not res then break; end; if res and (Result.Find(tmp[i]) < 0) then Result.Add(tmp[i]); end; end; if AFirstOnly then while Result.Count > 1 do Result.Pop; end; class function TPLHTMLDocumentQueries.querySelector(const AQuery: TPLString; AObject: TPLHTMLObject): TPLHTMLObject; var objs: IPLHTMLObjects; begin // false cuz we can omit while by objs.First objs := querySelectorFast(AQuery, AObject, false); if not objs.Empty then Result := objs.First else Result := nil; end; class function TPLHTMLDocumentQueries.querySelectorAll(const AQuery: TPLString; AObject: TPLHTMLObject): TPLHTMLObjects; begin Result := querySelectorFast(AQuery, AObject, false); end; end.
unit ThItemHandle; interface uses GR32, ThTypes, ThUtils, ThClasses, System.UITypes, System.Generics.Collections; type TThItemHandle = class(TThInterfacedObject, IThItemHandle) private FRadius: Single; function GetCursor: TCursor; virtual; procedure SetPoint(const Value: TFloatPoint); protected FPoint: TFloatPoint; function GetPoly: TThPoly; overload; public constructor Create(ARadius: Single); property Point: TFloatPoint read FPoint write SetPoint; property Poly: TThPoly read GetPoly; property Cursor: TCursor read GetCursor; property Radius: Single read FRadius; function GetPoly(APoint: TFloatPoint): TThPoly; overload; virtual; end; TShapeHandleDirection = ( shdTopLeft, shdTop, shdTopRight, shdRight, shdBottomRight, shdBottom, shdBottomLeft, shdLeft ); TThShapeHandle = class(TThItemHandle) private FDirection: TShapeHandleDirection; function GetCursor: TCursor; override; public constructor Create(ADirection: TShapeHandleDirection; ARadius: Single); reintroduce; property Direction: TShapeHandleDirection read FDirection; end; TLineHandleDirection = ( shdLineFrom, shdLineTo ); TThLineHandle = class(TThItemHandle) private FDirection: TLineHandleDirection; function GetCursor: TCursor; override; public constructor Create(ADirection: TLineHandleDirection; ARadius: Single); reintroduce; property Direction: TLineHandleDirection read FDirection; end; TThCustomItemHandles = class(TInterfacedObject, IThItemHandles) private FVisible: Boolean; procedure SetHotHandle(const Value: IThItemHandle); function GetHotHandle: IThItemHandle; function GetHandleAtPoint(APoint: TFloatPoint): TThItemHandle; function GetVisible: Boolean; procedure SetVisible(const Value: Boolean); protected FParentItem: IThItem; FMouseDowned: Boolean; FHandles: TArray<TThItemHandle>; FHotHandle: IThItemHandle; FFillColor, FHotColor, FBorderColor: TColor32; FRadius: Single; FBorderWidth: Single; procedure DrawHandles(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); virtual; procedure MouseDown(const APoint: TFloatPoint); virtual; procedure MouseMove(const APoint: TFloatPoint); virtual; procedure MouseUp(const APoint: TFloatPoint); virtual; procedure CreateHandles; virtual; abstract; procedure FreeHandles; virtual; procedure RealignHandles; virtual; abstract; procedure ReleaseHotHandle; public constructor Create(AParent: IThItem); virtual; destructor Destroy; override; function PtInHandles(APoint: TFloatPoint): Boolean; virtual; property HandleRadius: Single read FRadius; property Visible: Boolean read GetVisible write SetVisible; end; implementation uses Winapi.Windows, System.Math, Vcl.Forms, ThItem, GR32_Polygons, GR32_Geometry, GR32_VectorUtils; const DEF_HANDLE_RADIUS = 4; { TThItemHandle } constructor TThItemHandle.Create(ARadius: Single); begin FRadius := DEF_HANDLE_RADIUS; end; function TThItemHandle.GetCursor: TCursor; begin Result := crDefault; end; function TThItemHandle.GetPoly(APoint: TFloatPoint): TThPoly; begin Result := Circle(APoint, FRadius); end; procedure TThItemHandle.SetPoint(const Value: TFloatPoint); begin FPoint := Value; end; function TThItemHandle.GetPoly: TThPoly; begin Result := GetPoly(FPoint); end; { TThShapeHandle } constructor TThShapeHandle.Create(ADirection: TShapeHandleDirection; ARadius: Single); begin inherited Create(ARadius); FDirection := ADirection; end; function TThShapeHandle.GetCursor: TCursor; const HANDLE_CURSOR: array[TShapeHandleDirection] of TCursor = ( crSizeNWSE, crSizeNS, crSizeNESW, crSizeWE, // TL, T, TR, R crSizeNWSE, crSizeNS, crSizeNESW, crSizeWE // BR, B, BL, L ); begin Result := HANDLE_CURSOR[FDirection]; end; { TThLineHandle } constructor TThLineHandle.Create(ADirection: TLineHandleDirection; ARadius: Single); begin inherited Create(ARadius); FDirection := ADirection; end; function TThLineHandle.GetCursor: TCursor; const HANDLE_CURSOR: array [TLineHandleDirection] of TCursor = ( crSizeNWSE, // From crSizeNWSE // To ); begin Result := HANDLE_CURSOR[FDirection]; end; { TThCustomItemHandles } constructor TThCustomItemHandles.Create(AParent: IThItem); begin FFillColor := clWhite32; FHotColor := clRed32; FBorderColor := clBlack32; FRadius := DEF_HANDLE_RADIUS; FBorderWidth := 1; FParentItem := AParent; FMouseDowned := False; CreateHandles; RealignHandles; FHotHandle := nil; end; destructor TThCustomItemHandles.Destroy; begin FreeHandles; inherited; end; procedure TThCustomItemHandles.DrawHandles(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); var P: TFloatPoint; H: TThItemHandle; Poly: TThPoly; begin for H in FHandles do begin P := H.Point.Scale(AScale).Offset(AOffset); Poly := H.GetPoly(P); if H = TThItemHandle(FHotHandle) then PolygonFS(Bitmap, Poly, FHotColor) else PolygonFS(Bitmap, Poly, FFillColor); PolylineFS(Bitmap, Poly, FBorderColor, True, FBorderWidth); end; end; function TThCustomItemHandles.GetHandleAtPoint( APoint: TFloatPoint): TThItemHandle; var H: TThItemHandle; begin Result := nil; for H in FHandles do begin if PtInCircle(APoint, H.Point, H.Radius * 2) then // if PointInPolygon(APoint, H.Poly) then Exit(H); end; end; function TThCustomItemHandles.PtInHandles(APoint: TFloatPoint): Boolean; begin Result := Assigned(GetHandleAtPoint(APoint)); end; function TThCustomItemHandles.GetHotHandle: IThItemHandle; begin Result := FHotHandle; end; function TThCustomItemHandles.GetVisible: Boolean; begin Result := FVisible; end; procedure TThCustomItemHandles.MouseDown(const APoint: TFloatPoint); begin FMouseDowned := True; end; procedure TThCustomItemHandles.MouseMove(const APoint: TFloatPoint); begin if not FMouseDowned then SetHotHandle(GetHandleAtPoint(APoint)); end; procedure TThCustomItemHandles.MouseUp(const APoint: TFloatPoint); begin SetHotHandle(GetHandleAtPoint(APoint)); FMouseDowned := False; end; procedure TThCustomItemHandles.FreeHandles; var H: TThItemHandle; begin for H in FHandles do H.Free; end; procedure TThCustomItemHandles.ReleaseHotHandle; begin FMouseDowned := False; SetHotHandle(nil); end; procedure TThCustomItemHandles.SetHotHandle(const Value: IThItemHandle); begin if FHotHandle = Value then Exit; FHotHandle := Value; if FHotHandle = nil then Screen.Cursor := crDefault else Screen.Cursor := FHotHandle.Cursor; end; procedure TThCustomItemHandles.SetVisible(const Value: Boolean); begin FVisible := Value; end; end.
{**************************************************************************************} { } { CCR.VirtualKeying - sending virtual keystrokes on OS X and Windows } { } { The contents of this file are subject to the Mozilla Public License Version 2.0 } { (the "License"); you may not use this file except in compliance with the License. } { You may obtain a copy of the License at https://www.mozilla.org/MPL/2.0 } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT } { WARRANTY OF ANY KIND, either express or implied. See the License for the specific } { language governing rights and limitations under the License. } { } { The Initial Developer of the Original Code is Chris Rolliston. Portions created by } { Chris Rolliston are Copyright (C) 2015 Chris Rolliston. All Rights Reserved. } { } {**************************************************************************************} unit VirtualKeying.Mac; interface {$IFDEF MACOS} uses MacApi.CocoaTypes, MacApi.CoreFoundation, MacApi.CoreGraphics, MacApi.KeyCodes, System.SysUtils, System.Classes, System.Generics.Collections, System.UITypes, VirtualKeying; type IMacVirtualKeySequence = interface ['{C4658C26-D73E-434E-89CC-77816BC1375B}'] function Add(KeyCode: CGKeyCode; EventType: TVirtualKeyEventType): CGEventRef; overload; function GetEventSourceRef: CGEventSourceRef; property EventSourceRef: CGEventSourceRef read GetEventSourceRef; end; TMacVirtualKeySequence = class(TVirtualKeySequenceBase, IVirtualKeySequence, IMacVirtualKeySequence) strict private FEventRefs: TList<CGEventRef>; FEventSourceRef: CGEventSourceRef; protected function Add(KeyCode: CGKeyCode; EventType: TVirtualKeyEventType): CGEventRef; overload; function Add(Key: Word; Shift: TShiftState; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; override; function Add(Ch: Char; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; override; function Execute: IVirtualKeySequence; function GetEventSourceRef: CGEventSourceRef; public constructor Create; overload; constructor Create(stateID: CGEventSourceStateID); overload; destructor Destroy; override; end; function VkToCGKeyCode(VkCode: Word): CGKeyCode; function ShiftStateToCGEventFlags(Shift: TShiftState): CGEventFlags; inline; {$ENDIF} implementation {$IFDEF MACOS} uses System.RTLConsts, VirtualKeying.Consts; function VkToCGKeyCode(VkCode: Word): CGKeyCode; begin case VkCode of 0: Result := 0; vkF1: Result := KEY_F1; vkF2: Result := KEY_F2; vkF3: Result := KEY_F3; vkF4: Result := KEY_F4; vkF5: Result := KEY_F5; vkF6: Result := KEY_F6; vkF7: Result := KEY_F7; vkF8: Result := KEY_F8; vkF9: Result := KEY_F9; vkF10: Result := KEY_F10; vkF11: Result := KEY_F11; vkF12: Result := KEY_F12; vkF13: Result := KEY_F13; vkF14: Result := KEY_F14; vkF15: Result := KEY_F15; vkF16: Result := KEY_F16; vkF17: Result := KEY_F17; vkF18: Result := KEY_F18; vkF19: Result := KEY_F19; vkF20: Result := KEY_F20; vkTab: Result := KEY_TAB; vkInsert: Result := KEY_INS; vkDelete: Result := KEY_DEL; vkHome: Result := KEY_HOME; vkEnd: Result := KEY_END; vkPrior: Result := KEY_PAGUP; vkNext: Result := KEY_PAGDN; vkUp: Result := KEY_UP; vkDown: Result := KEY_DOWN; vkLeft: Result := KEY_LEFT; vkRight: Result := KEY_RIGHT; vkNumLock: Result := KEY_NUMLOCK; vkBack: Result := KEY_BACKSPACE; vkReturn: Result := KEY_ENTER; vkEscape: Result := KEY_ESC; vkSpace: Result := KEY_SPACE; vkNumpad0: Result := KEY_NUMPAD0; vkNumpad1: Result := KEY_NUMPAD1; vkNumpad2: Result := KEY_NUMPAD2; vkNumpad3: Result := KEY_NUMPAD3; vkNumpad4: Result := KEY_NUMPAD4; vkNumpad5: Result := KEY_NUMPAD5; vkNumpad6: Result := KEY_NUMPAD6; vkNumpad7: Result := KEY_NUMPAD7; vkNumpad8: Result := KEY_NUMPAD8; vkNumpad9: Result := KEY_NUMPAD9; vkDivide: Result := KEY_PADDIV; vkMultiply: Result := KEY_PADMULT; vkSubtract: Result := KEY_PADSUB; vkAdd: Result := KEY_PADADD; vkDecimal: Result := KEY_PADDEC; vkSemicolon: Result := KEY_SEMICOLON; vkEqual: Result := KEY_EQUAL; vkComma: Result := KEY_COMMA; vkMinus: Result := KEY_MINUS; vkPeriod: Result := KEY_PERIOD; vkSlash: Result := KEY_SLASH; vkTilde: Result := KEY_TILDE; vkLeftBracket: Result := KEY_LEFTBRACKET; vkBackslash: Result := KEY_BACKSLASH; vkRightBracket: Result := KEY_RIGHTBRACKET; vkQuote: Result := KEY_QUOTE; vkPara: Result := KEY_PARA; vk1: Result := KEY_1; vk2: Result := KEY_2; vk3: Result := KEY_3; vk4: Result := KEY_4; vk5: Result := KEY_5; vk6: Result := KEY_6; vk7: Result := KEY_7; vk8: Result := KEY_8; vk9: Result := KEY_9; vk0: Result := KEY_0; vkQ: Result := KEY_Q; vkW: Result := KEY_W; vkE: Result := KEY_E; vkR: Result := KEY_R; vkT: Result := KEY_T; vkY: Result := KEY_Y; vkU: Result := KEY_U; vkI: Result := KEY_I; vkO: Result := KEY_O; vkP: Result := KEY_P; vkA: Result := KEY_A; vkS: Result := KEY_S; vkD: Result := KEY_D; vkF: Result := KEY_F; vkG: Result := KEY_G; vkH: Result := KEY_H; vkJ: Result := KEY_J; vkK: Result := KEY_K; vkL: Result := KEY_L; vkZ: Result := KEY_Z; vkX: Result := KEY_X; vkC: Result := KEY_C; vkV: Result := KEY_V; vkB: Result := KEY_B; vkN: Result := KEY_N; vkM: Result := KEY_M; vkOem102: Result := KEY_CURRENCY; else raise EArgumentOutOfRangeException.CreateResFmt(@SUnrecognizedVirtualKeyCode, [VkCode]); end; end; function ShiftStateToCGEventFlags(Shift: TShiftState): CGEventFlags; begin Result := 0; if ssAlt in Shift then Result := Result or kCGEventFlagMaskAlternate; if ssCommand in Shift then Result := Result or kCGEventFlagMaskCommand; if ssCtrl in Shift then Result := Result or kCGEventFlagMaskControl; if ssShift in Shift then Result := Result or kCGEventFlagMaskShift; end; { TMacVirtualKeySequence } constructor TMacVirtualKeySequence.Create; begin Create(kCGEventSourceStateHIDSystemState); end; constructor TMacVirtualKeySequence.Create(stateID: CGEventSourceStateID); begin inherited Create; FEventRefs := TList<CGEventRef>.Create; FEventSourceRef := CGEventSourceCreate(stateID); if FEventSourceRef = nil then RaiseLastOSError; end; destructor TMacVirtualKeySequence.Destroy; var Ref: CGEventRef; begin for Ref in FEventRefs do CFRelease(Ref); FEventRefs.Free; if FEventSourceRef <> nil then CFRelease(FEventSourceRef); inherited; end; function TMacVirtualKeySequence.Add(KeyCode: CGKeyCode; EventType: TVirtualKeyEventType): CGEventRef; const KeyDownFlags: array[TVirtualKeyEventType] of Integer = (1, 0); begin Result := CGEventCreateKeyboardEvent(FEventSourceRef, KeyCode, KeyDownFlags[EventType]); if Result = nil then RaiseLastOSError; FEventRefs.Add(Result); end; function TMacVirtualKeySequence.Add(Key: Word; Shift: TShiftState; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; var EventType: TVirtualKeyEventType; MacKey: CGKeyCode; MacFlags: CGEventFlags; begin MacKey := VkToCGKeyCode(Key); MacFlags := ShiftStateToCGEventFlags(Shift); for EventType in EventTypes do CGEventSetFlags(Add(MacKey, EventType), MacFlags); Result := Self; end; function TMacVirtualKeySequence.Add(Ch: Char; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; var EventType: TVirtualKeyEventType; Key: CGKeyCode; Flags: CGEventFlags; Ref: CGEventRef; begin Flags := 0; case Ch of 'A'..'Z': begin Key := VkToCGKeyCode(Ord(Ch)); Flags := kCGEventFlagMaskShift; end; 'a'..'z': Key := VkToCGKeyCode(Ord(UpCase(Ch))); #9, #13, ' ', '0'..'9': Key := VkToCGKeyCode(Ord(Ch)); '-': Key := KEY_MINUS; '_': begin Key := KEY_MINUS; Flags := kCGEventFlagMaskShift; end; '=': Key := KEY_EQUALS; '+': Key := KEY_ADD; '[': Key := KEY_LEFTBRACKET; ']': Key := KEY_RIGHTBRACKET; '''': Key := KEY_QUOTE; ';': Key := KEY_SEMICOLON; ',': Key := KEY_COMMA; '\': Key := KEY_BACKSLASH; '/': Key := KEY_SLASH; '.': Key := KEY_PERIOD; '~': Key := KEY_TILDE; '*': Key := KEY_MULTIPLY; else Key := 0; end; for EventType in EventTypes do begin Ref := Add(Key, EventType); if Flags <> 0 then CGEventSetFlags(Ref, Flags); CGEventKeyboardSetUnicodeString(Ref, 1, @Ch); end; Result := Self; end; function TMacVirtualKeySequence.Execute: IVirtualKeySequence; var Ref: CGEventRef; begin for Ref in FEventRefs do CGEventPost(kCGHIDEventTap, Ref); Result := Self; end; function TMacVirtualKeySequence.GetEventSourceRef: CGEventSourceRef; begin Result := FEventSourceRef; end; initialization TVirtualKeySequence.SetDefaultImplementation<TMacVirtualKeySequence>; {$ENDIF} end.
unit HTTPServer; // simplistic HTTP server interface uses SysUtils, Classes, {$IFDEF WIN32} Windows, WinSock, {$ELSE} FakeWinSock, Sockets, {$ENDIF} IRCServer; type TRequest=class(TThread) Socket: TSocket; ConnectingFrom: string; FileName: string; Parameters: TStringList; procedure Execute; override; procedure SendLn(S: string); end; TGame=record Created: TDateTime; Name, Password, Loc: string; HosterNickname, HosterAddress: string; GameID: Integer; end; var Games: array of TGame; GameCounter: Integer=0; procedure StartHTTPServer; implementation uses {$IFDEF WINDOWS} Windows, {$ENDIF} Base, Data, DateUtils; procedure CleanUpGames; var I, J: Integer; begin for I:=Length(Games)-1 downto 0 do if MinutesBetween(Games[I].Created, Now)>4 then begin for J:=I to Length(Games)-2 do Games[J]:=Games[J+1]; SetLength(Games, Length(Games)-1); end; end; {$I mime.inc} procedure TRequest.Execute; var Buffer, S, Headers, Body: string; I, J, N, R, Bytes: Integer; User: TUser; Game: TGame; begin try Buffer:=''; repeat R:=ioctlsocket(Socket, FIONREAD, Bytes); if R=SOCKET_ERROR then begin Log('[HTTP] '+ConnectingFrom+' Connection error ('+WinSockErrorCodeStr(WSAGetLastError)+').'); Exit; end; if Bytes=0 then begin Sleep(10); Continue; end; SetLength(S, Bytes); R:=recv(Socket, S[1], Bytes, 0); if(R=0)or(R=SOCKET_ERROR)then begin Log('[HTTP] '+ConnectingFrom+' Connection error ('+WinSockErrorCodeStr(WSAGetLastError)+').'); Exit; end; SetLength(S, R); Buffer := Buffer + S; until Copy(Buffer, Length(Buffer)-3, 4)=#13#10#13#10; // ends with an empty line GetLine(Buffer, S); Log('[HTTP] '+ConnectingFrom+' '+S); if Copy(S, 1, 4)<>'GET ' then raise Exception.Create('Only GET requests are supported'); Delete(S, 1, 4); S:=Copy(S, 1, Pos(' ', S+' ')-1); if LowerCase(Copy(S, 1, 7))='http://' then begin Delete(S, 1, 7); Delete(S, 1, Pos('/', S)-1); end; if Copy(S, 1, 2)='//' then // workaround to some dumb bug begin Delete(S, 1, 2); Delete(S, 1, Pos('/', S)); end; while Copy(S, 1, 1)='/' do Delete(S, 1, 1); if Copy(S, 1, 15)='wormageddonweb/' then Delete(S, 1, 15); FileName:=Copy(S, 1, Pos('?', S+'?')-1); Delete(S, 1, Pos('?', S)); S:=S+'&'; Parameters:=TStringList.Create; Parameters.NameValueSeparator:='='; while S<>'' do begin Parameters.Add(Copy(S, 1, Pos('&', S)-1)); Delete(S, 1, Pos('&', S)); end; //while GetLine(Buffer, S) do // WriteLn('> ' + S); Headers:='HTTP/1.0 200 OK'#13#10; Headers:=Headers+'X-Powered-By: MyWormNET'#13#10; Headers:=Headers+'X-Test: BlaBla'#13#10; Body:=''; if FileName='Login.asp' then begin if ConnectingFrom='127.0.0.1' then Body:='<CONNECT 127.0.0.1>' else Body:='<CONNECT '+ServerHost+'>'; end else if FileName='RequestChannelScheme.asp' then Body:='<SCHEME=Pf,Be>' else // Cmd=Create&Name=▀CyberShadow-MD&HostIP=cybershadow.no-ip.org&Nick=CyberShadow-MD&Pwd=123&Chan=AnythingGoes&Loc=40&Type=0 HTTP/1.0 if FileName='Game.asp' then if Parameters.Values['Cmd']='Create' then begin Inc(GameCounter); Game.Name:=Parameters.Values['Name']; if Length(Game.Name) > 29 then Game.Name := Copy(Game.Name, 1, 29); Game.Password:=Parameters.Values['Pwd']; Game.Loc:=Parameters.Values['Loc']; Game.GameID:=GameCounter; Game.Created:=Now; if IRCPort>0 then begin User:=nil; for I:=0 to Length(Users)-1 do // this check also matches the IP address if (Users[I].Nickname=Parameters.Values['Nick']){and(Users[I].ConnectingFrom=ConnectingFrom)} then User:=Users[I]; if User=nil then raise Exception.Create('Can''t find IRC user "'+Parameters.Values['Nick']+'".'); //if(Pos('http://wormnat.xeon.cc/', Parameters.Values['HostIP'])<>0)or(User.ConnectingFrom='127.0.0.1')or(Copy(User.ConnectingFrom, ) then //Game.HosterAddress:=Parameters.Values['HostIP']; //else if Pos(':', Parameters.Values['HostIP'])>0 then Game.HosterAddress:=User.ConnectingFrom + Copy(Parameters.Values['HostIP'], Pos(':', Parameters.Values['HostIP']), 1000) else Game.HosterAddress:=User.ConnectingFrom; // auto-detect the user's external address Game.HosterNickname:=User.Nickname; end else begin Game.HosterNickname:=Parameters.Values['Nick']; Game.HosterAddress:=Parameters.Values['HostIP']; end; SetLength(Games, Length(Games)+1); Games[Length(Games)-1]:=Game; for I:=0 to Length(Users)-1 do if Users[I].InChannel then Users[I].SendLn(':'+ServerHost+' NOTICE '+IRCChannel+' :'+Game.HosterNickname+' has created a game ("'+Game.Name+'").'); EventLog(Game.HosterNickname+' ('+Game.HosterAddress+') has created a game ("'+Game.Name+'").'); Headers:=Headers+'SetGameId: : '+IntToStr(Game.GameID)+#13#10; Body:='<NOTHING>'; end else if Parameters.Values['Cmd']='Close' then begin N:=-1; for I:=0 to Length(Games)-1 do if IntToStr(Games[I].GameID)=Parameters.Values['GameID'] then begin Game:=Games[I]; for J:=I to Length(Games)-2 do Games[J]:=Games[J+1]; SetLength(Games, Length(Games)-1); N:=I; end; if N=-1 then //raise Exception.Create('No such game'); Log('Trying to close a non-existant game ('+Parameters.Values['GameID']+')') else begin for I:=0 to Length(Users)-1 do if Users[I].InChannel then Users[I].SendLn(':'+ServerHost+' NOTICE '+IRCChannel+' :'+Game.HosterNickname+'''s game "'+Game.Name+'" has closed.'); EventLog(Game.HosterNickname+'''s game "'+Game.Name+'" has closed.'); end; end else if Parameters.Values['Cmd']='Failed' then // ? begin Body:='<NOTHING>'; end else raise Exception.Create('Unknown game command - '+Parameters.Values['Cmd']) else if FileName='GameList.asp' then begin CleanUpGames; Body:=Body+'<GAMELISTSTART>'#13#10; for I:=0 to Length(Games)-1 do with Games[I] do Body:=Body+'<GAME '+Name+' '+HosterNickname+' '+HosterAddress+' '+Loc+' 1 0 '+IntToStr(GameID)+' 0><BR>'#13#10; Body:=Body+'<GAMELISTEND>'#13#10; end else if FileName='UpdatePlayerInfo.asp' then // ignore else begin for I:=Length(FileName) downto 1 do if(FileName[I]='/')and(PathDelim='\') then FileName[I]:=PathDelim else if FileName[I]='%' then begin FileName[I]:=Chr(StrToInt('$'+Copy(FileName, I+1, 2))); Delete(FileName, I+1, 2); end; if Pos('..', FileName)+Pos(PathDelim+PathDelim, FileName)<>0 then raise Exception.Create('hmm hmm hmm'); if(FileName='')or(FileName[Length(FileName)]=PathDelim)then FileName:=FileName+'index.html'; if FileExists('wwwroot'+PathDelim+FileName) then begin Log('[HTTP] '+ConnectingFrom+' Sending file '+FileName); S:='application/octet-stream'; for I:=1 to High(MimeTypes) do if '.'+MimeTypes[I].Extension=ExtractFileExt(FileName) then S:=MimeTypes[I].MimeType; Headers:=Headers+'Content-Type: '+S+#13#10; Body:=GetFile('wwwroot'+PathDelim+FileName); end else raise Exception.Create('"File" not found - '+FileName); end; Headers:=Headers+'Content-Length: '+IntToStr(Length(Body))+#13#10; S:=Headers+#13#10+Body; SendLn(S); Parameters.Free; except on E: Exception do try Log('[HTTP] Error with '+ConnectingFrom+' : '+E.Message); S:=Headers+'Error: : '+E.Message+#13#10#13#10+'Error: '+E.Message; SendLn(S); except end; end; closesocket(Socket); FreeOnTerminate:=True; end; procedure TRequest.SendLn(S: string); begin //WriteLn('> '+S); S:=S+#13#10; if send(Socket, S[1], Length(S), 0)<>Length(S) then Log('[HTTP > Failed ('+WinSockErrorCodeStr(WSAGetLastError)+') ]'); end; // *************************************************************** function MainProc(Nothing: Pointer): Integer; stdcall; var m_socket, AcceptSocket: TSocket; service, incoming: TSockAddrIn; T: Integer; Request: TRequest; begin Result:=0; m_socket := socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); service.sin_family := AF_INET; service.sin_addr.s_addr := inet_addr( '0.0.0.0' ); service.sin_port := htons( HTTPPort ); if bind(m_socket, service, sizeof(service))=SOCKET_ERROR then begin Log('[HTTP] bind error ('+WinSockErrorCodeStr(WSAGetLastError)+').'); Exit; end; if listen( m_socket, 50 )=SOCKET_ERROR then begin Log('[HTTP] bind error ('+WinSockErrorCodeStr(WSAGetLastError)+').'); Exit; end; Log('[HTTP] Listening on port '+IntToStr(HTTPPort)+'.'); repeat T:=SizeOf(incoming); AcceptSocket := accept( m_socket, @incoming, @T ); if AcceptSocket<>INVALID_SOCKET then begin T:=SizeOf(incoming); WriteLn('[HTTP] Connection established from '+inet_ntoa(incoming.sin_addr)); Request:=TRequest.Create(True); Request.Socket:=AcceptSocket; Request.ConnectingFrom:=inet_ntoa(incoming.sin_addr); Request.Resume; end else Sleep(1); until False; end; var ThreadID: Cardinal = 0; procedure StartHTTPServer; begin if ThreadID=0 then // start only once CreateThread(nil, 0, @MainProc, nil, 0, ThreadID); end; end.
unit uFrmInstagram; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.StdCtrls, FMX.Layouts, FMX.Controls.Presentation, System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions, FMX.MediaLibrary, FMX.Platform, System.Messaging; type TForm1 = class(TForm) ToolBar1: TToolBar; btnPhoto: TButton; Button2: TButton; ToolBar2: TToolBar; Button1: TButton; Layout1: TLayout; Rectangle1: TRectangle; SpeedButton1: TSpeedButton; Path1: TPath; ImgInsta: TImage; ActionList1: TActionList; TakePhotoFromCameraAction1: TTakePhotoFromCameraAction; TakePhotoFromLibraryAction1: TTakePhotoFromLibraryAction; Button3: TButton; ShowShareSheetAction1: TShowShareSheetAction; procedure TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap); procedure TakePhotoFromLibraryAction1DidFinishTaking(Image: TBitmap); procedure Button3Click(Sender: TObject); procedure ShowShareSheetAction1BeforeExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } procedure DoDidFinish(Image: TBitmap); procedure DoMessageListener(const Sender: TObject; const M: TMessage); end; var Form1: TForm1; implementation {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.NmXhdpiPh.fmx ANDROID} {$R *.SmXhdpiPh.fmx ANDROID} { TForm1 } procedure TForm1.Button3Click(Sender: TObject); var Service: IFMXCameraService; Params: TParamsPhotoQuery; begin if TPlatformServices.Current.SupportsPlatformService(IFMXCameraService, Service) then begin Params.Editable := True; // Specifies whether to save a picture to device Photo Library Params.NeedSaveToAlbum := True; Params.RequiredResolution := TSize.Create(640, 640); Params.OnDidFinishTaking := DoDidFinish; Service.TakePhoto(Button3, Params); end else ShowMessage('This device does not support the camera service'); end; procedure TForm1.DoDidFinish(Image: TBitmap); begin ImgInsta.Bitmap.Assign(Image); end; procedure TForm1.DoMessageListener(const Sender: TObject; const M: TMessage); begin if M is TMessageDidFinishTakingImageFromLibrary then ImgInsta.Bitmap.Assign(TMessageDidFinishTakingImageFromLibrary(M).Value); end; procedure TForm1.FormCreate(Sender: TObject); begin TMessageManager.DefaultManager.SubscribeToMessage( TMessageDidFinishTakingImageFromLibrary, DoMessageListener); end; procedure TForm1.ShowShareSheetAction1BeforeExecute(Sender: TObject); begin ShowShareSheetAction1.Bitmap.Assign(ImgInsta.Bitmap); end; procedure TForm1.TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap); begin DoDidFinish(Image); end; procedure TForm1.TakePhotoFromLibraryAction1DidFinishTaking(Image: TBitmap); begin DoDidFinish(Image); end; end.
unit HomeLibrary_AboutForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, HomeLibrary_Version, MySkinEngine, StdCtrls, MySkinCtrls, MySkinButtons, MySkinGroups, MySkinBBLabel; type { TAboutForm } TAboutForm = class(TMyForm) sbOk: TMySkinButton; sgbInfo: TMySkinGroupBox; slbName: TMySkinLabel; slbAuthor: TMySkinLabel; slbVersion: TMySkinLabel; slbDate: TMySkinLabel; slbMail: TMySkinLabel; slbSupport: TMySkinLabel; slbThirdParty: TMySkinLabel; sbbSQLite: TMySkinBBLabel; sbbSkinsLibrary: TMySkinBBLabel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var AboutForm: TAboutForm; implementation {$R *.dfm} uses HomeLibrary_MainForm; { TAboutForm } procedure TAboutForm.FormCreate(Sender: TObject); begin Color := MainForm.stMain.ContentColor; slbVersion.Caption := AIMPVersionFullString; slbDate.Caption := AIMPVersionDate; sbbSQLite.Font.Color := MainForm.stMain.StyleLabel.ColorText; sbbSkinsLibrary.Font.Color := MainForm.stMain.StyleLabel.ColorText; end; end.
{ SuperMaximo GameLibrary : SuperMaximo SDL unit by Max Foster License : http://creativecommons.org/licenses/by/3.0/ } { Thanks for your interest in the SuperMaximo GameLibrary! I just want to discuss two things that are used across many of the units in the library. BANKS ===== For each class, there is a 'bank' associated with it. This allows for quick and easy prototyping as it means you don't need to manage instances of objects yourself. Taking TTexture as an example, to create and display an instance's using the banks, you can do: addTexture("myTexture", <other args>); writeln(texture("myTexture")^.name); destroyTexture("myTexture"); //OR destroyAllTextures; The bank is indexed which helps speed up the bank search, but I still do not recommend using it in a CPU intensive game! RELATIVE ======== Some methods in some classes (especially in GameObject) have a 'relative' parameter, which defaults to FALSE. If this value is set to TRUE then the amount being passed will be multiplied by a compensation value and then added to the value that you are modifying. For example, if you wanted an instance of GameObject, with X position 0, to get to position 60 in exactly one second, with an 'idealFramerate' of 60 (see the Display unit), regardless of a computers processing speed you can do: myGameObject.setX(0); //Set the position absolutely myGameObject.setX(1, true); //Add 1*<frame compensation> to the X value every frame This is crucial to maintaining a good gameplay experience, because it means no matter what computer you play the game on, the gameplay will remain the same speed, no matter what the video framerate is! } unit SMSDL; interface uses SDL; const SDL_INIT_TIMER = $00000001; SDL_INIT_AUDIO = $00000010; SDL_INIT_VIDEO = $00000020; SDL_INIT_CDROM = $00000100; SDL_INIT_JOYSTICK = $00000200; SDL_INIT_NOPARACHUTE = $00100000; SDL_INIT_EVENTTHREAD = $01000000; SDL_INIT_EVERYTHING = $0000FFFF; procedure initSDL(flags : Uint32); procedure quitSDL; procedure wait(time : longint); implementation procedure initSDL(flags : Uint32); begin if (flags <> SDL_INIT_NOPARACHUTE) then SDL_Init(flags or SDL_INIT_NOPARACHUTE) else SDL_Init(SDL_INIT_NOPARACHUTE); end; procedure quitSDL; begin SDL_Quit; end; procedure wait(time : longint); begin SDL_Delay(time); end; end.
UNIT UBackTracking; INTERFACE USES UStructures,UEquipes,UPointeurs,UAffichage,UFonctions; FUNCTION Match (VAR c1 : chapeau; VAR c2 : chapeau; i : INTEGER; VAR ptrTab : listeAdv; VAR Blacklist : listeAdv; VAR t : tirage; VAR flag:BOOLEAN): INTEGER; PROCEDURE BackTracking(VAR c1 : chapeau;VAR c2 : chapeau;VAR ptrTab : listeAdv; i : INTEGER; VAR Blacklist : listeAdv; VAR t : tirage); IMPLEMENTATION { * Procedure de retour sur trace pour régler les conflits * * c1,c2 les chapeaux d'équipes * i le numéro du tour où on doit régler le problème. Autrement dit ce sera i-1 car si titage imposssible au tour i alors problème au tour i-1 * prtTab le tableau des liste d'adversaire pour chaque tirage * Blacklist la liste des equipes qui mènent à des tirages impossibles * t le tableau des rencontres } PROCEDURE BackTracking(VAR c1 : chapeau;VAR c2 : chapeau;VAR ptrTab : listeAdv; i : INTEGER; VAR Blacklist : listeAdv; VAR t : tirage); BEGIN writeln('Entrez dans Backtracking'); ajouterDebut(t[i-1].e1,Blacklist[i-1]); IF @Blacklist[i-1]^.eq = @ptrTab[i-1]^.eq THEN writeln('meme adresse'); rajouterEquipe(c1,t[i-1].e1); writeln('Fin de backtracking'); END; FUNCTION Match (VAR c1 : chapeau; VAR c2 : chapeau; i : INTEGER; VAR ptrTab : listeAdv;VAR Blacklist : listeAdv; VAR t : tirage; VAR flag:BOOLEAN): INTEGER; VAR eSelec : equipe; adv : ptrNoeud; num,taille : INTEGER; BEGIN IF (NOT flag) THEN eSelec := selectionDeLEquipeDuC2(c2) // séléction d'une équipe du chapeau 2 ELSE BEGIN ptrTab[i] := supprimerListe(ptrTab[i]); writeln('BL apres supprimerListe'); afficherListe(Blacklist[i]); eSelec := t[i].e2; END; creerAdv(eSelec,Blacklist[i],ptrTab[i],c1); //création liste des adversaires IF ptrTab[i] <> Nil THEN BEGIN taille := longueur(ptrTab[i]); num := Random(taille) + 1; //séléction d'un élément aléatoire dans la liste d'adv new(adv); adv := parcourirListe(num,ptrTab[i]);//accès à l'élément num de la liste t[i].e1 := copierEq(adv^.eq); t[i].e2 := copierEq(eSelec); dispose(adv); effacerEquipe(t[i].e1,c1);// on retire du chapeau 1 l'équipe car elle a été tiré effacerEquipe(t[i].e2,c2);// on retire du chapeau 2 l'équipe car elle a été tiré flag := false; Match := i; END ELSE BEGIN BackTracking(c1,c2,ptrTab,i,Blacklist,t); flag:= TRUE; Match := i-2; END; END; END.
unit DesignScrollBox; interface uses Classes, Controls, Forms, Graphics; type TDesignScrollBox = class(TScrollBox) constructor Create(inOwner: TComponent); override; procedure AutoScrollInView(AControl: TControl); override; end; implementation { TDesignScrollBox } constructor TDesignScrollBox.Create(inOwner: TComponent); begin inherited; Align := alClient; HorzScrollBar.Tracking := true; VertScrollBar.Tracking := true; BevelInner := bvNone; BevelOuter := bvNone; BorderStyle := bsNone; Color := clWhite; end; procedure TDesignScrollBox.AutoScrollInView(AControl: TControl); begin // end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Gooch shader : Gooch shading is used to substitute photorealistic rendering by rendering that focuses on structore and shape of the object. Instead of usage of light and shadow, Gooch shading uses concept of warm and cool colors. Standard Blinn-Phong shading only modulates base color of the object. In Gooch shading intensity of diffuse lighting is used to determine how to blend warm and cold colors together. At this time only one light source is supported } unit VXS.GLSLGoochShader; interface //{$I VXScene.inc} uses System.Classes, VXS.Scene, VXS.CrossPlatform, VXS.BaseClasses, VXS.State, Winapi.OpenGL, Winapi.OpenGLext, VXS.OpenGL1x, VXS.Context, VXS.RenderContextInfo, VXS.VectorGeometry, VXS.Coordinates, VXS.TextureFormat, VXS.Color, VXS.Texture, VXS.Material, GLSL.Shader, VXS.CustomShader; //TVXCustomGLSLSimpleGoochShader // { Custom class for GLSLSimpleGoochShader. } type TVXCustomGLSLSimpleGoochShader = class(TVXCustomGLSLShader) private FDiffuseColor : TVXColor; FWarmColor : TVXColor; FCoolColor : TVXColor; FSpecularColor : TVXColor; FAmbientColor : TVXColor; FDiffuseWarm : Single; FDiffuseCool : Single; FAmbientFactor : Single; FDiffuseFactor : Single; FSpecularFactor : Single; FBlendingMode: TVXBlendingModeEx; procedure SetDiffuseColor(AValue: TVXColor); procedure SetAmbientColor(AValue: TVXColor); procedure SetSpecularColor(AValue: TVXColor); procedure SetWarmColor(AValue: TVXColor); procedure SetCoolColor(AValue: TVXColor); protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; property DiffuseColor : TVXColor read FDiffuseColor Write setDiffuseColor; property WarmColor : TVXColor read FWarmColor Write setWarmColor; property CoolColor : TVXColor Read FCoolColor Write setCoolColor; property SpecularColor : TVXColor Read FSpecularColor Write setSpecularColor; property AmbientColor : TVXColor Read FAmbientColor Write setAmbientColor; property WarmFactor : Single Read FDiffuseWarm Write FDiffuseWarm; property CoolFactor : Single Read FDiffuseCool Write FDiffuseCool; property AmbientFactor : Single Read FAmbientFactor Write FAmbientFactor; property DiffuseFactor : Single Read FDiffuseFactor Write FDiffuseFactor; property SpecularFactor : Single Read FSpecularFactor Write FSpecularFactor; property BlendingMode: TVXBlendingModeEx read FBlendingMode write FBlendingMode default bmxOpaque; end; type TVXSLSimpleGoochShader = class(TVXCustomGLSLSimpleGoochShader) published property DiffuseColor; property WarmColor; property CoolColor; property SpecularColor; property AmbientColor; property WarmFactor; property CoolFactor; property AmbientFactor; property DiffuseFactor; property SpecularFactor; end; implementation { TVXCustomGLSLSimpleGoochShader } constructor TVXCustomGLSLSimpleGoochShader.Create(AOwner: TComponent); begin inherited; with VertexProgram.Code do begin Clear; Add('varying vec3 vNormal; '); Add('varying vec3 lightVec; '); Add('varying vec3 viewVec; '); Add('varying vec3 ReflectVec; '); Add(' '); Add('void main() '); Add('{ '); Add(' gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; '); Add(' vec4 lightPos = gl_LightSource[0].position;'); Add(' vec4 vert = gl_ModelViewMatrix * gl_Vertex; '); Add(' vec3 normal = gl_NormalMatrix * gl_Normal; '); Add(' vNormal = normalize(normal); '); Add(' lightVec = vec3(lightPos - vert); '); Add(' ReflectVec = normalize(reflect(-lightVec, vNormal)); '); Add(' viewVec = -vec3(vert); '); Add('} '); end; with FragmentProgram.Code do begin Clear; Add('uniform vec4 SurfaceColor; '); Add('uniform vec4 WarmColor; '); Add('uniform vec4 CoolColor; '); Add('uniform vec4 SpecularColor; '); Add('uniform vec4 AmbientColor; '); Add('uniform float DiffuseWarm; '); Add('uniform float DiffuseCool; '); Add('uniform float AmbientFactor; '); Add('uniform float DiffuseFactor; '); Add('uniform float SpecularFactor; '); Add('varying vec3 vNormal; '); Add('varying vec3 lightVec; '); Add('varying vec3 viewVec; '); Add('varying vec3 ReflectVec; '); Add(' '); Add('void main() '); Add('{ '); Add('vec3 L = normalize(lightVec); '); Add('vec3 V = normalize(viewVec); '); Add('vec3 halfAngle = normalize(L + V); '); Add('float NdotL = (dot(L, vNormal) + 1.0) * 0.5; '); Add('float NdotH = clamp(dot(halfAngle, vNormal), 0.0, 1.0); '); Add('// "Half-Lambert" technique for more pleasing diffuse term '); Add('float diffuse = 0.5 * NdotL + 0.5; '); Add('vec3 nreflect = normalize(ReflectVec); '); Add('float specular = max(dot(nreflect, V), 0.0); '); Add('specular = pow(specular, 64.0); '); Add('vec4 kCool = min(CoolColor + DiffuseCool * SurfaceColor, 1.0); '); Add('vec4 kWarm = min(WarmColor + DiffuseWarm * SurfaceColor, 1.0); '); Add('vec4 Cgooch = mix(kWarm, kCool, diffuse); '); Add('vec3 result = AmbientFactor * AmbientColor.rgb + DiffuseFactor * Cgooch.rgb + SpecularColor.rgb * SpecularFactor *specular; '); Add('gl_FragColor = vec4(result,SurfaceColor.a); '); Add('} '); end; // Initial stuff. FDiffuseColor := TVXColor.Create(self); FDiffuseColor.SetColor(0.75,0.75,0.75,1.0); FWarmColor := TVXColor.Create(self); FWarmColor.SetColor(0.88,0.81,0.49,1.0); FCoolColor := TVXColor.Create(self); FCoolColor.SetColor(0.58,0.10,0.76,1.0); FAmbientColor := TVXColor.Create(self); FAmbientColor.SetColor(0.3,0.3,0.3,1.0); FSpecularColor := TVXColor.Create(self); FSpecularColor.SetColor(1.0,1.0,1.0,1.0); FDiffuseWarm := 0.55; FDiffuseCool := 0.30; FAmbientFactor := 1.0; FDiffuseFactor :=0.8; FSpecularFactor :=0.9; FBlendingMode:=bmxOpaque; end; destructor TVXCustomGLSLSimpleGoochShader.Destroy; begin FDiffuseColor.Free; FWarmColor.Free; FCoolColor.Free; FSpecularColor.Free; FAmbientColor.Free; inherited; end; procedure TVXCustomGLSLSimpleGoochShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject); begin GetGLSLProg.UseProgramObject; param['SurfaceColor'].AsVector4f := FDiffuseColor.Color; param['WarmColor'].AsVector4f := FWarmColor.Color; param['CoolColor'].AsVector4f := FCoolColor.Color; param['AmbientColor'].AsVector4f := FAmbientColor.Color; param['SpecularColor'].AsVector4f := FSpecularColor.Color; param['DiffuseWarm'].AsVector1f := FDiffuseWarm; param['DiffuseCool'].AsVector1f := FDiffuseCool; param['AmbientFactor'].AsVector1f := FAmbientFactor; param['DiffuseFactor'].AsVector1f := FDiffuseFactor; param['SpecularFactor'].AsVector1f := FSpecularFactor; // glPushAttrib(GL_COLOR_BUFFER_BIT); ApplyBlendingModeEx(FBlendingMode); // glEnable(GL_BLEND); // gl.BlendFunc(cGLBlendFunctionToGLEnum[FBlendSrc],cGLBlendFunctionToGLEnum[FBlendDst]); end; function TVXCustomGLSLSimpleGoochShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean; begin gl.ActiveTexture(GL_TEXTURE0_ARB); GetGLSLProg.EndUseProgramObject; UnApplyBlendingModeEx; // glPopAttrib; Result := False; end; procedure TVXCustomGLSLSimpleGoochShader.SetDiffuseColor(AValue: TVXColor); begin FDiffuseColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLSimpleGoochShader.SetAmbientColor(AValue: TVXColor); begin FAmbientColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLSimpleGoochShader.SetSpecularColor(AValue: TVXColor); begin FSpecularColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLSimpleGoochShader.SetWarmColor(AValue: TVXColor); begin FWarmColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLSimpleGoochShader.SetCoolColor(AValue: TVXColor); begin FCoolColor.DirectColor := AValue.Color; end; end.
unit mrConfigLookupSvr; interface uses sysutils, classes, Provider, DBClient, DB, Variants, ADODB; type TmrCommandButton = (cbNew, cbOpen, cbDelete,cbClear); TmrCommandButtons = set of TmrCommandButton; TmrRecordType = (rtEnabled, rtDisabled, rtBoth); TmrRecordTypes = set of TmrRecordType; TmrConfigLookupSvr = class(TComponent) private FCommandButtons: TmrCommandButtons; FConnectionSourceName: String; FDataSetProvider: TDataSetProvider; FFchClassName: String; FKeyFieldName: String; FListFieldNames: TStringList; FProviderSourceName: String; FRecordTypes: TmrRecordTypes; FTableNamePrefix: String; { Eventos } FOnAfterGetRecords: TRemoteEvent; FOnBeforeGetRecords: TRemoteEvent; FOnGetDataSetProperties: TGetDSProps; procedure SetDataSetProvider(const Value: TDataSetProvider); function GetLisTmrCommandButtons: String; function GetListFieldNames(ListFieldNames: TStringList): String; procedure SetListFieldNames(const Value: TStringList); procedure DoGetDataSetProperties(Sender: TObject; DataSet: TDataSet; out Properties: OleVariant); procedure DoBeforeGetRecords(Sender: TObject; var OwnerData: OleVariant); procedure DoAfterGetRecords(Sender: TObject; var OwnerData: OleVariant); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property CommandButtons: TmrCommandButtons read FCommandButtons write FCommandButtons; property ConnectionSourceName: String read FConnectionSourceName write FConnectionSourceName; property DataSetProvider: TDataSetProvider read FDataSetProvider write SetDataSetProvider; property FchClassName: String read FFchClassName write FFchClassName; property KeyFieldName: String read FKeyFieldName write FKeyFieldName; property ListFieldNames: TStringList read FListFieldNames write SetListFieldNames; property ProviderSourceName: String read FProviderSourceName write FProviderSourceName; property RecordTypes: TmrRecordTypes read FRecordTypes write FRecordTypes; property TableNamePrefix: String read FTableNamePrefix write FTableNamePrefix; property OnAfterGetRecords: TRemoteEvent read FOnAfterGetRecords write FOnAfterGetRecords; property OnBeforeGetRecords: TRemoteEvent read FOnBeforeGetRecords write FOnBeforeGetRecords; property OnGetDataSetProperties: TGetDSProps read FOnGetDataSetProperties write FOnGetDataSetProperties; end; procedure Register; implementation uses uSQLFunctions, uMRSQLParam; { TmrConfigLookupSvr } procedure Register; begin RegisterComponents('MultiTierLib', [TmrConfigLookupSvr]); end; procedure TmrConfigLookupSvr.SetListFieldNames(const Value: TStringList); begin FListFieldNames.Assign(Value); end; constructor TmrConfigLookupSvr.Create(AOwner: TComponent); begin inherited Create(AOwner); FListFieldNames := TStringList.Create; end; destructor TmrConfigLookupSvr.Destroy; begin FListFieldNames.Free; inherited Destroy; end; function TmrConfigLookupSvr.GetLisTmrCommandButtons: String; begin Result := ''; if cbNew in FCommandButtons then Result := Result + 'CBNEW;'; if cbOpen in FCommandButtons then Result := Result + 'CBOPEN'; if cbDelete in FCommandButtons then Result := Result + 'CBDELETE'; if cbClear in FCommandButtons then Result := Result + 'CBCLEAR'; end; procedure TmrConfigLookupSvr.DoAfterGetRecords(Sender: TObject; var OwnerData: OleVariant); begin if OwnerData <> '' then TADOQuery(FDataSetProvider.DataSet).SQL.Text := OwnerData; if Assigned(FOnAfterGetRecords) then OnAfterGetRecords(Self, OwnerData); end; procedure TmrConfigLookupSvr.DoBeforeGetRecords(Sender: TObject; var OwnerData: OleVariant); var sOldSQL: String; Where: TMRSQLParam; begin try sOldSQL := TADOQuery(FDataSetProvider.DataSet).SQL.Text; Where := TMRSQLParam.Create; Where.ParamString := OwnerData; if Assigned(FOnBeforeGetRecords) then OnBeforeGetRecords(Self, OwnerData) else OwnerData := Where.GetWhereSQL; TADOQuery(FDataSetProvider.DataSet).SQL.Text := ChangeWhereClause(TADOQuery(FDataSetProvider.DataSet).SQL.Text, OwnerData, True); OwnerData := sOldSQL; finally FreeAndNil(Where); end; end; { TmrConfigLookupSvr } procedure TmrConfigLookupSvr.DoGetDataSetProperties(Sender: TObject; DataSet: TDataSet; out Properties: OleVariant); var ListFieldNames: OleVariant; begin Properties := VarArrayCreate([0, 5], varVariant); Properties[0] := VarArrayOf(['ConnectionSourceName', FConnectionSourceName, True]); Properties[1] := VarArrayOf(['ProviderSourceName', FProviderSourceName, True]); Properties[2] := VarArrayOf(['FchClassName', FFchClassName, True]); Properties[3] := VarArrayOf(['KeyFieldName', FKeyFieldName, True]); if Assigned(FListFieldNames) then ListFieldNames := GetListFieldNames(FListFieldNames); Properties[4] := VarArrayOf(['ListFieldNames', ListFieldNames, True]); Properties[5] := VarArrayOf(['CommandButtons', GetLisTmrCommandButtons, True]); if Assigned(FOnGetDataSetProperties) then OnGetDataSetProperties(Self, DataSet, Properties); end; function TmrConfigLookupSvr.GetListFieldNames(ListFieldNames: TStringList): String; var I: Integer; begin Result := ''; for I := 0 to ListFieldNames.Count-1 do Result := Result + ListFieldNames[I] + ';'; end; procedure TmrConfigLookupSvr.SetDataSetProvider(const Value: TDataSetProvider); begin FDataSetProvider := Value; with FDataSetProvider do if Assigned(FDataSetProvider) then begin OnGetDataSetProperties := DoGetDataSetProperties; BeforeGetRecords := DoBeforeGetRecords; AfterGetRecords := DoAfterGetRecords; end; end; end.
unit fre_db_persistance_common; { (§LIC) (c) Autor,Copyright Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch FirmOS Business Solutions GmbH www.openfirmos.org New Style BSD Licence (OSI) Copyright (c) 2001-2013, FirmOS Business Solutions GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <FirmOS Business Solutions GmbH> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (§LIC_END) } {$mode objfpc}{$H+} {$modeswitch nestedprocvars} // VOLATILE Objects are not in WAL (or Cluster) (node local) {-$DEFINE DEBUG_STORELOCK} // Debug Storelock on Commit {-$DEFINE DEBUG_SUBOBJECTS_STORED} // Debug Storelock on Commit {-$DEFINE DEBUG_CONSOLE_DUMP_TRANS} // Debuglog the in transaction final updated object {$DEFINE DEBUG_OFFENDERS} interface uses Classes,contnrs,SysUtils,FRE_SYSTEM,FRE_DB_COMMON,FRE_DB_INTERFACE,FRE_DB_CORE,FOS_ARRAYGEN,FOS_GENERIC_SORT,FOS_TOOL_INTERFACES,FOS_AlignedArray,FOS_REDBLACKTREE_GEN, fos_art_tree,fos_sparelistgen; type TFRE_DB_Persistance_Collection=class; { TFRE_DB_IndexValueStore } TFRE_DB_IndexValueStore=class private FOBJArray : TFRE_DB_GUIDArray; procedure InternalCheck; public function Exists (const guid : TFRE_DB_GUID) : boolean; function Add (const objuid : TFRE_DB_GUID) : boolean; procedure StreamToThis (const stream:TStream); procedure LoadFromThis (const stream:TStream ; const coll: TFRE_DB_PERSISTANCE_COLLECTION); function ObjectCount : NativeInt; procedure AppendObjectUIDS (var uids: TFRE_DB_GUIDArray; const ascending: boolean; var down_counter, up_counter: NativeInt; const max_count: Nativeint); function RemoveUID (const guid : TFRE_DB_GUID) : boolean; constructor create ; destructor Destroy ;override; end; { TFRE_DB_MM_Index } TFRE_DB_MM_IndexClass = class of TFRE_DB_MM_Index; TFRE_DB_MM_Index=class private type tvaltype = (val_NULL,val_ZERO,val_VAL,val_NEG); protected FIndex : TFRE_ART_TREE; FIndexName : TFRE_DB_NameType; FUniqueName : TFRE_DB_NameType; FFieldname : TFRE_DB_NameType; FUniqueFieldname : TFRE_DB_NameType; FFieldType : TFRE_DB_FIELDTYPE; FUnique : Boolean; FAllowNull : Boolean; FUniqueNullVals : Boolean; FIsADomainIndex : Boolean; { the index key gets prefixed with a domain uid, thus is per domaind id unique } FCollection : TFRE_DB_PERSISTANCE_COLLECTION_BASE; procedure _InternalCheckAdd (const key: PByte ; const keylen : Nativeint ; const isNullVal,isUpdate : Boolean ; const obj_uid : TFRE_DB_GUID); procedure _InternalCheckDel (const key: PByte ; const keylen : Nativeint ; const isNullVal : Boolean ; const obj_uid : TFRE_DB_GUID); procedure _InternalAddGuidToValstore (const key: PByte ; const keylen: Nativeint; const isNullVal: boolean; const uid: TFRE_DB_GUID); procedure _InternalRemoveGuidFromValstore (const key: PByte ; const keylen: Nativeint; const isNullVal: boolean; const uid: TFRE_DB_GUID); function GetStringRepresentationOfTransientKey (const isnullvalue:boolean ; const key: PByte ; const keylen: Nativeint ): String; function FetchIndexedValsTransformedKey (var obj : TFRE_DB_GUIDArray ; const key: PByte ; const keylen : Nativeint):boolean; procedure ForAllIndexedValsTransformedKeys (var uids : TFRE_DB_GUIDArray ; const mikey,makey : PByte ; const milen,malen : NativeInt ; const ascending: boolean ; const max_count : NativeInt=-1 ; skipfirst : NativeInt=0); procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint); virtual; abstract; procedure TransformToBinaryComparableDomain (const domid_field: TFRE_DB_FIELD; const fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint); class procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint ; const is_casesensitive : boolean ; const invert_key : boolean = false); virtual; abstract; function CompareTransformedKeys (const key1,key2: PByte ; const keylen1,keylen2 : Nativeint) : boolean; procedure StreamHeader (const stream: TStream);virtual; procedure StreamToThis (const stream: TStream);virtual; procedure StreamIndex (const stream: TStream);virtual; function GetIndexDefinitionObject : IFRE_DB_Object ;virtual ; function GetIndexDefinition : TFRE_DB_INDEX_DEF; virtual; procedure LoadIndex (const stream: TStream ; const coll : TFRE_DB_PERSISTANCE_COLLECTION);virtual; class function CreateFromStream (const stream: TStream ; const coll : TFRE_DB_PERSISTANCE_COLLECTION):TFRE_DB_MM_Index; class function CreateFromDef (const def : TFRE_DB_INDEX_DEF ; const coll : TFRE_DB_PERSISTANCE_COLLECTION):TFRE_DB_MM_Index; class procedure InitializeNullKey ; virtual ; abstract; function _IndexIsFullUniqe : Boolean; function _GetIndexStringSpec : String; public class function GetIndexClassForFieldtype (const fieldtype: TFRE_DB_FIELDTYPE ; var idxclass: TFRE_DB_MM_IndexClass): TFRE_DB_Errortype; class procedure GetKeyLenForFieldtype (const fieldtype: TFRE_DB_FIELDTYPE ; var FixedKeyLen : NativeInt);inline; constructor Create (const idx_name,fieldname: TFRE_DB_NameType ; const fieldtype : TFRE_DB_FIELDTYPE ; const unique : boolean ; const collection : TFRE_DB_PERSISTANCE_COLLECTION_BASE;const allow_null : boolean;const unique_null:boolean ; const domain_idx : boolean); destructor Destroy ; override; function Indexname : TFRE_DB_NameType; function Uniquename : PFRE_DB_NameType; procedure FieldTypeIndexCompatCheck (fld:TFRE_DB_FIELD); virtual; abstract; function NullvalueExists (var vals : TFRE_DB_IndexValueStore):boolean; virtual ; abstract; function NullvalueExistsForObject (const obj : TFRE_DB_Object):boolean; procedure IndexAddCheck (const obj : TFRE_DB_Object; const check_only : boolean); virtual; // Object is added procedure IndexUpdCheck (const new_obj,old_obj : TFRE_DB_Object; const check_only : boolean); virtual; // Object gets changed procedure IndexDelCheck (const obj,new_obj : TFRE_DB_Object; const check_only : boolean); virtual; // Object gets deleted function SupportsDataType (const typ : TFRE_DB_FIELDTYPE):boolean; virtual ; abstract; function SupportsIndexType (const ix_type : TFRE_DB_INDEX_TYPE):boolean; function SupportsStringQuery : boolean; virtual ; abstract; function SupportsSignedQuery : boolean; virtual ; abstract; function SupportsUnsignedQuery : boolean; virtual ; abstract; function SupportsRealQuery : boolean; virtual ; abstract; function IsUnique : Boolean; function IsDomainIndex : boolean; procedure AppendAllIndexedUids (var guids : TFRE_DB_GUIDArray ; const ascending: boolean ; const max_count: NativeInt; skipfirst: NativeInt); procedure AppendAllIndexedUidsDomain (var guids : TFRE_DB_GUIDArray ; const ascending: boolean ; const max_count: NativeInt; skipfirst: NativeInt ; const domid_field: TFRE_DB_FIELD); function IndexTypeTxt : String; function IndexedCount (const unique_values : boolean): NativeInt; function IndexIsFullyUnique : Boolean; procedure FullClearIndex ; procedure FullReindex ; end; { TFRE_DB_UnsignedIndex } TFRE_DB_UnsignedIndex=class(TFRE_DB_MM_Index) private class var nullkey : Array [0..16] of Byte; // Nullkey is short in every domain nullkeylen : NativeInt; protected class procedure InitializeNullKey ; override; public procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint); override; class procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint ; const is_cassensitive : boolean ; const invert_key : boolean = false); override; procedure SetBinaryComparableKey (const keyvalue:qword ; const key_target : PByte ; var key_len : NativeInt ; const is_null : boolean); class procedure SetBinaryComparableKey (const keyvalue:qword ; const key_target : PByte ; var key_len : NativeInt ; const is_null : boolean ; const FieldType : TFRE_DB_FIELDTYPE; const invert_key : boolean = false); constructor CreateStreamed (const stream : TStream ; const idx_name, fieldname: TFRE_DB_NameType ; const fieldtype : TFRE_DB_FIELDTYPE ; const unique : boolean ; const collection : TFRE_DB_PERSISTANCE_COLLECTION;const allow_null:boolean;const unique_null:boolean; const domain_idx : boolean); procedure FieldTypeIndexCompatCheck (fld:TFRE_DB_FIELD ); override; function NullvalueExists (var vals: TFRE_DB_IndexValueStore): boolean; override; function SupportsDataType (const typ: TFRE_DB_FIELDTYPE): boolean; override; procedure ForAllIndexedUnsignedRange (const min, max: QWord; var guids : TFRE_DB_GUIDArray ; const ascending: boolean ; const min_is_null : boolean = false ; const max_is_max : boolean = false ; const max_count : NativeInt=-1 ; skipfirst : NativeInt=0); function SupportsSignedQuery : boolean; override; function SupportsUnsignedQuery : boolean; override; function SupportsStringQuery : boolean; override; function SupportsRealQuery : boolean; override; end; { TFRE_DB_SignedIndex } TFRE_DB_SignedIndex=class(TFRE_DB_MM_Index) private class var nullkey : Array [0..16] of Byte; // Nullkey is short in every domain nullkeylen : NativeInt; protected class procedure InitializeNullKey ; override; public procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint); override; class procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint ; const is_casesensitive : boolean ; const invert_key : boolean = false); override; procedure SetBinaryComparableKey (const keyvalue:int64 ; const key_target : PByte ; var key_len : NativeInt ; const is_null : boolean); class procedure SetBinaryComparableKey (const keyvalue:int64 ; const key_target : PByte ; var key_len : NativeInt ; const is_null : boolean ; const FieldType : TFRE_DB_FIELDTYPE ; const invert_key : boolean = false); constructor CreateStreamed (const stream: TStream; const idx_name, fieldname: TFRE_DB_NameType; const fieldtype: TFRE_DB_FIELDTYPE; const unique: boolean; const collection: TFRE_DB_PERSISTANCE_COLLECTION; const allow_null: boolean; const unique_null: boolean; const domain_idx : boolean); procedure FieldTypeIndexCompatCheck (fld:TFRE_DB_FIELD ); override; function NullvalueExists (var vals: TFRE_DB_IndexValueStore): boolean; override; function SupportsDataType (const typ: TFRE_DB_FIELDTYPE): boolean; override; function SupportsSignedQuery : boolean; override; function SupportsUnsignedQuery : boolean; override; function SupportsStringQuery : boolean; override; function SupportsRealQuery : boolean; override; procedure ForAllIndexedSignedRange (const min, max: int64; var guids : TFRE_DB_GUIDArray ; const ascending: boolean ; const min_is_null : boolean = false ; const max_is_max : boolean = false ; const max_count : NativeInt=-1 ; skipfirst : NativeInt=0); end; { TFRE_DB_RealIndex } TFRE_DB_RealIndex=class(TFRE_DB_MM_Index) { currently implemented via int64 * 10000 conversion (bad) -> TODO real floating point binary compare} private class var nullkey : Array [0..16] of Byte; // Nullkey is short in every domain nullkeylen : NativeInt; protected class procedure InitializeNullKey ; override; public procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint); override; class procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint ; const is_casesensitive : boolean ; const invert_key : boolean = false); override; procedure SetBinaryComparableKey (const keyvalue:Double ; const key_target : PByte ; var key_len : NativeInt ; const is_null : boolean); class procedure SetBinaryComparableKey (const keyvalue:Double ; const key_target : PByte ; var key_len : NativeInt ; const is_null : boolean ; const FieldType : TFRE_DB_FIELDTYPE ; const invert_key : boolean = false); constructor CreateStreamed (const stream: TStream; const idx_name, fieldname: TFRE_DB_NameType; const fieldtype: TFRE_DB_FIELDTYPE; const unique: boolean; const collection: TFRE_DB_PERSISTANCE_COLLECTION; const allow_null: boolean; const unique_null: boolean ; const domain_idx : boolean); procedure FieldTypeIndexCompatCheck (fld:TFRE_DB_FIELD ); override; function NullvalueExists (var vals: TFRE_DB_IndexValueStore): boolean; override; function SupportsDataType (const typ: TFRE_DB_FIELDTYPE): boolean; override; function SupportsSignedQuery : boolean; override; function SupportsUnsignedQuery : boolean; override; function SupportsStringQuery : boolean; override; function SupportsRealQuery : boolean; override; procedure ForAllIndexedRealRange (const min, max: Double; var guids : TFRE_DB_GUIDArray ; const ascending: boolean ; const min_is_null : boolean = false ; const max_is_max : boolean = false ; const max_count : NativeInt=-1 ; skipfirst : NativeInt=0); end; { TFRE_DB_TextIndex } TFRE_DB_TextIndex=class(TFRE_DB_MM_Index) //TODO Unicode Key Conversion private FCaseInsensitive : Boolean; class var nullkey : Array [0..16] of Byte; // Nullkey is short in every domain nullkeylen : NativeInt; protected procedure SetBinaryComparableKey (const keyvalue : TFRE_DB_String ; const key_target : PByte ; var key_len : NativeInt ; const is_null : boolean); class procedure SetBinaryComparableKey (const keyvalue : TFRE_DB_String ; const key_target : PByte ; var key_len : NativeInt ; const is_null : boolean ; const case_insensitive : boolean ; const invert_key : boolean = false); procedure StreamHeader (const stream: TStream);override; function GetIndexDefinitionObject : IFRE_DB_Object;override; function GetIndexDefinition : TFRE_DB_INDEX_DEF; override; class procedure InitializeNullKey ; override; public constructor Create (const idx_name,fieldname: TFRE_DB_NameType ; const fieldtype : TFRE_DB_FIELDTYPE ; const unique, case_insensitive : boolean ; const collection : TFRE_DB_PERSISTANCE_COLLECTION_BASE;const allow_null : boolean;const unique_null:boolean; const domain_idx : boolean); constructor CreateStreamed (const stream : TStream ; const idx_name, fieldname: TFRE_DB_NameType ; const fieldtype : TFRE_DB_FIELDTYPE ; const unique : boolean ; const collection : TFRE_DB_PERSISTANCE_COLLECTION;const allow_null : boolean;const unique_null:boolean; const domain_idx : boolean); procedure FieldTypeIndexCompatCheck (fld:TFRE_DB_FIELD ); override; function NullvalueExists (var vals: TFRE_DB_IndexValueStore): boolean; override; procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint); override; class procedure TransformToBinaryComparable (fld:TFRE_DB_FIELD ; const key: PByte ; var keylen : Nativeint ; const is_casesensitive :boolean ; const invert_key : boolean = false); override; function SupportsDataType (const typ: TFRE_DB_FIELDTYPE): boolean; override; function SupportsSignedQuery : boolean; override; function SupportsUnsignedQuery : boolean; override; function SupportsStringQuery : boolean; override; function SupportsRealQuery : boolean; override; function ForAllIndexedTextRange (const min, max: TFRE_DB_String; var guids : TFRE_DB_GUIDArray ; const ascending: boolean ; const min_is_null : boolean = false ; const max_is_max : boolean = false ; const max_count : NativeInt=-1 ; skipfirst : NativeInt=0 ; const only_count_unique_vals : boolean = false):boolean; function ForAllIndexPrefixString (const prefix : TFRE_DB_String; var guids : TFRE_DB_GUIDArray ; const index_name : TFRE_DB_NameType ; const ascending: boolean = true ; const max_count : NativeInt=0 ; skipfirst : NativeInt=0):boolean; end; { TFRE_DB_Persistance_Collection } TFRE_DB_Master_Data = class; TFRE_DB_Persistance_Collection=class(TFRE_DB_PERSISTANCE_COLLECTION_BASE) private FName : TFRE_DB_NameType; FUpperName : TFRE_DB_NameType; FMasterLink : TFRE_DB_Master_Data; FVolatile : Boolean; FGuidObjStore : TFRE_ART_TREE; FIndexStore : array of TFRE_DB_MM_INDEX; function IsVolatile : boolean; override; procedure AddIndex (const idx : TFRE_DB_MM_Index); procedure IndexAddCheck (const obj : TFRE_DB_Object;const check_only : boolean); procedure IndexUpdCheck (const new_obj, old_obj : TFRE_DB_Object;const check_only : boolean); procedure IndexDelCheck (const del_obj : TFRE_DB_Object;const check_only : boolean); procedure StoreInThisColl (const new_iobj : IFRE_DB_Object ; const checkphase : boolean); procedure UpdateInThisColl (const new_ifld,old_ifld : IFRE_DB_FIELD ; const old_iobj,new_iobj : IFRE_DB_Object ; const update_typ : TFRE_DB_ObjCompareEventType ; const in_child_obj : boolean ; const checkphase : boolean); procedure DeleteFromThisColl (const del_iobj: IFRE_DB_Object ; const checkphase : boolean); function DefineIndexOnFieldReal (const checkonly : boolean ; const FieldName : TFRE_DB_NameType ; const FieldType : TFRE_DB_FIELDTYPE ; const unique : boolean ; const ignore_content_case: boolean ; const index_name : TFRE_DB_NameType ; const allow_null_value : boolean; const unique_null_values: boolean ; const domain_index : boolean ; var prelim_index : TFRE_DB_MM_Index): TFRE_DB_Errortype; function DropIndexReal (const checkonly : boolean ; const index_name : TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : TFRE_DB_Errortype; function _GetIndexedObjUids (const query_value: TFRE_DB_String ; out arr: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const check_is_unique: boolean ; const is_null : boolean): boolean; function GetPersLayer : IFRE_DB_PERSISTANCE_LAYER; override; procedure GetAllIndexedUidsEncodedField (const qry_val: IFRE_DB_Object; const index_name: TFRE_DB_NameType ; var uids : TFRE_DB_GUIDArray ; const check_is_unique : boolean); procedure GetAllIndexedUidsEncFieldRange (const min,max: IFRE_DB_Object; const index_name: TFRE_DB_NameType ; var uids : TFRE_DB_GUIDArray ; const ascending : boolean ; const max_count,skipfirst : NativeInt ; const min_val_is_a_prefix : boolean); public function CloneOutObject (const inobj:TFRE_DB_Object):TFRE_DB_Object; function CloneOutArray (const objarr : TFRE_DB_GUIDArray):TFRE_DB_ObjectArray; function CloneOutArrayOI (const objarr : TFRE_DB_GUIDArray):IFRE_DB_ObjectArray; function CloneOutArrayII (const objarr : IFRE_DB_ObjectArray):IFRE_DB_ObjectArray; function GetIndexedObjInternal (const query_value : TFRE_DB_String ; out obj : IFRE_DB_Object ; const index_name : TFRE_DB_NameType='def' ; const val_is_null : boolean = false):boolean; // for the string fieldtype, dont clone function GetIndexedValueCountRC (const qry_val: IFRE_DB_Object; const index_name: TFRE_DB_NameType ; const user_context: PFRE_DB_GUID): NativeInt; function GetIndexedUidsRC (const qry_val: IFRE_DB_Object; out uids_out : TFRE_DB_GUIDArray ; const index_must_be_fullyunique : boolean ; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; function GetIndexedObjsClonedRC (const qry_val: IFRE_DB_Object; out objs : IFRE_DB_ObjectArray ; const index_must_be_fullyunique : boolean ; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; function GetIndexedValuecountRCRange (const min,max: IFRE_DB_Object; const ascending : boolean ; const max_count,skipfirst : NativeInt ; const min_val_is_a_prefix : boolean ; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; function GetIndexedUidsRCRange (const min,max: IFRE_DB_Object; const ascending : boolean ; const max_count,skipfirst : NativeInt ; out uids_out : TFRE_DB_GUIDArray ; const min_val_is_a_prefix : boolean ; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; function GetIndexedObjsClonedRCRange (const min,max: IFRE_DB_Object; const ascending : boolean ; const max_count,skipfirst : NativeInt ; out objs : IFRE_DB_ObjectArray ; const min_val_is_a_prefix : boolean ; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; function GetFirstLastIdxCnt (const idx: Nativeint ; out obj: IFRE_DB_Object ; const user_context: PFRE_DB_GUID):NativeInt; procedure GetAllUIDsRC (var uids : TFRE_DB_GUIDArray ; const user_context: PFRE_DB_GUID); procedure GetAllObjectsRCInt (var objs : IFRE_DB_ObjectArray ; const user_context: PFRE_DB_GUID); procedure GetAllObjectsRC (var objs : IFRE_DB_ObjectArray ; const user_context: PFRE_DB_GUID); function IndexExists (const idx_name : TFRE_DB_NameType):NativeInt; function GetIndexDefinition (const idx_name : TFRE_DB_NameType ; const user_context: PFRE_DB_GUID):TFRE_DB_INDEX_DEF; function IndexNames : TFRE_DB_NameTypeArray; {< Do all streaming changes for this section } procedure StreamToThis (const stream : TStream); procedure StreamIndexToThis (const ix_name : TFRE_DB_NameType ; const stream : TStream); function GetIndexDefObject : IFRE_DB_Object; procedure CreateIndexDefsFromObj (const obj : IFRE_DB_Object); procedure LoadFromThis (const stream : TStream); function BackupToObject : IFRE_DB_Object; procedure RestoreFromObject (const obj:IFRE_DB_Object); { Do all streaming changes for this section >} function CollectionName (const unique:boolean=false):TFRE_DB_NameType; override ; // function GetPersLayerIntf : IFRE_DB_PERSISTANCE_COLLECTION_4_PERISTANCE_LAYER; override; function UniqueName : PFRE_DB_NameType; constructor Create (const coll_name: TFRE_DB_NameType ; Volatile: Boolean; const masterdata : TFRE_DB_Master_Data); destructor Destroy ; override; function Count : int64; override; function Exists (const ouid: TFRE_DB_GUID): boolean; procedure Clear ; // Clear Store but dont free procedure GetAllUIDS (var uids : TFRE_DB_GUIDArray); procedure GetAllObjects (var objs : IFRE_DB_ObjectArray); procedure GetAllObjectsInt (var objs : IFRE_DB_ObjectArray); function Remove (const ouid : TFRE_DB_GUID):TFRE_DB_Errortype; function FetchO (const uid:TFRE_DB_GUID ; var obj : TFRE_DB_Object) : boolean; function Fetch (const uid:TFRE_DB_GUID ; var iobj : IFRE_DB_Object) : boolean; function FetchIntFromColl (const uid:TFRE_DB_GUID ; out obj : IFRE_DB_Object):boolean; function FetchIntFromCollO (const uid:TFRE_DB_GUID ; out obj : TFRE_DB_Object ; const no_store_lock_check : boolean=false):boolean; function FetchIntFromCollArrOI (const objarr : TFRE_DB_GUIDArray):IFRE_DB_ObjectArray; function FetchIntFromCollAll : IFRE_DB_ObjectArray; procedure ForAllInternalI (const iter : IFRE_DB_Obj_Iterator); procedure ForAllInternal (const iter : TFRE_DB_Obj_Iterator); procedure ForAllInternalBreak (const iter: TFRE_DB_ObjectIteratorBrk; var halt: boolean; const descending: boolean); procedure CheckFieldChangeAgainstIndex (const oldfield,newfield : TFRE_DB_FIELD ; const change_type : TFRE_DB_ObjCompareEventType ; const check : boolean ; old_obj,new_obj : TFRE_DB_Object); end; { TFRE_DB_CollectionTree } { TFRE_DB_CollectionManageTree } TFRE_DB_PersColl_Iterator = procedure (const coll:TFRE_DB_PERSISTANCE_COLLECTION) is nested; TFRE_DB_CollectionManageTree = class private FCollTree : TFRE_ART_TREE; dummy : PtrUInt; public constructor Create; destructor Destroy; override; procedure Clear; function NewCollection (const coll_name : TFRE_DB_NameType ; out Collection:TFRE_DB_PERSISTANCE_COLLECTION ; const volatile_in_memory:boolean ; const masterdata : TFRE_DB_Master_Data) : TFRE_DB_Errortype; function DeleteCollection (const coll_name : TFRE_DB_NameType):TFRE_DB_Errortype; function GetCollection (const coll_name : TFRE_DB_NameType ; out Collection:TFRE_DB_PERSISTANCE_COLLECTION) : boolean; function GetCollectionInt (const coll_name : TFRE_DB_NameType ; out Collection:TFRE_DB_PERSISTANCE_COLLECTION) : boolean; procedure CMTForAllCollections (const iter : TFRE_DB_PersColl_Iterator); function GetCollectionCount : Integer; end; RFRE_DB_GUID_RefLink_InOut_Key = packed record GUID : Array [0..15] of Byte; RefTyp : Byte; // 17 Bytes // Outlink = $99 // Inlink= $AA ToFromGuid : Array [0..15] of Byte; // 25 Bytes // Outlink = $99 // Inlink= $AA SchemeSepField : Array [0..129] of Byte; // VARIABLE LENGTH(!) // TODO THINK ABOUT filter prefix scan (schemeclass) "SCHEME|FIELD" KeyLength : Byte; // Length (not part of key) end; PFRE_DB_GUID_RefLink_In_Key = ^RFRE_DB_GUID_RefLink_InOut_Key; type TFRE_DB_TransactionalUpdateList = class; var G_DB_TX_Number : Qword; G_UserTokens : TFPHashList; G_AllNonsysMasters : Array of TFRE_DB_Master_Data; G_SysMaster : TFRE_DB_Master_Data; G_Transaction : TFRE_DB_TransactionalUpdateList; G_SysScheme : TFRE_DB_Object; G_OverlayRights : TFRE_DB_Object; function G_FetchNewTransactionID : QWord; procedure G_UpdateUserToken (const user_uid : TFRE_DB_GUID ; const uti : TFRE_DB_USER_RIGHT_TOKEN); function G_GetUserToken (const user_uid : PFRE_DB_GUID ; out uti : TFRE_DB_USER_RIGHT_TOKEN ; const raise_ex : boolean):boolean; type { TFRE_DB_Master_Data } TFRE_DB_Master_Data=class(TObject) private FMyMastername : String; FIsSysMaster : Boolean; FMasterPersistentObjStore : TFRE_ART_TREE; FMasterVolatileObjStore : TFRE_ART_TREE; FMasterRefLinks : TFRE_ART_TREE; FMasterCollectionStore : TFRE_DB_CollectionManageTree; FLayer : IFRE_DB_PERSISTANCE_LAYER; function GetOutBoundRefLinks (const from_obj : TFRE_DB_GUID): TFRE_DB_ObjectReferences; function GetInboundRefLinks (const to_obj : TFRE_DB_GUID): TFRE_DB_ObjectReferences; procedure __RemoveInboundReflink (const from_uid,to_uid : TFRE_DB_GUID ; const scheme_link_key : TFRE_DB_NameTypeRL ; const notifif : IFRE_DB_DBChangedNotification ; const tsid : TFRE_DB_TransStepId); procedure __RemoveOutboundReflink (const from_uid,to_uid : TFRE_DB_GUID ; const scheme_link_key : TFRE_DB_NameTypeRL ; const notifif : IFRE_DB_DBChangedNotification ; const tsid : TFRE_DB_TransStepId); procedure __RemoveRefLink (const from_uid,to_uid:TFRE_DB_GUID;const upper_from_schemename,upper_fieldname,upper_to_schemename : TFRE_DB_NameType ; const notifif : IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId); procedure __SetupOutboundLinkKey (const from_uid,to_uid: TFRE_DB_GUID ; const scheme_link_key : TFRE_DB_NameTypeRL ; var refoutkey : RFRE_DB_GUID_RefLink_InOut_Key); //inline; procedure __SetupInboundLinkKey (const from_uid,to_uid: TFRE_DB_GUID ; const scheme_link_key : TFRE_DB_NameTypeRL ; var refinkey : RFRE_DB_GUID_RefLink_InOut_Key); //inline; procedure __SetupInitialRefLink (const from_key : TFRE_DB_Object ; FromFieldToSchemename,LinkFromSchemenameField: TFRE_DB_NameTypeRL ; const references_to : TFRE_DB_GUID ; const notifif : IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId); procedure _SetupInitialRefLinks (const from_key : TFRE_DB_Object ; const references_to_list : TFRE_DB_ObjectReferences ; const schemelink_arr : TFRE_DB_NameTypeRLArray ; const notifif : IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId); procedure _RemoveAllRefLinks (const from_key : TFRE_DB_Object ; const notifif : IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId); function __RefLinkOutboundExists (const from_uid: TFRE_DB_GUID;const fieldname: TFRE_DB_NameType; to_object: TFRE_DB_GUID; const scheme_link: TFRE_DB_NameTypeRL):boolean; function __RefLinkInboundExists (const from_uid: TFRE_DB_GUID;const fieldname: TFRE_DB_NameType; to_object: TFRE_DB_GUID; const scheme_link: TFRE_DB_NameTypeRL):boolean; procedure __CheckReferenceLink (const obj: TFRE_DB_Object; fieldname: TFRE_DB_NameType; link: TFRE_DB_GUID ; var scheme_link : TFRE_DB_NameTypeRL;const allow_existing_links : boolean=false); procedure _ChangeRefLink (const from_obj: TFRE_DB_Object; const upper_schemename: TFRE_DB_NameType; const upper_fieldname: TFRE_DB_NameType; const old_links, new_links: TFRE_DB_GUIDArray ; const notifif : IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId); // Check full referential integrity, check if to objects exist procedure _CheckRefIntegrityForObject (const obj:TFRE_DB_Object ; var ref_array : TFRE_DB_ObjectReferences ; var schemelink_arr : TFRE_DB_NameTypeRLArray); procedure _CheckExistingReferencelinksAndRemoveMissingFromObject (const obj:TFRE_DB_Object); { auto repair function, use with care } class function _CheckFetchRightUID (const uid : TFRE_DB_GUID ; const ut : TFRE_DB_USER_RIGHT_TOKEN) : boolean; class procedure _TransactionalLockObject (const uid : TFRE_DB_GUID ); function _SetCheckFilterbaseclass (const scheme_prefix_filter : TFRE_DB_NameType ; const exact_filter_and_derived : boolean) : TFRE_DB_ObjectClassEx; public function CloneOutObject (const inobj:TFRE_DB_Object):TFRE_DB_Object; function MyLayer : IFRE_DB_PERSISTANCE_LAYER; function GetPersistantRootObjectCount (const UppercaseSchemesFilter: TFRE_DB_StringArray=nil): Integer; function InternalStoreObjectFromStable (const obj : TFRE_DB_Object) : TFRE_DB_Errortype; function InternalRebuildRefindex : TFRE_DB_Errortype; function InternalCheckRestoredBackup : TFRE_DB_Errortype; procedure InternalStoreLock ; procedure InternalCheckStoreLocked ; procedure InternalCheckSubobjectsStored ; procedure FDB_CleanUpMasterData ; constructor Create (const master_name: string; const Layer: IFRE_DB_PERSISTANCE_LAYER); destructor Destroy ; override; function GetReferencesRC (const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const user_context: PFRE_DB_GUID ; const concat_call: boolean ; const exact_filter_and_derived_classes: boolean): TFRE_DB_GUIDArray; function GetReferencesRCRecurse (const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const user_context: PFRE_DB_GUID ; const exact_filter_and_derived_classes: boolean): TFRE_DB_GUIDArray; function GetReferencesCountRC (const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ; const field_exact_filter : TFRE_DB_NameType ; const user_context: PFRE_DB_GUID ; const concat_call: boolean ; const exact_filter_and_derived_classes: boolean ): NativeInt; function GetReferencesDetailedRC (const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ; const field_exact_filter : TFRE_DB_NameType ; const user_context: PFRE_DB_GUID ; const concat_call: boolean ; const exact_filter_and_derived_classes: boolean): TFRE_DB_ObjectReferences; procedure ExpandReferencesRC (const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; out expanded_refs: TFRE_DB_GUIDArray ; const allow_derived_classes: boolean); function ExpandReferencesCountRC (const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; const allow_derived_classes: boolean): NativeInt; procedure FetchExpandReferencesRC (const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; out expanded_refs: IFRE_DB_ObjectArray; const allow_derived_classes: boolean); function BulkFetchRC (const user_context: PFRE_DB_GUID; const obj_uids: TFRE_DB_GUIDArray; out objects: IFRE_DB_ObjectArray):TFRE_DB_Errortype; function FetchObjectRC (const user_context: PFRE_DB_GUID; const obj_uid : TFRE_DB_GUID ; out obj : TFRE_DB_Object ; const internal_obj : boolean) : boolean; function ExistsObject (const obj_uid : TFRE_DB_GUID ) : Boolean; function FetchObject (const obj_uid : TFRE_DB_GUID ; out obj : TFRE_DB_Object ; const internal_obj : boolean) : boolean; procedure StoreObjectSingle (const obj : TFRE_DB_Object; const check_only: boolean; const notifif: IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId); procedure StoreObjectWithSubjs (const obj : TFRE_DB_Object; const check_only: boolean; const notifif: IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId); procedure DeleteObjectSingle (const obj_uid : TFRE_DB_GUID ; const check_only : boolean ; const notifif : IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId); { frees root objects } procedure DeleteObjectWithSubobjs (const del_obj : TFRE_DB_Object ; const check_only : boolean ; const notifif : IFRE_DB_DBChangedNotification; const tsid : TFRE_DB_TransStepId;const must_be_child:boolean=false); procedure ForAllObjectsInternal (const pers,volatile:boolean ; const iter:TFRE_DB_ObjectIteratorBrk); // No Clone function MasterColls : TFRE_DB_CollectionManageTree; end; { TFRE_DB_ChangeStep } TFRE_DB_ChangeStep=class protected FLayer : IFRE_DB_PERSISTANCE_LAYER; FNotifIF : IFRE_DB_DBChangedNotification; Fmaster : TFRE_DB_Master_Data; FTransList : TFRE_DB_TransactionalUpdateList; FStepID : NativeInt; FUserContext : PFRE_DB_GUID; FUserToken : TFRE_DB_USER_RIGHT_TOKEN; procedure InternalWriteObject (const m : TMemoryStream;const obj : TFRE_DB_Object); procedure InternalReadObject (const m : TStream ; var obj : TFRE_DB_Object); protected procedure CheckWriteThroughIndexDrop (Coll : TFRE_DB_PERSISTANCE_COLLECTION_BASE ; const index : TFRE_DB_NameType); procedure CheckWriteThroughColl (Coll : TFRE_DB_PERSISTANCE_COLLECTION_BASE); procedure CheckWriteThroughDeleteColl (Collname : TFRE_DB_NameType); procedure CheckWriteThroughObj (obj : IFRE_DB_Object); procedure CheckWriteThroughDeleteObj (obj : IFRE_DB_Object); function _GetCollection (const coll_name : TFRE_DB_NameType ; out Collection:TFRE_DB_PERSISTANCE_COLLECTION) : Boolean; public constructor Create (const layer : IFRE_DB_PERSISTANCE_LAYER ; const masterdata : TFRE_DB_Master_Data ; const user_context : PFRE_DB_GUID); procedure CheckExistenceAndPreconds ; virtual; { CHECK Only: Preconditions satisfied ? -> fetch usertoken if needed } procedure ChangeInCollectionCheckOrDo (const check : boolean); virtual ; abstract; { Do all collection related checks or stores (+collection indices) } procedure MasterStore (const check : boolean); virtual ; abstract; { Do all objectc related checks or stores, (+reflink index) } procedure SetStepID (const id:NativeInt); function GetTransActionStepID : TFRE_DB_TransStepId; function Master : TFRE_DB_Master_Data; end; { TFRE_DB_NewCollectionStep } TFRE_DB_NewCollectionStep=class(TFRE_DB_ChangeStep) private FCollname : TFRE_DB_NameType; FVolatile : Boolean; FNewCollection : TFRE_DB_PERSISTANCE_COLLECTION; public constructor Create (const layer : IFRE_DB_PERSISTANCE_LAYER;const masterdata : TFRE_DB_Master_Data;const coll_name: TFRE_DB_NameType;const volatile_in_memory: boolean ; const user_context : PFRE_DB_GUID); procedure CheckExistenceAndPreconds ; override; procedure ChangeInCollectionCheckOrDo (const check: boolean); override; procedure MasterStore (const check: boolean); override; function GetNewCollection : TFRE_DB_PERSISTANCE_COLLECTION_BASE; end; { TFRE_DB_DefineIndexOnFieldStep } TFRE_DB_DefineIndexOnFieldStep=class(TFRE_DB_ChangeStep) private FCollname : TFRE_DB_NameType; FVolatile : Boolean; FCollection : TFRE_DB_PERSISTANCE_COLLECTION; FindexName : TFRE_DB_NameType; FPreliminaryIndex : TFRE_DB_MM_Index; Fcoll_name : TFRE_DB_NameType; FFieldName : TFRE_DB_NameType; FFieldType : TFRE_DB_FIELDTYPE; FUnique : boolean; FIgnoreCC : boolean; Fallownull : boolean; FUniqueNull : boolean; FDomainIndex : boolean; public constructor Create (const layer : IFRE_DB_PERSISTANCE_LAYER;const masterdata : TFRE_DB_Master_Data;const coll_name: TFRE_DB_NameType ; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean ; const is_a_domain_index: boolean ; const user_context : PFRE_DB_GUID); procedure CheckExistenceAndPreconds ; override; procedure ChangeInCollectionCheckOrDo (const check: boolean); override; procedure MasterStore (const check: boolean); override; end; { TFRE_DB_DropIndexStep } TFRE_DB_DropIndexStep=class(TFRE_DB_ChangeStep) private FCollname : TFRE_DB_NameType; FIndexName : TFRE_DB_NameType; FCollection : TFRE_DB_PERSISTANCE_COLLECTION; FVolatile : boolean; public constructor Create (const layer : IFRE_DB_PERSISTANCE_LAYER;const masterdata : TFRE_DB_Master_Data;const coll_name,index_name: TFRE_DB_NameType;const user_context : PFRE_DB_GUID); procedure CheckExistenceAndPreconds ; override; procedure ChangeInCollectionCheckOrDo (const check: boolean); override; procedure MasterStore (const check: boolean); override; end; { TFRE_DB_DeleteCollectionStep } TFRE_DB_DeleteCollectionStep=class(TFRE_DB_ChangeStep) private FCollname : TFRE_DB_NameType; FPersColl : TFRE_DB_PERSISTANCE_COLLECTION; FVolatile : boolean; public constructor Create (const layer : IFRE_DB_PERSISTANCE_LAYER;const masterdata : TFRE_DB_Master_Data;const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID); procedure CheckExistenceAndPreconds ; override; procedure ChangeInCollectionCheckOrDo (const check: boolean); override; procedure MasterStore (const check: boolean); override; end; { TFRE_DB_InsertStep } TFRE_DB_InsertStep=class(TFRE_DB_ChangeStep) private FInsertList : TFRE_DB_ObjectArray; FColl : TFRE_DB_PERSISTANCE_COLLECTION; FCollName : TFRE_DB_NameType; FThisIsAnAddToAnotherColl : Boolean; FReplaceExistingSubOWithL : Boolean; public constructor Create (const layer : IFRE_DB_PERSISTANCE_LAYER;const masterdata : TFRE_DB_Master_Data;new_obj : TFRE_DB_Object ; const insert_in_coll : TFRE_DB_NameType ; const user_context : PFRE_DB_GUID ; const replace_existing_subobjects_with_weak_links : boolean); procedure CheckExistenceAndPreconds ; override; procedure ChangeInCollectionCheckOrDo (const check : boolean); override; procedure MasterStore (const check : boolean); override; end; { TFRE_DB_DeleteObjectStep } TFRE_DB_DeleteObjectStep=class(TFRE_DB_ChangeStep) protected FDeleteObjectUid : TFRE_DB_GUID; FDeleteList : TFRE_DB_ObjectArray; CollName : TFRE_DB_NameType; FWouldNeedMasterDelete : Boolean; FDelFromCollectionsNames : TFRE_DB_NameTypeArray; FDelFromCollections : TFRE_DB_PERSISTANCE_COLLECTION_ARRAY; public constructor Create (const layer : IFRE_DB_PERSISTANCE_LAYER;const masterdata : TFRE_DB_Master_Data;const del_obj_uid : TFRE_DB_GUID ; const from_coll : TFRE_DB_NameType ; const user_context : PFRE_DB_GUID); // all collections or a single collection procedure CheckExistenceAndPreconds ; override; procedure ChangeInCollectionCheckOrDo (const check : boolean); override; procedure MasterStore (const check : boolean); override; end; TFRE_DB_UpdateStep=class; { TFRE_DB_UpdateStep } RFRE_DB_UpdateSubStep=record updtyp : TFRE_DB_ObjCompareEventType; newfield : TFRE_DB_FIELD; oldfield : TFRE_DB_FIELD; up_obj : TFRE_DB_Object; in_child_obj : Boolean; in_del_list : boolean; end; TFRE_DB_UpdateStep=class(TFRE_DB_ChangeStep) protected FSublist : Array of RFRE_DB_UpdateSubStep; FCnt : NativeInt; FDiffUpdate : TFRE_DB_Object; upobj : TFRE_DB_Object; // "new" object to_upd_obj : TFRE_DB_Object; // "old" object (Fields of object will be updated by newobjects fields) FCollName : TFRE_DB_NameType; procedure InternallApplyChanges (const check: boolean); public procedure AddSubStep (const uptyp: TFRE_DB_ObjCompareEventType; const new, old: TFRE_DB_FIELD; const is_a_child_field: boolean;const update_obj: TFRE_DB_Object ; const is_in_delete_list:boolean=false); { update_obj = to_update_obj or child} constructor Create (const layer : IFRE_DB_PERSISTANCE_LAYER;const masterdata : TFRE_DB_Master_Data; obj : TFRE_DB_Object ; const update_in_coll : TFRE_DB_NameType ; const user_context : PFRE_DB_GUID); constructor CreateFromDiffTransport (const layer : IFRE_DB_PERSISTANCE_LAYER;const masterdata : TFRE_DB_Master_Data; diff_update_obj : TFRE_DB_Object ; const update_in_coll : TFRE_DB_NameType ; const user_context : PFRE_DB_GUID); procedure CheckExistenceAndPreconds ; override; procedure ChangeInCollectionCheckOrDo (const check : boolean); override; procedure MasterStore (const check : boolean); override; end; OFRE_SL_TFRE_DB_ChangeStep = specialize OFOS_SpareList<TFRE_DB_ChangeStep>; { TFRE_DB_TransactionalUpdateList } PFRE_DB_ChangeStep = ^TFRE_DB_ChangeStep; TFRE_DB_TransactionalUpdateList = class(TObject) private FChangeList : OFRE_SL_TFRE_DB_ChangeStep; // The sparse List has to be ordered (!) / deletetions and reinsertions must not happen FTransId : TFRE_DB_NameType; FTransNumber : QWord; FLastStepId : TFRE_DB_TransStepId; FLockDir : TFRE_DB_Object; procedure ProcessCheck ; public constructor Create (const TransID : TFRE_DB_NameType ; const master_data : TFRE_DB_Master_Data ; const notify_if : IFRE_DB_DBChangedNotification); function AddChangeStep (const step:TFRE_DB_ChangeStep):NativeInt; procedure Record_And_UnlockObject (const obj : TFRE_DB_Object); procedure Record_A_NewObject (const obj : TFRE_DB_Object); procedure Forget_UnlockedObject (const obj : TFRE_DB_Object); procedure Lock_Unlocked_Objects ; function GetTransActionId : TFRE_DB_NameType; function GetTransLastStepTransId : TFRE_DB_TransStepId; function Commit :boolean; procedure Rollback ; destructor Destroy ;override; end; { TFRE_DB_DBChangedNotificationBase } TFRE_DB_DBChangedNotificationBase = class(TObject,IFRE_DB_DBChangedNotification) protected FLayerDB : Shortstring; public constructor Create (const conn_db : TFRE_DB_NameType); destructor Destroy ;override; procedure StartNotificationBlock (const key : TFRE_DB_TransStepId); virtual; procedure FinishNotificationBlock(out block : IFRE_DB_Object); virtual; procedure SendNotificationBlock (const block : IFRE_DB_Object); virtual; procedure CollectionCreated (const coll_name: TFRE_DB_NameType; const in_memory_only : boolean ; const tsid : TFRE_DB_TransStepId) ; virtual ; procedure CollectionDeleted (const coll_name: TFRE_DB_NameType; const tsid : TFRE_DB_TransStepId) ; virtual ; procedure IndexDefinedOnField (const coll_name: TFRE_DB_NameType ; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean; const tsid : TFRE_DB_TransStepId);virtual; procedure IndexDroppedOnField (const coll_name: TFRE_DB_NameType ; const index_name: TFRE_DB_NameType; const tsid : TFRE_DB_TransStepId);virtual; procedure ObjectStored (const coll_name: TFRE_DB_NameType ; const obj : IFRE_DB_Object; const tsid : TFRE_DB_TransStepId) ; virtual; procedure ObjectDeleted (const coll_names: TFRE_DB_NameTypeArray ; const obj : IFRE_DB_Object; const tsid : TFRE_DB_TransStepId) ; virtual; procedure ObjectRemoved (const coll_names: TFRE_DB_NameTypeArray ; const obj : IFRE_DB_Object ; const is_a_full_delete : boolean ; const tsid : TFRE_DB_TransStepId); virtual; procedure ObjectUpdated (const obj : IFRE_DB_Object ; const colls:TFRE_DB_StringArray; const tsid : TFRE_DB_TransStepId);virtual; { FULL STATE } procedure DifferentiallUpdStarts (const obj : IFRE_DB_Object; const tsid : TFRE_DB_TransStepId); virtual; { DIFFERENTIAL STATE} procedure DifferentiallUpdEnds (const obj_uid : TFRE_DB_GUID; const tsid : TFRE_DB_TransStepId); virtual; { DIFFERENTIAL STATE} procedure FieldDelete (const old_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); virtual; procedure FieldAdd (const new_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); virtual; procedure FieldChange (const old_field,new_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); virtual; procedure SetupOutboundRefLink (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);virtual; procedure SetupInboundRefLink (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);virtual; procedure InboundReflinkDropped (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);virtual; procedure OutboundReflinkDropped (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);virtual; procedure FinalizeNotif ; end; { TFRE_DB_DBChangedNotificationProxy } { All objects reported by the Notification Subsystem must be freed, and must not have side effects on persistance data, thus copy in embedded case} TFRE_DB_DBChangedNotificationProxy=class(TFRE_DB_DBChangedNotificationBase,IFRE_DB_DBChangedNotification) private FRealIF : IFRE_DB_DBChangedNotificationBlock; FBlockList : IFRE_DB_Object; FBlocksendMethod : IFRE_DB_InvokeProcedure; protected procedure CheckBlockStarted ; procedure CheckBlockNotStarted ; procedure AddNotificationEntry (const entry:IFRE_DB_Object); procedure AssertCheckTransactionID (const obj : IFRE_DB_Object ; const transid : TFRE_DB_TransStepId); public constructor Create (const real_interface : IFRE_DB_DBChangedNotificationBlock ; const db_name : TFRE_DB_NameType ; const BlocksendMethod : IFRE_DB_InvokeProcedure=nil); destructor Destroy ;override; procedure StartNotificationBlock (const key : TFRE_DB_TransStepId); override; procedure FinishNotificationBlock(out block : IFRE_DB_Object); override; procedure SendNotificationBlock (const block : IFRE_DB_Object);override; procedure CollectionCreated (const coll_name: TFRE_DB_NameType; const in_memory_only : boolean ; const tsid : TFRE_DB_TransStepId) ; override; procedure CollectionDeleted (const coll_name: TFRE_DB_NameType; const tsid : TFRE_DB_TransStepId) ; override ; procedure IndexDefinedOnField (const coll_name: TFRE_DB_NameType ; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean; const tsid : TFRE_DB_TransStepId);override; procedure IndexDroppedOnField (const coll_name: TFRE_DB_NameType ; const index_name: TFRE_DB_NameType; const tsid : TFRE_DB_TransStepId);override; procedure ObjectStored (const coll_name: TFRE_DB_NameType ; const obj : IFRE_DB_Object; const tsid : TFRE_DB_TransStepId) ; override; procedure ObjectDeleted (const coll_names: TFRE_DB_NameTypeArray ; const obj : IFRE_DB_Object; const tsid : TFRE_DB_TransStepId) ; override; procedure ObjectRemoved (const coll_names: TFRE_DB_NameTypeArray ; const obj : IFRE_DB_Object; const is_a_full_delete : boolean ; const tsid : TFRE_DB_TransStepId); override; procedure ObjectUpdated (const obj : IFRE_DB_Object ; const colls:TFRE_DB_StringArray; const tsid : TFRE_DB_TransStepId);override; procedure DifferentiallUpdStarts (const obj : IFRE_DB_Object; const tsid : TFRE_DB_TransStepId); override; procedure DifferentiallUpdEnds (const obj_uid : TFRE_DB_GUID; const tsid : TFRE_DB_TransStepId); override; procedure FieldDelete (const old_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); override; procedure FieldAdd (const new_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); override; procedure FieldChange (const old_field,new_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); override; procedure SetupOutboundRefLink (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);override; procedure SetupInboundRefLink (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);override; procedure InboundReflinkDropped (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);override; procedure OutboundReflinkDropped (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);override; end; implementation function G_FetchNewTransactionID : QWord; begin inc(G_DB_TX_Number); result := G_DB_TX_Number; end; procedure G_UpdateUserToken(const user_uid: TFRE_DB_GUID; const uti: TFRE_DB_USER_RIGHT_TOKEN); var suti : TFRE_DB_USER_RIGHT_TOKEN; idx : Integer; hname : ShortString; uidh : ShortString; begin hname := FREDB_G2SB(user_uid); uidh := FREDB_G2H(user_uid)+' / '+uti.GetFullUserLogin; assert(user_uid=uti.GetUserUIDP^,'internal fault uids dont match'); idx :=G_UserTokens.FindIndexOf(hname); if idx>=0 then begin suti := TFRE_DB_USER_RIGHT_TOKEN(G_UserTokens.Items[idx]); G_UserTokens.Delete(idx); suti.Free; end; G_UserTokens.add(hname,uti); end; function G_GetUserToken(const user_uid: PFRE_DB_GUID; out uti: TFRE_DB_USER_RIGHT_TOKEN; const raise_ex: boolean): boolean; var idx : Integer; hname : ShortString; uidh : ShortString; begin if not assigned(user_uid) then begin uti := nil; exit; end; uidh := FREDB_G2H(user_uid^); hname := FREDB_G2SB(user_uid^); idx :=G_UserTokens.FindIndexOf(hname); if idx>=0 then begin uti := TFRE_DB_USER_RIGHT_TOKEN(G_UserTokens.Items[idx]); end else uti := nil; if raise_ex and (not assigned(uti)) then begin raise EFRE_DB_PL_Exception.Create(edb_ERROR,'the specified user [%s] does not exist',[FREDB_G2H(user_uid^)]); end; end; { TFRE_DB_DropIndexStep } constructor TFRE_DB_DropIndexStep.Create(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data; const coll_name, index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID); begin Inherited Create(layer,masterdata,user_context); FCollname := coll_name; FIndexName := index_name; end; procedure TFRE_DB_DropIndexStep.CheckExistenceAndPreconds; begin if not Master.MasterColls.GetCollection(FCollname,FCollection) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'collection [%s] does not exists!',[FCollname]); end; procedure TFRE_DB_DropIndexStep.ChangeInCollectionCheckOrDo(const check: boolean); var res : TFRE_DB_Errortype; begin res := FCollection.DropIndexReal(check,FIndexName,FUserContext); if res<>edb_OK then raise EFRE_DB_PL_Exception.Create(res,'collection [%s], index [%s] drop failed!',[FCollname,FindexName]); end; procedure TFRE_DB_DropIndexStep.MasterStore(const check: boolean); begin if not check then begin if assigned(FNotifIF) then FNotifIF.IndexDroppedOnField(FCollname,FIndexName,GetTransActionStepID); CheckWriteThroughIndexDrop(FCollection,FIndexName); end; end; { TFRE_DB_RealIndex } class procedure TFRE_DB_RealIndex.InitializeNullKey; begin SetBinaryComparableKey(0,@nullkey,nullkeylen,true,fdbft_Int16); { fieldtype is irrelevant for the null key } end; procedure TFRE_DB_RealIndex.TransformToBinaryComparable(fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint); begin TransformToBinaryComparable(fld,key,keylen,false); end; class procedure TFRE_DB_RealIndex.TransformToBinaryComparable(fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint; const is_casesensitive: boolean; const invert_key: boolean); var is_null_value : Boolean; begin is_null_value := not assigned(fld); if not is_null_value then SetBinaryComparableKey(fld.AsReal64,key,keylen,is_null_value,fld.FieldType,invert_key) else SetBinaryComparableKey(0,key,keylen,is_null_value,fdbft_NotFound,invert_key); end; procedure TFRE_DB_RealIndex.SetBinaryComparableKey(const keyvalue: Double; const key_target: PByte; var key_len: NativeInt; const is_null: boolean); begin SetBinaryComparableKey(keyvalue,key_target,key_len,is_null,FFieldType); end; class procedure TFRE_DB_RealIndex.SetBinaryComparableKey(const keyvalue: Double; const key_target: PByte; var key_len: NativeInt; const is_null: boolean; const FieldType: TFRE_DB_FIELDTYPE; const invert_key: boolean); var FFixedKeylen : NativeInt; i : NativeInt; keyvalue_fake : int64; begin if not is_null then begin keyvalue_fake := round(keyvalue*10000); GetKeyLenForFieldtype(FieldType,FFixedKeylen); key_len := FFixedKeylen+1; case FFixedKeylen of 8: PInt64(@key_target[1])^ := SwapEndian(keyvalue_fake); else raise EFRE_DB_PL_Exception.Create(edb_UNSUPPORTED,'unsupported fixed length in index transform to binary comparable'); end; key_target[1] := key_target[1] xor 128; key_target[0] := 1; // 0 , val , -val are ordered after NULL values which are prefixed by '0' not by '1' if invert_key then for i := 1 to key_len do key_target[i] := not key_target[i]; end else begin key_len:=1; if not invert_key then key_target[0]:=0 else key_target[0]:=2; end; end; constructor TFRE_DB_RealIndex.CreateStreamed(const stream: TStream; const idx_name, fieldname: TFRE_DB_NameType; const fieldtype: TFRE_DB_FIELDTYPE; const unique: boolean; const collection: TFRE_DB_PERSISTANCE_COLLECTION; const allow_null: boolean; const unique_null: boolean; const domain_idx : boolean); begin Create(idx_name,fieldname,fieldtype,unique,collection,allow_null,unique_null,domain_idx); LoadIndex(stream,collection); end; procedure TFRE_DB_RealIndex.FieldTypeIndexCompatCheck(fld: TFRE_DB_FIELD); begin if not SupportsDataType(fld.FieldType) then raise EFRE_DB_PL_Exception.Create(edb_ILLEGALCONVERSION,'the real index can only be used to index a real32/real64 number field, not a [%s] field.',[fld.FieldTypeAsString]) end; function TFRE_DB_RealIndex.NullvalueExists(var vals: TFRE_DB_IndexValueStore): boolean; var dummy : NativeUint; begin result := FIndex.ExistsBinaryKey(@nullkey,nullkeylen,dummy); if result then vals := FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore else vals := nil; end; function TFRE_DB_RealIndex.SupportsDataType(const typ: TFRE_DB_FIELDTYPE): boolean; begin case typ of fdbft_Real32, fdbft_Real64: result := true; else result := false; end; end; function TFRE_DB_RealIndex.SupportsSignedQuery: boolean; begin result := false; end; function TFRE_DB_RealIndex.SupportsUnsignedQuery: boolean; begin result := false; end; function TFRE_DB_RealIndex.SupportsStringQuery: boolean; begin result := false; end; function TFRE_DB_RealIndex.SupportsRealQuery: boolean; begin result := true; end; procedure TFRE_DB_RealIndex.ForAllIndexedRealRange(const min, max: Double; var guids: TFRE_DB_GUIDArray; const ascending: boolean; const min_is_null: boolean; const max_is_max: boolean; const max_count: NativeInt; skipfirst: NativeInt); var lokey,hikey : Array [0..8] of Byte; lokeylen,hikeylen : NativeInt; lokeyp,hikeyp : PByte; procedure IteratorBreak(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var break : boolean ; var down_counter,up_counter : NativeInt; const abscntr : NativeInt); begin (FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore).AppendObjectUIDS(guids,ascending,down_counter,up_counter,abscntr); end; begin if not min_is_null then begin SetBinaryComparableKey(min,@lokey,lokeylen,min_is_null); lokeyp := lokey; end else lokeyp := nil; if not max_is_max then begin SetBinaryComparableKey(max,@hikey,hikeylen,max_is_max); hikeyp := hikey; end else hikeyp := nil; FIndex.RangeScan(lokeyp,hikeyp,lokeylen,hikeylen,@IteratorBreak,max_count,skipfirst,ascending) end; { TFRE_DB_DefineIndexOnFieldStep } constructor TFRE_DB_DefineIndexOnFieldStep.Create(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data; const coll_name: TFRE_DB_NameType; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean; const is_a_domain_index: boolean; const user_context: PFRE_DB_GUID); begin Inherited Create(layer,masterdata,user_context); FCollname := coll_name; FFieldName := FieldName; FFieldType := FieldType; FUnique := unique; FIgnoreCC := ignore_content_case; FindexName := index_name; Fallownull := allow_null_value; FUniqueNull := unique_null_values; FDomainIndex := is_a_domain_index; end; procedure TFRE_DB_DefineIndexOnFieldStep.CheckExistenceAndPreconds; begin if not Master.MasterColls.GetCollection(FCollname,FCollection) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'collection [%s] does not exists!',[FCollname]); end; procedure TFRE_DB_DefineIndexOnFieldStep.ChangeInCollectionCheckOrDo(const check: boolean); var res : TFRE_DB_Errortype; begin res := FCollection.DefineIndexOnFieldReal(check,FFieldName,FFieldType,FUnique,FIgnoreCC,FindexName,Fallownull,FUniqueNull,FDomainIndex,FPreliminaryIndex); if res<>edb_OK then raise EFRE_DB_PL_Exception.Create(res,'collection [%s], index [%s] creation failed! [%s]',[FCollname,FindexName,res.Msg]); end; procedure TFRE_DB_DefineIndexOnFieldStep.MasterStore(const check: boolean); begin if not check then begin if assigned(FNotifIF) then FNotifIF.IndexDefinedOnField(FCollname,FFieldName,FFieldType,FUnique,FIgnoreCC,FindexName,Fallownull,FUniqueNull,GetTransActionStepID); CheckWriteThroughColl(FCollection); end; end; { TFRE_DB_DBChangedNotificationProxy } procedure TFRE_DB_DBChangedNotificationProxy.CheckBlockStarted; begin if not assigned(FBlockList) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'BLOCK LIST NOT STARTED'); end; procedure TFRE_DB_DBChangedNotificationProxy.CheckBlockNotStarted; begin if assigned(FBlockList) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'BLOCK LIST ALREADY STARTED'); end; procedure TFRE_DB_DBChangedNotificationProxy.AddNotificationEntry(const entry: IFRE_DB_Object); begin FBlockList.Field('N').AddObject(entry); end; procedure TFRE_DB_DBChangedNotificationProxy.AssertCheckTransactionID(const obj: IFRE_DB_Object; const transid: TFRE_DB_TransStepId); var ttag : TFRE_DB_TransStepId; begin ttag := obj.Field(cFRE_DB_SYS_T_LMO_TRANSID).AsString; if ttag <>transid then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'NOTPROXY : transaction id mismatch OBJ=[%s] NOTIFY=[%s]',[ttag,transid]); end; constructor TFRE_DB_DBChangedNotificationProxy.Create(const real_interface: IFRE_DB_DBChangedNotificationBlock; const db_name: TFRE_DB_NameType; const BlocksendMethod: IFRE_DB_InvokeProcedure); begin FRealIF := real_interface; FLayerDB := db_name; FBlocksendMethod := BlocksendMethod; end; destructor TFRE_DB_DBChangedNotificationProxy.Destroy; begin inherited Destroy; end; procedure TFRE_DB_DBChangedNotificationProxy.StartNotificationBlock(const key: TFRE_DB_TransStepId); begin try Inherited; { log } CheckBlockNotStarted; FBlockList := GFRE_DBI.NewObject; FBlockList.Field('KEY').AsString := key; FBlockList.Field('L').AsString := FLayerDB; except on e:Exception do begin GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'proxy notification error: StartNotificationBlock '+e.Message); end; end; end; procedure TFRE_DB_DBChangedNotificationProxy.FinishNotificationBlock(out block: IFRE_DB_Object); begin try Inherited; { log } CheckBlockStarted; block := FBlockList; FBlockList := nil; except on e:Exception do begin GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'proxy notification error: FinishNotificationBlock '+e.Message); end; end; end; procedure TFRE_DB_DBChangedNotificationProxy.SendNotificationBlock(const block: IFRE_DB_Object); var s:string; begin try Inherited; { log } if assigned(FRealIF) then FRealIF.SendNotificationBlock(block) else if assigned(FBlocksendMethod) then FBlocksendMethod(block) else block.Finalize; except on e:Exception do begin GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'proxy notification error: SendNotificationBlock '+e.Message); end; end; end; procedure TFRE_DB_DBChangedNotificationProxy.CollectionCreated(const coll_name: TFRE_DB_NameType; const in_memory_only: boolean; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'CC'; newe.Field('CC').AsString := coll_name; newe.Field('CV').AsBoolean := in_memory_only; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: CollectionCreated '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.CollectionDeleted(const coll_name: TFRE_DB_NameType; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'CD'; newe.Field('CC').AsString := coll_name; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: CollectionDeleted '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.IndexDefinedOnField(const coll_name: TFRE_DB_NameType; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'IC'; newe.Field('CC').AsString := coll_name; newe.Field('IN').AsString := index_name; newe.Field('FN').AsString := FieldName; newe.Field('FT').AsString := CFRE_DB_FIELDTYPE_SHORT[FieldType]; newe.Field('UI').AsBoolean := unique; newe.Field('AN').AsBoolean := allow_null_value; newe.Field('UN').AsBoolean := unique_null_values; newe.Field('IC').AsBoolean := ignore_content_case; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: IndexDefinedOnField '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.IndexDroppedOnField(const coll_name: TFRE_DB_NameType; const index_name: TFRE_DB_NameType; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'ID'; newe.Field('CC').AsString := coll_name; newe.Field('IN').AsString := index_name; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: IndexDroppedOnField '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.ObjectStored(const coll_name: TFRE_DB_NameType; const obj: IFRE_DB_Object; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'OS'; newe.Field('CC').AsString := coll_name; newe.Field('OBJ').AsObject := obj.CloneToNewObject; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: ObjectStored '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.ObjectDeleted(const coll_names: TFRE_DB_NameTypeArray; const obj: IFRE_DB_Object; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'OD'; newe.Field('CC').AsStringArr := FREDB_NametypeArray2StringArray(coll_names); newe.Field('OBJ').AsObject := obj; //Is already cloned .CloneToNewObject; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: ObjectDeleted '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.ObjectRemoved(const coll_names: TFRE_DB_NameTypeArray; const obj: IFRE_DB_Object; const is_a_full_delete: boolean; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'OR'; newe.Field('CC').AsStringArr := FREDB_NametypeArray2StringArray(coll_names); newe.Field('FD').AsBoolean := is_a_full_delete; newe.Field('OBJ').AsObject := obj.CloneToNewObject; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: ObjectRemoved '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.ObjectUpdated(const obj: IFRE_DB_Object; const colls: TFRE_DB_StringArray; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'OU'; newe.Field('CC').AsStringArr:= colls; newe.Field('OBJ').AsObject := obj.CloneToNewObject; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); AssertCheckTransactionID(obj,tsid); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: ObjectUpdated '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.DifferentiallUpdStarts(const obj: IFRE_DB_Object; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'DUS'; newe.Field('O').AsObject := obj; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: DiffUpstart '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.DifferentiallUpdEnds(const obj_uid: TFRE_DB_GUID; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'DUE'; newe.Field('O').AsGUID := obj_uid; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: DiffUpEnds '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.FieldDelete(const old_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'FD'; newe.Field('FLD').AsObject := old_field.CloneToNewStreamableObj; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: FieldDelete '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.FieldAdd(const new_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'FA'; newe.Field('FLD').AsObject := new_field.CloneToNewStreamableObj; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: FieldAdd '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.FieldChange(const old_field, new_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'FC'; newe.Field('FLDO').AsObject := old_field.CloneToNewStreamableObj; newe.Field('FLDN').AsObject := new_field.CloneToNewStreamableObj; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: FieldChange '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.SetupOutboundRefLink(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'SOL'; newe.Field('FO').AsObject := from_obj.CloneToNewObject; newe.Field('TO').AsObject := to_obj.CloneToNewObject; newe.Field('KD').AsString := key_description; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: SetupOutboundRefLink '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.SetupInboundRefLink(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'SIL'; newe.Field('FO').AsObject := from_obj.CloneToNewObject; newe.Field('TO').AsObject := to_obj.CloneToNewObject; newe.Field('KD').AsString := key_description; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: SetupInboundRefLink '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.InboundReflinkDropped(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'DIL'; newe.Field('FO').AsObject := from_obj.CloneToNewObject; newe.Field('TO').AsObject := to_obj.CloneToNewObject(); newe.Field('KD').AsString := key_description; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: InboundReflinkDropped '+e.Message); end; end; procedure TFRE_DB_DBChangedNotificationProxy.OutboundReflinkDropped(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId); var newe : IFRE_DB_Object; begin try Inherited; { log } CheckBlockStarted; newe := GFRE_DBI.NewObject; newe.Field('C').AsString := 'DOL'; newe.Field('FO').AsObject := from_obj.CloneToNewObject; newe.Field('TO').AsObject := to_obj.CloneToNewObject; newe.Field('KD').AsString := key_description; newe.Field('TSID').AsString := tsid; AddNotificationEntry(newe); except on e:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'notification error: OutboundReflinkDropped '+e.Message); end; end; { TFRE_DB_DBChangedNotificationBase } constructor TFRE_DB_DBChangedNotificationBase.Create(const conn_db: TFRE_DB_NameType); begin FLayerDB := conn_db; end; destructor TFRE_DB_DBChangedNotificationBase.Destroy; begin inherited Destroy; end; procedure TFRE_DB_DBChangedNotificationBase.StartNotificationBlock(const key: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s]> NOTIFICATION BLOCK START [%s] ',[FLayerDB,key])); end; procedure TFRE_DB_DBChangedNotificationBase.FinishNotificationBlock(out block: IFRE_DB_Object); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s]> NOTIFICATION BLOCK FINISH',[FLayerDB])); block := nil; end; procedure TFRE_DB_DBChangedNotificationBase.SendNotificationBlock(const block: IFRE_DB_Object); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s]> NOTIFICATION BLOCK SEND',[FLayerDB])); end; procedure TFRE_DB_DBChangedNotificationBase.CollectionCreated(const coll_name: TFRE_DB_NameType; const in_memory_only: boolean; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> COLLECTION CREATED : [%s (%s)] ',[FLayerDB,tsid,coll_name,BoolToStr(in_memory_only,'Volatile','Persistent')])); end; procedure TFRE_DB_DBChangedNotificationBase.CollectionDeleted(const coll_name: TFRE_DB_NameType; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> COLLECTION DELETED : [%s]',[FLayerDB,tsid,coll_name])); end; procedure TFRE_DB_DBChangedNotificationBase.IndexDefinedOnField(const coll_name: TFRE_DB_NameType; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> INDEX [%s] ON COLLECTION CREATED : [%s] (%s)',[FLayerDB,tsid,index_name,coll_name,FieldName+'/'+CFRE_DB_FIELDTYPE[FieldType]])); end; procedure TFRE_DB_DBChangedNotificationBase.IndexDroppedOnField(const coll_name: TFRE_DB_NameType; const index_name: TFRE_DB_NameType; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> INDEX [%s] ON COLLECTION DROPPED : [%s]',[FLayerDB,tsid,index_name,coll_name])); end; procedure TFRE_DB_DBChangedNotificationBase.ObjectStored(const coll_name: TFRE_DB_NameType; const obj: IFRE_DB_Object; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> OBJECT STORE IN [%s] -> %s',[FLayerDB,tsid,coll_name,obj.GetDescriptionID])); end; procedure TFRE_DB_DBChangedNotificationBase.ObjectDeleted(const coll_names: TFRE_DB_NameTypeArray; const obj: IFRE_DB_Object; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> OBJECT FINAL DELETE FROM [%s] -> %s',[FLayerDB,tsid,FREDB_CombineString(FREDB_NametypeArray2StringArray(coll_names),','),obj.GetDescriptionID])); end; procedure TFRE_DB_DBChangedNotificationBase.ObjectRemoved(const coll_names: TFRE_DB_NameTypeArray; const obj: IFRE_DB_Object; const is_a_full_delete: boolean; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> OBJECT REMOVED FROM [%s] -> %s (%s)',[FLayerDB,tsid,FREDB_CombineString(FREDB_NametypeArray2StringArray(coll_names),','),obj.GetDescriptionID,BoolToStr(is_a_full_delete,'FULL DELETE','COLLECTION REMOVE')])); end; procedure TFRE_DB_DBChangedNotificationBase.ObjectUpdated(const obj: IFRE_DB_Object; const colls: TFRE_DB_StringArray; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> OBJECT UPDATED -> %s in [%s]',[FLayerDB,tsid,obj.GetDescriptionID,FREDB_CombineString(colls,',')])); end; procedure TFRE_DB_DBChangedNotificationBase.DifferentiallUpdStarts(const obj: IFRE_DB_Object; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> DIFFERENTIAL UPDATE START -> %s',[FLayerDB,tsid,obj.GetDescriptionID])); end; procedure TFRE_DB_DBChangedNotificationBase.DifferentiallUpdEnds(const obj_uid: TFRE_DB_GUID; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> DIFFERENTIAL UPDATE END [UID: %s]',[FLayerDB,tsid,FREDB_G2H(obj_uid)])); end; procedure TFRE_DB_DBChangedNotificationBase.FieldDelete(const old_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> FIELD [%s/(%s)] DELETED FROM OBJECT -> %s',[FLayerDB,tsid,old_field.FieldName,old_field.FieldTypeAsString,old_field.ParentObject.GetDescriptionID])); end; procedure TFRE_DB_DBChangedNotificationBase.FieldAdd(const new_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> FIELD [%s/(%s)] ADDED TO OBJECT -> %s',[FLayerDB,tsid,new_field.FieldName,new_field.FieldTypeAsString,new_field.ParentObject.GetDescriptionID])); end; procedure TFRE_DB_DBChangedNotificationBase.FieldChange(const old_field, new_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> FIELD [%s/(%s)] CHANGED IN OBJECT -> %s',[FLayerDB,tsid,new_field.FieldName,new_field.FieldTypeAsString,new_field.ParentObject.GetDescriptionID])); end; procedure TFRE_DB_DBChangedNotificationBase.SetupOutboundRefLink(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> NEW OUTBOUND REFLINK [%s] -> [%s] (%s)',[FLayerDB,tsid,from_obj.UID_String+'/'+from_obj.SchemeClass,to_obj.UID_String+'/'+to_obj.SchemeClass,key_description])); end; procedure TFRE_DB_DBChangedNotificationBase.SetupInboundRefLink(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> NEW INBOUND REFLINK [%s] -> [%s] (%s)',[FLayerDB,tsid,from_obj.UID_String+'/'+from_obj.SchemeClass,to_obj.UID_String+'/'+to_obj.SchemeClass,key_description])); end; procedure TFRE_DB_DBChangedNotificationBase.InboundReflinkDropped(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> DROPPED INBOUND REFLINK [%s] -> [%s] (%s)',[FLayerDB,tsid,from_obj.UID_String+'/'+from_obj.SchemeClass,to_obj.UID_String+'/'+to_obj.SchemeClass,key_description])); end; procedure TFRE_DB_DBChangedNotificationBase.OutboundReflinkDropped(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId); begin GFRE_DBI.LogInfo(dblc_PERSISTANCE_NOTIFY,Format('[%s/%s]> DROPPED OUTBOUND REFLINK [%s] -> [%s] (%s)',[FLayerDB,tsid,from_obj.UID_String+'/'+from_obj.SchemeClass,to_obj.UID_String+'/'+to_obj.SchemeClass,key_description])); end; procedure TFRE_DB_DBChangedNotificationBase.FinalizeNotif; begin Free; end; { TFRE_DB_DeleteCollectionStep } constructor TFRE_DB_DeleteCollectionStep.Create(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data; const coll_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID); begin inherited create(layer,masterdata,user_context); FCollname := coll_name; end; procedure TFRE_DB_DeleteCollectionStep.CheckExistenceAndPreconds; begin if not Master.MasterColls.GetCollection(FCollname,FPersColl) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'collection [%s] does not exists!',[FCollname]); if FPersColl.Count<>0 then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'collection [%s] is not empty (%d) - only empty collections may be deleted!',[FCollname,FPersColl.Count]); FVolatile := FPersColl.IsVolatile; end; procedure TFRE_DB_DeleteCollectionStep.ChangeInCollectionCheckOrDo(const check: boolean); begin end; procedure TFRE_DB_DeleteCollectionStep.MasterStore(const check: boolean); var res:TFRE_DB_Errortype; begin if not check then begin res := Master.MasterColls.DeleteCollection(FCollname); if res<>edb_OK then raise EFRE_DB_PL_Exception.Create(res,'failed to delete new collection [%s] in transaction step',[FCollname]); if assigned(FNotifIF) then FNotifIF.CollectionDeleted(FCollname,GetTransActionStepID); if not FVolatile then CheckWriteThroughDeleteColl(FCollname); end; end; { TFRE_DB_DeleteObjectStep } constructor TFRE_DB_DeleteObjectStep.Create(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data; const del_obj_uid: TFRE_DB_GUID; const from_coll: TFRE_DB_NameType ; const user_context: PFRE_DB_GUID); begin inherited Create(layer,masterdata,user_context); CollName := from_coll; if CollName='' then FWouldNeedMasterDelete := true else FWouldNeedMasterDelete := false; FDeleteObjectUid := del_obj_uid; end; procedure TFRE_DB_DeleteObjectStep.CheckExistenceAndPreconds; var del_obj : TFRE_DB_Object; begin inherited CheckExistenceAndPreconds; if not FMaster.FetchObject(FDeleteObjectUid,del_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'an object should be deleted but was not found [%s]',[FREDB_G2H(FDeleteObjectUid)]); if (CollName<>'') then if del_obj.__InternalCollectionExistsName(CollName)=-1 then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the request to delete object [%s] from collection [%s] could not be completed, the object is not stored in the requested collection',[del_obj.UID_String,CollName]); if assigned(FUserToken) and (FUserToken.CheckStdRightSetUIDAndClass(del_obj.UID,del_obj.DomainID,del_obj.SchemeClass,[sr_DELETE])<>edb_OK) then raise EFRE_DB_Exception.Create(edb_ACCESS,'no right to delete object [%s]',[FREDB_G2H(FDeleteObjectUid)]); if not del_obj.IsObjectRoot then raise EFRE_DB_Exception.Create(edb_ERROR,'a delete of a subobject is only allowed via an update of an root object'); G_Transaction.Record_And_UnlockObject(del_obj); FDeleteList := del_obj.GetFullHierarchicObjectList(true); if FDeleteList[0].IsObjectRoot=false then raise EFRE_DB_Exception.Create(edb_INTERNAL,'unexpected/non objectroot delete'); end; procedure TFRE_DB_DeleteObjectStep.ChangeInCollectionCheckOrDo(const check: boolean); var arr : TFRE_DB_PERSISTANCE_COLLECTION_ARRAY; i : NativeInt; idx: NativeInt; begin if check and (CollName<>'') then begin if FDeleteList[0].__InternalCollectionExistsName(CollName)=-1 then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the request to delete object [%s] from collection [%s] could not be completed, the object is not stored in the requested collection',[FDeleteList[0].UID_String,CollName]); end; arr := FDeleteList[0].__InternalGetCollectionList; if CollName='' then begin { Delete from all } SetLength(FDelFromCollections,Length(arr)); SetLength(FDelFromCollectionsNames,Length(arr)); for i := 0 to high(arr) do begin FDelFromCollections[i] := arr[i]; FDelFromCollectionsNames[i] := arr[i].CollectionName(false); (arr[i] as TFRE_DB_Persistance_Collection).DeleteFromThisColl(FDeleteList[0],check); if not check then begin FDeleteList[0].Field(cFRE_DB_SYS_T_LMO_TRANSID).AsString:=GetTransActionStepID; CheckWriteThroughColl(arr[i]); end; end; if not check then if assigned(FNotifIF) then FNotifIF.ObjectRemoved(FDelFromCollectionsNames,FDeleteList[0],true,GetTransActionStepID); end else begin { Delete from specific collection} idx := FDeleteList[0].__InternalCollectionExistsName(CollName); // Delete from this collection self.FDelObj; assert(idx<>-1); (arr[idx] as TFRE_DB_Persistance_Collection).DeleteFromThisColl(FDeleteList[0],check); if check and (Length(FDeleteList[0].__InternalGetCollectionList)=1) then FWouldNeedMasterDelete:=true; SetLength(FDelFromCollections,1); SetLength(FDelFromCollectionsNames,1); FDelFromCollections[0] := arr[idx]; FDelFromCollectionsNames[0] := arr[idx].CollectionName(false); if not check then begin FDeleteList[0].Field(cFRE_DB_SYS_T_LMO_TRANSID).AsString:=GetTransActionStepID; if assigned(FNotifIF) then FNotifIF.ObjectRemoved(FDelFromCollectionsNames, FDeleteList[0],FWouldNeedMasterDelete,GetTransActionStepID); CheckWriteThroughColl(arr[idx]); end; end; end; procedure TFRE_DB_DeleteObjectStep.MasterStore(const check: boolean); var notify_delob : IFRE_DB_Object; i : NativeInt; begin if check and FWouldNeedMasterDelete then { this is the check phase, the internalcount is >1} begin master.DeleteObjectWithSubobjs(FDeleteList[0],check,FNotifIF,GetTransActionStepID); end else begin if length(FDeleteList[0].__InternalGetCollectionList)=0 then { this is the real phase} begin G_Transaction.Forget_UnlockedObject(FDeleteList[0]); { do not unlock it, later it ceases to be } if assigned(FNotifIF) then begin notify_delob := FDeleteList[0].CloneToNewObject; notify_delob.Field(cFRE_DB_SYS_T_LMO_TRANSID).AsString:=GetTransActionStepID; end; CheckWriteThroughDeleteObj(FDeleteList[0]); { the changes must only be recorded persistent when the object is finally deleted, the internal collection assosciation is not stored persistent } if FDeleteList[0].IsSystemDB then G_SysMaster.DeleteObjectWithSubobjs(FDeleteList[0],check,FNotifIF,GetTransActionStepID) else master.DeleteObjectWithSubobjs(FDeleteList[0],check,FNotifIF,GetTransActionStepID); if assigned(FNotifIF) then FNotifIF.ObjectDeleted(FDelFromCollectionsNames,notify_delob,GetTransActionStepID); { Notify after delete } end; for i:=0 to high(FDelFromCollections) do CheckWriteThroughColl(FDelFromCollections[i]); end; end; { TFRE_DB_NewCollectionStep } constructor TFRE_DB_NewCollectionStep.Create(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data; const coll_name: TFRE_DB_NameType; const volatile_in_memory: boolean; const user_context: PFRE_DB_GUID); begin inherited Create(layer,masterdata,user_context); FCollname := coll_name; FVolatile := volatile_in_memory; end; procedure TFRE_DB_NewCollectionStep.CheckExistenceAndPreconds; var coll : TFRE_DB_PERSISTANCE_COLLECTION; begin if Master.MasterColls.GetCollection(FCollname,coll) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'collection [%s] already exists!',[FCollname]); end; procedure TFRE_DB_NewCollectionStep.ChangeInCollectionCheckOrDo(const check: boolean); begin end; procedure TFRE_DB_NewCollectionStep.MasterStore(const check: boolean); var res:TFRE_DB_Errortype; begin if not check then begin res := Master.MasterColls.NewCollection(FCollname,FNewCollection,FVolatile,Master); if res<>edb_OK then raise EFRE_DB_PL_Exception.Create(res,'failed to create new collectiion in step [%s] ',[FCollname]); if assigned(FNotifIF) then FNotifIF.CollectionCreated(FCollname,FVolatile,GetTransActionStepID); CheckWriteThroughColl(FNewCollection); end; end; function TFRE_DB_NewCollectionStep.GetNewCollection: TFRE_DB_PERSISTANCE_COLLECTION_BASE; begin result := FNewCollection; end; { TFRE_DB_SignedIndex } class procedure TFRE_DB_SignedIndex.InitializeNullKey; begin SetBinaryComparableKey(0,@nullkey,nullkeylen,true,fdbft_Int16); { fieldtype is irrelevant for the null key } end; procedure TFRE_DB_SignedIndex.TransformToBinaryComparable(fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint); begin TransformToBinaryComparable(fld,key,keylen,false); end; class procedure TFRE_DB_SignedIndex.TransformToBinaryComparable(fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint; const is_casesensitive: boolean; const invert_key: boolean); var is_null_value : Boolean; begin is_null_value := not assigned(fld); if not is_null_value then SetBinaryComparableKey(fld.AsInt64,key,keylen,is_null_value,fld.FieldType,invert_key) else SetBinaryComparableKey(0,key,keylen,true,fdbft_NotFound,invert_key); end; procedure TFRE_DB_SignedIndex.SetBinaryComparableKey(const keyvalue: int64; const key_target: PByte; var key_len: NativeInt; const is_null: boolean); begin SetBinaryComparableKey(keyvalue,key_target,key_len,is_null,FFieldType); end; class procedure TFRE_DB_SignedIndex.SetBinaryComparableKey(const keyvalue: int64; const key_target: PByte; var key_len: NativeInt; const is_null: boolean; const FieldType: TFRE_DB_FIELDTYPE; const invert_key: boolean); var FFixedKeylen : NativeInt; i : NativeInt; begin if not is_null then begin GetKeyLenForFieldtype(FieldType,FFixedKeylen); key_len := FFixedKeylen+1; case FFixedKeylen of 2: PSmallInt(@key_target[1])^ := SwapEndian(SmallInt(keyvalue)); 4: PInteger(@key_target[1])^ := SwapEndian(Integer(keyvalue)); 8: PInt64(@key_target[1])^ := SwapEndian(keyvalue); else raise EFRE_DB_PL_Exception.Create(edb_UNSUPPORTED,'unsupported fixed length in index transform to binary comparable'); end; key_target[1] := key_target[1] xor 128; key_target[0] := 1; // 0 , val , -val are ordered after NULL values which are prefixed by '0' not by '1' if invert_key then for i := 1 to key_len do key_target[i] := not key_target[i]; end else begin key_len:=1; if not invert_key then key_target[0]:=0 else key_target[0]:=2; end; end; constructor TFRE_DB_SignedIndex.CreateStreamed(const stream: TStream; const idx_name, fieldname: TFRE_DB_NameType; const fieldtype: TFRE_DB_FIELDTYPE; const unique: boolean; const collection: TFRE_DB_PERSISTANCE_COLLECTION; const allow_null: boolean; const unique_null: boolean; const domain_idx: boolean); begin Create(idx_name,fieldname,fieldtype,unique,collection,allow_null,unique_null,domain_idx); LoadIndex(stream,collection); end; procedure TFRE_DB_SignedIndex.FieldTypeIndexCompatCheck(fld: TFRE_DB_FIELD); begin if not SupportsDataType(fld.FieldType) then raise EFRE_DB_PL_Exception.Create(edb_ILLEGALCONVERSION,'the signed index can only be used to index a signed number field, not a [%s] field.',[fld.FieldTypeAsString]) end; function TFRE_DB_SignedIndex.NullvalueExists(var vals: TFRE_DB_IndexValueStore): boolean; var dummy : NativeUint; begin result := FIndex.ExistsBinaryKey(@nullkey,nullkeylen,dummy); if result then vals := FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore else vals := nil; end; function TFRE_DB_SignedIndex.SupportsDataType(const typ: TFRE_DB_FIELDTYPE): boolean; begin case typ of fdbft_Int16, fdbft_Int32, fdbft_Int64, fdbft_DateTimeUTC, fdbft_Currency: result := true; else result := false; end; end; function TFRE_DB_SignedIndex.SupportsSignedQuery: boolean; begin result := true; end; function TFRE_DB_SignedIndex.SupportsUnsignedQuery: boolean; begin result := false; end; function TFRE_DB_SignedIndex.SupportsStringQuery: boolean; begin result := false; end; function TFRE_DB_SignedIndex.SupportsRealQuery: boolean; begin result := false; end; procedure TFRE_DB_SignedIndex.ForAllIndexedSignedRange(const min, max: int64; var guids: TFRE_DB_GUIDArray; const ascending: boolean; const min_is_null: boolean; const max_is_max: boolean; const max_count: NativeInt; skipfirst: NativeInt); var lokey,hikey : Array [0..8] of Byte; lokeylen,hikeylen : NativeInt; lokeyp,hikeyp : PByte; procedure IteratorBreak(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var break : boolean ; var down_counter,up_counter : NativeInt; const abscntr : NativeInt); begin (FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore).AppendObjectUIDS(guids,ascending,down_counter,up_counter,abscntr); end; begin if not min_is_null then begin SetBinaryComparableKey(min,@lokey,lokeylen,min_is_null); lokeyp := lokey; end else lokeyp := nil; if not max_is_max then begin SetBinaryComparableKey(max,@hikey,hikeylen,max_is_max); hikeyp := hikey; end else hikeyp := nil; FIndex.RangeScan(lokeyp,hikeyp,lokeylen,hikeylen,@IteratorBreak,max_count,skipfirst,ascending) end; { TFRE_DB_UnsignedIndex } class procedure TFRE_DB_UnsignedIndex.InitializeNullKey; begin SetBinaryComparableKey(0,@nullkey,nullkeylen,true,fdbft_UInt16); { exact fieldtype is irrelevant for null key} end; procedure TFRE_DB_UnsignedIndex.TransformToBinaryComparable(fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint); begin TransformToBinaryComparable(fld,key,keylen,false); end; class procedure TFRE_DB_UnsignedIndex.TransformToBinaryComparable(fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint; const is_cassensitive: boolean; const invert_key: boolean); var guid : TFRE_DB_GUID; is_null_value : boolean; isguid : boolean; i : NativeInt; begin is_null_value := not assigned(fld); isguid := false; if (not is_null_value) and (fld.FieldType=fdbft_GUID) then begin guid := fld.AsGUID; isguid := true; end else if (not is_null_value) and (fld.FieldType=fdbft_ObjLink) then begin guid := fld.AsObjectLink; isguid := true; end; if isguid then begin if not is_null_value then begin move(guid,key[1],sizeof(TFRE_DB_GUID)); keylen:=17; key[0]:=1; if invert_key then for i:=1 to sizeof(TFRE_DB_GUID) do key[i] := not key[i]; end else begin keylen := 2; if not invert_key then key[0] := 0 else key[0] := 2; end end else begin if not is_null_value then SetBinaryComparableKey(fld.AsUInt64,key,keylen,is_null_value,fld.FieldType,invert_key) else SetBinaryComparableKey(0,key,keylen,is_null_value,fdbft_NotFound,invert_key); end; end; procedure TFRE_DB_UnsignedIndex.SetBinaryComparableKey(const keyvalue: qword; const key_target: PByte; var key_len: NativeInt; const is_null: boolean); begin SetBinaryComparableKey(keyvalue,key_target,key_len,is_null,FFieldType); end; class procedure TFRE_DB_UnsignedIndex.SetBinaryComparableKey(const keyvalue: qword; const key_target: PByte; var key_len: NativeInt; const is_null: boolean; const FieldType: TFRE_DB_FIELDTYPE; const invert_key: boolean); var FixedKeyLen : NativeInt; i : NativeInt; begin if not is_null then begin GetKeyLenForFieldtype(FieldType,FixedKeyLen); key_len := FixedKeylen+1; case FixedKeylen of 1: PByte(@key_target[1])^ := Byte(keyvalue); 2: PWord(@key_target[1])^ := SwapEndian(Word(keyvalue)); 4: PCardinal(@key_target[1])^ := SwapEndian(Cardinal(keyvalue)); 8: PQWord(@key_target[1])^ := SwapEndian(keyvalue); else raise EFRE_DB_PL_Exception.Create(edb_UNSUPPORTED,'unsupported fixed length in index transform to binary comparable'); end; key_target[0] := 1; // 0 , val are ordered after NULL values which are prefixed by '0' not by '1' if invert_key then for i := 1 to key_len do key_target[i] := not key_target[i]; end else begin key_len := 1 ; // FixedKeylen; {} if not invert_key then key_target[0] := 0 // first value else key_target[0] := 2 // last value end; end; constructor TFRE_DB_UnsignedIndex.CreateStreamed(const stream: TStream; const idx_name, fieldname: TFRE_DB_NameType; const fieldtype: TFRE_DB_FIELDTYPE; const unique: boolean; const collection: TFRE_DB_PERSISTANCE_COLLECTION; const allow_null: boolean; const unique_null: boolean; const domain_idx: boolean); begin Create(idx_name,fieldname,fieldtype,unique,collection,allow_null,unique_null,domain_idx); LoadIndex(stream,collection); end; procedure TFRE_DB_UnsignedIndex.FieldTypeIndexCompatCheck(fld: TFRE_DB_FIELD); begin if not SupportsDataType(fld.FieldType) then raise EFRE_DB_PL_Exception.Create(edb_ILLEGALCONVERSION,'the unsigned index can only be used to index a unsigned number field, not a [%s] field.',[fld.FieldTypeAsString]) end; function TFRE_DB_UnsignedIndex.NullvalueExists(var vals: TFRE_DB_IndexValueStore): boolean; var dummy : NativeUint; begin result := FIndex.ExistsBinaryKey(@nullkey,nullkeylen,dummy); if result then vals := FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore else vals := nil; end; function TFRE_DB_UnsignedIndex.SupportsDataType(const typ: TFRE_DB_FIELDTYPE): boolean; begin case typ of fdbft_Byte, fdbft_UInt16, fdbft_UInt32, fdbft_UInt64, fdbft_Boolean, fdbft_GUID, fdbft_ObjLink, fdbft_DateTimeUTC: result := true; else result := false; end; end; function TFRE_DB_UnsignedIndex.SupportsSignedQuery: boolean; begin result := false; end; function TFRE_DB_UnsignedIndex.SupportsUnsignedQuery: boolean; begin result := true; end; function TFRE_DB_UnsignedIndex.SupportsStringQuery: boolean; begin result := false; end; function TFRE_DB_UnsignedIndex.SupportsRealQuery: boolean; begin result := false; end; procedure TFRE_DB_UnsignedIndex.ForAllIndexedUnsignedRange(const min, max: QWord; var guids: TFRE_DB_GUIDArray; const ascending: boolean; const min_is_null: boolean; const max_is_max: boolean; const max_count: NativeInt; skipfirst: NativeInt); var lokey,hikey : Array [0..8] of Byte; lokeylen,hikeylen : NativeInt; lokeyp,hikeyp : PByte; procedure IteratorBreak(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var break : boolean ; var down_counter,up_counter : nativeint ; const abscntr : NativeInt); begin (FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore).AppendObjectUIDS(guids,ascending,down_counter,up_counter,abscntr); end; begin if (FFieldType = fdbft_GUID) or (FFieldType = fdbft_ObjLink) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'no range queries on an uid or objectlink index are allowed'); if not min_is_null then begin SetBinaryComparableKey(min,@lokey,lokeylen,min_is_null); lokeyp := lokey; end else lokeyp := nil; if not max_is_max then begin SetBinaryComparableKey(max,@hikey,hikeylen,max_is_max); hikeyp := hikey; end else hikeyp := nil; FIndex.RangeScan(lokeyp,hikeyp,lokeylen,hikeylen,@IteratorBreak,max_count,skipfirst,ascending) end; { TFRE_DB_ChangeStep } procedure TFRE_DB_ChangeStep.InternalWriteObject(const m: TMemoryStream; const obj: TFRE_DB_Object); var nsize: NativeInt; begin nsize := obj.NeededSize; m.WriteAnsiString(IntToStr(nsize)); if (m.Size-m.Position)<(nsize) then m.SetSize(m.Size + nsize + 4096); obj.CopyToMemory(m.Memory+m.Position); m.Position:=m.Position+nsize; end; procedure TFRE_DB_ChangeStep.InternalReadObject(const m: TStream; var obj: TFRE_DB_Object); var nsize : NativeInt; mem : Pointer; s : string; stackm : Array [1..4096] of Byte; begin s := m.ReadAnsiString; nsize := FREDB_String2NativeInt(s); if nsize>4096 then Getmem(mem,nsize) else mem := @stackm[1]; try m.ReadBuffer(mem^,nsize); obj := TFRE_DB_Object.CreateFromMemory(mem); finally if nsize>4096 then Freemem(mem); end; end; procedure TFRE_DB_ChangeStep.CheckWriteThroughIndexDrop(Coll: TFRE_DB_PERSISTANCE_COLLECTION_BASE; const index: TFRE_DB_NameType); begin CheckWriteThroughColl(coll); end; procedure TFRE_DB_ChangeStep.CheckWriteThroughColl(Coll: TFRE_DB_PERSISTANCE_COLLECTION_BASE); var layer : IFRE_DB_PERSISTANCE_LAYER; begin if coll.IsVolatile then exit; try layer := FLayer; if GDBPS_TRANS_WRITE_THROUGH then begin layer := coll.GetPersLayer; layer.WT_StoreCollectionPersistent(coll); GFRE_DBI.LogDebug(dblc_PERSISTANCE,Format('[%s]> WRITE THROUGH STORE COLLECTION (%s)',[Layer.GetConnectedDB,coll.CollectionName()])); end; except on e:Exception do begin GFRE_DBI.LogEmergency(dblc_PERSISTANCE,Format('[%s]> WRITE THROUGH ERROR STORE COLLECTION (%s) (%s)',[Layer.GetConnectedDB,coll.CollectionName(),e.Message])); end; end; end; procedure TFRE_DB_ChangeStep.CheckWriteThroughDeleteColl(Collname: TFRE_DB_NameType); begin try if GDBPS_TRANS_WRITE_THROUGH then begin FLayer.WT_DeleteCollectionPersistent(Collname); GFRE_DBI.LogDebug(dblc_PERSISTANCE,Format('[%s]> WRITE THROUGH DELETE COLLECTION (%s)',[FLayer.GetConnectedDB,Collname])); end; except on e:Exception do begin GFRE_DBI.LogEmergency(dblc_PERSISTANCE,Format('[%s]> WRITE THROUGH ERROR DELETE COLLECTION (%s) (%s)',[FLayer.GetConnectedDB,Collname,e.Message])); end; end; end; procedure TFRE_DB_ChangeStep.CheckWriteThroughObj(obj: IFRE_DB_Object); var layer : IFRE_DB_PERSISTANCE_LAYER; cdb : String; begin try if GDBPS_TRANS_WRITE_THROUGH then begin layer := FLayer; if (obj.Implementor as TFRE_DB_Object).IsSystemDB then begin layer := G_SysMaster.MyLayer; layer.WT_StoreObjectPersistent(obj); end else FLayer.WT_StoreObjectPersistent(obj); cdb := Layer.GetConnectedDB; GFRE_DBI.LogDebug(dblc_PERSISTANCE,Format('[%s]> WRITE THROUGH OBJECT (%s)',[cdb,obj.GetDescriptionID])); end; except on e:Exception do begin GFRE_DBI.LogEmergency(dblc_PERSISTANCE,Format('[%s]> WRITE THROUGH ERROR OBJECT (%s) (%s)',[Layer.GetConnectedDB,obj.GetDescriptionID,e.Message])); end; end; end; procedure TFRE_DB_ChangeStep.CheckWriteThroughDeleteObj(obj: IFRE_DB_Object); var layer : IFRE_DB_PERSISTANCE_LAYER; cdb : TFRE_DB_NameType; begin try if GDBPS_TRANS_WRITE_THROUGH then begin layer := FLayer; if (obj.Implementor as TFRE_DB_Object).IsVolatile then exit; if (obj.Implementor as TFRE_DB_Object).IsSystemDB then begin layer := G_SysMaster.MyLayer; Layer.WT_DeleteObjectPersistent(obj); end else Layer.WT_DeleteObjectPersistent(obj); cdb := Layer.GetConnectedDB; GFRE_DBI.LogDebug(dblc_PERSISTANCE,Format('[%s]> WRITE THROUGH DELETE OBJECT (%s)',[cdb,obj.GetDescriptionID])); end; except on e:Exception do begin GFRE_DBI.LogEmergency(dblc_PERSISTANCE,Format('[%s]> WRITE THROUGH ERROR DELETE OBJECT (%s) (%s)',[FLayer.GetConnectedDB,obj.GetDescriptionID,e.Message])); end; end; end; function TFRE_DB_ChangeStep._GetCollection(const coll_name: TFRE_DB_NameType; out Collection: TFRE_DB_PERSISTANCE_COLLECTION): Boolean; begin result := FMaster.MasterColls.GetCollection(coll_name,Collection); end; constructor TFRE_DB_ChangeStep.Create(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data ; const user_context : PFRE_DB_GUID); begin FLayer := layer; Fmaster := masterdata; FNotifIF := Flayer.GetNotificationRecordIF; FUserContext := user_context; end; procedure TFRE_DB_ChangeStep.CheckExistenceAndPreconds; begin if assigned(FUserContext) then G_GetUserToken(FUserContext,FUserToken,true); end; procedure TFRE_DB_ChangeStep.SetStepID(const id: NativeInt); begin FStepID:=id; end; function TFRE_DB_ChangeStep.GetTransActionStepID: TFRE_DB_TransStepId; begin result := FTransList.GetTransActionId+'/'+inttostr(FStepID); end; function TFRE_DB_ChangeStep.Master: TFRE_DB_Master_Data; begin result := Fmaster; end; { TFRE_DB_UpdateStep } constructor TFRE_DB_UpdateStep.Create(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data; obj: TFRE_DB_Object; const update_in_coll: TFRE_DB_NameType; const user_context: PFRE_DB_GUID); begin inherited Create(layer,masterdata,user_context); SetLength(FSublist,25); upobj := obj; FCollName := update_in_coll; end; constructor TFRE_DB_UpdateStep.CreateFromDiffTransport(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data; diff_update_obj: TFRE_DB_Object; const update_in_coll: TFRE_DB_NameType; const user_context: PFRE_DB_GUID); begin inherited Create(layer,masterdata,user_context); SetLength(FSublist,25); upobj := nil; FCollName := update_in_coll; FDiffUpdate := diff_update_obj; end; procedure TFRE_DB_UpdateStep.CheckExistenceAndPreconds; var P : TFRE_DB_GUIDArray; procedure GenUpdate(const is_child_update : boolean ; const up_obj : IFRE_DB_Object ; const update_type :TFRE_DB_ObjCompareEventType ;const new_ifield, old_ifield: IFRE_DB_Field); var child : TFRE_DB_Object; new_object : TFRE_DB_Object; old_fld, new_fld : TFRE_DB_FIELD; s : string; begin if assigned(old_ifield) then begin old_fld := old_ifield.Implementor as TFRE_DB_FIELD; s:=old_fld.FieldName; end else old_fld := nil; if assigned(new_ifield) then begin new_fld := new_ifield.Implementor as TFRE_DB_FIELD; s:=new_fld.FieldName; end else new_fld := nil; case update_type of cev_FieldDeleted: addsubstep(cev_FieldDeleted,nil,old_fld,is_child_update,up_obj.Implementor as TFRE_DB_Object); cev_FieldAdded: addsubstep(cev_FieldAdded,new_fld,nil,is_child_update,up_obj.Implementor as TFRE_DB_Object); cev_FieldChanged : if (new_fld.FieldType=fdbft_Object) and (new_fld.AsObject.UID=old_fld.AsObject.UID) then begin s:='HERE'; exit; { ignore updates on object fields with same uid, handled in this object } end else addsubstep(cev_FieldChanged,new_fld,old_fld,is_child_update,up_obj.Implementor as TFRE_DB_Object); end; end; procedure GenerateTheChangeListFromDiffObject; var deleted_fields, updated_fields, inserted_fields : TFRE_DB_StringArray; child_update : boolean; i : NativeInt; to_update_obj : TFRE_DB_Object; new_obj : TFRE_DB_Object; { child or root (!) } oldfield : TFRE_DB_FIELD; newfield : TFRE_DB_FIELD; difffield : TFRE_DB_FIELD; fieldname : TFRE_DB_NameType; iff : TFRE_DB_NameType; ichld : TFRE_DB_Object; inchld : TFRE_DB_Object; f_in_delete : boolean; begin deleted_fields := FDiffUpdate.Field('D_FN').AsStringArr; updated_fields := FDiffUpdate.Field('U_FN').AsStringArr; inserted_fields := FDiffUpdate.Field('I_FN').AsStringArr; child_update := Length(P)>1; if not child_update then begin to_update_obj := to_upd_obj; { "old" root } new_obj := upobj; { "new" root } end else begin new_obj := upobj; { "new" child } { search original old child, and create intermediate new childs } ichld := to_upd_obj; for i:=1 to high(p) do begin //writeln(i,'-- ICHILD ',ichld.UID_String,' search ',p[i].AsHexString); if not ichld.FetchObjByUIDNonHierarchic(p[i],iff,ichld) then begin //writeln('---FULLSTOP--- at index ',i); //writeln(to_upd_obj.DumpToString()); //writeln('---- ',p[i].AsHexString,' ----------'); //writeln(ichld.DumpToString()); //writeln('--------------'); raise EFRE_DB_Exception.Create(edb_ERROR,'diffupdate, find field, path not existent'); end; to_update_obj := ichld; inchld := TFRE_DB_Object.Create; inchld.Field('UID').AsGUID := p[i]; new_obj.Field(iff).AsObject := inchld; new_obj := inchld; end; end; for i := 0 to high(deleted_fields) do begin fieldname := deleted_fields[i]; if not to_update_obj.FieldOnlyExisting(fieldname,oldfield) then raise EFRE_DB_Exception.Create(edb_ERROR,'diffupdate deletefield / field not found [%s] in [%s]',[fieldname,to_update_obj.UID_String]); AddSubStep(cev_FieldDeleted,nil,oldfield,child_update,to_update_obj); end; for i := 0 to high(inserted_fields) do begin fieldname := inserted_fields[i]; f_in_delete:=false; if to_update_obj.FieldOnlyExisting(fieldname,oldfield) then begin if not FREDB_StringInArray(fieldname,deleted_fields) then raise EFRE_DB_Exception.Create(edb_ERROR,'diffupdate insertfield / field already existing field found [%s], and it is not in the actual delete list(!)',[fieldname]); f_in_delete := true; end; if not FDiffUpdate.FieldOnlyExisting('I_F_'+inttostr(i),difffield) then raise EFRE_DB_Exception.Create(edb_ERROR,'diffupdate difffield encoding insert [%s] / field not found [%s]',['I_F_'+inttostr(i),fieldname]); newfield := new_obj.Field(fieldname); newfield.CloneFromField(difffield); AddSubStep(cev_FieldAdded,newfield,nil,child_update,to_update_obj,f_in_delete); end; for i := 0 to high(updated_fields) do begin fieldname := updated_fields[i]; if not FDiffUpdate.FieldOnlyExisting('U_F_'+inttostr(i),difffield) then raise EFRE_DB_Exception.Create(edb_ERROR,'diffupdate difffield encoding update [%s] / field not found [%s]',['U_F_'+inttostr(i),fieldname]); if not to_update_obj.FieldOnlyExisting(fieldname,oldfield) then begin raise EFRE_DB_Exception.Create(edb_ERROR,'diffupdate updatefield / field not found [%s]',[fieldname]); end else begin newfield := new_obj.Field(fieldname); newfield.CloneFromField(difffield); if newfield.FieldType<>oldfield.FieldType then raise EFRE_DB_Exception.Create(edb_ERROR,'diff bulkupdate, fieldupdate, fiedtypes differ Field [%s] [%s]<>[%s]',[newfield.FieldName,newfield.FieldTypeAsString,oldfield.FieldTypeAsString]); if newfield.CompareToFieldShallow(oldfield) then raise EFRE_DB_Exception.Create(edb_ERROR,'diff bulkupdate, fieldupdate, rejecting update, fieldvalues are the same for field [%s]/[%s] in [%s]',[newfield.FieldName,newfield.FieldTypeAsString,to_update_obj.UID_String]); AddSubStep(cev_FieldChanged,newfield,oldfield,child_update,to_update_obj); end; end; end; begin inherited CheckExistenceAndPreconds; if not assigned(FDiffUpdate) then begin { Standard Update } FCnt := 0; if upobj.DomainID=CFRE_DB_NullGUID then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'persistance failure, an object without a domainid cannot be stored'); upobj._InternalGuidNullCheck; if not upobj.IsObjectRoot then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the object [%s] is a child object, only root objects updates are allowed',[upobj.UID_String]); if not FMaster.FetchObject(upobj.UID,to_upd_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'an object should be updated but was not found [%s]',[upobj.UID_String]); if length(to_upd_obj.__InternalGetCollectionList)=0 then begin writeln('BAD INTERNAL ::: OFFENDING OBJECT ', to_upd_obj.DumpToString()); if not GDBPS_SKIP_STARTUP_CHECKS then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'fetched to update ubj must have internal collections(!)'); end; if FCollName<>'' then if to_upd_obj.__InternalCollectionExistsName(FCollName)=-1 then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'update, a collectionname was given for updaterequest, but the dbo is not in that collection'); G_Transaction.Record_And_UnlockObject(to_upd_obj); TFRE_DB_Object.GenerateAnObjChangeList(upobj,to_upd_obj,nil,nil,@GenUpdate); end else begin { Differential Update } upobj := TFRE_DB_Object.Create; { create an dummy embedding updated object containing the "diff" fields } P := FDiffUpdate.Field('P').AsGUIDArr; upobj.Field('UID').AsGUID := P[0]; try if not FMaster.FetchObject(upobj.UID,to_upd_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'an object should be updated but was not found [%s]',[upobj.UID_String]); upobj.SetDomainID(to_upd_obj.DomainID); if upobj.DomainID=CFRE_DB_NullGUID then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'persistance failure, an object without a domainid cannot be stored'); if length(to_upd_obj.__InternalGetCollectionList)=0 then begin writeln('BAD INTERNAL ::: OFFENDING OBJECT ', to_upd_obj.DumpToString()); if not GDBPS_SKIP_STARTUP_CHECKS then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'fetched to update ubj must have internal collections(!)'); end; if FCollName<>'' then if to_upd_obj.__InternalCollectionExistsName(FCollName)=-1 then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'update, a collectionname was given for updaterequest, but the dbo is not in that collection'); G_Transaction.Record_And_UnlockObject(to_upd_obj); GenerateTheChangeListFromDiffObject; except on e:exception do begin writeln('DIFFUPDATE ERROR ------------'); writeln(e.Message); writeln(FDiffUpdate.DumpToString()); writeln('-----------------'); raise; end; end; end; end; procedure TFRE_DB_UpdateStep.AddSubStep(const uptyp: TFRE_DB_ObjCompareEventType; const new, old: TFRE_DB_FIELD; const is_a_child_field: boolean; const update_obj: TFRE_DB_Object; const is_in_delete_list: boolean); begin if FCnt>=Length(FSublist) then SetLength(FSublist,Length(FSublist)+25); with FSublist[fcnt] do begin updtyp := uptyp; newfield := new; oldfield := old; up_obj := update_obj; in_child_obj := is_a_child_field; in_del_list := is_in_delete_list; end; inc(fcnt); end; procedure TFRE_DB_UpdateStep.InternallApplyChanges(const check: boolean); var i,j : NativeInt; collarray : TFRE_DB_PERSISTANCE_COLLECTION_ARRAY; inmemobject : TFRE_DB_Object; procedure _DeletedField; begin with FSublist[i] do begin if not check then if assigned(FNotifIF) then FNotifIF.FieldDelete(oldfield,GetTransActionStepID); { Notify before delete } case oldfield.FieldType of fdbft_Object: begin if check then begin master.DeleteObjectWithSubobjs(oldfield.AsObject,true,FNotifIF,GetTransActionStepID,true); end else begin master.DeleteObjectWithSubobjs(oldfield.AsObject,false,FNotifIF,GetTransActionStepID,true); inmemobject.DeleteField(oldfield.FieldName); end; end; fdbft_ObjLink: begin if check then begin if in_child_obj then { new links are nil } raise EFRE_DB_Exception.Create(edb_INTERNAL,'UPDATE/DELETEFIELD a child object must not have reflinks/unexpected case'); end else begin master._ChangeRefLink(inmemobject,uppercase(inmemobject.SchemeClass),uppercase(oldfield.FieldName),oldfield.AsObjectLinkArray,nil,FNotifIF,GetTransActionStepID); inmemobject.Field(oldfield.FieldName).Clear; end; end; else begin if not check then inmemobject.DeleteField(oldfield.FieldName); end; // ok end; end; end; procedure _AddedField; var sc,fn : TFRE_DB_NameType; j : nativeint; procedure SubObjectInsert; var FInsertList : TFRE_DB_ObjectArray; k : NativeInt; begin if check then // debug begin if not FSublist[i].in_del_list then { skip store checks for to be in teh same step deleted objects } master.StoreObjectWithSubjs(FSublist[i].newfield.AsObject,check,FNotifIF,GetTransActionStepID); end else begin { for real } inmemobject.Field(FSublist[i].newfield.FieldName).AsObject := FSublist[i].newfield.AsObject.CloneToNewObject(); { subobject insert} master.StoreObjectWithSubjs(inmemobject.Field(FSublist[i].newfield.FieldName).AsObject,check,FNotifIF,GetTransActionStepID); end; end; begin assert(assigned(inmemobject),'internal, logic'); with FSublist[i] do begin if not check then if assigned(FNotifIF) then FNotifIF.FieldAdd(newfield,GetTransActionStepID) else if (inmemobject.FieldExists(newfield.FieldName) and (not in_del_list)) then raise EFRE_DB_Exception.Create(edb_ERROR,'updatestep add field [%s] to object [%s], but the field already exists, and it is not in a delete that happens before',[newfield.FieldName,inmemobject.UID_String]); case newfield.FieldType of fdbft_NotFound,fdbft_GUID,fdbft_Byte,fdbft_Int16,fdbft_UInt16,fdbft_Int32,fdbft_UInt32,fdbft_Int64,fdbft_UInt64, fdbft_Real32,fdbft_Real64,fdbft_Currency,fdbft_String,fdbft_Boolean,fdbft_DateTimeUTC,fdbft_Stream : begin if check then exit; inmemobject.Field(newfield.fieldName).CloneFromField(newfield); end; fdbft_Object: begin SubObjectInsert; end; fdbft_ObjLink: if check then begin if not FREDB_CheckGuidsUnique(newfield.AsObjectLinkArray) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'objectlink array field is not unique Field[%s] Object[%s]',[newfield.FieldName,newfield.ParentObject.UID_String]); for j:=0 to high(newfield.AsObjectLinkArray) do master.__CheckReferenceLink(inmemobject,newfield.FieldName,newfield.AsObjectLinkArray[j],sc); end else begin fn := uppercase(inmemobject.SchemeClass)+'<'+ uppercase(newfield.FieldName); inmemobject.Field(newfield.FieldName).AsObjectLinkArray:=newfield.AsObjectLinkArray; for j:=0 to high(newfield.AsObjectLinkArray) do begin master.__CheckReferenceLink(inmemobject,newfield.FieldName,newfield.AsObjectLinkArray[j],sc); master.__SetupInitialRefLink(inmemobject,sc,fn,newfield.AsObjectLinkArray[j],FNotifIF,GetTransActionStepID); end; end; end; end; end; procedure _ChangedField; var sc,fn : TFRE_DB_NameType; j : nativeint; oldlinks : TFRE_DB_GUIDArray; existobj : TFRE_DB_Object; begin with FSublist[i] do begin assert(up_obj.ObjectRoot = to_upd_obj,'internal, logic'); if (not check) then begin if assigned(FNotifIF) then FNotifIF.FieldChange(oldfield, newfield,GetTransActionStepID); end; case newfield.FieldType of fdbft_NotFound,fdbft_GUID,fdbft_Byte,fdbft_Int16,fdbft_UInt16,fdbft_Int32,fdbft_UInt32,fdbft_Int64,fdbft_UInt64, fdbft_Real32,fdbft_Real64,fdbft_Currency,fdbft_String,fdbft_Boolean,fdbft_DateTimeUTC,fdbft_Stream : begin if check then exit; inmemobject.Field(newfield.FieldName).CloneFromField(newfield); end; fdbft_Object: begin if oldfield.AsObject.UID = newfield.AsObject.UID then raise EFRE_DB_Exception.Create(edb_ERROR,'it is not allowed to do a subobject filedupdate with the same uid (same) object in field [%s] of obj [%s] with new objuid [%s]',[newfield.FieldName,inmemobject.UID_String,newfield.AsObject.UID_String]); { Free old object, masterfree(old uid=1), store new object, masterstore new object(uid = 1) } if check then begin if FMaster.FetchObject(newfield.AsObject.UID,existobj,true) then begin if existobj.IsObjectRoot then raise EFRE_DB_Exception.Create(edb_ERROR,'the subobject [%s] that is to be inserted in field [%s] of object [%s], is already stored as root object',[newfield.AsObject.UID_String,newfield.FieldName,to_upd_obj.UID_String]) else raise EFRE_DB_Exception.Create(edb_ERROR,'the subobject [%s] that is to be inserted in field [%s] of object [%s], is already stored as field [%s] in object [%s]',[newfield.AsObject.UID_String,newfield.FieldName,to_upd_obj.UID_String,existobj.ParentField.FieldName,to_upd_obj.UID_String]) end; end else begin master.DeleteObjectWithSubobjs(oldfield.AsObject,false,FNotifIF,GetTransActionStepID,true); inmemobject.DeleteField(oldfield.FieldName); inmemobject.Field(newfield.FieldName).AsObject := newfield.AsObject.CloneToNewObject(); { subobject insert} master.StoreObjectWithSubjs(inmemobject.Field(newfield.FieldName).AsObject,check,FNotifIF,GetTransActionStepID); end; end; fdbft_ObjLink: if check then begin if not FREDB_CheckGuidsUnique(newfield.AsObjectLinkArray) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'objectlink array field is not unique Field[%s] Object[%s]',[newfield.FieldName,newfield.ParentObject.UID_String]); for j:=0 to high(newfield.AsObjectLinkArray) do master.__CheckReferenceLink(inmemobject,newfield.FieldName,newfield.AsObjectLinkArray[j],sc,true); end else begin oldlinks := oldfield.AsObjectLinkArray; inmemobject.Field(newfield.FieldName).AsObjectLinkArray:=newfield.AsObjectLinkArray; if inmemobject.IsSystemDB then begin G_SysMaster._ChangeRefLink(inmemobject,uppercase(inmemobject.SchemeClass),uppercase(newfield.FieldName),oldlinks,newfield.AsObjectLinkArray,FNotifIF,GetTransActionStepID); end else begin master._ChangeRefLink(inmemobject,uppercase(inmemobject.SchemeClass),uppercase(newfield.FieldName),oldlinks,newfield.AsObjectLinkArray,FNotifIF,GetTransActionStepID); end; end; end; end; end; procedure CheckWriteThrough; var arr : TFRE_DB_PERSISTANCE_COLLECTION_ARRAY; i : NativeInt; begin CheckWriteThroughObj(to_upd_obj); arr := to_upd_obj.__InternalGetCollectionList; for i:=0 to high(arr) do CheckWriteThroughColl(arr[i]); end; var diffupdo : TFRE_DB_Object; begin if not check then begin to_upd_obj.Field(cFRE_DB_SYS_T_LMO_TRANSID).AsString := GetTransActionStepID; diffupdo := to_upd_obj.CloneToNewObject; { TODO: replace with a more efficient solution, new object (streaming/weak ...)} diffupdo.ClearAllFields; diffupdo.Field('uid').AsGUID := to_upd_obj.UID; diffupdo.Field('domainid').AsGUID := to_upd_obj.DomainID; if assigned(FNotifIF) then FNotifIF.DifferentiallUpdStarts(diffupdo,GetTransActionStepID); end; for i:=0 to FCnt-1 do begin with FSublist[i] do begin //writeln(i,' >> ',updtyp,' ',check,' ',in_del_list); inmemobject := up_obj; { a object in to_upd_obj, or = to_upd_obj } case updtyp of cev_FieldDeleted: _DeletedField; cev_FieldAdded: _AddedField; cev_FieldChanged: _ChangedField; end; end; end; if not check then if assigned(FNotifIF) then FNotifIF.DifferentiallUpdEnds(to_upd_obj.UID,GetTransActionStepID); { Notifications will be transmitted on block level -> no special handling here, block get deleted on error } if not check then begin to_upd_obj.Field(cFRE_DB_SYS_T_LMO_TRANSID).AsString := GetTransActionStepID; if assigned(FNotifIF) then FNotifIF.ObjectUpdated(to_upd_obj,to_upd_obj.__InternalGetCollectionListUSL,GetTransActionStepID); {$IFDEF DEBUG_CONSOLE_DUMP_TRANS} writeln('---UPDATESTEP DUMP --- FINAL'); writeln(to_upd_obj.ObjectRoot.DumpToString()); writeln('---UPDATESTEP DUMP --- DONE'); {$ENDIF} CheckWriteThrough; end; end; procedure TFRE_DB_UpdateStep.ChangeInCollectionCheckOrDo(const check: boolean); var i,j : NativeInt; collarray : TFRE_DB_PERSISTANCE_COLLECTION_ARRAY; begin for i:=0 to FCnt-1 do with FSublist[i] do begin collarray := to_upd_obj.__InternalGetCollectionList; for j := 0 to high(collarray) do (collarray[j] as TFRE_DB_Persistance_Collection).UpdateInThisColl(newfield,oldfield,to_upd_obj,upobj,updtyp,in_child_obj,check); { need to check indices, if appropriate } end end; //Check what has to be done at master level, (reflinks) procedure TFRE_DB_UpdateStep.MasterStore(const check: boolean); begin if to_upd_obj.IsObjectRoot then if length(to_upd_obj.__InternalGetCollectionList)=0 then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'must have internal collections to store into'); InternallApplyChanges(check); end; { TFRE_DB_TransactionalUpdateList } //function ChangeStepNull (const cs : PFRE_DB_ChangeStep):boolean; //begin // result := not assigned(cs^); //end; // //function ChangeStepSame (const cs1,cs2 : PFRE_DB_ChangeStep):boolean; //begin // result := cs1^=cs2^; //end; constructor TFRE_DB_TransactionalUpdateList.Create(const TransID: TFRE_DB_NameType; const master_data: TFRE_DB_Master_Data; const notify_if: IFRE_DB_DBChangedNotification); begin // FChangeList.InitSparseList(nil,@ChangeStepNull,@ChangeStepSame,10); FChangeList.InitSparseListPtrCmp(10); FTransNumber := G_FetchNewTransactionID; FTransId := IntToStr(G_DB_TX_Number)+'#'+TransID; FLockDir := TFRE_DB_Object.Create; end; function TFRE_DB_TransactionalUpdateList.AddChangeStep(const step: TFRE_DB_ChangeStep): NativeInt; begin step.FTransList := self; result := FChangeList.Add(step); step.SetStepID(result); FLastStepId := step.GetTransActionStepID; end; procedure TFRE_DB_TransactionalUpdateList.Record_And_UnlockObject(const obj: TFRE_DB_Object); begin obj.Assert_CheckStoreLocked; obj.Set_Store_Locked(false); FLockDir.Field(obj.UID_String).AsBoolean:=true; end; procedure TFRE_DB_TransactionalUpdateList.Record_A_NewObject(const obj: TFRE_DB_Object); begin FLockDir.Field(obj.UID_String).AsBoolean:=true; end; procedure TFRE_DB_TransactionalUpdateList.Forget_UnlockedObject(const obj: TFRE_DB_Object); begin FLockDir.DeleteField(obj.UID_String); end; procedure TFRE_DB_TransactionalUpdateList.Lock_Unlocked_Objects; procedure Lockit(const f:TFRE_DB_FIELD); var uid : TFRE_DB_GUID; fn : TFRE_DB_NameType; begin if f.FieldType=fdbft_Boolean then begin fn := f.FieldName; uid := FREDB_H2G(fn); try TFRE_DB_Master_Data._TransactionalLockObject(uid); except on e:exception do begin GFRE_DBI.LogError(dblc_PERSISTANCE,'LockUnockedObjects(Transaction) Failure : '+e.Message); raise; end; end; end; end; begin try try FLockDir.ForAllFields(@Lockit); finally FLockDir.ClearAllFields; end; except on e: exception do begin writeln('INTERNAL FAULT>> Lock_Unlocked_Objects '+e.Message); end; end; end; function ObjecTFRE_DB_GUIDCompare (const o1,o2 : PFRE_DB_Object):boolean; begin result := FREDB_Guids_Same(o1^.UID,o2^.UID); end; function DBObjIsNull (const obj : PFRE_DB_Object) : Boolean; begin result := not assigned(obj^); end; function TFRE_DB_TransactionalUpdateList.GetTransActionId: TFRE_DB_NameType; begin result := FTransId; end; function TFRE_DB_TransactionalUpdateList.GetTransLastStepTransId: TFRE_DB_TransStepId; begin result := FLastStepId; end; procedure TFRE_DB_TransactionalUpdateList.ProcessCheck; var failure : boolean; procedure CheckForExistence(var step:TFRE_DB_ChangeStep;const idx:NativeInt ; var halt_flag:boolean); begin with step do CheckExistenceAndPreconds; end; procedure StoreInCollectionCheck(var step:TFRE_DB_ChangeStep;const idx:NativeInt ; var halt_flag:boolean); begin with step do ChangeInCollectionCheckOrDo(true); end; procedure MasterStoreCheck(var step:TFRE_DB_ChangeStep;const idx:NativeInt ; var halt_flag:boolean); begin with step do MasterStore(true); end; begin failure := false; FChangeList.ForAllBreak(@CheckForExistence); FChangeList.ForAllBreak(@StoreInCollectionCheck); FChangeList.ForAllBreak(@MasterStoreCheck); end; function TFRE_DB_TransactionalUpdateList.Commit: boolean; var changes : boolean; l_notifs : TList; ftransid_w_layer : IFRE_DB_PERSISTANCE_LAYER; procedure StoreInCollection(var step:TFRE_DB_ChangeStep;const idx:NativeInt ; var halt_flag:boolean); begin step.ChangeInCollectionCheckOrDo(false); if step is TFRE_DB_InsertStep then halt_flag:=true; end; //Store objects and sub objects procedure MasterStore(var step:TFRE_DB_ChangeStep;const idx:NativeInt ; var halt_flag:boolean); begin if not assigned(ftransid_w_layer) then ftransid_w_layer := step.FLayer; { just get one layer to write the last transaction id on success } step.MasterStore(false); end; procedure GatherNotifs(var step:TFRE_DB_ChangeStep;const idx:NativeInt ; var halt_flag:boolean); var ni : IFRE_DB_DBChangedNotification; begin ni := step.FNotifIF; if assigned(ni) then if l_notifs.IndexOf(ni)=-1 then l_notifs.Add(ni); end; procedure StartNotifBlocks; var i : NativeInt; begin for i := 0 to l_notifs.Count-1 do with IFRE_DB_DBChangedNotification(l_notifs.Items[i]) do StartNotificationBlock(FTransId); end; procedure SendNotifBlocks; var i : NativeInt; block : IFRE_DB_Object; begin for i := 0 to l_notifs.Count-1 do with IFRE_DB_DBChangedNotification(l_notifs.Items[i]) do begin FinishNotificationBlock(block); if assigned(block) then SendNotificationBlock(block); end; end; begin ftransid_w_layer := nil; try { Perform all necessary prechecks before changing the Database } ProcessCheck; changes := FChangeList.Count>0; { Apply the changes, and record the Notifications } if changes then begin try if changes then begin try l_notifs := TList.Create; FChangeList.ForAllBreak(@GatherNotifs); StartNotifBlocks; FChangeList.ForAllBreak(@StoreInCollection); FChangeList.ForAllBreak(@MasterStore); ftransid_w_layer.WT_TransactionID(FTransNumber); SendNotifBlocks; except on e:exception do begin GFRE_DBI.LogEmergency(dblc_PERSISTANCE,'-TRANSACTION FAILURE (NOT IN CHECK PHASE) [%s]'+e.Message); GFRE_BT.CriticalAbort('-TRANSACTION FAILURE (NOT IN CHECK PHASE) [%s]'+e.Message); end; end; end else changes:=changes; finally l_notifs.free; end; end; result := changes; finally Lock_Unlocked_Objects; end; {$IFDEF DEBUG_STORELOCK} GFRE_DB_PS_LAYER.DEBUG_InternalFunction(1); { Full Storelocking Check } {$ENDIF} {$IFDEF DEBUG_SUBOBJECTS_STORED} GFRE_DB_PS_LAYER.DEBUG_InternalFunction(2); { Full Subobject Storage Check } {$ENDIF} end; procedure TFRE_DB_TransactionalUpdateList.Rollback; begin abort; end; destructor TFRE_DB_TransactionalUpdateList.Destroy; procedure CleanUp(var step:TFRE_DB_ChangeStep;const idx:NativeInt ; var halt_flag:boolean); begin step.Free; end; begin FChangeList.ForAllBreak(@Cleanup); FLockDir.Free; end; { TFRE_DB_InsertStep } constructor TFRE_DB_InsertStep.Create(const layer: IFRE_DB_PERSISTANCE_LAYER; const masterdata: TFRE_DB_Master_Data; new_obj: TFRE_DB_Object; const insert_in_coll: TFRE_DB_NameType; const user_context: PFRE_DB_GUID; const replace_existing_subobjects_with_weak_links: boolean); var cn:string; begin inherited Create(layer,masterdata,user_context); FCollName := insert_in_coll; FReplaceExistingSubOWithL := replace_existing_subobjects_with_weak_links; FInsertList := new_obj.GetFullHierarchicObjectList(true); end; procedure TFRE_DB_InsertStep.CheckExistenceAndPreconds; var existing_object : TFRE_DB_Object; i : NativeInt; Foldobject : TFRE_DB_Object; procedure CheckExistingOtherCollectionStore; begin if i<>0 then { a subobject } raise EFRE_DB_Exception.Create(edb_INTERNAL,'a subobject of the to be inserted object already exist as an objectroot / offender : [%s / %s]',[existing_object.UID_String,existing_object.SchemeClass]); G_Transaction.Record_And_UnlockObject(existing_object); if existing_object.__InternalCollectionExistsName(FCollName)<>-1 then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'the to be stored rootobject [%s] does already exist in master data as subobject or rootobject, and in the specified collection [%s]',[FInsertList[i].UID_String,FCollName]); if not TFRE_DB_Object.CompareObjectsEqual(FInsertList[i],existing_object) then raise EFRE_DB_PL_Exception.Create(edb_MISMATCH,'add to other collection / the to be stored rootobject [%s] does already exist in master data as subobject or rootobject, it is requested to store in the new collection [%s], but the insert object is not exactly the same as the existing object',[FInsertList[i].UID_String,FCollName]); FThisIsAnAddToAnotherColl := true; Foldobject := FInsertList[0]; SetLength(FInsertList,1); FInsertList[0] := existing_object; try Foldobject.free; except on e:exception do begin GFRE_DBI.LogError(dblc_PERSISTANCE,'unexpected exception InsertStep/Checkexistience multiple collection store [%s]',[e.Message]); end; end; end; procedure PreProcessInsertList; var cycle : boolean; i : NativeInt; ex_obj : TFRE_DB_Object; fld : IFRE_DB_Field; fname : TFRE_DB_NameType; src_uid: TFRE_DB_GUID; begin repeat cycle := false; for i:=1 to high(FInsertList) do { start at the first child } begin src_uid := FInsertList[i].UID; if master.ExistsObject(src_uid) then begin { a subobject already exists, stored } cycle := true; if not FInsertList[0].FetchObjFieldByUID(src_uid,fld) then raise EFRE_DB_Exception.Create(edb_INTERNAL,'critical - subobjectfield [%s] should be found but was not',[src_uid.AsHexString]); fname := fld.FieldName; fld.Clear; { replace the object by a uid } fld.AsString := cFRE_DB_DIFFUP_SUBOBJ_EXISTS+':'+src_uid.AsHexString; FInsertList := FInsertList[0].GetFullHierarchicObjectList(true); { replace the current insert list, and cycle } break; { break for loop } end; end; if not cycle then break; until false; end; begin {$IFDEF DEBUG_OFFENDERS} try {$ENDIF} if FCollName='' then raise EFRE_DB_PL_Exception.Create(edb_INVALID_PARAMS,'a collectionname must be provided on store request'); if not _GetCollection(FCollName,FColl) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'store step, the specified collection [%s] was not found',[FCollName]); if FInsertList[0].IsObjectRoot=false then raise EFRE_DB_Exception.Create(edb_INTERNAL,'initial store of non root objects is not allowed'); if FInsertList[0].DomainID=CFRE_DB_NullGUID then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'store, persistance failure, an object without a domainid cannot be stored'); if FReplaceExistingSubOWithL then PreprocessInsertList; FInsertList[0]._InternalGuidNullCheck; if Fcoll.IsVolatile then FInsertList[0].Set_Volatile; for i:=0 to high(FInsertList) do begin if master.FetchObject(FInsertList[i].UID,existing_object,true) then if existing_object.IsObjectRoot then begin CheckExistingOtherCollectionStore; break; { stop insert object processing } end else begin raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'for the to be stored rootobject [%s] a subobject [%s] does already exist in master data as subobject or rootobject, the specified collection is [%s]',[FInsertList[0].UID_String,FInsertList[i].UID_String,FCollName]); end; end; {$IFDEF DEBUG_OFFENDERS} except writeln('>INSERT---OFFENDING OBJECT---'); writeln(FInsertList[0].DumpToString(2)); writeln('<INSERT---OFFENDING OBJECT---'); raise end; {$ENDIF} end; procedure TFRE_DB_InsertStep.ChangeInCollectionCheckOrDo(const check: boolean); begin try (FColl as TFRE_DB_Persistance_Collection).StoreInThisColl(FInsertList[0],check); except on e:Exception do begin writeln('INSERT STEP <',GetTransActionStepID,'> FAILURE ('+e.Message+')'); { TODO -> In transaction and Step ID} writeln('Offending Object'); writeln('-------------------'); writeln(FInsertList[0].DumpToString(2)); writeln('-------------------'); raise; end; end; end; procedure TFRE_DB_InsertStep.MasterStore(const check: boolean); var i : NativeInt; begin assert((check=true) or (length(FInsertList[0].__InternalGetCollectionList)>0)); if check then G_Transaction.Record_A_NewObject(FInsertList[0]); if not FThisIsAnAddToAnotherColl then begin master.StoreObjectWithSubjs(FInsertList[0],check,FNotifIF,GetTransActionStepID); end; if not check then begin FInsertList[0].Field(cFRE_DB_SYS_T_LMO_TRANSID).AsString := GetTransActionStepID; if assigned(FNotifIF) then FNotifIF.ObjectStored(FColl.CollectionName, FInsertList[0],GetTransActionStepID); CheckWriteThroughObj(FInsertList[0]); CheckWriteThroughColl(FColl); end; end; { TFRE_DB_IndexValueStore } procedure TFRE_DB_IndexValueStore.InternalCheck; var i:NativeInt; begin //try // for i:=0 to high(FOBJArray) do // FOBJArray[i].Assert_CheckStoreLocked; //except on e:Exception do // begin // writeln('E ',e.Message); // writeln('LEN ARRAY ',Length(FOBJArray)); // for i:=0 to high(FOBJArray) do // begin // writeln('--',i,' ',FOBJArray[i].InternalUniqueDebugKey); // writeln(FOBJArray[i].DumpToString()); // writeln('--'); // end; // raise; // end; //end; end; function TFRE_DB_IndexValueStore.Exists(const guid: TFRE_DB_GUID): boolean; var i : NativeInt; begin for i := 0 to High(FOBJArray) do if FREDB_Guids_Compare(FOBJArray[i],guid)=0 then exit(true); result := false; end; function TFRE_DB_IndexValueStore.Add(const objuid: TFRE_DB_GUID): boolean; begin if Exists(objuid) then exit(false); SetLength(FOBJArray,Length(FOBJArray)+1); FOBJArray[high(FOBJArray)] := objuid; result := true; end; procedure TFRE_DB_IndexValueStore.StreamToThis(const stream: TStream); var i : NativeInt; begin stream.WriteQWord(Length(FOBJArray)); for i:=0 to high(FOBJArray) do stream.WriteBuffer(FOBJArray[i],SizeOf(TFRE_DB_GUID)); end; procedure TFRE_DB_IndexValueStore.LoadFromThis(const stream: TStream; const coll: TFRE_DB_PERSISTANCE_COLLECTION); var i,cnt : NativeInt; uid : TFRE_DB_GUID; obj : IFRE_DB_Object; begin cnt := stream.ReadQWord; SetLength(FOBJArray,cnt); for i:=0 to high(FOBJArray) do begin stream.ReadBuffer(uid,SizeOf(TFRE_DB_GUID)); FOBJArray[i] := uid; if not coll.FetchIntFromColl(uid,obj) then // raise EFRE_DB_PL_Exception.Create(edb_ERROR,'STREAM LOAD INDEX ERROR CANT FIND [%s] IN COLLECTION',[FREDB_G2H(uid)]); end; end; function TFRE_DB_IndexValueStore.ObjectCount: NativeInt; begin result := Length(FOBJArray); end; procedure TFRE_DB_IndexValueStore.AppendObjectUIDS(var uids: TFRE_DB_GUIDArray; const ascending: boolean; var down_counter, up_counter: NativeInt ; const max_count : Nativeint); var i,pos : NativeInt; begin pos := Length(uids); SetLength(uids,Length(uids)+ObjectCount); if ascending then for i := 0 to high(FOBJArray) do begin if down_counter>0 then dec(down_counter) else begin uids[pos] := FOBJArray[i]; inc(pos); inc(up_counter); if (max_count>0) and (up_counter>=max_count) then break; end; end else for i := high(FOBJArray) downto 0 do begin if down_counter>0 then dec(down_counter) else begin uids[pos] := FOBJArray[i]; inc(pos); inc(up_counter); if (max_count>0) and (up_counter>=max_count) then break; end; end; if pos<>Length(uids) then SetLength(uids,pos); end; function TFRE_DB_IndexValueStore.RemoveUID(const guid: TFRE_DB_GUID): boolean; var i : NativeInt; newarray : TFRE_DB_GUIDArray; cnt : NativeInt; begin SetLength(newarray,high(FOBJArray)); cnt := 0; result := false; for i := 0 to High(FOBJArray) do if FOBJArray[i]<>guid then begin newarray[cnt] := FOBJArray[i]; inc(cnt); end else result := true; FOBJArray := newarray; end; constructor TFRE_DB_IndexValueStore.create; begin inherited; end; destructor TFRE_DB_IndexValueStore.Destroy; begin inherited Destroy; end; { TFRE_DB_Master_Data } function TFRE_DB_Master_Data.GetOutBoundRefLinks(const from_obj: TFRE_DB_GUID): TFRE_DB_ObjectReferences; var key : RFRE_DB_GUID_RefLink_InOut_Key; cnt : NativeInt; procedure Iterate(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var halt : boolean); var namelen : NativeInt; name : TFRE_DB_NameType; begin if cnt=Length(result) then SetLength(result,Length(result)+10); assert(value=$BAD0BEEF); namelen := KeyLen-33; Assert(namelen>0); SetLength(name,namelen); move(PFRE_DB_GUID_RefLink_In_Key(key)^.SchemeSepField,name[1],namelen); // copy name result[cnt].fieldname := GFRE_BT.SepLeft(name,'>'); result[cnt].schemename := GFRE_BT.SepRight(name,'>'); move(PFRE_DB_GUID_RefLink_In_Key(key)^.ToFromGuid,result[cnt].linked_uid,16); // copy guid inc(cnt); end; begin cnt := 0; move(from_obj,key.GUID,16); key.RefTyp:=$99; FMasterRefLinks.PrefixScan(@key,17,@Iterate); SetLength(result,cnt); end; function TFRE_DB_Master_Data.GetInboundRefLinks(const to_obj: TFRE_DB_GUID): TFRE_DB_ObjectReferences; var key : RFRE_DB_GUID_RefLink_InOut_Key; cnt : NativeInt; procedure Iterate(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var halt : boolean); var namelen : NativeInt; name : TFRE_DB_NameType; begin if cnt=Length(result) then SetLength(result,Length(result)+10); assert(value=$BEEF0BAD); namelen := KeyLen-33; Assert(namelen>0); SetLength(name,namelen); move(PFRE_DB_GUID_RefLink_In_Key(key)^.SchemeSepField,name[1],namelen); // copy name result[cnt].fieldname := GFRE_BT.SepRight(name,'<'); result[cnt].schemename := GFRE_BT.SepLeft(name,'<'); move(PFRE_DB_GUID_RefLink_In_Key(key)^.ToFromGuid,result[cnt].linked_uid,16); // copy guid inc(cnt); end; begin cnt := 0; move(to_obj,key.GUID,16); key.RefTyp:=$AA; FMasterRefLinks.PrefixScan(@key,17,@Iterate); SetLength(result,cnt); end; procedure TFRE_DB_Master_Data.__RemoveInboundReflink(const from_uid, to_uid: TFRE_DB_GUID; const scheme_link_key: TFRE_DB_NameTypeRL; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var refinkey : RFRE_DB_GUID_RefLink_InOut_Key; exists : boolean; value : PtrUInt; from_obj : TFRE_DB_Object; to_obj : TFRE_DB_Object; lock_statef : boolean; lock_statet : boolean; begin __SetupInboundLinkKey(from_uid,to_uid,scheme_link_key,refinkey); exists := FMasterRefLinks.RemoveBinaryKey(@refinkey,refinkey.KeyLength,value); if not exists then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'internal inbound reflink structure bad, inbound link not found for outbound from,to,schemelink [%s, %s, %s]',[FREDB_G2H(from_uid),FREDB_G2H(to_uid),scheme_link_key]); if value<>$BEEF0BAD then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'internal inbound reflink structure bad, value invalid [%d]',[value]); if not FetchObject(from_uid,from_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'remove inbound reflink from obj not found %s',[from_obj.UID_String]); if not FetchObject(to_uid,to_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'remove inbound reflink to obj not found %s',[to_obj.UID_String]); if assigned(notifif) then begin from_obj.Set_Store_LockedUnLockedIf(false,lock_statef); { Locking is ok here, to reduce cloning } to_obj.Set_Store_LockedUnLockedIf(false,lock_statet); { Locking is ok here, to reduce cloning } try notifif.InboundReflinkDropped(from_obj,to_obj,scheme_link_key,tsid); finally from_obj.Set_Store_LockedUnLockedIf(true,lock_statef); to_obj.Set_Store_LockedUnLockedIf(true,lock_statet); end; end; end; procedure TFRE_DB_Master_Data.__RemoveOutboundReflink(const from_uid, to_uid: TFRE_DB_GUID; const scheme_link_key: TFRE_DB_NameTypeRL; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var refoutkey : RFRE_DB_GUID_RefLink_InOut_Key; exists : boolean; value : PtrUInt; from_obj : TFRE_DB_Object; to_obj : TFRE_DB_Object; lock_statef : boolean; lock_statet : boolean; begin __SetupOutboundLinkKey(from_uid,to_uid,scheme_link_key,refoutkey); exists := FMasterRefLinks.RemoveBinaryKey(@refoutkey,refoutkey.KeyLength,value); if not exists then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'internal outbound reflink structure bad, inbound link not found for outbound from,to,schemelink [%s, %s, %s]',[FREDB_G2H(from_uid),FREDB_G2H(to_uid),scheme_link_key]); if value<>$BAD0BEEF then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'internal outbound reflink structure bad, value invalid [%d]',[value]); if not FetchObject(from_uid,from_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'remove outbound reflink from obj not found %s',[from_obj.UID_String]); if not FetchObject(to_uid,to_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'remove outbound reflink to obj not found %s',[to_obj.UID_String]); if assigned(notifif) then begin to_obj.Set_Store_LockedUnLockedIf(false,lock_statet); from_obj.Set_Store_LockedUnLockedIf(false,lock_statef); try notifif.OutboundReflinkDropped(from_obj,to_obj,scheme_link_key,tsid); { Locking is ok here, to reduce cloning } finally to_obj.Set_Store_LockedUnLockedIf(true,lock_statet); from_obj.Set_Store_LockedUnLockedIf(true,lock_statef); end; end; end; procedure TFRE_DB_Master_Data.__RemoveRefLink(const from_uid, to_uid: TFRE_DB_GUID; const upper_from_schemename, upper_fieldname, upper_to_schemename: TFRE_DB_NameType; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var scheme_link_key : TFRE_DB_NameTypeRL; begin scheme_link_key := upper_from_schemename+'<'+upper_fieldname; __RemoveInboundRefLink(from_uid,to_uid,scheme_link_key,notifif,tsid); scheme_link_key := upper_fieldname+'>'+upper_to_schemename; __RemoveOutboundReflink(from_uid,to_uid,scheme_link_key,notifif,tsid); end; procedure TFRE_DB_Master_Data.__SetupOutboundLinkKey(const from_uid, to_uid: TFRE_DB_GUID; const scheme_link_key: TFRE_DB_NameTypeRL; var refoutkey: RFRE_DB_GUID_RefLink_InOut_Key); begin move(from_uid,refoutkey.GUID,16); refoutkey.RefTyp := $99; move(to_uid,refoutkey.ToFromGuid,16); move(scheme_link_key[1],refoutkey.SchemeSepField,Length(scheme_link_key)); refoutkey.KeyLength := 33+Length(scheme_link_key); end; procedure TFRE_DB_Master_Data.__SetupInboundLinkKey(const from_uid, to_uid: TFRE_DB_GUID; const scheme_link_key: TFRE_DB_NameTypeRL; var refinkey: RFRE_DB_GUID_RefLink_InOut_Key); begin move(to_uid,refinkey.GUID,16); refinkey.RefTyp := $AA; move(from_uid,refinkey.ToFromGuid,16); move(scheme_link_key[1],refinkey.SchemeSepField,length(scheme_link_key)); refinkey.KeyLength := 33+Length(scheme_link_key); end; function TFRE_DB_Master_Data.__RefLinkOutboundExists(const from_uid: TFRE_DB_GUID; const fieldname: TFRE_DB_NameType; to_object: TFRE_DB_GUID; const scheme_link: TFRE_DB_NameTypeRL): boolean; var refoutkey : RFRE_DB_GUID_RefLink_InOut_Key; value : PtrUInt; begin __SetupOutboundLinkKey(from_uid,to_object,scheme_link,refoutkey); result := FMasterRefLinks.ExistsBinaryKey(@refoutkey,refoutkey.KeyLength,value); if result and (value<>$BAD0BEEF) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'internal outbound reflink structure bad, value invalid [%d]',[value]); end; function TFRE_DB_Master_Data.__RefLinkInboundExists(const from_uid: TFRE_DB_GUID; const fieldname: TFRE_DB_NameType; to_object: TFRE_DB_GUID; const scheme_link: TFRE_DB_NameTypeRL): boolean; var refinkey : RFRE_DB_GUID_RefLink_InOut_Key; value : PtrUInt; begin __SetupInboundLinkKey(from_uid,to_object,scheme_link,refinkey); result := FMasterRefLinks.ExistsBinaryKey(@refinkey,refinkey.KeyLength,value); if result and (value<>$BEEF0BAD) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'internal inbound reflink structure bad, value invalid [%d]',[value]); end; procedure TFRE_DB_Master_Data.__CheckReferenceLink(const obj: TFRE_DB_Object; fieldname: TFRE_DB_NameType; link: TFRE_DB_GUID; var scheme_link: TFRE_DB_NameTypeRL;const allow_existing_links : boolean); var j : NativeInt; ref_obj : TFRE_DB_Object; begin //writeln('TODO _ PARALLEL CHECK OF REFLINK INDEX TREE'); if not FetchObject(link,ref_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'referential link check: link from obj(%s:%s) to obj(%s) : the to object does not exist!',[obj.GetDescriptionID,fieldname,FREDB_G2H(link)]); if obj.IsVolatile or obj.IsSystem then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'referential link check: link from obj(%s:%s) to obj(%s) : the linking object is volatile or system!',[obj.GetDescriptionID,fieldname,FREDB_G2H(link)]); scheme_link := uppercase(fieldname+'>'+ref_obj.SchemeClass); if (not allow_existing_links) and __RefLinkOutboundExists(obj.UID,fieldname,link,scheme_link) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'outbound reflink already existing from from obj(%s:%s) to obj(%s:%s)',[obj.UID_String,fieldname,FREDB_G2H(link),ref_obj.SchemeClass]); if (not allow_existing_links) and __RefLinkInboundExists(obj.UID,fieldname,link,uppercase(obj.SchemeClass+'<'+fieldname)) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'outbound reflink already existing from from obj(%s:%s) to obj(%s:%s)',[obj.UID_String,fieldname,FREDB_G2H(link),ref_obj.SchemeClass]); end; // Setup the "to_list" for KEY-UID,Field,(Subkeys) // For every in the "to_list" referenced object set an inbound link, from KEY-UID procedure TFRE_DB_Master_Data.__SetupInitialRefLink(const from_key: TFRE_DB_Object; FromFieldToSchemename, LinkFromSchemenameField: TFRE_DB_NameTypeRL; const references_to: TFRE_DB_GUID; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var refoutkey : RFRE_DB_GUID_RefLink_InOut_Key; refinkey : RFRE_DB_GUID_RefLink_InOut_Key; ref_obj : TFRE_DB_Object; fieldname : TFRE_DB_NameType; schemename : TFRE_DB_NameType; was_locked : boolean; begin assert(pos('>',FromFieldToSchemename)>0,'internal reflink failure 1'); FREDB_SplitRefLinkDescription(FromFieldToSchemename,fieldname,schemename); if not FetchObject(references_to,ref_obj,true) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'referential link check: link from obj(%s:%s) to obj(%s) : the to object does not exist!',[from_key.GetDescriptionID,FromFieldToSchemename,FREDB_G2H(references_to)]); if not ref_obj.IsObjectRoot then begin writeln('SSSLL :::'); writeln(ref_obj.DumpToString()); halt; end; FromFieldToSchemename := uppercase(fieldname+'>'+ref_obj.SchemeClass); LinkFromSchemenameField := uppercase(from_key.SchemeClass+'<'+fieldname); __SetupOutboundLinkKey(from_key.UID,references_to,FromFieldToSchemename,refoutkey); if not FMasterRefLinks.InsertBinaryKey(@refoutkey,refoutkey.KeyLength,$BAD0BEEF) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'although prechecked the reflink fromkey exists. :-('); assert(pos('<',LinkFromSchemenameField)>0,'internal reflink failure 2'); __SetupInboundLinkKey(from_key.UID,references_to,LinkFromSchemenameField,refinkey); if not FMasterRefLinks.InsertBinaryKey(@refinkey,refinkey.KeyLength,$BEEF0BAD) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'although prechecked the reflink tokey exists. :-('); { Notify after link setup } if assigned(notifif) then begin ref_obj.Set_Store_LockedUnLockedIf(false,was_locked); { Locking is ok here, to reduce cloning } try notifif.SetupOutboundRefLink(from_key,ref_obj,FromFieldToSchemename,tsid); notifif.SetupInboundRefLink(from_key,ref_obj,LinkFromSchemenameField,tsid); finally ref_obj.Set_Store_LockedUnLockedIf(true,was_locked); end; end; end; procedure TFRE_DB_Master_Data._ChangeRefLink(const from_obj: TFRE_DB_Object; const upper_schemename: TFRE_DB_NameType; const upper_fieldname: TFRE_DB_NameType; const old_links, new_links: TFRE_DB_GUIDArray; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var inserted_list : TFRE_DB_GUIDArray; removed_list : TFRE_DB_GUIDArray; i,idx : NativeInt; dbg : Nativeint; outlist : TFRE_DB_ObjectReferences; object_references : TFRE_DB_ObjectReferences; to_scheme_name : TFRE_DB_NameType; schemelink : TFRE_DB_NameTypeRL; function FREDB_GetToUidSchemeclassfromReferences(const from_obr : TFRE_DB_ObjectReferences; const upper_from_fieldname : TFRE_DB_NameType; const to_uid:TFRE_DB_GUID; var tolink_schemename:TFRE_DB_NameType) : boolean; var i:integer; begin result:=false; for i:=0 to high(object_references) do begin if (from_obr[i].fieldname=upper_fieldname) and (from_obr[i].linked_uid=to_uid) then begin tolink_schemename := from_obr[i].schemename; exit(true); end; end; end; begin dbg := Length(old_links); dbg := Length(new_links); SetLength(inserted_list,Length(new_links)); SetLength(removed_list,Length(old_links)); idx := 0; for i:=0 to high(old_links) do if FREDB_GuidInArray(old_links[i],new_links)=-1 then begin removed_list[idx] := old_links[i]; inc(idx); end; SetLength(removed_list,idx); idx := 0; for i:=0 to high(new_links) do if FREDB_GuidInArray(new_links[i],old_links)=-1 then begin inserted_list[idx] := new_links[i]; inc(idx); end; SetLength(inserted_list,idx); object_references := GetOutBoundRefLinks(from_obj.UID); for i:= 0 to high(removed_list) do begin FREDB_GetToUidSchemeclassfromReferences(object_references,upper_fieldname,removed_list[i],to_scheme_name); __RemoveRefLink(from_obj.UID,removed_list[i],upper_schemename,upper_fieldname,to_scheme_name,notifif,tsid); end; for i:= 0 to high(inserted_list) do begin __CheckReferenceLink(from_obj,upper_fieldname,inserted_list[i],schemelink,false); __SetupInitialRefLink(from_obj,schemelink,upper_schemename+'<'+upper_fieldname,inserted_list[i],notifif,tsid); end; end; procedure TFRE_DB_Master_Data._SetupInitialRefLinks(const from_key: TFRE_DB_Object; const references_to_list: TFRE_DB_ObjectReferences; const schemelink_arr: TFRE_DB_NameTypeRLArray; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var i: NativeInt; begin assert(Length(references_to_list)=Length(schemelink_arr),'internal error'); for i:=0 to high(references_to_list) do __SetupInitialRefLink(from_key,schemelink_arr[i],uppercase(from_key.SchemeClass+'<'+references_to_list[i].fieldname),references_to_list[i].linked_uid,notifif,tsid); end; procedure TFRE_DB_Master_Data._RemoveAllRefLinks(const from_key: TFRE_DB_Object; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var object_references : TFRE_DB_ObjectReferences; refoutkey : RFRE_DB_GUID_RefLink_InOut_Key; refinkey : RFRE_DB_GUID_RefLink_InOut_Key; i : NativeInt; from_uid,to_object : TFRE_DB_GUID; sc_from : TFRE_DB_NameType; scheme_link_key : TFRE_DB_NameTypeRL; //begin // scheme_link_key := sc_from+'<'+object_references[i].fieldname; // __RemoveInboundRefLink(from_uid,object_references[i].linked_uid,scheme_link_key); // scheme_link_key := object_references[i].fieldname+'>'+object_references[i].schemename; // __RemoveOutboundReflink(from_uid,object_references[i].linked_uid,scheme_link_key); //end; begin from_uid := from_key.UID; sc_from := uppercase(from_key.SchemeClass); object_references := GetOutBoundRefLinks(from_key.UID); for i:=0 to high(object_references) do __RemoveRefLink(from_uid,object_references[i].linked_uid,sc_from,object_references[i].fieldname,object_references[i].schemename,notifif,tsid); end; procedure TFRE_DB_Master_Data._CheckRefIntegrityForObject(const obj: TFRE_DB_Object; var ref_array: TFRE_DB_ObjectReferences; var schemelink_arr: TFRE_DB_NameTypeRLArray); var i : NativeInt; begin ref_array := obj.ReferencesFromData; SetLength(schemelink_arr,Length(ref_array)); for i:=0 to high(ref_array) do __CheckReferenceLink(obj,ref_array[i].fieldname,ref_array[i].linked_uid,schemelink_arr[i]); end; procedure TFRE_DB_Master_Data._CheckExistingReferencelinksAndRemoveMissingFromObject(const obj: TFRE_DB_Object); var i : NativeInt; ref_array : TFRE_DB_ObjectReferences; schemelink_arr : TFRE_DB_NameTypeRLArray; rls : TFRE_DB_GUIDArray; begin ref_array := obj.ReferencesFromData; SetLength(schemelink_arr,Length(ref_array)); for i:=0 to high(ref_array) do begin try __CheckReferenceLink(obj,ref_array[i].fieldname,ref_array[i].linked_uid,schemelink_arr[i]); except on e:exception do begin writeln('>RECOVERY EXCEPTION : ',e.Message); writeln(format('> TRY REMOVING REF LINK : [%s.%s -> %s (%s)]',[obj.GetDescriptionID,ref_array[i].fieldname,FREDB_G2H(ref_array[i].linked_uid),schemelink_arr[i]])); obj.Field(ref_array[i].fieldname).RemoveObjectLinkByUID(ref_array[i].linked_uid); writeln('REMOVED -> RECURSE'); _CheckExistingReferencelinksAndRemoveMissingFromObject(obj); end; end; end; end; function TFRE_DB_Master_Data.MyLayer: IFRE_DB_PERSISTANCE_LAYER; begin result := FLayer; end; function TFRE_DB_Master_Data.GetPersistantRootObjectCount(const UppercaseSchemesFilter: TFRE_DB_StringArray): Integer; var brk:integer; procedure Scan(const obj : TFRE_DB_Object ; var break : boolean); begin if obj.IsObjectRoot then begin if (length(UppercaseSchemesFilter)=0) or (FREDB_StringInArray(uppercase(obj.SchemeClass),UpperCaseSchemesFilter)) then inc(result); end; end; begin result := 0; ForAllObjectsInternal(true,false,@scan); end; function TFRE_DB_Master_Data.InternalStoreObjectFromStable(const obj: TFRE_DB_Object): TFRE_DB_Errortype; var key : TFRE_DB_GUID; dummy : PtrUInt; halt : boolean=false; procedure Store(const obj:TFRE_DB_Object; var halt:boolean); begin dummy := FREDB_ObjectToPtrUInt(obj); key := obj.UID; //writeln('RELOAD STORE : ',obj.UID_String,' ',obj.IsObjectRoot); if not FMasterPersistentObjStore.InsertBinaryKeyOrFetch(@key,sizeof(TFRE_DB_GUID),dummy) then result := edb_EXISTS; if result<>edb_OK then halt := true end; begin Result := edb_OK; obj.ForAllObjectsBreakHierarchic(@Store,halt); end; function TFRE_DB_Master_Data.InternalRebuildRefindex: TFRE_DB_Errortype; procedure BuildRef(const obj:TFRE_DB_Object ; var break : boolean); var references_to_list : TFRE_DB_ObjectReferences; scheme_links : TFRE_DB_NameTypeRLArray; setup_repair : boolean; begin try setup_repair := false; _CheckRefIntegrityForObject(obj,references_to_list,scheme_links); // Todo Check inbound From Links (unique?) except on e:exception do begin if GDBPS_SKIP_STARTUP_CHECKS then begin setup_repair := true; end else raise; end; end; if setup_repair then begin _CheckExistingReferencelinksAndRemoveMissingFromObject(obj); _CheckRefIntegrityForObject(obj,references_to_list,scheme_links); // Todo Check inbound From Links (unique?) FLayer.WT_StoreObjectPersistent(obj); writeln('WROTE THROUGH PATCHED OBJECT : '); writeln(obj.DumpToString(2)); end; if Length(references_to_list)>0 then _SetupInitialRefLinks(obj,references_to_list,scheme_links,nil,'BOOT'); end; begin ForAllObjectsInternal(true,false,@BuildRef); result := edb_OK; end; function TFRE_DB_Master_Data.InternalCheckRestoredBackup: TFRE_DB_Errortype; var cnt : NativeInt; procedure CheckObjectInCollection(const obj:TFRE_DB_Object ; var break : boolean); var obrefs : TFRE_DB_ObjectReferences; i : NativeInt; begin if obj.IsObjectRoot then begin obj.Set_Store_Locked(False); try if length(obj.__InternalGetCollectionList)=0 then begin inc(cnt); writeln('INTERNAL FAILURE ('+FLayer.GetConnectedDB+'):::DB VERIFY - OFFENDING OBJECT (not stored in an collection ?)'); writeln(obj.DumpToString(2)); writeln('--Looking for references'); obrefs := GetReferencesDetailedRC(obj.UID,false,'','',nil,false,true); for i:=0 to high(obrefs) do begin writeln('Is referenced by : ',obrefs[i].schemename,'(',FREDB_G2H(obrefs[i].linked_uid),').',obrefs[i].fieldname); end; end; finally obj.Set_Store_Locked(True); end; end; end; begin cnt := 0; ForAllObjectsInternal(true,false,@CheckObjectInCollection); if cnt>0 then begin writeln('FAILURES : ',cnt); exit(edb_INTERNAL); end; result := edb_OK; end; procedure TFRE_DB_Master_Data.InternalStoreLock; procedure StoreLock(const obj:TFRE_DB_Object ; var break : boolean); begin if obj.IsObjectRoot then obj.Set_Store_Locked(true); end; begin ForAllObjectsInternal(true,false,@Storelock); end; procedure TFRE_DB_Master_Data.InternalCheckStoreLocked; procedure StoreLock(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint); var obj : TFRE_DB_Object; begin obj := FREDB_PtrUIntToObject(value) as TFRE_DB_Object; if obj.IsObjectRoot then obj.Assert_CheckStoreLocked; end; begin FMasterPersistentObjStore.LinearScanKeyVals(@StoreLock); end; procedure TFRE_DB_Master_Data.InternalCheckSubobjectsStored; procedure CheckStored(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint); var obj : TFRE_DB_Object; fso : TFRE_DB_Object; oa : TFRE_DB_ObjectArray; i : NativeInt; begin obj := FREDB_PtrUIntToObject(value) as TFRE_DB_Object; if obj.IsObjectRoot then begin oa := obj.GetFullHierarchicObjectList(false); for i := 0 to high(oa) do begin if not FetchObject(oa[i].UID,fso,true) then begin raise EFRE_DB_Exception.Create(edb_INTERNAL,'internal subobject validation failed - '); end; end; end; end; begin FMasterPersistentObjStore.LinearScanKeyVals(@CheckStored); end; procedure TFRE_DB_Master_Data.FDB_CleanUpMasterData; procedure CleanReflinks(var refl : NativeUint); begin if (refl<>$BEEF0BAD) and (refl<>$BAD0BEEF) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'tree node inconsistency/bad value'); end; procedure CleanObj(var ob : NativeUint); var obj : TFRE_DB_Object; begin if ob=0 then exit; obj := FREDB_PtrUIntToObject(ob) as TFRE_DB_Object; if obj.IsObjectRoot then begin obj.Set_Store_Locked(False); obj.Free; end; end; procedure CleanAllChilds(var ob : NativeUint); var obj : TFRE_DB_Object; begin obj := FREDB_PtrUIntToObject(ob) as TFRE_DB_Object; if not obj.IsObjectRoot then ob:=0; end; begin FMasterPersistentObjStore.LinearScan(@CleanAllChilds); FMasterPersistentObjStore.LinearScan(@CleanObj); FMasterPersistentObjStore.Clear; FMasterVolatileObjStore.LinearScan(@CleanAllChilds); FMasterVolatileObjStore.LinearScan(@CleanObj); FMasterVolatileObjStore.Clear; FMasterRefLinks.LinearScan(@CleanReflinks); FMasterRefLinks.Clear; FMasterCollectionStore.Clear; end; constructor TFRE_DB_Master_Data.Create(const master_name: string ; const Layer : IFRE_DB_PERSISTANCE_LAYER); begin FMasterPersistentObjStore := TFRE_ART_TREE.Create; FMasterVolatileObjStore := TFRE_ART_TREE.Create; FMasterRefLinks := TFRE_ART_TREE.Create; FMasterCollectionStore := TFRE_DB_CollectionManageTree.Create; FMyMastername := master_name; FLayer := Layer; if (uppercase(master_name)='SYSTEM') then FIsSysMaster:=true; if FMyMastername='' then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'BAD NO NAME'); end; destructor TFRE_DB_Master_Data.Destroy; begin FDB_CleanUpMasterData; FMasterPersistentObjStore.Free; FMasterVolatileObjStore.Free; FMasterRefLinks.Free; FMasterCollectionStore.Free; inherited Destroy; end; class function TFRE_DB_Master_Data._CheckFetchRightUID(const uid: TFRE_DB_GUID; const ut: TFRE_DB_USER_RIGHT_TOKEN): boolean; var obj : TFRE_DB_Object; i : NativeInt; begin if not G_SysMaster.FetchObject(uid,obj,true) then for i := 0 to high(G_AllNonsysMasters) do if G_AllNonsysMasters[i].FetchObject(uid,obj,true) then break; if not Assigned(obj) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not internal fetch object for checkright [%s]',[FREDB_G2H(uid)]); if not assigned(ut) then exit(true); result := ut.CheckStdRightsetInternalObj(obj,[sr_FETCH])=edb_OK; end; class procedure TFRE_DB_Master_Data._TransactionalLockObject(const uid: TFRE_DB_GUID); var obj : TFRE_DB_Object; i : NativeInt; begin if not G_SysMaster.FetchObject(uid,obj,true) then for i := 0 to high(G_AllNonsysMasters) do if G_AllNonsysMasters[i].FetchObject(uid,obj,true) then break; if not Assigned(obj) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not internal fetch object for TransactionLockObject [%s]',[FREDB_G2H(uid)]); obj.Assert_CheckStoreUnLocked; obj.Set_Store_Locked(true); end; function TFRE_DB_Master_Data._SetCheckFilterbaseclass(const scheme_prefix_filter: TFRE_DB_NameType; const exact_filter_and_derived: boolean): TFRE_DB_ObjectClassEx; begin if (scheme_prefix_filter<>'') and exact_filter_and_derived then begin result := GFRE_DB.GetObjectClassEx(scheme_prefix_filter); if not assigned(result) then raise EFRE_DB_PL_Exception.Create(edb_INVALID_PARAMS,'with the specified filter (used as baseclass) the class [%s] could not be found !',[scheme_prefix_filter]); end else result := nil; end; function TFRE_DB_Master_Data.CloneOutObject(const inobj: TFRE_DB_Object): TFRE_DB_Object; begin inobj.Assert_CheckStoreLocked; inobj.Set_Store_Locked(false); try if Length(inobj.__InternalGetCollectionList)<1 then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'logic failure, object has no assignment to internal collections'); result := inobj.CloneToNewObject; if result = inobj then abort; finally inobj.Set_Store_Locked(true); end; end; function TFRE_DB_Master_Data.GetReferencesRC(const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const user_context: PFRE_DB_GUID; const concat_call: boolean; const exact_filter_and_derived_classes: boolean): TFRE_DB_GUIDArray; var obr : TFRE_DB_ObjectReferences; obrc : TFRE_DB_ObjectReferences; i,j,cnt : NativeInt; add : boolean; spf : TFRE_DB_NameType; fef : TFRE_DB_NameType; sysrefs : TFRE_DB_GUIDArray; uti : TFRE_DB_USER_RIGHT_TOKEN; filterbaseclass : TFRE_DB_ObjectClassEx; { should work via schemes ? unknow classe in pl core ? (soft code) / or via derivation trees & weak classes (tightly bound code modules) } begin filterbaseclass := _SetCheckFilterbaseclass(scheme_prefix_filter,exact_filter_and_derived_classes); G_GetUserToken(user_context,uti,true); if from then obr := GetOutBoundRefLinks(obj_uid) else begin obr := GetInboundRefLinks(obj_uid); if FIsSysMaster and (not concat_call) then { there possibly exist non system reflinks to the system db, gather them too, if this is a SYSTEM ONLY call (concat=false) } begin for j := 0 to high(G_AllNonsysMasters) do begin obrc := G_AllNonsysMasters[j].GetInboundRefLinks(obj_uid); if Length(obrc)>0 then FREDB_ConcatReferenceArrays(obr,obrc); end; end; end; SetLength(result,length(obr)); fef := uppercase(field_exact_filter); if assigned(filterbaseclass) then { exact class and derived filter } begin cnt := 0; for i:=0 to high(obr) do if GFRE_DB.IsAClassOrDerived(obr[i].schemename,filterbaseclass) and ((fef='') or (fef=obr[i].fieldname)) then if _CheckFetchRightUID(obr[i].linked_uid,uti) then begin result[cnt] := obr[i].linked_uid; inc(cnt); end; end else begin spf := uppercase(scheme_prefix_filter); { prefix filter} cnt := 0; for i:=0 to high(obr) do if ((spf='') or (pos(spf,obr[i].schemename)=1)) and ((fef='') or (fef=obr[i].fieldname)) then if _CheckFetchRightUID(obr[i].linked_uid,uti) then begin result[cnt] := obr[i].linked_uid; inc(cnt); end; end; SetLength(result,cnt); if not FIsSysMaster then { gather the system db references too} begin sysrefs := G_SysMaster.GetReferencesRC(obj_uid,from,scheme_prefix_filter,field_exact_filter,user_context,true,exact_filter_and_derived_classes); FREDB_ConcatGUIDArrays(result,sysrefs); end; end; function TFRE_DB_Master_Data.GetReferencesRCRecurse(const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const user_context: PFRE_DB_GUID; const exact_filter_and_derived_classes: boolean): TFRE_DB_GUIDArray; var uti : TFRE_DB_USER_RIGHT_TOKEN; spf : TFRE_DB_NameType; fef : TFRE_DB_NameType; cnt : NativeInt; concat : TFRE_DB_GUIDArray; filterbaseclass : TFRE_DB_ObjectClassEx; { should work via schemes ? unknow classe in pl core ? (soft code) / or via derivation trees & weak classes (tightly bound code modules) } matched : boolean; function GetReferencesRCRecurseInt(const obj_uid: TFRE_DB_GUID ; lvl : NativeInt):NativeInt; var i : NativeInt; refs : TFRE_DB_ObjectReferences; cr : boolean; begin result := 0; if lvl>50 then begin GFRE_DBI.LogWarning(dblc_PERSISTANCE,'Too deep referenced link recursion (50) expansion for uid: [%s]',[obj_uid.AsHexString]); exit; end; refs := GetReferencesDetailedRC(obj_uid,from,'',field_exact_filter,user_context,false,false); { disable scheme filter, to get all schemes } for i:=0 to High(refs) do begin cr := _CheckFetchRightUID(refs[i].linked_uid,uti); if cr then inc(result); { there are accessible parents } if assigned(filterbaseclass) then matched := GFRE_DB.IsAClassOrDerived(refs[i].schemename,filterbaseclass) else matched := pos(spf,refs[i].schemename)=1; if matched then { and the schemename is ok } begin if cr then { rights are ok } begin if cnt=Length(concat) then SetLength(concat,Length(concat)+25); concat[cnt] := refs[i].linked_uid; { add link } inc(cnt); end end else { wrong scheme } begin if (GetReferencesRCRecurseInt(refs[i].linked_uid,lvl+1)=0) and (spf='') then { no parents, and search til end } begin if cnt=Length(concat) then SetLength(concat,Length(concat)+25); concat[cnt] := refs[i].linked_uid; { add link } inc(cnt); end; end; end; end; begin filterbaseclass := _SetCheckFilterbaseclass(scheme_prefix_filter,exact_filter_and_derived_classes); G_GetUserToken(user_context,uti,true); spf := uppercase(scheme_prefix_filter); fef := uppercase(field_exact_filter); cnt := 0; SetLength(concat,0); GetReferencesRCRecurseInt(obj_uid,0); SetLength(concat,cnt); result := concat; end; function TFRE_DB_Master_Data.GetReferencesCountRC(const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const user_context: PFRE_DB_GUID; const concat_call: boolean; const exact_filter_and_derived_classes: boolean): NativeInt; var obr : TFRE_DB_ObjectReferences; obrc : TFRE_DB_ObjectReferences; i,j : NativeInt; spf : TFRE_DB_NameType; fef : TFRE_DB_NameType; syscnt : NativeInt; uti : TFRE_DB_USER_RIGHT_TOKEN; filterbaseclass : TFRE_DB_ObjectClassEx; { should work via schemes ? unknow classe in pl core ? (soft code) / or via derivation trees & weak classes (tightly bound code modules) } begin filterbaseclass := _SetCheckFilterbaseclass(scheme_prefix_filter,exact_filter_and_derived_classes); G_GetUserToken(user_context,uti,true); if from then obr := GetOutBoundRefLinks(obj_uid) else begin obr := GetInboundRefLinks(obj_uid); if FIsSysMaster and (not concat_call) then { there possibly exist non system reflinks to the system db, gather them too, if this is a SYSTEM ONLY call (concat=false) } begin for j := 0 to high(G_AllNonsysMasters) do begin obrc := G_AllNonsysMasters[j].GetInboundRefLinks(obj_uid); if Length(obrc)>0 then FREDB_ConcatReferenceArrays(obr,obrc); end; end; end; fef := uppercase(field_exact_filter); if assigned(filterbaseclass) then { use exact base/derived filtering } begin result := 0; for i:=0 to high(obr) do if GFRE_DB.IsAClassOrDerived(obr[i].schemename,filterbaseclass) and ((fef='') or (fef=obr[i].fieldname)) then if _CheckFetchRightUID(obr[i].linked_uid,uti) then begin inc(result); end; end else begin { use prefix filtering } spf := uppercase(scheme_prefix_filter); result := 0; for i:=0 to high(obr) do if ((spf='') or (pos(spf,obr[i].schemename)=1)) and ((fef='') or (fef=obr[i].fieldname)) then if _CheckFetchRightUID(obr[i].linked_uid,uti) then begin inc(result); end; end; if not FIsSysMaster then { gather the system db references too} begin syscnt := G_SysMaster.GetReferencesCountRC(obj_uid,from,scheme_prefix_filter,field_exact_filter,user_context,true,exact_filter_and_derived_classes); inc(result,syscnt); end; end; function TFRE_DB_Master_Data.GetReferencesDetailedRC(const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const user_context: PFRE_DB_GUID; const concat_call: boolean; const exact_filter_and_derived_classes: boolean): TFRE_DB_ObjectReferences; var obr : TFRE_DB_ObjectReferences; obrc : TFRE_DB_ObjectReferences; i,j,cnt : NativeInt; add : boolean; spf : TFRE_DB_NameType; fef : TFRE_DB_NameType; sysobrs : TFRE_DB_ObjectReferences; uti : TFRE_DB_USER_RIGHT_TOKEN; filterbaseclass : TFRE_DB_ObjectClassEx; { should work via schemes ? unknow classe in pl core ? (soft code) / or via derivation trees & weak classes (tightly bound code modules) } begin filterbaseclass := _SetCheckFilterbaseclass(scheme_prefix_filter,exact_filter_and_derived_classes); G_GetUserToken(user_context,uti,true); if from then obr := GetOutBoundRefLinks(obj_uid) else begin obr := GetInboundRefLinks(obj_uid); if FIsSysMaster and (not concat_call) then { there possibly exist non system reflinks to the system db, gather them too, if this is a SYSTEM ONLY call (concat=false) } begin for j := 0 to high(G_AllNonsysMasters) do begin obrc := G_AllNonsysMasters[j].GetInboundRefLinks(obj_uid); if Length(obrc)>0 then FREDB_ConcatReferenceArrays(obr,obrc); end; end; end; SetLength(result,length(obr)); fef := uppercase(field_exact_filter); if assigned(filterbaseclass) then begin cnt := 0; for i:=0 to high(obr) do if GFRE_DB.IsAClassOrDerived(obr[i].schemename,filterbaseclass) and ((fef='') or (fef=obr[i].fieldname)) then if _CheckFetchRightUID(obr[i].linked_uid,uti) then begin result[cnt] := obr[i]; inc(cnt); end; end else begin spf := uppercase(scheme_prefix_filter); cnt := 0; for i:=0 to high(obr) do if ((spf='') or (pos(spf,obr[i].schemename)=1)) and ((fef='') or (fef=obr[i].fieldname)) then if _CheckFetchRightUID(obr[i].linked_uid,uti) then begin result[cnt] := obr[i]; inc(cnt); end; end; SetLength(result,cnt); if not FIsSysMaster then { gather the system db references too} begin sysobrs := G_SysMaster.GetReferencesDetailedRC(obj_uid,from,scheme_prefix_filter,field_exact_filter,user_context,true,exact_filter_and_derived_classes); FREDB_ConcatReferenceArrays(result,sysobrs); end; end; procedure TFRE_DB_Master_Data.ExpandReferencesRC(const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; out expanded_refs: TFRE_DB_GUIDArray; const allow_derived_classes: boolean); var i : NativeInt; count : NativeInt; procedure FetchChained(uid:TFRE_DB_GUID ; field_chain : TFRE_DB_NameTypeRLArray ; depth : NativeInt); var obrefs : TFRE_DB_GUIDArray; i : NativeInt; scheme : TFRE_DB_NameType; field : TFRE_DB_NameType; outbound : Boolean; recurse : boolean; begin if depth<length(field_chain) then begin outbound := FREDB_SplitRefLinkDescriptionEx(field_chain[depth],field,scheme,recurse); if not recurse then obrefs := GetReferencesRC(uid,outbound,scheme,field,user_context,false,allow_derived_classes) else obrefs := GetReferencesRCRecurse(uid,outbound,scheme,field,user_context,allow_derived_classes); for i := 0 to high(obrefs) do begin FetchChained(obrefs[i],field_chain,depth+1); end; end else begin if Length(expanded_refs) = count then SetLength(expanded_refs,Length(expanded_refs)+256); if FREDB_GuidInArray(uid,expanded_refs)=-1 then begin expanded_refs[count] := uid; inc(count); end; end; end; begin SetLength(expanded_refs,0); count := 0; for i := 0 to High(ObjectList) do FetchChained(ObjectList[i],ref_constraints,0); SetLength(expanded_refs,count); end; function TFRE_DB_Master_Data.ExpandReferencesCountRC(const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; const allow_derived_classes: boolean): NativeInt; var expanded_refs: TFRE_DB_GUIDArray; begin ExpandReferencesRC(user_context,ObjectList,ref_constraints,expanded_refs,allow_derived_classes); result := Length(expanded_refs); end; procedure TFRE_DB_Master_Data.FetchExpandReferencesRC(const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; out expanded_refs: IFRE_DB_ObjectArray; const allow_derived_classes: boolean); var expanded_ref: TFRE_DB_GUIDArray; begin ExpandReferencesRC(user_context,ObjectList,ref_constraints,expanded_ref,allow_derived_classes); BulkFetchRC(nil,expanded_ref,expanded_refs); end; function TFRE_DB_Master_Data.BulkFetchRC(const user_context: PFRE_DB_GUID; const obj_uids: TFRE_DB_GUIDArray; out objects: IFRE_DB_ObjectArray): TFRE_DB_Errortype; var dboa : TFRE_DB_ObjectArray; i : NativeInt; all : Boolean; begin SetLength(dboa,length(obj_uids)); all := true; for i := 0 to high(dboa) do if not FetchObjectRC(user_context,obj_uids[i],dboa[i],true) then begin all := false; break; end; if all then begin SetLength(objects,Length(dboa)); for i := 0 to high(objects) do objects[i] := CloneOutObject(dboa[i]); exit(edb_OK); end; result := edb_NOT_FOUND; end; function TFRE_DB_Master_Data.FetchObjectRC(const user_context: PFRE_DB_GUID; const obj_uid: TFRE_DB_GUID; out obj: TFRE_DB_Object; const internal_obj: boolean): boolean; var uti : TFRE_DB_USER_RIGHT_TOKEN; begin G_GetUserToken(user_context,uti,true); result := FetchObject(obj_uid,obj,true); if result then begin if not assigned(user_context) then begin if internal_obj=false then { only cloneout if needed } obj := CloneOutObject(obj); exit(true); end; result := uti.CheckStdRightsetInternalObj(obj,[sr_FETCH])=edb_OK; if result=false then begin obj := nil; end else begin if internal_obj=false then { only cloneout if needed } obj := CloneOutObject(obj); end; end; end; function TFRE_DB_Master_Data.ExistsObject(const obj_uid: TFRE_DB_GUID): Boolean; var dummy : NativeUint; begin if FMasterVolatileObjStore.ExistsBinaryKey(@obj_uid,SizeOf(TFRE_DB_GUID),dummy) then exit(true); if FMasterPersistentObjStore.ExistsBinaryKey(@obj_uid,SizeOf(TFRE_DB_GUID),dummy) then exit(true); exit(false); end; function TFRE_DB_Master_Data.FetchObject(const obj_uid: TFRE_DB_GUID; out obj: TFRE_DB_Object; const internal_obj: boolean): boolean; var dummy : NativeUint; clobj : TFRE_DB_Object; begin obj := nil; result := FMasterVolatileObjStore.ExistsBinaryKey(@obj_uid,SizeOf(TFRE_DB_GUID),dummy); if result then begin obj := FREDB_PtrUIntToObject(dummy) as TFRE_DB_Object; end else begin result := FMasterPersistentObjStore.ExistsBinaryKey(@obj_uid,SizeOf(TFRE_DB_GUID),dummy); if result then obj := FREDB_PtrUIntToObject(dummy) as TFRE_DB_Object; end; if result and FIsSysMaster then obj.Set_SystemDB; { set internal flag that this object comes from the sys layer ( update/wt) } if result and not internal_obj then begin if not obj.IsObjectRoot then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'the object [%s] is a subobject,a "root" of the fetch of the subobject is not allowed',[FREDB_G2H(obj_uid)]); obj.Assert_CheckStoreLocked; obj.Set_Store_Locked(false); try clobj := obj.CloneToNewObject; finally obj.Set_Store_Locked(true); end; obj := clobj; end; if not result then { not found here, search in system master data, but not the other way round } if not FIsSysMaster then result := G_SysMaster.FetchObject(obj_uid,obj,internal_obj); end; procedure TFRE_DB_Master_Data.StoreObjectSingle(const obj: TFRE_DB_Object; const check_only: boolean; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var references_to_list : TFRE_DB_ObjectReferences; key : TFRE_DB_GUID; dummy : PtrUInt; scheme_links : TFRE_DB_NameTypeRLArray; begin key := obj.UID; _CheckRefIntegrityForObject(obj,references_to_list,scheme_links); // Todo Check inbound From Links (unique?) if (obj.IsVolatile or obj.IsSystem or (not obj.IsObjectRoot)) and (Length(references_to_list)>0) then begin raise EFRE_DB_PL_Exception.Create(edb_INVALID_PARAMS,'a volatile,system or child object [%s] is not allowed to reference other objects [%s => %s(%s)] ',[obj.UID_String,references_to_list[0].fieldname,references_to_list[0].linked_uid.AsHexString,references_to_list[0].schemename]); end; if obj.ObjectRoot.IsVolatile then {!! essential} begin if check_only then begin if FMasterVolatileObjStore.ExistsBinaryKey(@key,SizeOf(TFRE_DB_GUID),dummy) then begin if obj.IsObjectRoot then begin raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'cannot store volatile rootobject, an object [%s] is already stored as root or subobject',[obj.UID_String]); end else begin raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'cannot store volatile subobject, an object [%s] is already stored as root or subobject',[obj.UID_String]); end; end; end else begin if not FMasterVolatileObjStore.InsertBinaryKey(@key,SizeOf(TFRE_DB_GUID),FREDB_ObjectToPtrUInt(obj)) then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'cannot store volatile object') end; end else begin { Not Volatile } dummy := FREDB_ObjectToPtrUInt(obj); if check_only then begin if FMasterPersistentObjStore.ExistsBinaryKey(@key,SizeOf(TFRE_DB_GUID),dummy) then begin if obj.IsObjectRoot then begin raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'cannot store persistent rootobject, an object [%s] is already stored as root or subobject',[obj.UID_String]); end else begin raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'cannot store persistent subobject, an object [%s] is already stored as root or subobject',[obj.UID_String]); end; end; end else begin { non check - do it } if tsid='' then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'transation id not set on store OBJ(%s)',[obj.UID_String]); obj.Field(cFRE_DB_SYS_T_LMO_TRANSID).AsString:=tsid; if not FMasterPersistentObjStore.InsertBinaryKeyOrFetch(@key,sizeof(TFRE_DB_GUID),dummy) then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'cannot store persistent object [%s]',[obj.InternalUniqueDebugKey]); if Length(references_to_list)>0 then _SetupInitialRefLinks(obj,references_to_list,scheme_links,notifif,tsid); end; end; end; procedure TFRE_DB_Master_Data.StoreObjectWithSubjs(const obj: TFRE_DB_Object; const check_only: boolean; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var lInsertList : TFRE_DB_ObjectArray; i : NativeInt; begin lInsertList := obj.GetFullHierarchicObjectList(true); for i:=0 to high(lInsertList) do StoreObjectSingle(lInsertList[i],check_only,notifif,tsid); end; procedure TFRE_DB_Master_Data.DeleteObjectSingle(const obj_uid: TFRE_DB_GUID; const check_only: boolean; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId); var dummyv : PtrUInt; dummyp : PtrUInt; obj : TFRE_DB_Object; ex_vol : boolean; ex_pers : boolean; isroot : boolean; cn : shortstring; begin if check_only then begin {$IFDEF DEBUG_OFFENDERS} try {$ENDIF} if GetReferencesCountRC(obj_uid,false,'','',nil,false,true) > 0 then raise EFRE_DB_PL_Exception.Create(edb_OBJECT_REFERENCED,'DELETE OF OBJECT [%s] FAILED, OBJECT IS REFERENCED',[FREDB_G2H(obj_uid)]); exit; {$IFDEF DEBUG_OFFENDERS} except writeln('>DELETE-FAILED -OFFENDING OBJECT -OBJECT ['+obj_uid.AsHexString+'] IS REFERENCED'); raise end; {$ENDIF} end; ex_vol := FMasterVolatileObjStore.ExistsBinaryKey(@obj_uid,SizeOf(TFRE_DB_GUID),dummyv); ex_pers := FMasterPersistentObjStore.ExistsBinaryKey(@obj_uid,SizeOf(TFRE_DB_GUID),dummyp); if (ex_vol=false) and (ex_pers=false) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'DELETE OF OBJECT [%s] FAILED, OBJECT NOT FOUND',[FREDB_G2H(obj_uid)]); if ex_vol then begin obj := FREDB_PtrUIntToObject(dummyv) as TFRE_DB_Object; if not FMasterVolatileObjStore.RemoveBinaryKey(@obj_uid,SizeOf(TFRE_DB_GUID),dummyv) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'cannot remove existing'); if obj.IsObjectRoot then obj.Free else obj:=obj; end; if ex_pers then begin try obj := FREDB_PtrUIntToObject(dummyp) as TFRE_DB_Object; except cn := TObject(dummyp).ClassName; end; _RemoveAllRefLinks(obj,notifif,tsid); if not FMasterPersistentObjStore.RemoveBinaryKey(@obj_uid,SizeOf(TFRE_DB_GUID),dummyp) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'cannot remove existing'); if obj.IsObjectRoot then obj.Free else obj:=obj; end; end; procedure TFRE_DB_Master_Data.DeleteObjectWithSubobjs(const del_obj: TFRE_DB_Object; const check_only: boolean; const notifif: IFRE_DB_DBChangedNotification; const tsid: TFRE_DB_TransStepId; const must_be_child: boolean); var lDelList : TFRE_DB_ObjectArray; k,h : NativeInt; begin lDelList := del_obj.GetFullHierarchicObjectList(true); { the list is build recursive top down, only free the root object, but remove the childs too !} if must_be_child and lDelList[0].IsObjectRoot then raise EFRE_DB_Exception.Create(edb_INTERNAL,'unexpected root object in DeleteObjectWithSubobjs'); h := high(lDelList); for k := h downto 0 do DeleteObjectSingle(lDelList[k].UID,check_only,notifif,tsid); end; procedure TFRE_DB_Master_Data.ForAllObjectsInternal(const pers, volatile: boolean; const iter: TFRE_DB_ObjectIteratorBrk); var break : boolean; procedure ObjCallBack(var val:NativeUint;var break : boolean); begin iter(FREDB_PtrUIntToObject(val) as TFRE_DB_Object,break); end; begin break := false; //self if pers then FMasterPersistentObjStore.LinearScanBreak(@ObjCallback,break); if volatile then FMasterVolatileObjStore.LinearScanBreak(@ObjCallback,break); end; function TFRE_DB_Master_Data.MasterColls: TFRE_DB_CollectionManageTree; begin result := FMasterCollectionStore; end; { TFRE_DB_TextIndex } procedure TFRE_DB_TextIndex.SetBinaryComparableKey(const keyvalue: TFRE_DB_String; const key_target: PByte; var key_len: NativeInt; const is_null: boolean); begin SetBinaryComparableKey(keyvalue,key_target,key_len,is_null,FCaseInsensitive); end; class procedure TFRE_DB_TextIndex.SetBinaryComparableKey(const keyvalue: TFRE_DB_String; const key_target: PByte; var key_len: NativeInt; const is_null: boolean ; const case_insensitive: boolean; const invert_key: boolean); var str : TFRE_DB_String; regular_value : boolean; i : NativeInt; begin regular_value := true; if case_insensitive then str := UpperCase(keyvalue) else str := keyvalue; str := #1+str; if is_null then begin regular_value:=false; if not invert_key then str := #0#0 else str := #2#1; // inverted null=max value end else begin if str=#1 then // "" (empty) String begin regular_value := false; if not invert_key then str := #0#1 else str := #2#0; // 1 before inverted null value end; end; key_len := Length(str); if invert_key and regular_value then begin for i:= 2 to Length(str) do byte(str[i]) := not byte(str[i]); end; Move(str[1],key_target^,key_len); end; procedure TFRE_DB_TextIndex.StreamHeader(const stream: TStream); begin inherited StreamHeader(stream); if FCaseInsensitive then stream.WriteByte(1) else stream.WriteByte(0); end; function TFRE_DB_TextIndex.GetIndexDefinitionObject: IFRE_DB_Object; begin Result:=inherited GetIndexDefinitionObject; result.Field('IXT_CSENS').AsBoolean := FCaseInsensitive; end; function TFRE_DB_TextIndex.GetIndexDefinition: TFRE_DB_INDEX_DEF; begin Result:=inherited GetIndexDefinition; result.IgnoreCase := FCaseInsensitive; end; class procedure TFRE_DB_TextIndex.InitializeNullKey; begin SetBinaryComparableKey('',@nullkey,nullkeylen,true,true); end; constructor TFRE_DB_TextIndex.Create(const idx_name, fieldname: TFRE_DB_NameType; const fieldtype: TFRE_DB_FIELDTYPE; const unique, case_insensitive: boolean; const collection: TFRE_DB_PERSISTANCE_COLLECTION_BASE; const allow_null: boolean; const unique_null: boolean; const domain_idx: boolean); begin inherited Create(idx_name,fieldname,fieldtype,unique,collection,allow_null,unique_null,domain_idx); FCaseInsensitive := case_insensitive; end; constructor TFRE_DB_TextIndex.CreateStreamed(const stream: TStream; const idx_name, fieldname: TFRE_DB_NameType; const fieldtype: TFRE_DB_FIELDTYPE; const unique: boolean; const collection: TFRE_DB_PERSISTANCE_COLLECTION; const allow_null: boolean; const unique_null: boolean; const domain_idx: boolean); var ci : Boolean; begin ci := stream.ReadByte=1; Create(idx_name,fieldname,fieldtype,unique,ci,collection,allow_null,unique_null,domain_idx); LoadIndex(stream,collection); end; procedure TFRE_DB_TextIndex.FieldTypeIndexCompatCheck(fld: TFRE_DB_FIELD); begin if fld.FieldType<>fdbft_String then raise EFRE_DB_PL_Exception.Create(edb_ILLEGALCONVERSION,'the text index can only be used to index a string field, not a [%s] field. Maybe use a calculated field with results a string field',[fld.FieldTypeAsString]) end; function TFRE_DB_TextIndex.NullvalueExists(var vals: TFRE_DB_IndexValueStore): boolean; var dummy : NativeUint; begin result := FIndex.ExistsBinaryKey(@nullkey,nullkeylen,dummy); if result then vals := FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore else vals := nil; end; procedure TFRE_DB_TextIndex.TransformToBinaryComparable(fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint); begin TransformToBinaryComparable(fld,key,keylen,FCaseInsensitive); end; class procedure TFRE_DB_TextIndex.TransformToBinaryComparable(fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint; const is_casesensitive: boolean; const invert_key: boolean); var is_null_value : Boolean; begin is_null_value := not assigned(fld); if not is_null_value then SetBinaryComparableKey(fld.AsString,key,keylen,is_null_value,is_casesensitive,invert_key) else SetBinaryComparableKey('',key,keylen,is_null_value,is_casesensitive,invert_key); end; function TFRE_DB_TextIndex.SupportsDataType(const typ: TFRE_DB_FIELDTYPE): boolean; begin if typ=fdbft_String then exit(true) else exit(false) end; function TFRE_DB_TextIndex.SupportsSignedQuery: boolean; begin result := false; end; function TFRE_DB_TextIndex.SupportsUnsignedQuery: boolean; begin result := false; end; function TFRE_DB_TextIndex.SupportsStringQuery: boolean; begin result := true; end; function TFRE_DB_TextIndex.SupportsRealQuery: boolean; begin result := false; end; function TFRE_DB_TextIndex.ForAllIndexedTextRange(const min, max: TFRE_DB_String; var guids: TFRE_DB_GUIDArray; const ascending: boolean; const min_is_null: boolean; const max_is_max: boolean; const max_count: NativeInt; skipfirst: NativeInt; const only_count_unique_vals: boolean): boolean; var lokey,hikey : Array [0..8] of Byte; lokeylen,hikeylen : NativeInt; lokeyp,hikeyp : PByte; procedure IteratorBreak(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var break : boolean ; var down_counter,up_counter : nativeint ; const abscntr : NativeInt); begin (FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore).AppendObjectUIDS(guids,ascending,down_counter,up_counter,abscntr); end; begin if not min_is_null then begin SetBinaryComparableKey(min,@lokey,lokeylen,min_is_null); lokeyp := lokey; end else lokeyp := nil; if not max_is_max then begin SetBinaryComparableKey(max,@hikey,hikeylen,max_is_max); hikeyp := hikey; end else hikeyp := nil; result := FIndex.RangeScan(lokeyp,hikeyp,lokeylen,hikeylen,@IteratorBreak,max_count,skipfirst,ascending) end; function TFRE_DB_TextIndex.ForAllIndexPrefixString(const prefix: TFRE_DB_String; var guids: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const ascending: boolean; const max_count: NativeInt; skipfirst: NativeInt): boolean; var transkey : Array [0..CFREA_maxKeyLen] of Byte; keylen : NativeInt; procedure IteratorBreak(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var break : boolean); var up_counter,down_counter,abscntr : NAtiveint; begin up_counter := 0 ; down_counter := 0 ;abscntr := 0; (FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore).AppendObjectUIDS(guids,ascending,down_counter,up_counter,abscntr); end; begin if (max_count<>0) or (skipfirst<>0) then E_FOS_Implement; SetBinaryComparableKey(prefix,@transkey,keylen,false); result := FIndex.PrefixScan(@transkey,keylen,@IteratorBreak); end; { TFRE_DB_MM_Index } constructor TFRE_DB_MM_Index.Create(const idx_name, fieldname: TFRE_DB_NameType; const fieldtype: TFRE_DB_FIELDTYPE; const unique: boolean; const collection: TFRE_DB_PERSISTANCE_COLLECTION_BASE; const allow_null: boolean; const unique_null: boolean; const domain_idx: boolean); begin FIndex := TFRE_ART_TREE.Create; FIndexName := idx_name; FUniqueName := UpperCase(FIndexName); FUnique := unique; FFieldname := fieldname; FUniqueFieldname := uppercase(fieldname); FFieldType := fieldtype; FUnique := unique; FCollection := collection; FAllowNull := allow_null; FUniqueNullVals := unique_null; FIsADomainIndex := domain_idx; //GetKeyLenForFieldtype(fieldtype,FFixedKeylen); InitializeNullKey; end; destructor TFRE_DB_MM_Index.Destroy; begin FullClearIndex; FIndex.Free; end; function TFRE_DB_MM_Index.Indexname: TFRE_DB_NameType; begin result := FIndexName; end; function TFRE_DB_MM_Index.Uniquename: PFRE_DB_NameType; begin result := @FUniqueName; end; function TFRE_DB_MM_Index.NullvalueExistsForObject(const obj: TFRE_DB_Object): boolean; var values : TFRE_DB_IndexValueStore; begin if NullvalueExists(values) then result := values.Exists(obj.UID) else result :=false; end; procedure TFRE_DB_MM_Index.IndexAddCheck(const obj: TFRE_DB_Object; const check_only: boolean); var fld : TFRE_DB_FIELD; isNullVal : boolean; key : Array [0..CFREA_maxKeyLen] of Byte; keylen : NativeInt; begin isNullVal := not obj.FieldOnlyExisting(FFieldname,fld); if isNullVal and (not FAllowNull) then raise EFRE_DB_PL_Exception.Create(edb_UNSUPPORTED,'for the index [%s] the usage of null values (=unset fields) is not allowed',[_GetIndexStringSpec]); if not isNullVal then FieldTypeIndexCompatCheck(fld); if FIsADomainIndex then TransformToBinaryComparableDomain(obj.Field('DomainID'),fld,@key,keylen) else TransformtoBinaryComparable(fld,@key,keylen); if check_only then _InternalCheckAdd(@key,keylen,isNullVal,false,obj.uid) else _InternalAddGuidToValstore(@key,keylen,isNullVal,obj.UID); end; procedure TFRE_DB_MM_Index.IndexUpdCheck(const new_obj, old_obj: TFRE_DB_Object; const check_only: boolean); var oldfld,newfld : TFRE_DB_FIELD; obj_uid : TFRE_DB_GUID; dummy : NativeUint; values : TFRE_DB_IndexValueStore; isNullValue : boolean; OldIsNullValue : boolean; key : Array [0..CFREA_maxKeyLen] of Byte; keylen : NativeInt; ukey : Array [0..CFREA_maxKeyLen] of Byte; ukeylen : NativeInt; begin assert(assigned(new_obj)); assert(assigned(old_obj)); assert(new_obj.UID=old_obj.UID); obj_uid := new_obj.UID; OldIsNullValue := not old_obj.FieldOnlyExisting(FFieldname,oldfld); if FIsADomainIndex then TransformToBinaryComparableDomain(old_obj.Field('DomainID'),oldfld,key,keylen) else TransformtoBinaryComparable(oldfld,key,keylen); isNullValue := not new_obj.FieldOnlyExisting(FFieldname,newfld); if not isNullValue then FieldTypeIndexCompatCheck(newfld); if FIsADomainIndex then TransformToBinaryComparableDomain(new_obj.Field('DomainID'),newfld,ukey,ukeylen) else TransformtoBinaryComparable(newfld,ukey,ukeylen); if CompareTransformedKeys(key,ukey,keylen,ukeylen) then { This should not happen, as the change compare has to happen earlier } begin // The change would not update the index / the key value is the same, which is only possible on Case insensitive indexes where the fieldvalue changed, but not the indexed value if (self is TFRE_DB_TextIndex) and ((self as TFRE_DB_TextIndex).FCaseInsensitive=true) then exit; raise EFRE_DB_PL_Exception.Create(edb_ERROR,'cant update the index for object [%s] / for the unique index [%s] the values would be the same ([%s]->[%s])',[new_obj.UID_String,_GetIndexStringSpec,FFieldname,GetStringRepresentationOfTransientKey(OldIsNullValue,key,keylen),GetStringRepresentationOfTransientKey(isNullValue,ukey,ukeylen)]); end; //writeln('INDEX CHANGE ',_GetIndexStringSpec,' REMOVE VAL ',oldfld.AsString,' ',new_obj.UID_String); //writeln('INDEX CHANGE ',_GetIndexStringSpec,' ADD VAL ' ,newfld.AsString,' ',new_obj.UID_String); if check_only then begin _InternalCheckAdd(@ukey,ukeylen,isNullValue,true,obj_uid) end else begin // Update - (1) Remove old object index value from index // (2) Add new object/field value to index _InternalRemoveGuidFromValstore(@key,keylen,isNullValue,obj_uid); _InternalAddGuidToValstore(@ukey,ukeylen,isNullValue,obj_uid); end; end; procedure TFRE_DB_MM_Index.IndexDelCheck(const obj, new_obj: TFRE_DB_Object; const check_only: boolean); var oldfld : TFRE_DB_FIELD; obj_uid : TFRE_DB_GUID; OldIsNullValue : boolean; key : Array [0..CFREA_maxKeyLen] of Byte; keylen : NativeInt; begin obj_uid := obj.UID; OldIsNullValue := not obj.FieldOnlyExisting(FFieldname,oldfld); if FIsADomainIndex then TransformToBinaryComparableDomain(obj.Field('DomainID'),oldfld,@key,keylen) else TransformtoBinaryComparable(oldfld,@key,keylen); if check_only then _InternalCheckDel(@key,keylen,OldIsNullValue,obj_uid) else _InternalRemoveGuidFromValstore(@key,keylen,OldIsNullValue,obj_uid); // Remove old object index value from index if FAllowNull and assigned(new_obj) then // if the new_obj is not assigned this is a full delete, not a field delete(!) IndexAddCheck(new_obj,check_only); // Need to Transform Null Value end; function TFRE_DB_MM_Index.SupportsIndexType(const ix_type: TFRE_DB_INDEX_TYPE): boolean; begin case ix_type of fdbit_Unsupported: raise EFRE_DB_PL_Exception.Create(edb_MISMATCH,'an unsupported index type is unsupported by definition, so dont query for support'); fdbit_Unsigned: result := SupportsUnsignedQuery; fdbit_Signed: result := SupportsSignedQuery; fdbit_Real: result := SupportsRealQuery; fdbit_Text: result := SupportsStringQuery; end; end; function TFRE_DB_MM_Index.IsUnique: Boolean; begin result := FUnique; end; function TFRE_DB_MM_Index.IsDomainIndex: boolean; begin result := FIsADomainIndex; end; procedure TFRE_DB_MM_Index.AppendAllIndexedUids(var guids: TFRE_DB_GUIDArray; const ascending: boolean; const max_count: NativeInt; skipfirst: NativeInt); var halt : boolean; down_counter,up_counter,abscntr : NativeInt; procedure NodeProc(var value : NativeUint ; var break:boolean); begin (FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore).AppendObjectUIDS(guids,ascending,down_counter,up_counter,abscntr); if (max_count>0) and (up_counter>=max_count) then break:=true; end; begin down_counter := skipfirst; up_counter := 0; abscntr := max_count; if ascending then FIndex.LinearScanBreak(@NodeProc,halt) else FIndex.LinearScanBreak(@NodeProc,halt,true); end; procedure TFRE_DB_MM_Index.AppendAllIndexedUidsDomain(var guids: TFRE_DB_GUIDArray; const ascending: boolean; const max_count: NativeInt; skipfirst: NativeInt; const domid_field: TFRE_DB_FIELD); var halt : boolean; down_counter,up_counter,abscntr : NativeInt; keylen : NativeInt; transkey : Array [0..CFREA_maxKeyLen] of Byte; procedure NodeProc(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var break : boolean); begin (FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore).AppendObjectUIDS(guids,ascending,down_counter,up_counter,abscntr); if (max_count>0) and (up_counter>=max_count) then break:=true; end; begin down_counter := skipfirst; up_counter := 0; abscntr := max_count; TFRE_DB_UnsignedIndex.TransformtoBinaryComparable(domid_field,@transkey[0],keylen,false,false); { domainid as prefix } if ascending then FIndex.PrefixScan(transkey,keylen,@NodeProc) else FIndex.PrefixScanReverse(transkey,keylen,@NodeProc); end; function TFRE_DB_MM_Index.IndexTypeTxt: String; begin result := CFRE_DB_INDEX_TYPE[FREDB_GetIndexTypeForFieldType(FFieldType)]; end; function TFRE_DB_MM_Index.IndexedCount(const unique_values: boolean): NativeInt; procedure CountValuesIndex(var dummy : NativeUint); begin result := result + TFRE_DB_IndexValueStore(FREDB_PtrUIntToObject(dummy)).ObjectCount; end; begin if unique_values then result := FIndex.GetValueCount else begin if (FUniqueNullVals=false) or (FUnique=false) then begin result := 0; FIndex.LinearScan(@CountValuesIndex); //TODO: Replace with Bookkeeping variant end else result := FIndex.GetValueCount; end; end; function TFRE_DB_MM_Index.IndexIsFullyUnique: Boolean; begin result := _IndexIsFullUniqe; end; procedure TFRE_DB_MM_Index.FullClearIndex; procedure ClearIndex(var dummy : NativeUint); begin TFRE_DB_IndexValueStore(FREDB_PtrUIntToObject(dummy)).free; end; begin FIndex.LinearScan(@ClearIndex); end; procedure TFRE_DB_MM_Index.FullReindex; procedure Add(const obj : TFRE_DB_Object); begin obj.Set_Store_Locked(false); try IndexAddCheck(obj,false); finally obj.Set_Store_Locked(true); end; end; begin FullClearIndex; (FCollection as TFRE_DB_Persistance_Collection).ForAllInternal(@Add); end; procedure TFRE_DB_MM_Index._InternalCheckAdd(const key: PByte; const keylen: Nativeint; const isNullVal, isUpdate: Boolean; const obj_uid: TFRE_DB_GUID); var dummy : NativeUint; values : TFRE_DB_IndexValueStore; begin if isNullVal and not FAllowNull then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'trying to add a null value for the index [%s/%s/%s], which is not allowing null values value=[ %s]',[FCollection.CollectionName(false),FIndexName,FFieldname,GetStringRepresentationOfTransientKey(isNullVal,key,keylen)]); if FIndex.ExistsBinaryKey(key,keylen,dummy) then // if not existing then begin values := FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore; if isNullVal then begin if FUniqueNullVals then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'for the null-unique index [%s] the null key value already exists [ %s]',[_GetIndexStringSpec,GetStringRepresentationOfTransientKey(isNullVal,key,keylen)]) else begin if values.Exists(obj_uid) then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'for the non null-unique index [%s] the value(=obj) already exists',[_GetIndexStringSpec]) end; end else begin if FUnique then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'for the unique index [%s] the key already exists [ %s]',[_GetIndexStringSpec,GetStringRepresentationOfTransientKey(isNullVal,key,keylen)]) else begin if values.Exists(obj_uid) then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'for the non unique index [%s] the value [ %s] already exists',[_GetIndexStringSpec,GetStringRepresentationOfTransientKey(isNullVal,key,keylen)]) end; end end end; procedure TFRE_DB_MM_Index._InternalCheckDel(const key: PByte; const keylen: Nativeint; const isNullVal: Boolean; const obj_uid: TFRE_DB_GUID); var dummy : NativeUint; values : TFRE_DB_IndexValueStore; nullvalExist : Boolean; begin if not FAllowNull and isNullVal then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'delete check failed idx [%s] does not allow null values.',[_GetIndexStringSpec]); nullvalExist := NullvalueExists(values); if FUniqueNullVals and isNullVal and nullvalExist then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'delete check failed idx [%s] does allow only one unique null value, and a null value already exist',[_GetIndexStringSpec]); if FIndex.ExistsBinaryKey(key,keylen,dummy) then // if not existing then begin values := FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore; if not values.Exists(obj_uid) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'delete check failed idx [%s] value does not exist [ %s]',[_GetIndexStringSpec,GetStringRepresentationOfTransientKey(isNullVal,key,keylen)]) end else raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'for the unique index [%s] the key to delete does not exists [ %s]',[_GetIndexStringSpec,GetStringRepresentationOfTransientKey(isNullVal,key,keylen)]) end; procedure TFRE_DB_MM_Index._InternalAddGuidToValstore(const key: PByte; const keylen: Nativeint ; const isNullVal : boolean ; const uid: TFRE_DB_GUID); var dummy : NativeUint; values : TFRE_DB_IndexValueStore; begin values := TFRE_DB_IndexValueStore.Create; dummy := FREDB_ObjectToPtrUInt(values); if FIndex.InsertBinaryKeyOrFetch(key,keylen,dummy) then begin //new if not FIndex.ExistsBinaryKey(key,keylen,dummy) then begin FIndex.InsertBinaryKey(key,keylen,dummy); // debug line GFRE_BT.CriticalAbort('inserted key but not finding it, failure in tree structure!'); end; if not values.Add(uid) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'unexpected internal index unique/empty/add failure'); end else begin // exists values.free; values := FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore; if isNullVal then begin if FUniqueNullVals then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'unexpected internal null-unique index add/exists failure') else if not values.Add(UID) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'unexpected internal index non null-unique add failure'); end else begin if FUnique then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'unexpected internal unique index add/exists failure') else if not values.Add(UID) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'unexpected internal index non unique add failure'); end; end; end; procedure TFRE_DB_MM_Index._InternalRemoveGuidFromValstore(const key: PByte; const keylen: Nativeint; const isNullVal: boolean; const uid: TFRE_DB_GUID); var dummy : NativeUint; values : TFRE_DB_IndexValueStore; begin if not FIndex.ExistsBinaryKey(key,keylen,dummy) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'index/field [%s] update, cannot find old value?',[_GetIndexStringSpec]); values := FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore; if not values.RemoveUID(uid) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'index/field [%s] update, cannot find old obj uid [%s] value in indexvaluestore?',[_GetIndexStringSpec,FREDB_G2H(uid)]); if values.ObjectCount=0 then begin if not FIndex.RemoveBinaryKey(key,keylen,dummy) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'index/field [%s] update, cannot remove the index node entry for old obj uid [%s] in indextree?',[_GetIndexStringSpec,FREDB_G2H(uid)]); values.free; end; end; function TFRE_DB_MM_Index.GetStringRepresentationOfTransientKey(const isnullvalue: boolean; const key: PByte; const keylen: Nativeint): String; begin if isnullvalue then exit('(NULL)') else result := GFRE_BT.Dump_Binary(@key[0],keylen,true,false) end; function TFRE_DB_MM_Index.FetchIndexedValsTransformedKey(var obj: TFRE_DB_GUIDArray; const key: PByte; const keylen: Nativeint): boolean; var dummy : NativeUint; down_counter,up_counter,abscntr : NativeInt; begin SetLength(obj,0); down_counter:=0; up_counter:=0; abscntr:=0; result := FIndex.ExistsBinaryKey(key,keylen,dummy); if result then (FREDB_PtrUIntToObject(dummy) as TFRE_DB_IndexValueStore).AppendObjectUIDS(obj,true,down_counter,up_counter,abscntr) end; procedure TFRE_DB_MM_Index.ForAllIndexedValsTransformedKeys(var uids: TFRE_DB_GUIDArray; const mikey, makey: PByte; const milen, malen: NativeInt; const ascending: boolean; const max_count: NativeInt; skipfirst: NativeInt); procedure IteratorBreak(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint ; var break : boolean ; var down_counter,up_counter : NativeInt; const abscntr : NativeInt); begin (FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore).AppendObjectUIDS(uids,ascending,down_counter,up_counter,abscntr); end; begin SetLength(uids,0); FIndex.RangeScan(mikey,makey,milen,malen,@IteratorBreak,max_count,skipfirst,ascending) end; procedure TFRE_DB_MM_Index.TransformToBinaryComparableDomain(const domid_field: TFRE_DB_FIELD; const fld: TFRE_DB_FIELD; const key: PByte; var keylen: Nativeint); var dkeylen : NativeInt; begin TFRE_DB_UnsignedIndex.TransformtoBinaryComparable(domid_field,key,dkeylen,false,false); { prefix with domainid } TransformtoBinaryComparable(fld,key+dkeylen,keylen); keylen := keylen+dkeylen; end; function TFRE_DB_MM_Index.CompareTransformedKeys(const key1, key2: PByte; const keylen1, keylen2: Nativeint): boolean; begin if keylen1=keylen2 then if CompareMemRange(@key1[0],@key2[0],keylen1)=0 then exit(true); exit(false); end; procedure TFRE_DB_MM_Index.StreamHeader(const stream: TStream); begin stream.WriteAnsiString('FOSIDX1'); stream.WriteAnsiString(ClassName); stream.WriteAnsiString(FIndexName); stream.WriteAnsiString(FFieldname); stream.WriteAnsiString(CFRE_DB_FIELDTYPE_SHORT[FFieldType]); if FUnique then stream.WriteByte(1) else stream.WriteByte(0); if FAllowNull then stream.WriteByte(1) else stream.WriteByte(0); if FUniqueNullVals then stream.WriteByte(1) else stream.WriteByte(0); if FIsADomainIndex then stream.WriteByte(1) else stream.WriteByte(0); end; procedure TFRE_DB_MM_Index.StreamToThis(const stream: TStream); begin StreamHeader(stream); StreamIndex(stream); end; procedure TFRE_DB_MM_Index.StreamIndex(const stream: TStream); var i:NativeInt; procedure StreamKeyVal(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint); var ixs : TFRE_DB_IndexValueStore; begin stream.WriteQWord(KeyLen); stream.WriteBuffer(Key^,KeyLen); ixs := FREDB_PtrUIntToObject(value) as TFRE_DB_IndexValueStore; ixs.StreamToThis(stream); end; begin i := FIndex.GetValueCount; stream.WriteQWord(i); FIndex.LinearScanKeyVals(@StreamKeyVal); end; function TFRE_DB_MM_Index.GetIndexDefinitionObject: IFRE_DB_Object; begin result := GFRE_DBI.NewObject; result.Field('IX_CLASS').AsString := ClassName; result.Field('IX_NAM').AsString := FIndexName; result.Field('IX_FN').AsString := FFieldname; result.Field('IX_FT').AsString := CFRE_DB_FIELDTYPE_SHORT[FFieldType]; result.Field('IX_UNQ').AsBoolean := FUnique; result.Field('IX_UNQN').AsBoolean := FUniqueNullVals; result.Field('IX_ANULL').AsBoolean := FAllowNull; result.Field('IX_DOM').AsBoolean := FIsADomainIndex; end; function TFRE_DB_MM_Index.GetIndexDefinition: TFRE_DB_INDEX_DEF; begin with result do begin IndexClass := ClassName; IndexName := FIndexName; FieldName := FFieldname; FieldType := FFieldType; Unique := FUnique; AllowNulls := FAllowNull; UniqueNull := FUniqueNullVals; IgnoreCase := false; DomainIndex := FIsADomainIndex; end; end; procedure TFRE_DB_MM_Index.LoadIndex(const stream: TStream ; const coll: TFRE_DB_PERSISTANCE_COLLECTION); var i,cnt : NativeInt; keylen : NativeUint; key : RawByteString; ixs : TFRE_DB_IndexValueStore; begin cnt := stream.ReadQWord; for i := 1 to cnt do begin keylen := stream.ReadQWord; SetLength(key,keylen); stream.ReadBuffer(Key[1],keylen); ixs := TFRE_DB_IndexValueStore.Create; ixs.LoadFromThis(stream,coll); if not FIndex.InsertBinaryKey(@key[1],keylen,FREDB_ObjectToPtrUInt(ixs)) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'stream load : index add failure [%s]',[key]); end; end; class function TFRE_DB_MM_Index.CreateFromStream(const stream: TStream; const coll: TFRE_DB_PERSISTANCE_COLLECTION): TFRE_DB_MM_Index; var vers : String; cn,idxn,fieldn : String; ft : TFRE_DB_FIELDTYPE; unique : boolean; allownull : boolean; uniquenull : boolean; domindex : boolean; begin vers := stream.ReadAnsiString; if vers='FOSIDX1' then begin cn := stream.ReadAnsiString; idxn := stream.ReadAnsiString; fieldn := stream.ReadAnsiString; ft := FREDB_FieldtypeShortString2Fieldtype(stream.ReadAnsiString); unique := stream.ReadByte=1; allownull := stream.ReadByte=1; uniquenull := stream.ReadByte=1; domindex := stream.ReadByte=1; end else begin cn := vers; idxn := stream.ReadAnsiString; fieldn := stream.ReadAnsiString; ft := FREDB_FieldtypeShortString2Fieldtype(stream.ReadAnsiString); unique := stream.ReadByte=1; allownull := stream.ReadByte=1; uniquenull := stream.ReadByte=1; domindex := false; end; case cn of 'TFRE_DB_TextIndex' : result := TFRE_DB_TextIndex.CreateStreamed (stream,idxn,fieldn,ft,unique,coll,allownull,uniquenull,domindex); 'TFRE_DB_RealIndex' : result := TFRE_DB_RealIndex.CreateStreamed (stream,idxn,fieldn,ft,unique,coll,allownull,uniquenull,domindex); 'TFRE_DB_SignedIndex' : result := TFRE_DB_SignedIndex.CreateStreamed (stream,idxn,fieldn,ft,unique,coll,allownull,uniquenull,domindex); 'TFRE_DB_UnsignedIndex' : result := TFRE_DB_UnsignedIndex.CreateStreamed(stream,idxn,fieldn,ft,unique,coll,allownull,uniquenull,domindex); else raise EFRE_DB_PL_Exception.Create(edb_ERROR,'Unsupported streaming index class [%s]',[cn]); end; end; class function TFRE_DB_MM_Index.CreateFromDef(const def: TFRE_DB_INDEX_DEF; const coll: TFRE_DB_PERSISTANCE_COLLECTION): TFRE_DB_MM_Index; begin with def do case IndexClass of 'TFRE_DB_TextIndex' : result := TFRE_DB_TextIndex.Create (IndexName,FieldName,FieldType,Unique,IgnoreCase,coll,AllowNulls,UniqueNull,DomainIndex); 'TFRE_DB_RealIndex' : result := TFRE_DB_RealIndex.Create (IndexName,FieldName,FieldType,Unique ,coll,AllowNulls,UniqueNull,DomainIndex); 'TFRE_DB_SignedIndex' : result := TFRE_DB_SignedIndex.Create (IndexName,FieldName,FieldType,Unique ,coll,AllowNulls,UniqueNull,DomainIndex); 'TFRE_DB_UnsignedIndex' : result := TFRE_DB_UnsignedIndex.Create(IndexName,FieldName,FieldType,Unique ,coll,AllowNulls,UniqueNull,DomainIndex); else raise EFRE_DB_PL_Exception.Create(edb_ERROR,'Unsupported streaming index class [%s]',[IndexClass]); end; end; function TFRE_DB_MM_Index._IndexIsFullUniqe: Boolean; begin result := (FUnique=true) and ((FUniqueNullVals=true) or (FAllowNull=false)); end; function TFRE_DB_MM_Index._GetIndexStringSpec: String; begin result := FCollection.CollectionName(false)+'#'+FIndexName+'('+FFieldname+')'; end; class function TFRE_DB_MM_Index.GetIndexClassForFieldtype(const fieldtype: TFRE_DB_FIELDTYPE; var idxclass: TFRE_DB_MM_IndexClass): TFRE_DB_Errortype; begin result := edb_OK; case FieldType of fdbft_GUID, fdbft_ObjLink, fdbft_Boolean, fdbft_Byte, fdbft_UInt16, fdbft_UInt32, fdbft_UInt64 : idxclass := TFRE_DB_UnsignedIndex; fdbft_Int16, // invert Sign bit by xor (1 shl (bits-1)), then swap endian fdbft_Int32, fdbft_Int64, fdbft_Currency, // = int64*10000; fdbft_DateTimeUTC: idxclass := TFRE_DB_SignedIndex; fdbft_Real32, fdbft_Real64: idxclass := TFRE_DB_RealIndex; fdbft_String: idxclass := TFRE_DB_TextIndex; //fdbft_Stream: ; //fdbft_Object: ; else exit(edb_UNSUPPORTED); end; end; class procedure TFRE_DB_MM_Index.GetKeyLenForFieldtype(const fieldtype: TFRE_DB_FIELDTYPE; var FixedKeyLen: NativeInt); begin case fieldtype of fdbft_GUID, fdbft_ObjLink: FixedKeylen := 16; fdbft_Byte: FixedKeylen := 1; fdbft_Int16: FixedKeylen := 2; fdbft_UInt16: FixedKeylen := 2; fdbft_Int32: FixedKeylen := 4; fdbft_UInt32: FixedKeylen := 4; fdbft_Int64: FixedKeylen := 8; fdbft_UInt64: FixedKeylen := 8; fdbft_Real32: FixedKeylen := 8; fdbft_Real64: FixedKeylen := 8; fdbft_Currency: FixedKeylen := 8; fdbft_String: FixedKeylen := 8; fdbft_Boolean: FixedKeylen := 1; fdbft_DateTimeUTC: FixedKeylen := 8; else FixedKeyLen := -1; end; end; { TFRE_DB_CollectionTree } constructor TFRE_DB_CollectionManageTree.Create; begin FCollTree := TFRE_ART_TREE.Create; end; destructor TFRE_DB_CollectionManageTree.Destroy; begin FCollTree.Clear; FCollTree.Free; inherited Destroy; end; procedure TFRE_DB_CollectionManageTree.Clear; procedure ClearTree(var dummy : NativeUint); begin TFRE_DB_Persistance_Collection(FREDB_PtrUIntToObject(dummy)).Free; end; begin FCollTree.LinearScan(@ClearTree); FCollTree.Clear; end; function TFRE_DB_CollectionManageTree.NewCollection(const coll_name: TFRE_DB_NameType; out Collection: TFRE_DB_PERSISTANCE_COLLECTION; const volatile_in_memory: boolean; const masterdata: TFRE_DB_Master_Data): TFRE_DB_Errortype; var coll : TFRE_DB_Persistance_Collection; safename : TFRE_DB_NameType; begin safename := UpperCase(coll_name); if FCollTree.ExistsBinaryKey(@safename[1],Length(safename),dummy) then begin Collection := TFRE_DB_Persistance_Collection(dummy); result := edb_EXISTS; end else begin coll := TFRE_DB_Persistance_Collection.Create(coll_name,volatile_in_memory,masterdata); if FCollTree.InsertBinaryKey(@coll.UniqueName^[1],length(coll.UniqueName^),FREDB_ObjectToPtrUInt(coll)) then begin Collection := coll; exit(edb_OK); end else begin coll.Free; exit(edb_INTERNAL); end; end; end; function TFRE_DB_CollectionManageTree.DeleteCollection(const coll_name: TFRE_DB_NameType): TFRE_DB_Errortype; var coll : TFRE_DB_Persistance_Collection; safename : TFRE_DB_NameType; colli : TFRE_DB_PERSISTANCE_COLLECTION_BASE; begin safename := UpperCase(coll_name); if FCollTree.RemoveBinaryKey(@safename[1],Length(safename),dummy) then begin Coll := TFRE_DB_Persistance_Collection(dummy); result := edb_OK; Coll.Free; end else begin result := edb_NOT_FOUND; end; end; function TFRE_DB_CollectionManageTree.GetCollection(const coll_name: TFRE_DB_NameType; out Collection: TFRE_DB_PERSISTANCE_COLLECTION): boolean; begin result := GetCollectionInt(coll_name,TFRE_DB_PERSISTANCE_COLLECTION(Collection)); end; function TFRE_DB_CollectionManageTree.GetCollectionInt(const coll_name: TFRE_DB_NameType; out Collection: TFRE_DB_PERSISTANCE_COLLECTION): boolean; var safename : TFRE_DB_NameType; begin safename:=uppercase(coll_name); if FCollTree.ExistsBinaryKey(@safename[1],length(safename),dummy) then begin Collection := TFRE_DB_Persistance_Collection(dummy); result := true; end else begin Collection := nil; Result := false; end; end; procedure TFRE_DB_CollectionManageTree.CMTForAllCollections(const iter: TFRE_DB_PersColl_Iterator); var brk : boolean; procedure IterateColls(var dummy:NativeUInt ; var brk : boolean); var coll : TFRE_DB_Persistance_Collection; begin coll := FREDB_PtrUIntToObject(dummy) as TFRE_DB_Persistance_Collection; iter(coll) end; begin brk := false; FCollTree.LinearScanBreak(@IterateColls,brk); end; function TFRE_DB_CollectionManageTree.GetCollectionCount: Integer; begin result := FCollTree.GetValueCount; end; { TFRE_DB_Persistance_Collection } function TFRE_DB_Persistance_Collection.IsVolatile: boolean; begin result := FVolatile; end; function TFRE_DB_Persistance_Collection.IndexExists(const idx_name: TFRE_DB_NameType): NativeInt; var i : NativeInt; FUniqueName : TFRE_DB_NameType; begin result := -1; FUniqueName := UpperCase(idx_name); for i := 0 to high(FIndexStore) do if FIndexStore[i].Uniquename^=FUniqueName then exit(i); end; function TFRE_DB_Persistance_Collection.GetIndexDefinition(const idx_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): TFRE_DB_INDEX_DEF; var i : NativeInt; begin i := IndexExists(idx_name); if i=-1 then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the requested index [%s] does not exist on collection [%s]',[idx_name,FName]); result := FIndexStore[i].GetIndexDefinition; end; function TFRE_DB_Persistance_Collection.IndexNames: TFRE_DB_NameTypeArray; var i : Integer; begin SetLength(result,Length(FIndexStore)); for i := 0 to high(FIndexStore) do result[i] := FIndexStore[i].Indexname; end; procedure TFRE_DB_Persistance_Collection.AddIndex(const idx: TFRE_DB_MM_Index); var high : NativeInt; begin high := Length(FIndexStore); SetLength(FIndexStore,high+1); FIndexStore[high] := idx; end; procedure TFRE_DB_Persistance_Collection.IndexAddCheck(const obj: TFRE_DB_Object; const check_only: boolean); var i : NativeInt; begin for i:= 0 to high(FIndexStore) do FIndexStore[i].IndexAddCheck(obj,check_only); end; procedure TFRE_DB_Persistance_Collection.IndexUpdCheck(const new_obj, old_obj: TFRE_DB_Object; const check_only: boolean); var i : NativeInt; begin for i:= 0 to high(FIndexStore) do FIndexStore[i].IndexUpdCheck(new_obj, old_obj,check_only); end; procedure TFRE_DB_Persistance_Collection.IndexDelCheck(const del_obj: TFRE_DB_Object; const check_only: boolean); var i : NativeInt; begin for i:= 0 to high(FIndexStore) do FIndexStore[i].IndexDelCheck(del_obj,nil,check_only); end; constructor TFRE_DB_Persistance_Collection.Create(const coll_name: TFRE_DB_NameType; Volatile: Boolean; const masterdata: TFRE_DB_Master_Data); begin FGuidObjStore := TFRE_ART_TREE.Create; FName := coll_name; FVolatile := Volatile; FMasterLink := masterdata; FUpperName := UpperCase(FName); end; destructor TFRE_DB_Persistance_Collection.Destroy; var i: NativeInt; begin for i := 0 to high(FIndexStore) do FIndexStore[i].Free; Clear; FGuidObjStore.Free; inherited Destroy; end; function TFRE_DB_Persistance_Collection.Count: int64; begin result := FGuidObjStore.GetValueCount; end; function TFRE_DB_Persistance_Collection.Exists(const ouid: TFRE_DB_GUID): boolean; var dummy : PtrUInt; begin result := FGuidObjStore.ExistsBinaryKey(@ouid,SizeOf(ouid),dummy); end; function TFRE_DB_Persistance_Collection.Remove(const ouid: TFRE_DB_GUID): TFRE_DB_Errortype; begin abort; //FLayer.DeleteObject(ouid,CollectionName(true)); //exit(edb_OK); end; function TFRE_DB_Persistance_Collection.FetchO(const uid: TFRE_DB_GUID; var obj: TFRE_DB_Object): boolean; var dummy : PtrUInt; begin result := FGuidObjStore.ExistsBinaryKey(@uid,SizeOf(TFRE_DB_GUID),dummy); if result then obj := CloneOutObject(FREDB_PtrUIntToObject(dummy) as TFRE_DB_Object) else obj := nil; end; procedure TFRE_DB_Persistance_Collection.Clear; begin FGuidObjStore.Clear; end; procedure TFRE_DB_Persistance_Collection.GetAllUIDS(var uids: TFRE_DB_GUIDArray); var cnt,maxc : NativeInt; procedure ForAll(var val:PtrUInt); var newobj : TFRE_DB_Object; begin newobj := FREDB_PtrUIntToObject(val) as TFRE_DB_Object; uids[cnt] := newobj.UID; inc(cnt); assert(cnt<=maxc); end; begin cnt := 0; maxc := FGuidObjStore.GetValueCount; SetLength(uids,maxc); FGuidObjStore.LinearScan(@ForAll); end; procedure TFRE_DB_Persistance_Collection.GetAllObjects(var objs: IFRE_DB_ObjectArray); var cnt,maxc : NativeInt; procedure ForAll(var val:PtrUInt); var newobj : TFRE_DB_Object; begin newobj := FREDB_PtrUIntToObject(val) as TFRE_DB_Object; objs[cnt] := CloneOutObject(newobj); inc(cnt); assert(cnt<=maxc); end; begin cnt := 0; maxc := FGuidObjStore.GetValueCount; SetLength(objs,maxc); FGuidObjStore.LinearScan(@ForAll); end; procedure TFRE_DB_Persistance_Collection.GetAllObjectsInt(var objs: IFRE_DB_ObjectArray); var cnt,maxc : NativeInt; procedure ForAll(var val:PtrUInt); var newobj : TFRE_DB_Object; begin newobj := FREDB_PtrUIntToObject(val) as TFRE_DB_Object; objs[cnt] := newobj; inc(cnt); assert(cnt<=maxc); end; begin cnt := 0; maxc := FGuidObjStore.GetValueCount; SetLength(objs,maxc); FGuidObjStore.LinearScan(@ForAll); end; // An object is allowed only once in a collection, but can be stored in multiple collections // An object is always at least in one collection, dangling objects (without beeing in a collection) are errors // All subobjects are stored and fetchable in the "Master" store too // Subobjects can only be parented once (can only be part of one object), thus need to be unique procedure TFRE_DB_Persistance_Collection.StoreInThisColl(const new_iobj: IFRE_DB_Object; const checkphase: boolean); var new_obj : TFRE_DB_Object; dummy : PtrUInt; begin // Check existance in this collection new_obj := new_iobj.Implementor as TFRE_DB_Object; if checkphase then begin if FGuidObjStore.ExistsBinaryKey(new_obj.UIDP,SizeOf(TFRE_DB_GUID),dummy) then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'object [%s] already exists on store in collection [%s]',[new_obj.UID_String,FName]); IndexAddCheck(new_obj,true); end else begin IndexAddCheck(new_obj,false); if not FGuidObjStore.InsertBinaryKey(new_obj.UIDP,SizeOf(TFRE_DB_GUID),FREDB_ObjectToPtrUInt(new_obj)) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'store of object [%s] in collection [%s] failed -> already exists on store after exist check ?',[new_obj.UID_String,FName]); new_obj.__InternalCollectionAdd(self); // Add The Colection Reference to a directly stored master or child object assert(length(new_obj.__InternalGetCollectionList)>0); end; end; procedure TFRE_DB_Persistance_Collection.UpdateInThisColl(const new_ifld, old_ifld: IFRE_DB_FIELD; const old_iobj, new_iobj: IFRE_DB_Object; const update_typ: TFRE_DB_ObjCompareEventType; const in_child_obj: boolean; const checkphase: boolean); var old_fld,new_fld : TFRE_DB_FIELD; old_obj,new_obj : TFRE_DB_Object; begin if Assigned(old_iobj) then old_obj := old_iobj.Implementor as TFRE_DB_Object else old_obj := nil; if assigned(new_iobj) then new_obj := new_iobj.Implementor as TFRE_DB_Object else new_obj := nil; if assigned(old_ifld) then old_fld := old_ifld.Implementor as TFRE_DB_FIELD else old_fld := nil; if assigned(new_ifld) then new_fld := new_ifld.Implementor as TFRE_DB_FIELD else new_fld := nil; if not in_child_obj then CheckFieldChangeAgainstIndex(old_fld,new_fld,update_typ,checkphase,old_obj,new_obj) else { indices must not be defined on child objects} end; procedure TFRE_DB_Persistance_Collection.DeleteFromThisColl(const del_iobj: IFRE_DB_Object; const checkphase: boolean); var cnt : NativeInt; del_obj : TFRE_DB_Object; dummy : PtrUInt; begin del_obj := del_iobj.Implementor as TFRE_DB_Object; if checkphase then begin if not FGuidObjStore.ExistsBinaryKey(del_obj.UIDP,SizeOf(TFRE_DB_GUID),dummy) then raise EFRE_DB_PL_Exception.Create(edb_EXISTS,'object [%s] does not exist on delete in collection [%s]',[del_obj.UID_String,FName]); IndexDelCheck(del_obj,true); end else begin IndexDelCheck(del_obj,false); if not FGuidObjStore.RemoveBinaryKey(del_obj.UIDP,SizeOf(TFRE_DB_GUID),dummy) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'delete of object [%s] in collection [%s] failed -> does not exists on delete after exist check ?',[del_obj.UID_String,FName]); cnt := del_obj.__InternalCollectionRemove(self); // Add The Colection Reference to a directly stored master or child object if cnt=0 then begin // Object will be finally removed on FMasterdata Step end; end; end; function TFRE_DB_Persistance_Collection.CloneOutObject(const inobj: TFRE_DB_Object): TFRE_DB_Object; begin result := FMasterLink.CloneOutObject(inobj); end; function TFRE_DB_Persistance_Collection.CloneOutArray(const objarr: TFRE_DB_GUIDArray): TFRE_DB_ObjectArray; var i:NativeInt; begin SetLength(result,length(objarr)); for i:=0 to high(objarr) do if not FetchO(objarr[i],result[i]) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'cloneout failed uid not found [%s]',[FREDB_G2H(objarr[i])]); end; function TFRE_DB_Persistance_Collection.CloneOutArrayOI(const objarr: TFRE_DB_GUIDArray): IFRE_DB_ObjectArray; var i:NativeInt; begin SetLength(result,length(objarr)); for i:=0 to high(objarr) do if not Fetch(objarr[i],result[i]) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'cloneout failed uid not found [%s]',[FREDB_G2H(objarr[i])]); end; function TFRE_DB_Persistance_Collection.CloneOutArrayII(const objarr: IFRE_DB_ObjectArray): IFRE_DB_ObjectArray; var i : NativeInt; begin SetLength(result,Length(objarr)); for i:=0 to high(objarr) do result[i] := CloneOutObject(objarr[i].Implementor as TFRE_DB_Object); end; function TFRE_DB_Persistance_Collection.FetchIntFromCollArrOI(const objarr: TFRE_DB_GUIDArray): IFRE_DB_ObjectArray; var i:NativeInt; begin SetLength(result,length(objarr)); for i:=0 to high(objarr) do if not FetchIntFromColl(objarr[i],result[i]) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'fetchinternalarr failed uid not found [%s]',[FREDB_G2H(objarr[i])]); end; function TFRE_DB_Persistance_Collection.FetchIntFromCollAll: IFRE_DB_ObjectArray; var uids : TFRE_DB_GUIDArray; begin GetAllUIDS(uids); result := FetchIntFromCollArrOI(uids) end; procedure TFRE_DB_Persistance_Collection.ForAllInternalI(const iter: IFRE_DB_Obj_Iterator); procedure ForAll(var val:PtrUInt); var newobj : TFRE_DB_Object; begin newobj := FREDB_PtrUIntToObject(val) as TFRE_DB_Object; iter(newobj); end; begin FGuidObjStore.LinearScan(@ForAll); end; procedure TFRE_DB_Persistance_Collection.ForAllInternal(const iter: TFRE_DB_Obj_Iterator); procedure ForAll(var val:PtrUInt); var newobj : TFRE_DB_Object; begin newobj := FREDB_PtrUIntToObject(val) as TFRE_DB_Object; iter(newobj); end; begin FGuidObjStore.LinearScan(@ForAll); end; procedure TFRE_DB_Persistance_Collection.ForAllInternalBreak(const iter: TFRE_DB_ObjectIteratorBrk;var halt : boolean ; const descending : boolean); procedure ForAll(var val : NativeUint ; var break : boolean); var newobj : TFRE_DB_Object; begin newobj := FREDB_PtrUIntToObject(val) as TFRE_DB_Object; iter(newobj,break); end; begin FGuidObjStore.LinearScanBreak(@ForAll,halt,descending); end; procedure TFRE_DB_Persistance_Collection.StreamToThis(const stream: TStream); var i,cnt,vcnt : nativeint; procedure AllGuids(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint); var s:string[16]; begin assert(KeyLen=16); SetLength(s,16); move(key^,s[1],16); stream.WriteAnsiString(s); // guid; inc(vcnt); end; begin if FVolatile then abort; stream.Position:=0; stream.WriteAnsiString('FDBC'); stream.WriteAnsiString(FName); stream.WriteAnsiString('*'); cnt := FGuidObjStore.GetValueCount; vcnt := 0; stream.WriteQWord(cnt); FGuidObjStore.LinearScanKeyVals(@AllGuids); assert(vcnt=cnt); //stream.WriteQWord(length(FIndexStore)); //for i:=0 to high(FIndexStore) do // FIndexStore[i].StreamToThis(stream); stream.WriteQWord(0); { index stream is not in the collection stream anymore } end; procedure TFRE_DB_Persistance_Collection.StreamIndexToThis(const ix_name: TFRE_DB_NameType; const stream: TStream); var ix : NativeInt; begin ix :=IndexExists(ix_name); if ix=-1 then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not fetch index by name [%s]',[ix_name]); FIndexStore[ix].StreamToThis(stream); end; function TFRE_DB_Persistance_Collection.GetIndexDefObject: IFRE_DB_Object; var obj : IFRE_DB_Object; i : NativeInt; begin obj := GFRE_DBI.NewObject; obj.Field('IndexNames').AsStringArr := FREDB_NametypeArray2StringArray(IndexNames); for i:=0 to high(FIndexStore) do obj.Field('ID_'+FIndexStore[i].Uniquename^).AsObject := FIndexStore[i].GetIndexDefinitionObject; result := obj; end; procedure TFRE_DB_Persistance_Collection.CreateIndexDefsFromObj(const obj: IFRE_DB_Object); var ido : IFRE_DB_Object; stream : TStream; loaded : boolean; ixdef : TFRE_DB_INDEX_DEF_ARRAY; i : NativeInt; begin if Length(FIndexStore)<>0 then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'index definitions could only be created on an empty index store(!)'); ixdef := FREDB_CreateIndexDefArrayFromObject(obj); SetLength(FIndexStore,Length(ixdef)); for i:=0 to high(ixdef) do begin loaded := false; if GetPersLayer.FDB_TryGetIndexStream(CollectionName(false),ixdef[i].IndexName,stream) then begin try GFRE_DBI.LogDebug(dblc_PERSISTANCE,'>>LOAD STREAM FOR DEF [%s]',[ixdef[i].IndexDescription]); FIndexStore[i] := TFRE_DB_MM_Index.CreateFromStream(stream,self); loaded := true; stream.Free; except on e:Exception do begin GFRE_DBI.LogError(dblc_PERSISTANCE,'FAILURE LOADING INDEX STREAM [%s/%s] (%s)',[CollectionName(false),ixdef[i].IndexName,e.Message]); loaded := false; end; end; end; if not loaded then begin GFRE_DBI.LogError(dblc_PERSISTANCE,'COULD NOT LOAD INDEX STREAM FOR [%s/%s]',[CollectionName(false),ixdef[i].IndexName]); FIndexStore[i] := TFRE_DB_MM_Index.CreateFromDef(ixdef[i],self); GFRE_DBI.LogWarning(dblc_PERSISTANCE,'REINDEXING [%s] (%s)',[CollectionName(false),ixdef[i].IndexDescription]); FIndexStore[i].FullReindex; GFRE_DBI.LogWarning(dblc_PERSISTANCE,'REINDEXING [%s/%s] DONE',[CollectionName(false),ixdef[i].IndexName]); end; end; end; procedure TFRE_DB_Persistance_Collection.LoadFromThis(const stream: TStream); var in_txt : String; cnt,i : NativeInt; uid : TFRE_DB_GUID; dbo : TFRE_DB_Object; begin in_txt := stream.ReadAnsiString; if in_txt<>'FDBC' then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'COLLECTION STREAM INVALID : signature bad'); in_txt := stream.ReadAnsiString; if in_txt<>FName then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'COLLECTION STREAM INVALID NAME DIFFERS: [%s <> %s]',[in_txt,FName]); stream.ReadAnsiString; // deprecated collectionclassname cnt := stream.ReadQWord; //writeln('RELOADING COLLECTION ',in_txt,' / ',cnt); for i := 1 to cnt do begin in_txt := stream.ReadAnsiString; // guid; assert(Length(in_txt)=16); move(in_txt[1],uid,16); if not FMasterLink.FetchObject(uid,dbo,true) or not assigned(dbo) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'COLLECTION [%s] LOAD / FETCH FAILED [%s]',[CollectionName(false),FREDB_G2H(uid)]); if not FGuidObjStore.InsertBinaryKey(dbo.UIDP,SizeOf(TFRE_DB_GUID),FREDB_ObjectToPtrUInt(dbo)) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'COLLECTION [%s] LOAD / INSERT FAILED [%s] EXISTS',[CollectionName(false),FREDB_G2H(uid)]); dbo.__InternalCollectionAdd(self); end; cnt := stream.ReadQWord; SetLength(FIndexStore,cnt); for i := 0 to high(FIndexStore) do begin FIndexStore[i] := TFRE_DB_MM_Index.CreateFromStream(stream,self); writeln('>>> WARNING'); writeln('>>> LOADING OLD FORMAT / INPLACE INDEX STREAM >>',FIndexStore[i].Indexname,'<<'); writeln('>>> WARNING'); end; end; function TFRE_DB_Persistance_Collection.BackupToObject: IFRE_DB_Object; var i,cnt,vcnt : nativeint; obj : IFRE_DB_Object; arr : TFRE_DB_GUIDArray; procedure AllGuids(var value : NativeUInt ; const Key : PByte ; const KeyLen : NativeUint); var pguid : PFRE_DB_GUID; begin assert(KeyLen=16); pguid := PFRE_DB_GUID(Key); arr[vcnt] := pguid^; inc(vcnt); end; begin if FVolatile then abort; obj := GFRE_DBI.NewObject; obj.Field('CollectionName').AsString := FName; obj.Field('ClassName').AsString := '*'; cnt := FGuidObjStore.GetValueCount; vcnt := 0; SetLength(arr,cnt); FGuidObjStore.LinearScanKeyVals(@AllGuids); assert(vcnt=cnt); obj.Field('ObjectUids').AsGUIDArr := arr; obj.Field('IndexCount').AsInt32 := length(FIndexStore); for i:=0 to high(FIndexStore) do FIndexStore[i].StreamToThis(obj.Field('Index_'+inttostr(i)).AsStream); obj.Field('Indexes').AsObject := GetIndexDefObject; result := obj; end; procedure TFRE_DB_Persistance_Collection.RestoreFromObject(const obj: IFRE_DB_Object); var in_txt : String; cnt,i : NativeInt; uid : TFRE_DB_GUID; dbo : TFRE_DB_Object; arr : TFRE_DB_GUIDArray; begin //FCClassname := obj.Field('ClassName').AsString; arr := obj.Field('ObjectUids').AsGUIDArr; for i := 0 to high(arr) do begin uid := arr[i]; if (not FMasterLink.FetchObject(uid,dbo,true)) or not assigned(dbo) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'COLLECTION LOAD / FETCH FAILED [%s]',[FREDB_G2H(uid)]); if not FGuidObjStore.InsertBinaryKey(dbo.UIDP,SizeOf(TFRE_DB_GUID),FREDB_ObjectToPtrUInt(dbo)) then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'COLLECTION LOAD / INSERT FAILED [%s] EXISTS',[FREDB_G2H(uid)]); dbo.__InternalCollectionAdd(self); end; cnt := obj.Field('IndexCount').AsInt32; SetLength(FIndexStore,cnt); for i := 0 to high(FIndexStore) do FIndexStore[i] := TFRE_DB_MM_Index.CreateFromStream(obj.Field('Index_'+inttostr(i)).AsStream,self); end; function TFRE_DB_Persistance_Collection.CollectionName(const unique: boolean): TFRE_DB_NameType; begin if unique then result := UniqueName^ else result := FName; end; function TFRE_DB_Persistance_Collection.Fetch(const uid: TFRE_DB_GUID; var iobj: IFRE_DB_Object): boolean; var dummy : PtrUInt; begin result := FGuidObjStore.ExistsBinaryKey(@uid,SizeOf(TFRE_DB_GUID),dummy); if result then iobj := CloneOutObject(FREDB_PtrUIntToObject(dummy) as TFRE_DB_Object) else iobj := nil; end; function TFRE_DB_Persistance_Collection.DefineIndexOnFieldReal(const checkonly: boolean; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean; const domain_index: boolean; var prelim_index: TFRE_DB_MM_Index): TFRE_DB_Errortype; begin result := edb_OK; if IndexExists(index_name)>=0 then exit(edb_EXISTS); if checkonly then begin case FieldType of fdbft_GUID, fdbft_ObjLink, fdbft_Boolean, fdbft_Byte, fdbft_UInt16, fdbft_UInt32, fdbft_UInt64 : prelim_index := TFRE_DB_UnsignedIndex.Create(index_name,fieldname,fieldtype,unique,self,allow_null_value,unique_null_values,domain_index); fdbft_Int16, // invert Sign bit by xor (1 shl (bits-1)), then swap endian fdbft_Int32, fdbft_Int64, fdbft_Currency, // = int64*10000; fdbft_DateTimeUTC: prelim_index := TFRE_DB_SignedIndex.Create(index_name,fieldname,fieldtype,unique,self,allow_null_value,unique_null_values,domain_index); fdbft_Real32, fdbft_Real64: prelim_index := TFRE_DB_RealIndex.Create(index_name,fieldname,fieldtype,unique,self,allow_null_value,unique_null_values,domain_index); fdbft_String: prelim_index := TFRE_DB_TextIndex.Create(index_name,FieldName,FieldType,unique,ignore_content_case,self,allow_null_value,unique_null_values,domain_index); else exit(edb_UNSUPPORTED); end; if Count>0 then begin try prelim_index.FullReindex; except on e:exception do begin try prelim_index.Free; finally end; result.Code := edb_ERROR; result.Msg := 'Reindexing Failure : '+e.Message; end; end; end; end; if not checkonly then AddIndex(prelim_index); end; function TFRE_DB_Persistance_Collection.DropIndexReal(const checkonly: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): TFRE_DB_Errortype; var idx : NativeInt; i : NativeInt; ix : TFRE_DB_MM_Index; idxsn : Array of TFRE_DB_MM_Index; begin if checkonly then begin idx := IndexExists(index_name); if idx=-1 then exit(edb_NOT_FOUND); exit(edb_OK); end else begin idx := IndexExists(index_name); if idx=-1 then exit(edb_NOT_FOUND); ix := FIndexStore[idx]; try FIndexStore[idx]:=nil; ix.free; except on E:Exception do GFRE_DBI.LogError(dblc_PERSISTANCE,'unexpected exception freeing index data [%s] on collection [%s]',[index_name,CollectionName(false)]); end; SetLength(idxsn,Length(FIndexStore)-1); idx := 0; for i := 0 to high(FIndexStore) do begin if FIndexStore[i]<>nil then begin idxsn[idx] := FIndexStore[i]; inc(idx) end; end; FIndexStore := idxsn; result := edb_OK; end; end; // Check if a field can be removed safely from an object stored in this collection, or if an index exists on that field //TODO -> handle indexed field change procedure TFRE_DB_Persistance_Collection.CheckFieldChangeAgainstIndex(const oldfield, newfield: TFRE_DB_FIELD; const change_type: TFRE_DB_ObjCompareEventType; const check: boolean; old_obj, new_obj: TFRE_DB_Object); var i : NativeInt; nullValExists : boolean; fieldname : TFRE_DB_NameType; idummy : TFRE_DB_Object; begin if assigned(newfield) then begin fieldname := uppercase(newfield.FieldName); end; if assigned(oldfield) then begin fieldname := uppercase(oldfield.FieldName); end; for i := 0 to high(FIndexStore) do if FIndexStore[i].FUniqueFieldname=fieldname then begin case change_type of cev_FieldDeleted: begin FIndexStore[i].IndexDelCheck(old_obj,new_obj,check); end; cev_FieldAdded: begin nullValExists := FIndexStore[i].NullvalueExistsForObject(new_obj); if nullValExists then // We need to do an index update if a nullvalue for this object is already indexed begin if not FetchIntFromCollO(new_obj.UID,idummy,true) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'FIELDCHANGE Internal an object should be updated but was not found [%s]',[new_obj.UID_String]); old_obj := idummy.Implementor as TFRE_DB_Object; FIndexStore[i].IndexUpdCheck(new_obj,old_obj,check); end else FIndexStore[i].IndexAddCheck(new_obj,check); end; cev_FieldChanged: begin FIndexStore[i].IndexUpdCheck(new_obj,old_obj,check); end; end; end; end; function TFRE_DB_Persistance_Collection.GetIndexedObjInternal(const query_value: TFRE_DB_String; out obj: IFRE_DB_Object; const index_name: TFRE_DB_NameType; const val_is_null: boolean): boolean; var arr : TFRE_DB_GUIDArray; begin result := _GetIndexedObjUids(query_value,arr,index_name,true,val_is_null); if not result then exit; if Length(arr)<>1 then raise EFRE_DB_PL_Exception.create(edb_INTERNAL,'a unique index internal store contains [%d] elements!',[length(arr)]); result := FetchIntFromColl(arr[0],obj); if not result then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'logic failure, the index uid cannot be fetched as object'); end; function TFRE_DB_Persistance_Collection._GetIndexedObjUids(const query_value: TFRE_DB_String; out arr: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const check_is_unique: boolean; const is_null: boolean): boolean; var idx : NativeInt; index : TFRE_DB_MM_Index; key : Array [0..CFREA_maxKeyLen] of Byte; keylen : NativeInt; begin idx := IndexExists(index_name); if idx=-1 then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'the requested index named [%s] does not exist on collection [%s]',[index_name,FName]); index := FIndexStore[idx]; if check_is_unique and not index.IsUnique then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'the requested index named [%s] is not unique you must not use a point query',[index_name]); if not index.SupportsStringQuery then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'the requested index named [%s] does not support a string query',[index_name]); (index as TFRE_DB_TextIndex).SetBinaryComparableKey(query_value,@key[0],keylen,is_null); result := index.FetchIndexedValsTransformedKey(arr,key,keylen); end; function TFRE_DB_Persistance_Collection.FetchIntFromColl(const uid: TFRE_DB_GUID; out obj: IFRE_DB_Object): boolean; var objo : TFRE_DB_Object; begin result := FetchIntFromCollO(uid,objo); if result then obj := objo else obj := nil; end; function TFRE_DB_Persistance_Collection.FetchIntFromCollO(const uid: TFRE_DB_GUID; out obj: TFRE_DB_Object; const no_store_lock_check: boolean): boolean; var dummy : PtrUInt; begin result := FGuidObjStore.ExistsBinaryKey(@uid,SizeOf(TFRE_DB_GUID),dummy); if result then begin obj := FREDB_PtrUIntToObject(dummy) as TFRE_DB_Object; if not no_store_lock_check then obj.Assert_CheckStoreLocked; if Length(obj.__InternalGetCollectionList)<1 then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'logic failure, object has no assignment to internal collections'); end else obj := nil; end; function TFRE_DB_Persistance_Collection.GetPersLayer: IFRE_DB_PERSISTANCE_LAYER; begin result := FMasterLink.FLayer; end; procedure TFRE_DB_Persistance_Collection.GetAllIndexedUidsEncodedField(const qry_val: IFRE_DB_Object; const index_name: TFRE_DB_NameType; var uids: TFRE_DB_GUIDArray; const check_is_unique: boolean); var ix : NativeInt; idx : TFRE_DB_MM_Index; valf : IFRE_DB_Field; domf : IFRE_DB_Field; key : Array [0..CFREA_maxKeyLen] of Byte; keylen : NativeInt; ix_type : TFRE_DB_INDEX_TYPE; begin ix := IndexExists(index_name); if ix=-1 then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the index named[%s] does not exist',[index_name]); ix_type := FREDB_GetIndexTypeFromObjectEncoding(qry_val); valf := FREDB_GetIndexFldValFromObjectEncoding(qry_val); idx := FIndexStore[ix]; if not idx.SupportsIndexType(ix_type) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the index named[%s] does not support the requested index type[%s], but index type[%s]',[index_name,CFRE_DB_INDEX_TYPE[ix_type],idx.IndexTypeTxt]); if check_is_unique and //not idx.IndexIsFullyUnique then { TODO -> Reindex System Collections, fix index definitions } not idx.IsUnique then { TODO -> Reindex System Collections, fix index definitions } raise EFRE_DB_PL_Exception.Create(edb_ERROR,'the requested index named [%s] is not unique you must not use a point query',[index_name]); if idx.IsDomainIndex then begin domf := FREDB_GetDomainIDFldValFromObjectEncoding(qry_val); if assigned(valf) then idx.TransformToBinaryComparableDomain(domf.Implementor as TFRE_DB_FIELD,valf.Implementor as TFRE_DB_FIELD,@key,keylen) else idx.TransformToBinaryComparableDomain(domf.Implementor as TFRE_DB_FIELD,nil,@key,keylen); end else begin if assigned(valf) then idx.TransformToBinaryComparable(valf.Implementor as TFRE_DB_FIELD,@key,keylen) else idx.TransformToBinaryComparable(nil,@key,keylen); end; idx.FetchIndexedValsTransformedKey(uids,@key,keylen); end; procedure TFRE_DB_Persistance_Collection.GetAllIndexedUidsEncFieldRange(const min, max: IFRE_DB_Object; const index_name: TFRE_DB_NameType; var uids: TFRE_DB_GUIDArray; const ascending: boolean; const max_count, skipfirst: NativeInt; const min_val_is_a_prefix: boolean); var ix : NativeInt; idx : TFRE_DB_MM_Index; valf : IFRE_DB_Field; keymin : Array [0..CFREA_maxKeyLen] of Byte; keymax : Array [0..CFREA_maxKeyLen] of Byte; keyminp : PByte; keymaxp : PByte; keylenmin : NativeInt; keylenmax : NativeInt; ix_type : TFRE_DB_INDEX_TYPE; ix_t_mi : TFRE_DB_INDEX_TYPE; ix_t_ma : TFRE_DB_INDEX_TYPE; domf : IFRE_DB_Field; begin ix := IndexExists(index_name); if ix=-1 then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the index named[%s] does not exist',[index_name]); idx := FIndexStore[ix]; if min_val_is_a_prefix then begin E_FOS_Implement; end; ix_t_mi := FREDB_GetIndexTypeFromObjectEncoding(min); ix_t_ma := FREDB_GetIndexTypeFromObjectEncoding(max); if (ix_t_mi=fdbit_SpecialValue) and (ix_t_ma=fdbit_SpecialValue) then begin { all indexed values } if idx.IsDomainIndex then begin domf := FREDB_GetDomainIDFldValFromObjectEncoding(min); {domain id must be encoded in minimum field } idx.AppendAllIndexedUidsDomain(uids,ascending,max_count,skipfirst,domf.Implementor as TFRE_DB_FIELD); end else idx.AppendAllIndexedUids(uids,ascending,max_count,skipfirst); exit; end else if (ix_t_mi=fdbit_SpecialValue) then begin if not idx.SupportsIndexType(ix_t_ma) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the index named[%s] does not support the requested index type[%s], but index type[%s]',[index_name,CFRE_DB_INDEX_TYPE[ix_t_ma],idx.IndexTypeTxt]); if idx.IsDomainIndex then begin E_FOS_Implement; end else begin valf := FREDB_GetIndexFldValFromObjectEncoding(max); idx.TransformToBinaryComparable(valf.Implementor as TFRE_DB_FIELD,@keymax,keylenmax); keyminp := nil; { from minimum key range } keymaxp := @keymax[0]; end; end else if (ix_t_ma=fdbit_SpecialValue) then begin if not idx.SupportsIndexType(ix_t_mi) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the index named[%s] does not support the requested index type[%s], but index type[%s]',[index_name,CFRE_DB_INDEX_TYPE[ix_t_mi],idx.IndexTypeTxt]); if idx.IsDomainIndex then begin E_FOS_Implement; end else begin valf := FREDB_GetIndexFldValFromObjectEncoding(min); idx.TransformToBinaryComparable(valf.Implementor as TFRE_DB_FIELD,@keymin,keylenmin); keymaxp := nil; { to maximum key range } keyminp := @keymin[0]; end; end else begin if ix_t_ma<>ix_t_mi then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the requested index type[%s] for minvalue range scan is different than the maxvalue index type[%s]',[CFRE_DB_INDEX_TYPE[ix_t_mi],CFRE_DB_INDEX_TYPE[ix_t_ma]]); if not idx.SupportsIndexType(ix_t_ma) then raise EFRE_DB_PL_Exception.Create(edb_NOT_FOUND,'the index named[%s] does not support the requested index type[%s], but index type[%s]',[index_name,CFRE_DB_INDEX_TYPE[ix_t_ma],idx.IndexTypeTxt]); if idx.IsDomainIndex then begin E_FOS_Implement; end else begin valf := FREDB_GetIndexFldValFromObjectEncoding(min); idx.TransformToBinaryComparable(valf.Implementor as TFRE_DB_FIELD,@keymin,keylenmin); keyminp := @keymin[0]; valf := FREDB_GetIndexFldValFromObjectEncoding(max); idx.TransformToBinaryComparable(valf.Implementor as TFRE_DB_FIELD,@keymax,keylenmax); keymaxp := @keymax[0]; end; end; idx.ForAllIndexedValsTransformedKeys(uids,keyminp,keymaxp,keylenmin,keylenmax,ascending,max_count,skipfirst); end; function TFRE_DB_Persistance_Collection.GetIndexedValueCountRC(const qry_val: IFRE_DB_Object; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; var i : NativeInt; uids : TFRE_DB_GUIDArray; uti : TFRE_DB_USER_RIGHT_TOKEN; err : TFRE_DB_Errortype; obj : TFRE_DB_Object; begin G_GetUserToken(user_context,uti,true); FREDB_SetUserDomIDFldValForObjectEncoding(qry_val,uti); GetAllIndexedUidsEncodedField(qry_val,index_name,uids,false); if not assigned(uti) then result := Length(uids) else begin result := 0; for i := 0 to high(uids) do begin if not FetchIntFromCollO(uids[i],obj) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not fetch collection object while evaluating index value count'); err := uti.CheckStdRightsetInternalObj(obj,[sr_FETCH]); if err=edb_OK then inc(Result); end; end; end; function TFRE_DB_Persistance_Collection.GetIndexedUidsRC(const qry_val: IFRE_DB_Object; out uids_out: TFRE_DB_GUIDArray; const index_must_be_fullyunique: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; var i : NativeInt; uids : TFRE_DB_GUIDArray; uti : TFRE_DB_USER_RIGHT_TOKEN; err : TFRE_DB_Errortype; obj : TFRE_DB_Object; begin G_GetUserToken(user_context,uti,true); FREDB_SetUserDomIDFldValForObjectEncoding(qry_val,uti); GetAllIndexedUidsEncodedField(qry_val,index_name,uids,index_must_be_fullyunique); if not assigned(uti) then begin uids_out := uids; end else begin result := 0; SetLength(uids_out,length(uids)); for i := 0 to high(uids) do begin if not FetchIntFromCollO(uids[i],obj) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not fetch collection object while evaluating index value count'); err := uti.CheckStdRightsetInternalObj(obj,[sr_FETCH]); if err=edb_OK then begin uids_out[result] := uids[i]; inc(Result); end; end; SetLength(uids_out,result); end; result := Length(uids_out); end; function TFRE_DB_Persistance_Collection.GetIndexedObjsClonedRC(const qry_val: IFRE_DB_Object; out objs: IFRE_DB_ObjectArray; const index_must_be_fullyunique: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; var i : NativeInt; uids : TFRE_DB_GUIDArray; uti : TFRE_DB_USER_RIGHT_TOKEN; err : TFRE_DB_Errortype; obj : TFRE_DB_Object; begin G_GetUserToken(user_context,uti,true); FREDB_SetUserDomIDFldValForObjectEncoding(qry_val,uti); GetAllIndexedUidsEncodedField(qry_val,index_name,uids,index_must_be_fullyunique); result := 0; SetLength(objs,length(uids)); for i := 0 to high(uids) do begin if not FetchIntFromCollO(uids[i],obj) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not fetch collection object while evaluating index value count'); if assigned(uti) then err := uti.CheckStdRightsetInternalObj(obj,[sr_FETCH]) else err := edb_OK; if err=edb_OK then begin objs[result] := CloneOutObject(obj); inc(Result); end; end; SetLength(objs,result); end; function TFRE_DB_Persistance_Collection.GetIndexedValuecountRCRange(const min, max: IFRE_DB_Object; const ascending: boolean; const max_count, skipfirst: NativeInt; const min_val_is_a_prefix: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; var i : NativeInt; uids : TFRE_DB_GUIDArray; uti : TFRE_DB_USER_RIGHT_TOKEN; err : TFRE_DB_Errortype; obj : TFRE_DB_Object; begin G_GetUserToken(user_context,uti,true); FREDB_SetUserDomIDFldValForObjectEncoding(min,uti); GetAllIndexedUidsEncFieldRange(min,max,index_name,uids,ascending,max_count,skipfirst,min_val_is_a_prefix); if not assigned(uti) then result := Length(uids) else begin result := 0; for i := 0 to high(uids) do begin if not FetchIntFromCollO(uids[i],obj) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not fetch collection object while evaluating index value count'); err := uti.CheckStdRightsetInternalObj(obj,[sr_FETCH]); if err=edb_OK then inc(Result); end; end; end; function TFRE_DB_Persistance_Collection.GetIndexedUidsRCRange(const min, max: IFRE_DB_Object; const ascending: boolean; const max_count, skipfirst: NativeInt; out uids_out: TFRE_DB_GUIDArray; const min_val_is_a_prefix: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; var i : NativeInt; uids : TFRE_DB_GUIDArray; uti : TFRE_DB_USER_RIGHT_TOKEN; err : TFRE_DB_Errortype; obj : TFRE_DB_Object; begin G_GetUserToken(user_context,uti,true); FREDB_SetUserDomIDFldValForObjectEncoding(min,uti); GetAllIndexedUidsEncFieldRange(min,max,index_name,uids,ascending,max_count,skipfirst,min_val_is_a_prefix); if not assigned(uti) then begin uids_out := uids; end else begin result := 0; SetLength(uids_out,length(uids)); for i := 0 to high(uids) do begin if not FetchIntFromCollO(uids[i],obj) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not fetch collection object while evaluating index value count'); err := uti.CheckStdRightsetInternalObj(obj,[sr_FETCH]); if err=edb_OK then begin inc(Result); uids_out[result] := uids[i]; end; end; SetLength(uids_out,result); end; end; function TFRE_DB_Persistance_Collection.GetIndexedObjsClonedRCRange(const min, max: IFRE_DB_Object; const ascending: boolean; const max_count, skipfirst: NativeInt; out objs: IFRE_DB_ObjectArray; const min_val_is_a_prefix: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; var i : NativeInt; uids : TFRE_DB_GUIDArray; uti : TFRE_DB_USER_RIGHT_TOKEN; err : TFRE_DB_Errortype; obj : TFRE_DB_Object; begin G_GetUserToken(user_context,uti,true); FREDB_SetUserDomIDFldValForObjectEncoding(min,uti); GetAllIndexedUidsEncFieldRange(min,max,index_name,uids,ascending,max_count,skipfirst,min_val_is_a_prefix); result := 0; SetLength(objs,length(uids)); for i := 0 to high(uids) do begin if not FetchIntFromCollO(uids[i],obj) then raise EFRE_DB_PL_Exception.Create(edb_INTERNAL,'could not fetch collection object while evaluating index value count'); if assigned(uti) then err := uti.CheckStdRightsetInternalObj(obj,[sr_FETCH]) else err := edb_OK; if err=edb_OK then begin obj.Set_Store_Locked(false); try objs[result] := obj.CloneToNewObject; inc(Result); finally obj.Set_Store_Locked(true); end; end; end; SetLength(objs,result); end; function TFRE_DB_Persistance_Collection.GetFirstLastIdxCnt(const idx: Nativeint; out obj: IFRE_DB_Object; const user_context: PFRE_DB_GUID): NativeInt; var objs : IFRE_DB_ObjectArray; halt : boolean; procedure MyGet(const myobj:TFRE_DB_Object; var halt:boolean); begin obj := CloneOutObject(myobj); end; begin result := 0; obj := nil; case idx of -1 : { First} begin halt := true; ForAllInternalBreak(@MyGet,halt,false); end; -2 : { Last } begin halt := true; ForAllInternalBreak(@MyGet,halt,true); end; -3 : { Cnt} begin GetAllObjectsRCInt(objs,user_context); result := Length(objs); end; else begin if idx<0 then raise EFRE_DB_PL_Exception.Create(edb_ERROR,'you must use an positive index on getfirstlastidxcnt'); GetAllObjectsRCInt(objs,user_context); result := Length(objs); if idx > high(objs) then raise EFRE_DB_PL_Exception.Create(edb_INDEXOUTOFBOUNDS,'you must use an index in the range of [%d - %d]',[0,high(objs)]); obj := CloneOutObject(objs[idx].Implementor as TFRE_DB_Object); end; end; end; procedure TFRE_DB_Persistance_Collection.GetAllUIDsRC(var uids: TFRE_DB_GUIDArray; const user_context: PFRE_DB_GUID); var cnt : NativeInt; ut : TFRE_DB_USER_RIGHT_TOKEN; procedure GatherWithRights(const obj : TFRE_DB_Object); begin if ut.CheckStdRightSetUIDAndClass(obj.UID,obj.DomainID,obj.SchemeClass,[sr_FETCH])=edb_OK then begin uids[cnt] := obj.UID; inc(cnt); end; end; begin if not assigned(user_context) then GetAllUIDS(uids) else begin G_GetUserToken(user_context,ut,true); SetLength(uids,Count); cnt := 0; ForAllInternal(@GatherWithRights); SetLength(uids,cnt); end; end; procedure TFRE_DB_Persistance_Collection.GetAllObjectsRCInt(var objs: IFRE_DB_ObjectArray; const user_context: PFRE_DB_GUID); var cnt : NativeInt; ut : TFRE_DB_USER_RIGHT_TOKEN; procedure GatherWithRights(const obj : TFRE_DB_Object); begin if ut.CheckStdRightSetUIDAndClass(obj.UID,obj.DomainID,obj.SchemeClass,[sr_FETCH])=edb_OK then begin objs[cnt] := obj; inc(cnt); end; end; begin if not assigned(user_context) then GetAllObjectsInt(objs) else begin G_GetUserToken(user_context,ut,true); SetLength(objs,Count); cnt := 0; ForAllInternal(@GatherWithRights); SetLength(objs,cnt); end; end; procedure TFRE_DB_Persistance_Collection.GetAllObjectsRC(var objs: IFRE_DB_ObjectArray; const user_context: PFRE_DB_GUID); var iobjs : IFRE_DB_ObjectArray; begin GetAllObjectsRCInt(iobjs,user_context); objs := CloneOutArrayII(iobjs); end; function TFRE_DB_Persistance_Collection.UniqueName: PFRE_DB_NameType; begin UniqueName := @FUpperName; end; initialization end.
unit Globals; interface uses SysUtils, Forms; var Home: string; BinHome: string; ConfigHome: string; ProjectsHome: string; TemplatesHome: string; implementation uses Config; const cConfigFolder = 'config\'; cProjectsFolder = 'projects\'; cConfigFile = 'application.cfg'; cTemplatesFolder = 'templates\'; procedure InitGlobals; begin BinHome := ExtractFilePath(Application.ExeName); Home := ExpandFileName(BinHome + '..\'); ProjectsHome := Home + cProjectsFolder; TemplatesHome := BinHome + cTemplatesFolder; ConfigHome := Home + cConfigFolder; Configuration.LoadFromFile(ConfigHome + cConfigFile); end; initialization InitGlobals; end.
unit uFormasPagamento; interface uses SysUtils, Classes; type TTipoPagamento = class; TMeioPagamento = class public IDMeioPag: Integer; TipoPagamento : TTipoPagamento; Imagem: Integer; CodFiscal, DescFiscal, MeioPag : String; RequireCustomer : Boolean; ValidateNonpayer : Boolean; constructor Create(ATipoPagamento : TTipoPagamento); destructor Destroy;override; end; TTipoPagamento = class private function GetMeiosPagamento(Index: Integer): TMeioPagamento; procedure Remove(Index: Integer); procedure SetMeiosPagamento(Index: Integer; const Value: TMeioPagamento); function GetCount: Integer; public Tipo: Integer; Descricao: String; FItems: TList; property Count: Integer read GetCount; property MeiosPagamento[Index: Integer]: TMeioPagamento read GetMeiosPagamento write SetMeiosPagamento; constructor Create; destructor Destroy;override; procedure Clear; function Add(AIDMeioPag, AImagem: Integer; ACodFiscal, ADescFiscal, AMeioPag : String; ARequireCustomer: Boolean; AValidateNonpayer: Boolean): TMeioPagamento; end; TFormasPagamento = class(TComponent) private FItems: TList; function GetTiposPagamento(Index: Integer): TTipoPagamento; procedure SetTiposPagamento(Index: Integer; const Value: TTipoPagamento); procedure Remove(Index: Integer); function GetCount: Integer; public property TiposPagamento[Index: Integer]: TTipoPagamento read GetTiposPagamento write SetTiposPagamento; property Count: Integer read GetCount; constructor Create(AOwner: TComponent);override; destructor Destroy;override; procedure Clear; function Add(ATipo: Integer; ADescricao: String): TTipoPagamento; end; procedure Register; implementation procedure Register; begin RegisterComponents('NewPower', [TFormasPagamento]); end; { TTipoPagamento } constructor TTipoPagamento.Create; begin inherited Create; FItems := TList.Create; end; destructor TTipoPagamento.Destroy; begin inherited Destroy; end; function TTipoPagamento.GetMeiosPagamento(Index: Integer): TMeioPagamento; begin result := FItems[Index]; end; procedure TTipoPagamento.Remove(Index: Integer); var MeioPagamento: TMeioPagamento; begin MeioPagamento := FItems[Index]; FreeAndNil(MeioPagamento); FItems.Delete(Index); end; procedure TTipoPagamento.Clear; begin while FItems.Count > 0 do Remove(0); end; procedure TTipoPagamento.SetMeiosPagamento(Index: Integer; const Value: TMeioPagamento); begin FItems[Index] := Value; end; function TTipoPagamento.GetCount: Integer; begin Result := FItems.Count; end; function TTipoPagamento.Add(AIDMeioPag, AImagem: Integer; ACodFiscal, ADescFiscal, AMeioPag: String; ARequireCustomer: Boolean; AValidateNonpayer: Boolean): TMeioPagamento; var MeioPagamento : TMeioPagamento; begin MeioPagamento := TMeioPagamento.Create(Self); with MeioPagamento do begin IDMeioPag := AIDMeioPag; Imagem := AImagem; CodFiscal := ACodFiscal; DescFiscal := ADescFiscal; MeioPag := AMeioPag; RequireCustomer := ARequireCustomer; ValidateNonpayer:= AValidateNonpayer; end; FItems.Add(MeioPagamento); Result := MeioPagamento; end; { TFormasPagamento } constructor TFormasPagamento.Create(AOwner: TComponent); begin inherited Create(AOwner); FItems := TList.Create; end; procedure TFormasPagamento.Remove(Index: Integer); var TipoPagamento: TTipoPagamento; begin TipoPagamento := FItems[Index]; FreeAndNil(TipoPagamento); FItems.Delete(Index); end; destructor TFormasPagamento.Destroy; begin Clear; inherited Destroy; end; function TFormasPagamento.GetTiposPagamento( Index: Integer): TTipoPagamento; begin Result := FItems[Index]; end; procedure TFormasPagamento.SetTiposPagamento(Index: Integer; const Value: TTipoPagamento); begin FItems[Index] := Value; end; procedure TFormasPagamento.Clear; begin while FItems.Count > 0 do Remove(0); end; function TFormasPagamento.Add(ATipo: Integer; ADescricao: String): TTipoPagamento; var TipoPagamento : TTipoPagamento; begin TipoPagamento := TTipoPagamento.Create; with TipoPagamento do begin Tipo := ATipo; Descricao := ADescricao; end; FItems.Add(TipoPagamento); Result := TipoPagamento; end; function TFormasPagamento.GetCount: Integer; begin Result := FItems.Count; end; { TMeioPagamento } constructor TMeioPagamento.Create(ATipoPagamento: TTipoPagamento); begin inherited Create; TipoPagamento := ATipoPagamento; end; destructor TMeioPagamento.Destroy; begin inherited Destroy; end; end.
unit PmPacket; //链路层帧协议封装 interface uses SysUtils,StrUtils; type TPmControlCode = class private FValue: Byte; procedure SetValue(const Value: Byte); function GetGongnengma: Byte; function GetIsQidongzhen: Boolean; function GetIsShangxingzhen: Boolean; function GetIsShangxingYaoqiufangwen: Boolean; function GetXiaxingZhenjishuwei: Boolean; function GetXiaxingZhenjishuYouxiao: Boolean; procedure SetGongnengma(const Value: Byte); procedure SetIsQidongzhen(const Value: Boolean); procedure SetIsShangxingzhen(const Value: Boolean); procedure SetShangxingYaoqiufangwen(const Value: Boolean); procedure SetXiaxingZhenjishuwei(const Value: Boolean); procedure SetXiaxingZhenjishuYouxiao(const Value: Boolean); public property Value: Byte read FValue write SetValue; //下面的都是从value来的 property IsShangxingzhen: Boolean read GetIsShangxingzhen write SetIsShangxingzhen; //方向 property IsQidongzhen: Boolean read GetIsQidongzhen write SetIsQidongzhen; //启动帧 property XiaxingZhenjishuwei: Boolean read GetXiaxingZhenjishuwei write SetXiaxingZhenjishuwei; //bit property XiaxingZhenjishuYouxiao: Boolean read GetXiaxingZhenjishuYouxiao write SetXiaxingZhenjishuYouxiao; property IsShangxingYaoqiufangwen: Boolean read GetIsShangxingYaoqiufangwen write SetShangxingYaoqiufangwen; property Gongnengma: Byte read GetGongnengma write SetGongnengma; function CStr: AnsiString; end; TPmAddress = class private FXingzhengquhao: AnsiString; Fzhongduandizhi: AnsiString; FZudizhiBiaozhi: Boolean; FZhuzhandizhi: byte; procedure SetXingzhengquhao(const Value: AnsiString); procedure Setzhongduandizhi(const Value: AnsiString); procedure SetZhuzhandizhi(const Value: byte); procedure SetZudizhiBiaozhi(const Value: Boolean); function GetValue: AnsiString; procedure SetValue(const Value: AnsiString); function GetZhongduanDizhiL: AnsiString; procedure SetZhongduanDizhiL(const Value: AnsiString); public procedure AfterConstruction; override; property Xingzhengquhao: AnsiString read FXingzhengquhao write SetXingzhengquhao; property zhongduandizhi: AnsiString read Fzhongduandizhi write Setzhongduandizhi; property Zhuzhandizhi: byte read FZhuzhandizhi write SetZhuzhandizhi; property ZudizhiBiaozhi: Boolean read FZudizhiBiaozhi write SetZudizhiBiaozhi; property Value: AnsiString read GetValue write SetValue; property ZhongduanDizhiL: AnsiString read GetZhongduanDizhiL write SetZhongduanDizhiL; //地区码+终端地址(CBIN) function CStr: AnsiString; end; TPmLinkLayerPacket = class private FControlCode: TPmControlCode; FAddress: TPmAddress; FContainLen: Word; FData: AnsiString; procedure SetData(const Value: AnsiString); function GetAsBinStr: AnsiString; procedure SetAsBinStr(const Value: AnsiString); class function CalcSum(p: PAnsiChar; const len: word): AnsiChar; public procedure AfterConstruction; override; destructor Destroy; override; property ContainLen: Word read FContainLen; //链路用户数据长度 property ControlCode: TPmControlCode read FControlcode; //链路控制字 property Address: TPmAddress read FAddress; //链路地址域 property Data: AnsiString read FData write SetData; //链路用户数据 class function GetPacket(var DataStr: AnsiString): TPmLinkLayerPacket; virtual; property AsBinStr: AnsiString read GetAsBinStr write SetAsBinStr; end; implementation uses PmHelper, uBCDHelper; const VERSION_CODE = $02; { TPmLinkLayerPacket } procedure TPmLinkLayerPacket.AfterConstruction; begin inherited; FControlCode := TPmControlCode.Create; FAddress := TPmAddress.Create; end; class function TPmLinkLayerPacket.CalcSum(p: PAnsiChar; const len: word): AnsiChar; var b: Byte; i: Word; begin b := 0; for i := 0 to len-1 do b := b+Ord((p+i)^); Result := Chr(b); end; destructor TPmLinkLayerPacket.Destroy; begin FControlCode.Free; FAddress.Free; end; function TPmLinkLayerPacket.GetAsBinStr: AnsiString; var Temp: AnsiString; begin temp := chr(FControlCode.Value)+FAddress.Value+FData; Result := #$68+TBcdHelper.Word2BinStr(((FContainLen+6) shl 2)+VERSION_CODE)+ TBcdHelper.Word2BinStr(((FContainLen+6) shl 2)+VERSION_CODE)+#$68+ temp+CalcSum(@(temp[1]),Length(temp)); Result := Result+#$16; end; class function TPmLinkLayerPacket.GetPacket(var DataStr: AnsiString): TPmLinkLayerPacket; var pb,de: PAnsiChar; len: Word; i: integer; function PickHead(var pb: PAnsiChar; const de: PAnsiChar): Boolean; begin while (pb+11<=de) and ((pb^<>#$68) or ((pb+5)^<>#$68)) do pb := pb+1; Result := (pb+11<=de) and (pb^=#$68) and ((pb+5)^=#$68); end; begin Result := nil; if Length(DataStr)<12 then exit; pb := @(DataStr[1]); de := pb+Length(DataStr); while PickHead(pb,de) do begin i := pb-@(DataStr[1])+1; len := TBcdHelper.BinStr2Word(Copy(DataStr,i+1,2)); if (len<>(TBcdHelper.BinStr2Word(Copy(DataStr,i+3,2)))) or ((len and $03)<>VERSION_CODE) then begin pb := pb+1; continue; end; len := len shr 2; if i+len+7>Length(DataStr) then begin pb := pb+1; continue; end; if (pb+len+7)^<>#$16 then begin pb := pb+1; continue; end; if CalcSum(pb+6,len)<>(pb+len+6)^ then begin pb := pb+1; continue; end; Result := TPmLinkLayerPacket.Create; Result.FContainLen := len-6; Result.FControlCode.FValue := Ord((pb+6)^); Result.FAddress.Value := Copy(DataStr,i+7,5); Result.FData := Copy(DataStr,i+12,len-6); DataStr := Copy(DataStr,i+8+len,Length(DataStr)-i-7-len); break; end; end; procedure TPmLinkLayerPacket.SetAsBinStr(const Value: AnsiString); var pb: PAnsiChar; len: Word; i: integer; begin if Length(Value)<12 then exit; pb := @(Value[1]); i := pb-@(Value[1])+1; len := TBcdHelper.BinStr2Word(Copy(Value,i+1,2)); if (len<>(TBcdHelper.BinStr2Word(Copy(Value,i+3,2)))) or ((len and $03)<>VERSION_CODE) then begin raise Exception.Create('报文结构非法: 长度域'); end; len := len shr 2; if i+len+7>Length(Value) then raise Exception.Create('报文结构非法: 报文太短'); if (pb+len+7)^<>#$16 then raise Exception.Create('报文结构非法: 结束标志'); if CalcSum(pb+6,len)<>(pb+len+6)^ then begin raise Exception.Create('报文结构非法: 校验位'); end; self.FContainLen := len-6; self.FControlCode.FValue := Ord((pb+6)^); self.FAddress.Value := Copy(Value,i+7,5); self.FData := Copy(Value,i+12,len-6); end; procedure TPmLinkLayerPacket.SetData(const Value: AnsiString); begin FData := Value; self.FContainLen := Length(Value); end; { TPmControlCode } function TPmControlCode.GetGongnengma: Byte; begin Result := self.FValue and $0F; end; function TPmControlCode.GetIsQidongzhen: Boolean; begin Result := (self.FValue and $40)=$40; end; function TPmControlCode.GetIsShangxingzhen: Boolean; begin Result := (self.FValue and $80)=$80; end; function TPmControlCode.GetIsShangxingYaoqiufangwen: Boolean; begin Result := (self.FValue and $20)=$20; end; function TPmControlCode.GetXiaxingZhenjishuwei: Boolean; begin Result := (self.FValue and $20)=$20; end; function TPmControlCode.GetXiaxingZhenjishuYouxiao: Boolean; begin Result := (self.FValue and $10)=$10; end; procedure TPmControlCode.SetGongnengma(const Value: Byte); begin self.FValue := (self.FValue and $F0) or (Value and $0F); end; procedure TPmControlCode.SetIsQidongzhen(const Value: Boolean); begin if Value then self.FValue := self.FValue or $40 else self.FValue := self.FValue and $BF; end; procedure TPmControlCode.SetIsShangxingzhen(const Value: Boolean); begin if Value then self.FValue := self.FValue or $80 else self.FValue := self.FValue and $7F; end; procedure TPmControlCode.SetValue(const Value: Byte); begin FValue := Value; end; procedure TPmControlCode.SetShangxingYaoqiufangwen(const Value: Boolean); begin if Value then self.FValue := self.FValue or $20 else self.FValue := self.FValue and $DF; end; procedure TPmControlCode.SetXiaxingZhenjishuwei(const Value: Boolean); begin if Value then self.FValue := self.FValue or $20 else self.FValue := self.FValue and $DF; end; procedure TPmControlCode.SetXiaxingZhenjishuYouxiao(const Value: Boolean); begin if Value then self.FValue := self.FValue or $10 else self.FValue := self.FValue and $EF; end; function TPmControlCode.CStr: AnsiString; begin if self.IsShangxingzhen then Result := '上行帧; ' else Result := '下行帧; '; if self.IsQidongzhen then Result := Result+'启动帧; ' else Result := Result+'非启动帧; '; if self.IsShangxingzhen then begin if self.IsShangxingYaoqiufangwen then Result := Result+'要求访问; ' else Result := Result+'不要求访问; '; end else begin if self.XiaxingZhenjishuYouxiao then begin if self.XiaxingZhenjishuwei then Result := Result+'帧计数有效; 帧计数位=1' else Result := Result+'帧计数有效; 帧计数位=0'; end else Result := Result+'帧计数无效; '; end; Result := Result+'功能码='+IntToStr(self.Gongnengma); end; { TPmAddress } procedure TPmAddress.AfterConstruction; begin inherited; self.FXingzhengquhao := '0000'; self.Fzhongduandizhi := '0001'; self.FZhuzhandizhi := 1; self.FZudizhiBiaozhi := false; end; function TPmAddress.CStr: AnsiString; begin Result := '终端地址='+self.ZhongduanDizhiL+'; 主站地址='+IntToStr(self.Zhuzhandizhi); if self.ZudizhiBiaozhi then Result := Result+'; 组播' else Result := Result+'; 单播'; end; function TPmAddress.GetValue: AnsiString; begin if self.FZudizhiBiaozhi then Result := ReverseString(TBcdHelper.CStr2BinStr(FXingzhengquhao))+ ReverseString(TBcdHelper.CStr2BinStr(Fzhongduandizhi))+ chr((Zhuzhandizhi shl 1)+1) else Result := ReverseString(TBcdHelper.CStr2BinStr(FXingzhengquhao))+ ReverseString(TBcdHelper.CStr2BinStr(Fzhongduandizhi))+ chr((Zhuzhandizhi shl 1)); end; function TPmAddress.GetZhongduanDizhiL: AnsiString; begin Result := FXingzhengquhao+Fzhongduandizhi; end; procedure TPmAddress.SetValue(const Value: AnsiString); var t: Byte; begin if Length(Value)=5 then begin self.FXingzhengquhao := TBcdHelper.BinStr2CStr(ReverseString(Copy(Value,1,2)),''); self.Fzhongduandizhi := TBcdHelper.BinStr2CStr(ReverseString(Copy(Value,3,2)),''); t := Ord(Value[5]); self.FZhuzhandizhi := t shr 1; self.FZudizhiBiaozhi := (t and 1)=1; end; end; procedure TPmAddress.SetXingzhengquhao(const Value: AnsiString); begin if Length(Value)=4 then FXingzhengquhao := Value else raise Exception.Create('行政区划码必须是4位'); end; procedure TPmAddress.Setzhongduandizhi(const Value: AnsiString); begin if Length(Value)=4 then Fzhongduandizhi := Value else raise Exception.Create('终端地址必须是4位'); end; procedure TPmAddress.SetZhongduanDizhiL(const Value: AnsiString); begin if Length(Value)=8 then begin FXingzhengquhao := Copy(Value,1,4); Fzhongduandizhi := Copy(Value,5,4); end else raise Exception.Create('终端全地址必须是8位'); end; procedure TPmAddress.SetZhuzhandizhi(const Value: byte); begin if Value<128 then FZhuzhandizhi := Value else raise Exception.Create('主站地址不能大于127'); end; procedure TPmAddress.SetZudizhiBiaozhi(const Value: Boolean); begin FZudizhiBiaozhi := Value; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Adds a dynamic texture image, which allows for easy updating of texture data. } unit VXS.DynamicTexture; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, Winapi.OpenGL, Winapi.OpenGLext, VXS.Context, VXS.Texture, VXS.TextureFormat, VXS.Graphics, VXS.CrossPlatform; type // TVXDynamicTextureImage // { Allows for fast updating of the texture at runtime. } TVXDynamicTextureImage = class(TVXBlankImage) private FUpdating: integer; FTexSize: integer; FBuffer: pointer; FPBO: TVXBufferObjectHandle; FData: pointer; FDirtyRect: TVXRect; FUseBGR: boolean; FUsePBO: boolean; procedure SetDirtyRectangle(const Value: TVXRect); procedure SetUsePBO(const Value: boolean); protected function GetTexSize: integer; function GetBitsPerPixel: integer; function GetDataFormat: integer; function GetTextureFormat: integer; procedure FreePBO; procedure FreeBuffer; property BitsPerPixel: integer read GetBitsPerPixel; property DataFormat: integer read GetDataFormat; property TextureFormat: integer read GetTextureFormat; public constructor Create(AOwner: TPersistent); override; class function FriendlyName : String; override; class function FriendlyDescription : String; override; procedure NotifyChange(Sender: TObject); override; { Must be called before using the Data pointer. Rendering context must be active! } procedure BeginUpdate; { Must be called after data is changed. This will upload the new data. } procedure EndUpdate; { Pointer to buffer data. Will be nil outside a BeginUpdate / EndUpdate block. } property Data: pointer read FData; { Marks the dirty rectangle inside the texture. BeginUpdate sets it to ((0, 0), (Width, Height)), ie the entire texture. Override it if you're only changing a small piece of the texture. Note that the Data pointer is relative to the DirtyRectangle, NOT the entire texture. } property DirtyRectangle: TVXRect read FDirtyRect write SetDirtyRectangle; { Indicates that the data is stored as BGR(A) instead of RGB(A). The default is to use BGR(A). } property UseBGR: boolean read FUseBGR write FUseBGR; { Enables or disables use of a PBO. Default is true. } property UsePBO: boolean read FUsePBO write SetUsePBO; end; implementation uses VXS.VectorGeometry; { TVXDynamicTextureImage } procedure TVXDynamicTextureImage.BeginUpdate; var LTarget: TVXTextureTarget; begin Assert(FUpdating >= 0, 'Unbalanced begin/end update'); FUpdating:= FUpdating + 1; if FUpdating > 1 then exit; // initialization if not (assigned(FPBO) or assigned(FBuffer)) then begin // cache so we know if it's changed FTexSize:= GetTexSize; if FUsePBO and TVXUnpackPBOHandle.IsSupported then begin FPBO:= TVXUnpackPBOHandle.CreateAndAllocate; // initialize buffer FPBO.BindBufferData(nil, FTexSize, GL_STREAM_DRAW_ARB); // unbind so we don't upload the data from it, which is unnecessary FPBO.UnBind; end else begin // fall back to regular memory buffer if PBO's aren't supported FBuffer:= AllocMem(FTexSize); end; // Force creation of texture // This is a bit of a hack, should be a better way... LTarget := TVXTexture(OwnerTexture).TextureHandle.Target; CurrentVXContext.VXStates.TextureBinding[0, LTarget] := TVXTexture(OwnerTexture).Handle; case LTarget of ttNoShape: ; ttTexture1D: ; ttTexture2D: glTexImage2D(GL_TEXTURE_2D, 0, TVXTexture(OwnerTexture).OpenVXTextureFormat, Width, Height, 0, TextureFormat, GL_UNSIGNED_BYTE, nil); ttTexture3D: ; ttTexture1DArray: ; ttTexture2DArray: ; ttTextureRect: ; ttTextureBuffer: ; ttTextureCube: ; ttTexture2DMultisample: ; ttTexture2DMultisampleArray: ; ttTextureCubeArray: ; end; end; CheckOpenGLError; if assigned(FPBO) then begin FPBO.Bind; FData:= FPBO.MapBuffer(GL_WRITE_ONLY_ARB); end else begin FData:= FBuffer; end; CheckOpenGLError; FDirtyRect:= GLRect(0, 0, Width, Height); end; constructor TVXDynamicTextureImage.Create(AOwner: TPersistent); begin inherited Create(AOwner); FUseBGR:= true; FUsePBO:= true; end; procedure TVXDynamicTextureImage.EndUpdate; var d: pointer; LTarget: TVXTextureTarget; begin Assert(FUpdating > 0, 'Unbalanced begin/end update'); FUpdating:= FUpdating - 1; if FUpdating > 0 then exit; if assigned(FPBO) then begin FPBO.UnmapBuffer; // pointer will act as an offset when using PBO d:= nil; end else begin d:= FBuffer; end; LTarget := TVXTexture(OwnerTexture).TextureHandle.Target; CurrentVXContext.VXStates.TextureBinding[0, LTarget] := TVXTexture(OwnerTexture).Handle; case LTarget of ttNoShape: ; ttTexture1D: ; ttTexture2D: begin glTexSubImage2D(GL_TEXTURE_2D, 0, FDirtyRect.Left, FDirtyRect.Top, FDirtyRect.Right-FDirtyRect.Left, FDirtyRect.Bottom-FDirtyRect.Top, TextureFormat, DataFormat, d); end; ttTexture3D: ; ttTexture1DArray: ; ttTexture2DArray: ; ttTextureRect: ; ttTextureBuffer: ; ttTextureCube: ; ttTexture2DMultisample: ; ttTexture2DMultisampleArray: ; ttTextureCubeArray: ; end; if assigned(FPBO) then FPBO.UnBind; FData:= nil; CheckOpenGLError; end; procedure TVXDynamicTextureImage.FreeBuffer; begin if assigned(FBuffer) then begin FreeMem(FBuffer); FBuffer:= nil; end; end; procedure TVXDynamicTextureImage.FreePBO; begin if assigned(FPBO) then begin FPBO.Free; FPBO:= nil; end; end; // FriendlyName // class function TVXDynamicTextureImage.FriendlyName : String; begin Result:='Dynamic Texture'; end; // FriendlyDescription // class function TVXDynamicTextureImage.FriendlyDescription : String; begin Result:='Dynamic Texture - optimised for changes at runtime'; end; function TVXDynamicTextureImage.GetBitsPerPixel: integer; begin Result := 8 * GetTextureElementSize( TVXTexture(OwnerTexture).TextureFormatEx ); end; function TVXDynamicTextureImage.GetDataFormat: integer; var data, color: GLEnum; begin FindCompatibleDataFormat(TVXTexture(OwnerTexture).TextureFormatEx, color, data); Result := data; end; function TVXDynamicTextureImage.GetTexSize: integer; begin result:= Width * Height * BitsPerPixel div 8; end; function TVXDynamicTextureImage.GetTextureFormat: integer; var data, color: GLEnum; begin FindCompatibleDataFormat(TVXTexture(OwnerTexture).TextureFormatEx, color, data); if FUseBGR then case color of GL_RGB: color := GL_BGR; GL_RGBA: color := GL_BGRA; end; Result := color; end; procedure TVXDynamicTextureImage.NotifyChange(Sender: TObject); begin if FTexSize <> GetTexSize then begin FreePBO; FreeBuffer; end; inherited; end; procedure TVXDynamicTextureImage.SetDirtyRectangle(const Value: TVXRect); begin FDirtyRect.Left:= MaxInteger(Value.Left, 0); FDirtyRect.Top:= MaxInteger(Value.Top, 0); FDirtyRect.Right:= MinInteger(Value.Right, Width); FDirtyRect.Bottom:= MinInteger(Value.Bottom, Height); end; procedure TVXDynamicTextureImage.SetUsePBO(const Value: boolean); begin Assert(FUpdating = 0, 'Cannot change PBO settings while updating'); if FUsePBO <> Value then begin FUsePBO := Value; if not FUsePBO then FreePBO else FreeBuffer; end; end; initialization RegisterGLTextureImageClass(TVXDynamicTextureImage); end.
unit uDBConnection; interface {$WARN SYMBOL_PLATFORM OFF} uses Winapi.Windows, Winapi.ShellApi, System.SysUtils, System.Classes, System.SyncObjs, System.Win.ComObj, System.Variants, Data.DB, Data.Win.ADODB, Dmitry.CRC32, Dmitry.Utils.System, Dmitry.Utils.Files, uConstants, uRuntime, uMemory, uLogger, uTime, uShellIntegration, uTranslate, uAppUtils, uSettings, uResources, uDBBaseTypes, uSplashThread, uSiteUtils, uShellUtils; const DB_TABLE_UNKNOWN = 0; DB_TABLE_GROUPS = 1; DB_TABLE_IMAGES = 2; DB_TABLE_PERSONS = 3; DB_TABLE_PERSON_MAPPING = 4; DB_TABLE_SETTINGS = 5; type TDBIsolationLevel = (dbilReadWrite, dbilRead, dbilExclusive, dbilBackgroundWrite); type TADOConnectionEx = class(TADOConnection) private FFileName: string; public property FileName: string read FFileName write FFileName; end; type TDBConnection = class(TObject) private FFileName: string; FFreeOnClose: Boolean; FThreadID: DWORD; FIsolationLevel: TDBIsolationLevel; FIsBusy: Boolean; FADOConnection: TADOConnectionEx; FRefreshDate: TDateTime; public constructor Create(FileName: string; IsolationLevel: TDBIsolationLevel); destructor Destroy; override; procedure Reuse; procedure Detach; property FreeOnClose: Boolean read FFreeOnClose write FFreeOnClose; property ThreadID: DWORD read FThreadID; property FileName: string read FFileName; property IsolationLevel: TDBIsolationLevel read FIsolationLevel; property IsBusy: Boolean read FIsBusy; property Connection: TADOConnectionEx read FADOConnection; end; TConnectionManager = class(TObject) private FConnections: TList; FSync: TCriticalSection; function GetCount: Integer; function GetValueByIndex(Index: Integer): TDBConnection; public constructor Create; destructor Destroy; override; procedure RemoveAt(Index: Integer); function Add(FileName: string; IsolationLevel: TDBIsolationLevel): TDBConnection; property Count: Integer read GetCount; property Items[Index: Integer]: TDBConnection read GetValueByIndex; default; end; var ADOConnections: TConnectionManager = nil; DBLoadInitialized: Boolean = False; FSync: TCriticalSection = nil; const ErrorCodeProviderNotFound = $800A0E7A; Jet40ProviderName = 'Microsoft.Jet.OLEDB.4.0'; ACE12ProviderName = 'Microsoft.ACE.OLEDB.12.0'; ACE14ProviderName = 'Microsoft.ACE.OLEDB.14.0'; Jet40ConnectionString: string = 'Provider=Microsoft.Jet.OLEDB.4.0;Password="";User ID=Admin;'+ 'Data Source=%s;Mode=%MODE%;Extended Properties="";'+ 'Jet OLEDB:System database="";Jet OLEDB:Registry Path="";'+ 'Jet OLEDB:Database Password="";Jet OLEDB:Engine Type=5;'+ 'Jet OLEDB:Database Locking Mode=1;'+ 'Jet OLEDB:Global Partial Bulk Ops=2;'+ 'Jet OLEDB:Global Bulk Transactions=2;'+ 'Jet OLEDB:New Database Password="";'+ 'Jet OLEDB:Create System Database=False;'+ 'Jet OLEDB:Encrypt Database=False;'+ 'Jet OLEDB:Don''t Copy Locale on Compact=False;'+ 'Jet OLEDB:Compact Without Replica Repair=False;'+ 'Jet OLEDB:SFP=False'; // Read Only String Jet40ReadOnlyConnectionString: string = 'Provider=Microsoft.Jet.OLEDB.4.0;Password="";'+ 'User ID=Admin;Data Source=%s;'+ 'Mode=Share Deny Write;Extended Properties="";'+ 'Jet OLEDB:System database="";Jet OLEDB:Registry Path="";'+ 'Jet OLEDB:Database Password="";Jet OLEDB:Engine Type=0;'+ 'Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=1;'+ 'Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="";'+ 'Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;'+ 'Jet OLEDB:Don''t Copy Locale on Compact=False;Jet OLEDB:'+ 'Compact Without Replica Repair=False;Jet OLEDB:SFP=False'; ACE12ConnectionString: string = 'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=%s;Persist Security Info=False'; ACE14ConnectionString: string = 'Provider=Microsoft.ACE.OLEDB.14.0;Data Source=%s;Persist Security Info=False'; function GetTable(CollectionFileName: string; TableID: Integer = DB_TABLE_UNKNOWN): TDataSet; function GetQuery(CollectionFileName: string; CreateNewConnection: Boolean = False; IsolationLevel: TDBIsolationLevel = dbilReadWrite): TDataSet; function TryOpenCDS(DS: TDataSet): Boolean; function OpenDS(DS: TDataSet): Boolean; procedure ForwardOnlyQuery(DS: TDataSet); procedure ReadOnlyQuery(DS: TDataSet); procedure SetSQL(SQL: TDataSet; SQLText: string); procedure ExecSQL(SQL: TDataSet); procedure GetTableNames(DSWithConnection: TDataSet; TableNames: TStrings); procedure FreeDS(var DS: TDataSet); procedure LoadParamFromStream(Query: TDataSet; index: Integer; Stream: TStream; FT: TFieldType); procedure SetDateParam(Query: TDataSet; name: string; Date: TDateTime); procedure SetBoolParam(Query: TDataSet; Index: Integer; Bool: Boolean); procedure SetStrParam(Query: TDataSet; Index: Integer; Value: string); procedure SetIntParam(Query: TDataSet; Index: Integer; Value: Integer); function GetBlobStream(F: TField; Mode: TBlobStreamMode) : TStream; procedure AssignParam(Query: TDataSet; Index: Integer; Value: TPersistent); procedure CreateMSAccessDatabase(FileName: string); function TryRemoveConnection(FileName: string; Delete: Boolean = False): Boolean; procedure PackTable(FileName: string; Progress: TSimpleCallBackProgressRef; BackupFileName: string = ''); function GetPathCRC(FileFullPath: string; IsFile: Boolean): Integer; function NormalizeDBString(S: string): string; function NormalizeDBStringLike(S: string): string; function DBReadOnly: Boolean; procedure NotifyOleException(E: Exception); implementation var FIsBrowserWithNotifyUserAboutErorrsInProvidersOpened: Boolean = False; FIsMessageBoxForUserAboutErorrsInProvidersOpened: Boolean = False; procedure NotifyOleException(E: Exception); var ErrorCode: HRESULT; begin ErrorCode := 0; if E is EOleException then ErrorCode := EOleException(E).ErrorCode; ShellExecute(0, 'open', PWideChar(ResolveLanguageString(ActionHelpPageURL) + 'ole-exception&code=' + IntToHex(ErrorCode, 8) + '&msg=' + E.Message + '&' + GenerateProgramSiteParameters), nil, nil, SW_NORMAL); end; procedure NotifyUserAboutErorrsInProviders; begin if not FIsBrowserWithNotifyUserAboutErorrsInProvidersOpened then begin FIsBrowserWithNotifyUserAboutErorrsInProvidersOpened := True; ShellExecute(0, 'open', PWideChar(ResolveLanguageString(ActionHelpPageURL) + 'provider-not-found'), nil, nil, SW_NORMAL); end; end; procedure RaiseProviderNotFoundException; var ProvidersList: string; begin //close splash screen if it's being shown CloseSplashWindow; //reset provider AppSettings.WriteString('Settings', 'DatabaseProvider', ''); //create error message if not FIsMessageBoxForUserAboutErorrsInProvidersOpened then begin FIsMessageBoxForUserAboutErorrsInProvidersOpened := True; ProvidersList := Jet40ProviderName + ', ' + ACE12ProviderName + ', ' + ACE14ProviderName; MessageBoxDB(0, FormatEx(TA('Fatal error: at least one provider should be registered: {0}', 'Errors'), [ProvidersList]), TA('Error'), TD_BUTTON_OK, TD_ICON_ERROR); end; //try to send user to page with detailed information NotifyUserAboutErorrsInProviders; end; function GetConnectionString(ConnectionString: string; Dbname: string; IsolationMode: TDBIsolationLevel): string; var Isolation: string; begin Isolation := 'Share Deny None'; if IsolationMode = dbilRead then Isolation := 'Read'; if IsolationMode = dbilExclusive then Isolation := 'Share Exclusive'; Result := StringReplace(ConnectionString, '%MODE%', Isolation, [rfReplaceAll, rfIgnoreCase]); Result := Format(Result, [Dbname]); end; function GetProviderConnectionString(ProviderName: string): string; begin if ProviderName = '' then RaiseProviderNotFoundException; if (ProviderName = ACE12ProviderName) or GetParamStrDBBool('/ace12') then Exit(ACE12ConnectionString); if (ProviderName = ACE14ProviderName) or GetParamStrDBBool('/ace14') then Exit(ACE14ConnectionString); if FolderView and DBReadOnly then Exit(Jet40ReadOnlyConnectionString); Result := Jet40ConnectionString; end; function IsProviderValidAndCanBeUsed(ProviderName: string): Boolean; var DBFileName, ConnectionString: string; Connection: TADOConnectionEx; List: TStrings; begin Result := True; DBFileName := GetTempFileName; CreateMSAccessDatabase(DBFileName); try //test database by reading it Connection := TADOConnectionEx.Create(nil); try Connection.FileName := DBFileName; ConnectionString := GetProviderConnectionString(ProviderName); ConnectionString := GetConnectionString(ConnectionString, DBFileName, dbilReadWrite); Connection.ConnectionString := ConnectionString; Connection.LoginPrompt := False; Connection.IsolationLevel := ilReadCommitted; List := TStringList.Create; try try Connection.GetTableNames(List, True); except on e: Exception do begin EventLog(e); Exit(False); end; end; finally F(List); end; finally F(Connection); end; finally DeleteFile(DBFileName); end; end; function DataBaseProvider: string; const ProviderList: array[0..2] of string = (Jet40ProviderName, ACE12ProviderName, ACE14ProviderName); var S: TStrings; I, J: Integer; begin Result := AppSettings.ReadString('Settings', 'DatabaseProvider'); if Result <> '' then Exit(Result); S := TStringList.Create; try try GetProviderNames(S); except on E: Exception do begin MessageBoxDB(0, E.Message, TA('Error'), TD_BUTTON_OK, TD_ICON_ERROR); NotifyOleException(E); end; end; for I := Low(ProviderList) to High(ProviderList) do begin for J := 0 to S.Count - 1 do begin if AnsiLowerCase(S[J]) = AnsiLowerCase(ProviderList[I]) then if IsProviderValidAndCanBeUsed(ProviderList[I]) then begin AppSettings.WriteString('Settings', 'DatabaseProvider', ProviderList[I]); Exit(ProviderList[I]); end; end; end; finally F(S); end; end; function ConnectionString: string; var Provider: string; begin Provider := DataBaseProvider; Result := GetProviderConnectionString(Provider); end; function GetConnection(FileName: string; ForseNewConnection: Boolean = False; IsolationLevel: TDBIsolationLevel = dbilReadWrite): TADOConnection; var I: Integer; DBConnection: TDBConnection; begin FileName := AnsiLowerCase(FileName); if not ForseNewConnection and (ADOConnections <> nil) then for I := 0 to ADOConnections.Count - 1 do begin DBConnection := ADOConnections[I]; if (DBConnection.FileName = FileName) and (DBConnection.IsolationLevel = IsolationLevel) and not DBConnection.IsBusy and not DBConnection.FreeOnClose then begin DBConnection.Reuse; Result := DBConnection.Connection; Exit; end; end; DBConnection := ADOConnections.Add(FileName, IsolationLevel); Result := DBConnection.Connection; end; function TryRemoveConnection(FileName: string; Delete: Boolean = False): Boolean; var I: Integer; begin Result := True; FSync.Enter; try if ADOConnections = nil then Exit; FileName := AnsiLowerCase(FileName); for I := ADOConnections.Count - 1 downto 0 do begin if ADOConnections[I].FileName = FileName then begin Result := False; if (not ADOConnections[I].IsBusy) and Delete then begin ADOConnections[I].Free; ADOConnections.RemoveAt(I); end; end; end; finally FSync.Leave; end; end; procedure RemoveADORef(ADOConnection: TADOConnectionEx); const MaxConnectionPoolRead = 5; MaxConnectionPoolWrite = 5; MaxConnectionPoolBackgroundWrite = 5; var I: Integer; Connection: TDBConnection; MaxConnectionPoolByLevel: Integer; FileName: string; function GetConnectionsCount(IsolationLevel: TDBIsolationLevel): Integer; var I: Integer; begin Result := 0; for I := 0 to ADOConnections.Count - 1 do if (not ADOConnections[I].IsBusy) and (ADOConnections[I].IsolationLevel = IsolationLevel) then Inc(Result); end; begin if ADOConnections = nil then Exit; FileName := ADOConnection.FileName; MaxConnectionPoolByLevel := 0; for I := 0 to ADOConnections.Count - 1 do begin Connection := ADOConnections[I]; if Connection.Connection = ADOConnection then begin if Connection.IsolationLevel = dbilRead then MaxConnectionPoolByLevel := MaxConnectionPoolRead; if Connection.IsolationLevel = dbilReadWrite then MaxConnectionPoolByLevel := MaxConnectionPoolWrite; if Connection.IsolationLevel = dbilBackgroundWrite then MaxConnectionPoolByLevel := MaxConnectionPoolBackgroundWrite; Connection.Detach; Break; end; end; //close old connections for I := ADOConnections.Count - 1 downto 0 do begin Connection := ADOConnections[I]; if (not Connection.IsBusy) and (Connection.FreeOnClose) then begin Connection.Free; ADOConnections.RemoveAt(I); Break; end; end; for I := ADOConnections.Count - 1 downto 0 do begin Connection := ADOConnections[I]; if (Connection.FileName = FileName) and not Connection.IsBusy and ((GetConnectionsCount(Connection.IsolationLevel) > MaxConnectionPoolByLevel) or (Connection.IsolationLevel = dbilExclusive)) then begin Connection.Free; ADOConnections.RemoveAt(I); end; end; end; procedure FlushJROCache(ConnectionObject: Variant); var fJetEngine: Variant; begin try // First time through we need to create the OLE object if VarIsEmpty(fJetEngine) then fJetEngine := CreateOleObject ('JRO.JetEngine') ; if VarIsEmpty(fJetEngine) then Exit; // "Ensure that my read cache is consistent with the database on disk" fJetEngine.RefreshCache(ConnectionObject); except on e: Exception do EventLog(e); end; end; procedure CloseReadOnlyConnections(ADOConnection: TADOConnectionEx); var I: Integer; Connection: TDBConnection; begin if ADOConnections = nil then Exit; for I := ADOConnections.Count - 1 downto 0 do begin Connection := ADOConnections[I]; if (Connection.FileName = ADOConnection.FileName) and (Connection.IsolationLevel = dbilRead) then Connection.FreeOnClose := True; end; end; procedure ForwardOnlyQuery(DS: TDataSet); begin TADOQuery(DS).CursorType := ctOpenForwardOnly; TADOQuery(DS).CursorLocation := clUseServer; ReadOnlyQuery(DS); end; procedure ReadOnlyQuery(DS: TDataSet); begin TADOQuery(DS).LockType := ltReadOnly; end; function TryOpenCDS(DS: TDataSet): Boolean; var I: Integer; begin for I := 1 to 20 do begin Result := True; try OpenDS(DS); except on e: Exception do begin Result := False; if E is EOleException then begin if (EOleException(E).ErrorCode and $FFFFFFFF) = ErrorCodeProviderNotFound then begin RaiseProviderNotFoundException; Exit; end; end; end; end; if Result then Break; Sleep(DelayExecuteSQLOperation); end; end; function OpenDS(DS: TDataSet): Boolean; begin try //refresh cache because of multi-connection work //TODO: check time for this line if TCustomADODataSet(DS).Connection <> nil then if TCustomADODataSet(DS).Connection.ConnectionObject <> nil then FlushJROCache(TCustomADODataSet(DS).Connection.ConnectionObject); DS.Open; Result := True; except on e: EOleException do begin if (E.ErrorCode and $FFFFFFFF) = ErrorCodeProviderNotFound then RaiseProviderNotFoundException; raise; end; end; end; function NormalizeDBString(S: string): string; begin Result := AnsiQuotedStr(S, '"') end; function NormalizeDBStringLike(S: string): string; var I: Integer; begin for I := 1 to Length(S) do if (S[I] = '[') or (S[I] = ']') or (S[I] = '\') then S[I] := '_'; Result := S; end; function GetBlobStream(F: TField; Mode: TBlobStreamMode): TStream; begin Result := nil; if (F is TBlobField) and (F.DataSet is TADOQuery) then Result := TADOBlobStream.Create(TBlobField(F), Mode); if (F is TBlobField) and (F.DataSet is TADODataSet) then Result := TADOBlobStream.Create(TBlobField(F), Mode); end; procedure LoadParamFromStream(Query: TDataSet; index: Integer; Stream: TStream; FT: TFieldType); begin Stream.Seek(0, SoFromBeginning); if (Query is TADOQuery) then (Query as TADOQuery).Parameters[index].LoadFromStream(Stream, FT); end; procedure AssignParam(Query : TDataSet; index : integer; Value : TPersistent); begin if (Query is TADOQuery) then (Query as TADOQuery).Parameters[index].Assign(Value); end; procedure SetBoolParam(Query: TDataSet; index: Integer; Bool: Boolean); begin if (Query is TADOQuery) then (Query as TADOQuery).Parameters[index].Value := Bool; end; procedure SetDateParam(Query: TDataSet; Name: string; Date: TDateTime); begin if (Query is TADOQuery) then (Query as TADOQuery).Parameters.FindParam(name).Value := Date; end; procedure SetIntParam(Query: TDataSet; Index: Integer; Value: integer); begin if (Query is TADOQuery) then (Query as TADOQuery).Parameters[Index].Value := Value; end; procedure SetStrParam(Query: TDataSet; Index: Integer; Value : string); begin if (Query is TADOQuery) then (Query as TADOQuery).Parameters[Index].Value := Value; end; procedure ExecSQL(SQL: TDataSet); begin if (SQL is TADOQuery) then begin TCustomADODataSet(SQL).Connection.BeginTrans; try (SQL as TADOQuery).ExecSQL; except TCustomADODataSet(SQL).Connection.RollbackTrans; raise; end; TCustomADODataSet(SQL).Connection.CommitTrans; FlushJROCache(TCustomADODataSet(SQL).Connection.ConnectionObject); CloseReadOnlyConnections((SQL as TADOQuery).Connection as TADOConnectionEx); end; end; procedure GetTableNames(DSWithConnection: TDataSet; TableNames: TStrings); begin if (DSWithConnection is TADOQuery) then begin (DSWithConnection as TADOQuery).Connection.GetTableNames(TableNames, True); end; end; procedure SetSQL(SQL: TDataSet; SQLText : String); var I: Integer; begin for I := 1 to 20 do begin try if (SQL is TADOQuery) then begin SQLText := StringReplace(SQLText, '$DB$', 'ImageTable', [RfReplaceAll, RfIgnoreCase]); (SQL as TADOQuery).SQL.Text := SQLText; (SQL as TADOQuery).Parameters.ParseSQL((SQL as TADOQuery).SQL.Text, True); end; Break; except on E: Exception do begin EventLog(':SetSQL() throw exception: ' + E.message); Sleep(50); end; end; end; end; function GetQuery(CollectionFileName: string; CreateNewConnection: Boolean = False; IsolationLevel: TDBIsolationLevel = dbilReadWrite): TDataSet; begin FSync.Enter; try Result := TADOQuery.Create(nil); (Result as TADOQuery).Connection := GetConnection(CollectionFileName, CreateNewConnection, IsolationLevel); if DBReadOnly then ReadOnlyQuery(Result); finally FSync.Leave; end; end; function GetTable(CollectionFileName: string; TableID: Integer = DB_TABLE_UNKNOWN): TDataSet; begin FSync.Enter; try Result := TADODataSet.Create(nil); (Result as TADODataSet).Connection := GetConnection(CollectionFileName); (Result as TADODataSet).CommandType := CmdTable; if TableID = DB_TABLE_GROUPS then (Result as TADODataSet).CommandText := 'Groups'; if TableID = DB_TABLE_IMAGES then (Result as TADODataSet).CommandText := 'ImageTable'; if TableID = DB_TABLE_SETTINGS then (Result as TADODataSet).CommandText := 'DBSettings'; if TableID = DB_TABLE_PERSONS then (Result as TADODataSet).CommandText := 'Persons'; if TableID = DB_TABLE_PERSON_MAPPING then (Result as TADODataSet).CommandText := 'PersonMapping'; finally FSync.Leave; end; end; procedure CreateMSAccessDatabase(FileName: string); var MS: TMemoryStream; FS: TFileStream; begin MS := GetRCDATAResourceStream('SampleDB'); try FS := TFileStream.Create(FileName, fmCreate, fmExclusive); try FS.CopyFrom(MS, MS.Size); finally F(FS); end; finally F(MS); end; end; procedure FreeDS(var DS: TDataSet); var Connection: TADOConnection; begin if DS = nil then Exit; FSync.Enter; try if DS is TADOQuery then begin Connection := (DS as TADOQuery).Connection; F(DS); RemoveADORef(Connection as TADOConnectionEx); Exit; end; if DS is TADODataSet then begin Connection := (DS as TADODataSet).Connection; F(DS); RemoveADORef(Connection as TADOConnectionEx); Exit; end; finally FSync.Leave; end; end; function CompactDatabase_JRO(DatabaseName:string; DestDatabaseName: string; Password: string; Progress: TSimpleCallBackProgressRef): Boolean; const Provider = 'Provider=Microsoft.Jet.OLEDB.4.0;'; var TempName: array[0..MAX_PATH] of Char; // имя временного файла TempPath: string; // путь до него Name: string; Src,Dest : WideString; V: Variant; WatchThread: TThread; PackInProgress: Boolean; TotalSize: Int64; begin Result := False; try TotalSize := GetFileSize(DatabaseName); Src := Provider + 'Data Source=' + DatabaseName; if DestDatabaseName <> '' then Name := DestDatabaseName else begin TempPath := ExtractFilePath(DatabaseName); if TempPath = '' then TempPath := GetCurrentDir; Winapi.Windows.GetTempFileName(PWideChar(TempPath), 'mdb' , 0, TempName); Name := StrPas(TempName); end; DeleteFile(Name); Dest := Provider + 'Data Source=' + Name; if Password<>'' then begin Src := Src + ';Jet OLEDB:Database Password=' + Password; Dest := Dest + ';Jet OLEDB:Database Password=' + Password; end; PackInProgress := True; WatchThread := TThread.CreateAnonymousThread( procedure var FS, CurrentSize: Int64; begin CurrentSize := 0; while PackInProgress do begin Sleep(250); if Assigned(Progress) then begin FS := GetFileSizeByName(Name); if FS > CurrentSize then CurrentSize := FS; if CurrentSize > TotalSize then CurrentSize := TotalSize; Progress(nil, TotalSize, CurrentSize); end; end; Sleep(100); ExitCode := 0; end ); WatchThread.FreeOnTerminate := False; WatchThread.Start; PackInProgress := True; try //TODO: Dao.DBEngine.120 V := CreateOleObject('jro.JetEngine'); try V.CompactDatabase(Src, Dest);// сжимаем Result := True; finally V := 0; end; finally PackInProgress := False; WatchThread.WaitFor; F(WatchThread); end; if DestDatabaseName = '' then begin DeleteFile(DatabaseName); //то удаляем не упакованную базу RenameFile(Name, DatabaseName); // и переименовываем упакованную базу end; except on e: Exception do EventLog(':CompactDatabase_JRO() throw exception: ' + e.Message); end; end; procedure PackTable(FileName: string; Progress: TSimpleCallBackProgressRef; BackupFileName: string = ''); var TempFileName: string; begin TryRemoveConnection(FileName, True); if BackupFileName = '' then CompactDatabase_JRO(FileName, '', '', Progress) else begin TempFileName := GetTempFileName; if CompactDatabase_JRO(FileName, TempFileName, '', Progress) then begin RenameFile(FileName, BackupFileName); RenameFile(TempFileName, FileName); end; end; end; { TADOConnections } function TConnectionManager.Add(FileName: string; IsolationLevel: TDBIsolationLevel): TDBConnection; begin Result := TDBConnection.Create(FileName, IsolationLevel); FConnections.Add(Result); end; constructor TConnectionManager.Create; begin FSync := TCriticalSection.Create; FConnections := TList.Create; end; destructor TConnectionManager.Destroy; begin FreeList(FConnections); F(FSync); inherited; end; function TConnectionManager.GetCount: Integer; begin Result := FConnections.Count; end; function TConnectionManager.GetValueByIndex(Index: Integer): TDBConnection; begin Result := FConnections[Index]; end; procedure TConnectionManager.RemoveAt(Index: Integer); begin if (Index > -1) and (Index < FConnections.Count) then FConnections.Delete(Index); end; function GetPathCRC(FileFullPath: string; IsFile: Boolean): Integer; var Folder, ApplicationPath : string; CRC: Cardinal; begin if IsFile then // c:\Folder\1.EXE => c:\Folder\ Folder := ExtractFileDir(FileFullPath) else Folder := FileFullPath; // c:\Folder\ => c:\folder Folder := AnsiLowerCase(ExcludeTrailingBackslash(Folder)); if FolderView then begin //C:\photodb.exe => c: ApplicationPath := ExcludeTrailingBackslash(AnsiLowerCase(ExtractFileDir(ParamStr(0)))); //c:\folder => \folder if (Length(ApplicationPath) <= Length(Folder)) and (Pos(ApplicationPath, Folder) = 1) then Delete(Folder, 1, Length(ApplicationPath)); // \folder => folder if (Folder <> '') and (Folder[1] = '\') then Delete(Folder, 1, 1); end; CalcStringCRC32(AnsiLowerCase(Folder), CRC); Result := Integer(CRC); end; function DBReadOnly: Boolean; var Attr: Integer; ProgramDir: string; begin Result := False; if not FolderView then Exit; ProgramDir := IncludeTrailingBackSlash(ExtractFileDir(ParamStr(0))); if FileExists(ProgramDir + 'FolderDB.photodb') then begin Attr := GetFileAttributes(PChar(ProgramDir + 'FolderDB.photodb')); if Attr and FILE_ATTRIBUTE_READONLY <> 0 then begin Result := True; Exit; end; end; if FileExists(ProgramDir + GetFileNameWithoutExt(ParamStr(0)) + '.photodb') then begin Attr := GetFileAttributes(PChar(ProgramDir + GetFileNameWithoutExt(ParamStr(0)) + '.photodb')); if Attr and FILE_ATTRIBUTE_READONLY <> 0 then Result := True; end; end; { TDBConnection } constructor TDBConnection.Create(FileName: string; IsolationLevel: TDBIsolationLevel); begin FFileName := AnsiLowerCase(FileName); FIsolationLevel := IsolationLevel; FThreadID := GetCurrentThreadId; FreeOnClose := False; FIsBusy := True; FRefreshDate := Now; FADOConnection := TADOConnectionEx.Create(nil); FADOConnection.FileName := FileName; FADOConnection.ConnectionString := GetConnectionString(ConnectionString, FileName, IsolationLevel); FADOConnection.LoginPrompt := False; if IsolationLevel = dbilRead then FADOConnection.IsolationLevel := ilReadCommitted; if IsolationLevel = dbilBackgroundWrite then FADOConnection.IsolationLevel := ilReadCommitted; end; destructor TDBConnection.Destroy; begin F(FADOConnection); inherited; end; procedure TDBConnection.Detach; begin FIsBusy := False; end; procedure TDBConnection.Reuse; begin if FreeOnClose then raise Exception.Create(FormatEx('Connection should be destroyed! ThreadId = {0}', [ThreadID])); if IsBusy then raise Exception.Create(FormatEx('Connection is already in use in thread {0}!', [ThreadID])); FIsBusy := True; FThreadID := GetCurrentThreadId; end; initialization FSync := TCriticalSection.Create; ADOConnections := TConnectionManager.Create; finalization F(ADOConnections); F(FSync); end.
unit EigenValues; interface uses math; { Copyright © 1999 CERN - European Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about the suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty. } // This file is derived from cern.colt.matrix.linalg; // It translates java codes from CERN, but I've reduced it for symmetric matrixes // only. type TEigenValueDecomposition = class private FDimension: cardinal; FSize: cardinal; FEigenValues: PSingle; FImagEigenValues: PSingle; FEigenVectors: PSingle; // Misc function hypot(_a, _b: single): single; procedure tred2(); procedure tql2(); public // Constructors and Destructors constructor Create(var _Matrix: PSingle; _Dimension: integer); destructor Destroy; override; // Gets function GetEigenvalues(_i: integer): single; function GetImagEigenvalues(_i: integer): single; function GetEigenVectors(_i, _j: integer): single; // Sets procedure SetEigenvalues(_i: integer; _value: single); procedure SetImagEigenvalues(_i: integer; _value: single); procedure SetEigenVectors(_i,_j: integer; _value: single); end; implementation // Warning: here we are taking into account that our _Matrix is symmetric. // If your matrix is not symmetric, it will fail hard! constructor TEigenValueDecomposition.Create(var _Matrix: PSingle; _Dimension: integer); var i : integer; begin // Get Dimension FDimension := _Dimension; // Copy Matrix FSize := FDimension * FDimension; GetMem(FEigenVectors,FSize); for i := 0 to FSize - 1 do begin PSingle(Cardinal(FEigenVectors)+i)^ := PSingle(Cardinal(_Matrix)+i)^; end; // Set Eigenvalues vectors. GetMem(FEigenValues,FDimension); GetMem(FImagEigenValues,FDimension); for i := 0 to FDimension - 1 do begin PSingle(Cardinal(FEigenValues)+i)^ := 0; PSingle(Cardinal(FEigenValues)+i)^ := 0; end; // Tridiagonalize. tred2(); // Diagonalize. tql2(); end; // Say bye bye! destructor TEigenValueDecomposition.Destroy; begin FreeMem(FEigenVectors); FreeMem(FEigenValues); FreeMem(FImagEigenValues); inherited Destroy; end; // Gets // These functions are relying too much at the programmer. They may have access // violation if misused. function TEigenValueDecomposition.GetEigenvalues(_i: integer): single; begin Result := PSingle(Cardinal(FEigenvalues)+_i)^ end; function TEigenValueDecomposition.GetImagEigenvalues(_i: integer): single; begin Result := PSingle(Cardinal(FImagEigenvalues)+_i)^ end; function TEigenValueDecomposition.GetEigenVectors(_i, _j: integer): single; begin Result := PSingle(Cardinal(FEigenVectors)+_i+(FDimension * _j))^; end; // Sets // These functions are relying too much at the programmer. They may have access // violation if misused. procedure TEigenValueDecomposition.SetEigenvalues(_i: integer; _value: single); begin PSingle(Cardinal(FEigenvalues)+_i)^ := _value; end; procedure TEigenValueDecomposition.SetImagEigenvalues(_i: integer; _value: single); begin PSingle(Cardinal(FImagEigenvalues)+_i)^ := _value; end; procedure TEigenValueDecomposition.SetEigenVectors(_i,_j: integer; _value: single); begin PSingle(Cardinal(FEigenVectors)+_i+(FDimension * _j))^ := _value; end; // Misc function TEigenValueDecomposition.hypot(_a, _b: single): single; begin if (abs(_a) > abs(_b)) then begin Result := _b/_a; Result := abs(_a) * sqrt(1+Result*Result); end else if (_b <> 0) then begin Result := _a/_b; Result := abs(_b) * sqrt(1+Result*Result); end else begin Result := 0; end; end; // Symmetric tridiagonal QL algorithm. procedure TEigenValueDecomposition.tql2 (); var i,l,m,j,k : cardinal; f,tst1,eps,g,p,r,dl1,h,c,c2,c3,el1,s,s2: single; //iter: cardinal; begin // This is derived from the Algol procedures tql2, by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. i := 1; while i < FDimension do begin SetImagEigenvalues(i-1,GetImagEigenvalues(i)); inc(i); end; SetImagEigenvalues(FDimension-1,0); f := 0; tst1 := 0.0; eps := math.Power(2,-52.0); l := 0; m := 0; while l < FDimension do begin // Find small subdiagonal element tst1 := Math.max(tst1,abs(GetEigenvalues(l)) + abs(GetImagEigenvalues(l))); m := l; while (m < FDimension) do begin if (abs(GetImagEigenvalues(m)) <= (eps*tst1)) then break; end; inc(m); inc(l); end; // If m == l, d[l] is an eigenvalue, // otherwise, iterate. if (m > l) then begin // iter := 0; repeat // iter := iter + 1; // (Could check iteration count here.) // Compute implicit shift g := GetEigenvalues(l); p := (GetEigenvalues(l+1) - g) / (2.0 * GetImagEigenvalues(l)); r := hypot(p,1); if (p < 0) then begin r := -r; end; SetEigenvalues(l,GetImagEigenvalues(l) / (p + r)); SetEigenvalues(l+1,GetImagEigenvalues(l) * (p + r)); dl1 := GetEigenvalues(l+1); h := g - GetEigenvalues(l); i := l+2; while i < FDimension do begin SetEigenvalues(i,GetEigenvalues(i) - h); inc(i); end; f := f + h; // Implicit QL transformation. p := GetEigenvalues(m); c := 1; c2 := c; c3 := c; el1 := GetImagEigenvalues(l+1); s := 0; s2 := 0; i := m-1; while i >= l do begin c3 := c2; c2 := c; s2 := s; g := c * GetImagEigenvalues(i); h := c * p; r := hypot(p,GetImagEigenvalues(i)); SetImagEigenvalues(i+1, s * r); s := GetImagEigenvalues(i) / r; c := p / r; p := c * GetEigenvalues(i) - s * g; SetEigenvalues(i+1, h + s * (c * g + s * GetEigenvalues(i))); // Accumulate transformation. k := 0; while (k < FDimension) do begin h := GetEigenVectors(k,i+1); SetEigenVectors(k, i+1, s * GetEigenVectors(k,i) + c * h); SetEigenVectors(k, i, c * GetEigenVectors(k,i) - s * h); inc(k); end; inc(i); end; p := -s * s2 * c3 * el1 * GetImagEigenvalues(l) / dl1; SetImagEigenvalues(l, s * p); SetEigenvalues(l, c * p); // Check for convergence. until (abs(GetImagEigenvalues(l)) <= (eps*tst1)); SetEigenvalues(l, GetEigenvalues(l) + f); SetImagEigenvalues(l, 0); end; // Sort eigenvalues and corresponding vectors. i := 0; while i < (FDimension-1) do begin k := i; p := GetEigenvalues(i); j := i+1; while j < FDimension do begin if (GetEigenvalues(j) < p) then begin k := j; p := GetEigenvalues(j); end; inc(j); end; inc(i); if (k <> i) then begin SetEigenvalues(k, GetEigenvalues(i)); SetEigenvalues(i, p); j := 0; while j < FDimension do begin p := GetEigenVectors(j,i); SetEigenVectors(j, i, GetEigenVectors(j,k)); SetEigenVectors(j, k, p); inc(j); end; end; end; end; //Symmetric Householder reduction to tridiagonal form. procedure TEigenValueDecomposition.tred2 (); var i,j,k: cardinal; scale,f,g,h,hh: single; begin // This is derived from the Algol procedures tred2 by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. j := 0; while j < FDimension do begin SetEigenValues(j, GetEigenVectors(FDimension-1, j)); inc(j); end; // Householder reduction to tridiagonal form. i := FDimension-1; while i > 0 do begin // Scale to avoid under/overflow. scale := 0; h := 0; k := 0; while k < i do begin scale := scale + abs(GetEigenValues(k)); inc(k); end; if (scale = 0) then begin SetImagEigenvalues(i, GetEigenValues(i-1)); j := 0; while j < i do begin SetEigenvalues(j, GetEigenVectors(i-1,j)); SetEigenVectors(i, j, 0); SetEigenVectors(j, i, 0); inc(j); end; end else begin // Generate Householder vector. k := 0; while k < i do begin SetEigenValues(k, GetEigenValues(k) / scale); h := h + (GetEigenValues(k) * GetEigenValues(k)); inc(k); end; f := GetEigenValues(i-1); g := sqrt(h); if (f > 0) then begin g := -g; end; SetImagEigenvalues(i, scale * g); h := h - f * g; SetEigenValues(i-1, f - g); j := 0; while j < i do begin SetImagEigenValues(j, 0); inc(j); end; // Apply similarity transformation to remaining columns. j := 0; while j < i do begin f := GetEigenValues(j); SetEigenVectors(j, i, f); g := GetImagEigenValues(j) + GetEigenVectors(j,j) * f; k := j+1; while k <= (i-1) do begin g := g + GetEigenVectors(k,j) * GetEigenValues(k); SetImagEigenvalues(k, GetImagEigenvalues(k) + GetEigenVectors(k,j) * f); inc(k); end; SetImagEigenvalues(j, g); inc(j); end; f := 0; j := 0; while j < i do begin SetImagEigenvalues(j, GetImagEigenvalues(j) / h); f := f + (GetImagEigenvalues(j) * GetEigenvalues(j)); inc(j); end; hh := f / (h + h); j := 0; while j < i do begin SetImagEigenvalues(j, GetImagEigenvalues(j) - hh * GetEigenvalues(j)); inc(j); end; j := 0; while j < i do begin f := GetEigenvalues(j); g := GetImagEigenvalues(j); k := j; while k <= (i-1) do begin SetEigenVectors(k, j, GetEigenVectors(k,j) - (f * GetImagEigenValues(k) + g * GetEigenvalues(k))); inc(k); end; SetEigenvalues(j, GetEigenVectors(i-1,j)); SetEigenVectors(i, j, 0); inc(j); end; end; SetEigenvalues(i, h); dec(i); end; // Accumulate transformations. i := 0; while i < (FDimension-1) do begin SetEigenVectors(FDimension-1, i, GetEigenVectors(i,i)); SetEigenVectors(i, i, 1); h := GetEigenvalues(i+1); if (h <> 0) then begin k := 0; while k <= i do begin SetEigenvalues(k, GetEigenVectors(k,i+1) / h); inc(k); end; j := 0; while j <= i do begin g := 0; k := 0; while k <= i do begin g := g + (GetEigenVectors(k,i+1) * GetEigenVectors(k,j)); inc(k); end; k := 0; while k <= i do begin SetEigenVectors(k, j, GetEigenVectors(k,j) - (g * GetEigenvalues(k))); inc(k); end; inc(j); end; end; k := 0; while k <= i do begin SetEigenVectors(k, i+1, 0); inc(k); end; inc(i); end; j := 0; while j < FDimension do begin SetEigenvalues(j,GetEigenVectors(FDimension-1,j)); SetEigenVectors(FDimension-1, j, 0); inc(j); end; SetEigenVectors(FDimension-1, FDimension-1, 1); SetImagEigenvalues(0, 0); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFE_DECLARACAO_IMPORTACAO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfeDeclaracaoImportacaoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, NfeImportacaoDetalheVO; type TNfeDeclaracaoImportacaoVO = class(TVO) private FID: Integer; FID_NFE_DETALHE: Integer; FNUMERO_DOCUMENTO: String; FDATA_REGISTRO: TDateTime; FLOCAL_DESEMBARACO: String; FUF_DESEMBARACO: String; FDATA_DESEMBARACO: TDateTime; FCODIGO_EXPORTADOR: String; FVIA_TRANSPORTE: Integer; FVALOR_AFRMM: Extended; FFORMA_INTERMEDIACAO: Integer; FCNPJ: String; FUF_TERCEIRO: String; FListaNfeImportacaoDetalheVO: TListaNfeImportacaoDetalheVO; //1:100 published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property IdNfeDetalhe: Integer read FID_NFE_DETALHE write FID_NFE_DETALHE; property NumeroDocumento: String read FNUMERO_DOCUMENTO write FNUMERO_DOCUMENTO; property DataRegistro: TDateTime read FDATA_REGISTRO write FDATA_REGISTRO; property LocalDesembaraco: String read FLOCAL_DESEMBARACO write FLOCAL_DESEMBARACO; property UfDesembaraco: String read FUF_DESEMBARACO write FUF_DESEMBARACO; property DataDesembaraco: TDateTime read FDATA_DESEMBARACO write FDATA_DESEMBARACO; property CodigoExportador: String read FCODIGO_EXPORTADOR write FCODIGO_EXPORTADOR; property ViaTransporte: Integer read FVIA_TRANSPORTE write FVIA_TRANSPORTE; property ValorAfrmm: Extended read FVALOR_AFRMM write FVALOR_AFRMM; property FormaIntermediacao: Integer read FFORMA_INTERMEDIACAO write FFORMA_INTERMEDIACAO; property Cnpj: String read FCNPJ write FCNPJ; property UfTerceiro: String read FUF_TERCEIRO write FUF_TERCEIRO; property ListaNfeImportacaoDetalheVO: TListaNfeImportacaoDetalheVO read FListaNfeImportacaoDetalheVO write FListaNfeImportacaoDetalheVO; end; TListaNfeDeclaracaoImportacaoVO = specialize TFPGObjectList<TNfeDeclaracaoImportacaoVO>; implementation constructor TNfeDeclaracaoImportacaoVO.Create; begin inherited; FListaNfeImportacaoDetalheVO := TListaNfeImportacaoDetalheVO.Create; end; destructor TNfeDeclaracaoImportacaoVO.Destroy; begin FreeAndNil(FListaNfeImportacaoDetalheVO); inherited; end; initialization Classes.RegisterClass(TNfeDeclaracaoImportacaoVO); finalization Classes.UnRegisterClass(TNfeDeclaracaoImportacaoVO); end.
Unit UnitProcess; interface uses Windows, ShellAPi, TLHelp32, psAPI; function ProcessList: widestring; function PidToPath(Pid: integer): widestring; function KillProc(Pid: integer): boolean; Function ResumeProcess(ProcessID: DWORD): Boolean; function SuspendProcess(PID:DWORD): Boolean; implementation uses UnitConstantes; function OpenThread(dwDesiredAccess: DWORD; bInheritHandle: BOOL; dwThreadId: DWORD): THandle; stdcall; external kernel32 Name 'OpenThread'; type P_TokenUser = ^User; User = record Userinfo: TSidAndAttributes; end; tUser = User; type tagPROCESSENTRY32 = record dwSize: DWORD; cntUsage: DWORD; th32ProcessID: DWORD; // this process th32DefaultHeapID: DWORD; th32ModuleID: DWORD; // associated exe cntThreads: DWORD; th32ParentProcessID: DWORD; // this process's parent process pcPriClassBase: Longint; // Base priority of process's threads dwFlags: DWORD; szExeFile: array[0..MAX_PATH - 1] of WChar;// Path end; TProcessEntry32 = tagPROCESSENTRY32; const THREAD_TERMINATE = ($0001); THREAD_SUSPEND_RESUME = ($0002); THREAD_GET_CONTEXT = ($0008); THREAD_SET_CONTEXT = ($0010); THREAD_SET_INFORMATION = ($0020); THREAD_QUERY_INFORMATION = ($0040); THREAD_SET_THREAD_TOKEN = ($0080); THREAD_IMPERSONATE = ($0100); THREAD_DIRECT_IMPERSONATION = ($0200); THREAD_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $3FF); function IntToStr(i: Int64): WideString; begin Str(i, Result); end; function StrToInt(S: WideString): Int64; var E: integer; begin Val(S, Result, E); end; function GetCreationTime(f: _filetime): WideString; var SysTime: TSystemTime; Month, Day, Hour, Minute, Second: WideString; LocalHour: integer; SystemHour: integer; Diferenca: integer; Real: integer; begin GetLocalTime(SysTime); LocalHour := systime.wHour; GetSystemTime(SysTime); SystemHour := systime.wHour; FileTimeToSystemTime(f, SysTime); Month := inttostr(systime.wMonth); Day := inttostr(systime.wDay); Hour := inttostr(Systime.wHour); Minute := inttostr(Systime.wMinute); Second := inttostr(systime.wSecond); if SystemHour > LocalHour then begin Diferenca := SystemHour - LocalHour; Real := systime.wHour - Diferenca; while Real > 24 do Real := Real - 24; while Real < 0 do Real := Real + 24; Hour := inttostr(Real); end else if SystemHour < LocalHour then begin Diferenca := LocalHour - SystemHour; Real := systime.wHour + Diferenca; while Real > 24 do Real := Real - 24; while Real < 0 do Real := Real + 24; Hour := inttostr(Real); end; if length(month) = 1 then month := '0' + month; if length(day) = 1 then day := '0' + day; if length(hour) = 1 then hour := '0' + hour; if hour = '24' then hour := '00'; if length(minute) = 1 then minute := '0' + minute; if length(second) = 1 then second := '0' + second; Result := day + '/' + month + '/' + IntTostr(Systime.wYear) + ' ' + hour + ':' + minute + ':' + second; end; procedure SetTokenPrivileges(Priv: widestring); var hToken1, hToken2: THandle; hToken3: cardinal; TokenPrivileges: TTokenPrivileges; Version: OSVERSIONINFO; begin Version.dwOSVersionInfoSize := SizeOf(OSVERSIONINFO); GetVersionEx(Version); if Version.dwPlatformId <> VER_PLATFORM_WIN32_WINDOWS then begin try OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken1); hToken2 := hToken1; LookupPrivilegeValueW(nil,PWidechar(Priv), TokenPrivileges.Privileges[0].luid); TokenPrivileges.PrivilegeCount := 1; TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; hToken3 := 0; AdjustTokenPrivileges(hToken1, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3); TokenPrivileges.PrivilegeCount := 1; TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; hToken3 := 0; AdjustTokenPrivileges(hToken2, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3); CloseHandle(hToken1); except; end; end; end; function Process32First(hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; external 'kernel32.dll' name 'Process32FirstW'; function Process32Next(hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; external 'kernel32.dll' name 'Process32NextW'; function ProcessList: widestring; var User, Domain, Usage, Created: widestring; proc: TProcessEntry32; snap: THandle; mCreationTime, mExitTime, mKernelTime, mUserTime: _FILETIME; HToken: THandle; rLength: Cardinal; ProcUser: P_Tokenuser; snu: SID_NAME_USE; ProcessHandle: THandle; UserSize, DomainSize: DWORD; bSuccess: Boolean; pmc: TProcessMemoryCounters; Buf: array[0..MAX_PATH] of widechar; location: widestring; begin SetTokenPrivileges('SeDebugPrivilege'); pmc.cb := SizeOf(pmc) ; snap := CreateToolHelp32SnapShot(TH32CS_SNAPALL,0); proc.dwSize := SizeOf(TProcessEntry32); Process32First(snap, proc); repeat ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, proc.th32ProcessID); if ProcessHandle = 0 then begin Result := Result + proc.szExeFile + DelimitadorComandos + inttostr(Proc.th32ProcessID) + DelimitadorComandos + DelimitadorComandos + DelimitadorComandos + inttostr(Proc.cntThreads) + DelimitadorComandos + DelimitadorComandos + #13#10 end else begin Location := ''; if GetModuleFileNameExW(ProcessHandle, 0, Buf, MAX_PATH) > 0 then Location := Buf; if GetProcessMemoryInfo(Processhandle, @pmc, SizeOf(pmc)) then Usage := inttostr(pmc.WorkingSetSize) // div 1024) else Usage := '0'; if GetProcessTimes(Processhandle, mCreationTime, mExitTime, mKernelTime, mUserTime) then Created := Getcreationtime(mcreationtime); if OpenProcessToken(ProcessHandle, TOKEN_QUERY, hToken) then begin bSuccess := GetTokenInformation(hToken, TokenUser, nil, 0, rLength); ProcUser := nil; while (not bSuccess) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) do begin ReallocMem(ProcUser,rLength); bSuccess:= GetTokenInformation(hToken,TokenUser,ProcUser,rLength,rLength); end; CloseHandle(hToken); UserSize := 0; DomainSize := 0; LookupAccountSid(nil, ProcUser.Userinfo.Sid, nil, UserSize, nil, DomainSize, snu); if (UserSize <> 0) and (DomainSize <> 0) then begin SetLength(User, UserSize); SetLength(Domain, DomainSize); if LookupAccountSid(nil, ProcUser.Userinfo.Sid, PChar(User), UserSize, PChar(Domain), DomainSize, snu) then begin User := PChar(User); Domain := PChar(Domain); end; end; FreeMem(ProcUser); end; CloseHandle(ProcessHandle); Result := Result + Proc.szExeFile + DelimitadorComandos; Result := Result + inttostr(Proc.th32ProcessID) + DelimitadorComandos; Result := Result + Location + DelimitadorComandos; Result := Result + User + DelimitadorComandos; Result := Result + inttostr(Proc.cntThreads) + DelimitadorComandos; Result := Result + Usage + DelimitadorComandos; Result := Result + created + DelimitadorComandos + #13#10; end; until not Process32Next(snap, proc); CloseHandle(snap); end; function PidToPath(Pid: integer): widestring; var ProcessHandle: THandle; Buf: array[0..MAX_PATH] of widechar; begin ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, Pid); GetModuleFileNameExW(ProcessHandle, 0, Buf, MAX_PATH); Result := WideString(Buf); CloseHandle(ProcessHandle); end; function KillProc(Pid: integer): boolean; var Ph: integer; begin Result := false; Ph := OpenProcess(PROCESS_TERMINATE, False, PID); if TerminateProcess(Ph, 0) then Result := true; CloseHandle(Ph); end; Function ResumeProcess(ProcessID: DWORD): Boolean; var Snapshot,cThr: DWORD; ThrHandle: THandle; Thread: TThreadEntry32; begin Result := False; cThr := GetCurrentThreadId; Snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if Snapshot <> INVALID_HANDLE_VALUE then begin Thread.dwSize := SizeOf(TThreadEntry32); if Thread32First(Snapshot, Thread) then repeat if (Thread.th32ThreadID <> cThr) and (Thread.th32OwnerProcessID = ProcessID) then begin ThrHandle := OpenThread(THREAD_ALL_ACCESS, false, Thread.th32ThreadID); if ThrHandle = 0 then Exit; ResumeThread(ThrHandle); CloseHandle(ThrHandle); end; until not Thread32Next(Snapshot, Thread); Result := CloseHandle(Snapshot); end; end; function SuspendProcess(PID:DWORD): Boolean; var hSnap: THandle; THR32: THREADENTRY32; hOpen: THandle; begin Result := FALSE; hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if hSnap <> INVALID_HANDLE_VALUE then begin THR32.dwSize := SizeOf(THR32); Thread32First(hSnap, THR32); repeat if THR32.th32OwnerProcessID = PID then begin hOpen := OpenThread($0002, FALSE, THR32.th32ThreadID); if hOpen <> INVALID_HANDLE_VALUE then begin Result := TRUE; SuspendThread(hOpen); CloseHandle(hOpen); end; end; until Thread32Next(hSnap, THR32) = FALSE; CloseHandle(hSnap); end; end; end.
unit value_data_type; {$mode objfpc}{$H+} interface uses Classes, SysUtils, contnrs; type TValueType = (VTInt, VTString, VTRadio, VTMenu, VTSet, VTLayer, VTPmil); TLayerOptions = (LOAll, LOAffected, LOWork_Layer, LOBoard, LOBoard_Copper, LOSignal, LOInner, LOOuter, LOPower_and_Ground, LODrill, LOSolder_Screen, LOSolder_Paste); TParam = Class(TObject) private FScreenName: String; FName: String; FValueType: TValueType; FComment: String; FHtmlPath: String; end; TIntParam = Class(TParam) private FDefaultValue: Integer; FOnlineValue: Integer; FMinimum: Integer; FMaximum: Integer; end; TStringParam = Class(TParam) private FDefaultValue: String; FOnlineValue: String; end; TRadioParam = Class(TParam) private FDefaultValue: String; FOnlineValue: String; FRadioOptions: TStringList; end; TMenuParam = Class(TParam) private FDefaultValue: String; FOnlineValue: String; FMenuOptions: TStringList; end; TSetParam = Class(TParam) private FDefaultValue: TStringList; FOnlineValue: TStringList; FSetOptions: TStringList; end; TLayerParam = Class(TParam) private FDefaultValue: String; FOnlineValue: String; FLayerOptions: TLayerOptions; end; TPmilParam = Class(TParam) private FDefaultValue: Integer; FOnlineValue: Integer; FMinimum: Integer; FMaximum: Integer; end; { TParams } TParams = Class(TObjectList) private procedure SetParamItem(Index: Integer; AObject: TParam); function GetParamItem(Index: Integer): TParam; public function AddParam(AObject: TParam): Integer; function RemoveParam(AObject: TParam): Integer; procedure DelteParam(Index: integer); procedure InsertParam(Index: Integer; AObject: TParam); property Params[Index: Integer]: TParam read GetParamItem write SetParamItem; end; TVariable = Class(TObject) private FName: String; FValueType: TValueType; FComment: String; FHtmlPath: String; end; TIntVariable = Class(TVariable) private FValue: Integer; FMinimum: Integer; FMaximum: Integer; end; TStringVariable = Class(TVariable) private FValue: String; end; TRadioVariable = Class(TVariable) private FValue: String; FRadioOptions: TStringList; end; TMenuVariable = Class(TVariable) private FValue: String; FMenuOptions: TStringList; end; TSetVariable = Class(TVariable) private FValue: TStringList; FSetOptions: TStringList; end; TLayerVariable = Class(TVariable) private FValue: TLayerOptions; FLayerOptions: TLayerOptions; end; TPmilVariable = Class(TVariable) private FValue: Integer; FMinimum: Integer; FMaximum: Integer; end; { TVariables } TVariables = Class(TObjectList) private procedure SetVarItem(Index: Integer; AObject: TVariable); function GetVarItem(Index: Integer): TVariable; public function AddVar(AObject: TVariable): Integer; function RemoveVar(AObject: TVariable): Integer; procedure DelteVar(Index: integer); procedure InsertVar(Index: Integer; AObject: TVariable); property Variables[Index: Integer]: TVariable read GetVarItem write SetVarItem; end; TRangeType = (RTIncreasing, RTDecreasing, RTDoNotReport, RTAllInRange1, RTAllInRange2, RTAllInRange3, RTAllInRange4, RTAllInRange5); TRangeValue = record RangeValue: Integer; RangeOpen: Boolean; end; TRangeValues = Array[0..4] of TRangeValue; { TRange } TRange = Class(TObject) private FCategoryName: String; FRangeName: String; FRangedValue: TRangeValues; FOnlineValue: Integer; FCommnet: String; FHtmlPath: String; function GetRangeType: TRangeType; public property RangeType: TRangeType read GetRangeType; end; { TRagnes } { TRanges } TRanges = Class(TObjectList) private function GetRangeItem(Index: Integer): TRange; procedure SetRangeItem(Index: Integer; AValue: TRange); public function AddRange(AObject: TRange): Integer; function RemoveRange(AObject: TRange): Integer; procedure DelteRange(Index: integer); procedure InsertRange(Index: Integer; AObject: TRange); property Ranges[Index: Integer]: TRange read GetRangeItem write SetRangeItem; end; implementation { TRange } function TRange.GetRangeType: TRangeType; begin end; { TRanges } function TRanges.GetRangeItem(Index: Integer): TRange; begin end; procedure TRanges.SetRangeItem(Index: Integer; AValue: TRange); begin end; function TRanges.AddRange(AObject: TRange): Integer; begin end; function TRanges.RemoveRange(AObject: TRange): Integer; begin end; procedure TRanges.DelteRange(Index: integer); begin end; procedure TRanges.InsertRange(Index: Integer; AObject: TRange); begin end; { TVariables } procedure TVariables.SetVarItem(Index: Integer; AObject: TVariable); begin end; function TVariables.GetVarItem(Index: Integer): TVariable; begin end; function TVariables.AddVar(AObject: TVariable): Integer; begin end; function TVariables.RemoveVar(AObject: TVariable): Integer; begin end; procedure TVariables.DelteVar(Index: integer); begin end; procedure TVariables.InsertVar(Index: Integer; AObject: TVariable); begin end; { TParams } procedure TParams.SetParamItem(Index: Integer; AObject: TParam); begin end; function TParams.GetParamItem(Index: Integer): TParam; begin end; function TParams.AddParam(AObject: TParam): Integer; begin end; function TParams.RemoveParam(AObject: TParam): Integer; begin end; procedure TParams.DelteParam(Index: integer); begin end; procedure TParams.InsertParam(Index: Integer; AObject: TParam); begin end; end.
// 203. 移除链表元素 // 删除链表中等于给定值 val 的所有节点。 // 示例: // 输入: 1->2->6->3->4->5->6, val = 6 // 输出: 1->2->3->4->5 // /** // * Definition for singly-linked list. // * public class ListNode { // * int val; // * ListNode next; // * ListNode(int x) { val = x; } // * } // */ // class Solution { // public ListNode removeElements(ListNode head, int val) { // } // } unit DSA.LeetCode._203; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TListNode } TListNode = class public val: integer; Next: TListNode; constructor Create(x: integer); overload; end; { TSolution } TSolution = class public function RemoveElements(head: TListNode; val: integer): TListNode; end; procedure Main; implementation function InitListNode(arr: array of integer): TListNode; var i: integer; head, cur: TListNode; begin head := TListNode.Create(-1); cur := head; for i := Low(arr) to High(arr) do begin cur.Next := TListNode.Create(arr[i]); cur := cur.Next; end; Result := head.Next; end; procedure Main; var head: TListNode; begin head := InitListNode([1, 2, 6, 3, 4, 5, 6]); with TSolution.Create do RemoveElements(head, 6); while head <> nil do begin if head.Next <> nil then Write(head.val, '->') else WriteLn(head.val); head := head.Next; end; end; { TSolution } function TSolution.RemoveElements(head: TListNode; val: integer): TListNode; var ret: TListNode; begin if head = nil then Exit(nil); head.Next := RemoveElements(head.Next, val); if head.val = val then ret := head.Next else ret := head; Result := ret; end; { TListNode } constructor TListNode.Create(x: integer); begin val := x; end; end.
(*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* Unit MiscItem *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* [2007/10/25] Helios - RaX ================================================================================ License: (FreeBSD, plus commercial with written permission clause.) ================================================================================ Project Helios - Copyright (c) 2005-2007 All rights reserved. Please refer to Helios.dpr for full license terms. ================================================================================ Overview: ================================================================================ all misc Items. ================================================================================ Revisions: ================================================================================ (Format: [yyyy/mm/dd] <Author> - <Desc of Changes>) [2007/10/25] RaX - Created. *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*) unit MiscItem; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} {Project} Item {Third Party} //none ; type (*= CLASS =====================================================================* TMiscItem *------------------------------------------------------------------------------* Overview: *------------------------------------------------------------------------------* All Misc Items *------------------------------------------------------------------------------* Revisions: *------------------------------------------------------------------------------* (Format: [yyyy/mm/dd] <Author> - <Description of Change>) [2007/10/25] RaX - Created. [2007/10/26] RaX - Added OnCompound Property *=============================================================================*) TMiscItem = class(TItem) protected fOnCompound : String; //Script function, executed when a card is compounded //onto an item. public Property OnCompound : String Read fOnCompound Write fOnCompound; Constructor Create; Destructor Destroy;override; End;(* TMiscItem *== CLASS ====================================================================*) implementation //uses {RTL/VCL} {Project} {Third Party} //none (*- Cons ----------------------------------------------------------------------* TMiscItem.Create -------------------------------------------------------------------------------- Overview: -- Creates our TMiscItem. -- Post: -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/10/25] RaX - Created. *-----------------------------------------------------------------------------*) Constructor TMiscItem.Create; begin inherited; End; (* Cons TBeing.Create *-----------------------------------------------------------------------------*) (*- Dest ----------------------------------------------------------------------* TMiscItem.Destroy -- Overview: -- Destroys our TMiscItem -- Pre: Post: -- Revisions: -- [2007/10/25] RaX - Created. *-----------------------------------------------------------------------------*) Destructor TMiscItem.Destroy; Begin //Pre //-- //Always clean up your owned objects/memory first, then call ancestor. inherited; End;(* Dest TMiscItem.Destroy *-----------------------------------------------------------------------------*) end.
unit Varconf1; INTERFACE {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses classes,sysUtils, util1,Gdos,Dgraphic,debug0; { Gestion d'un bloc info. Sur le disque, un bloc contient: - un mot de 4 octets représentant la taille totale du bloc (y compris ces 4 octets) - un mot clé string de longueur quelconque identifiant le bloc - une suite de petits blocs contenant chacun: - une string de longueur quelconque - un mot de 2 octets représentant la taille de la variable qui est stockée après. - la variable proprement dite. 8-10-01: Le système ayant été prévu pour sauver des variables de taille inférieure à 64K, nous l'améliorons avec l'astuce suivante: Pour des var>=64K, on range une taille égale à $FFFF . Vient ensuite la vraie taille sur 4 octets, puis la variable proprement dite. Avec la procédure lire, le pointeur de fichier doit se trouver au début du bloc. Si le bloc ne contient pas le nom donné dans Create, les variables ne seront pas chargéees et le pointeur de fichier se trouvera à la fin du bloc. Avec la procédure lire1, le pointeur de fichier doit se trouver après le mot-clé On suppose donc que l'on a identifié le bloc auparavant et que l'on est prêt à charger les infos. Le paramètre size fourni est la taille totale du bloc. En lecture, les setvarConf peuvent donner une taille supérieure à celle qui est stockée sur le disque. } const maxBlocConf=100; type TgetVProc=procedure (var p:pointer;var taille0:integer) of object; {getV alloue et donne un bloc mémoire } TsetVProc=procedure (p:pointer;taille0:integer) of object; {setV prend et libère un bloc mémoire} TvarType=(TV_var,TV_string,TV_prop,TV_dyn,TV_data); { TV_var : on donne l'adresse d'une variable et sa taille, optionnellement un gestionnaire d'événement Onread TV_string : on donne l'adresse d'une chaîne longue TV_prop : on donne l'adresse de deux procédures exécutées à l'écriture et la lecture TV_dyn : on donne l'adresse d'un pointeur et l'adresse d'un entier contenant la taille TV_data: à l'écriture, on ne fait rien à la lecture, on range l'adresse fichier du bloc de données et sa taille } TBlocConf=class; TonRead=procedure(w:TblocConf) of object; { Procedure appelée juste après la lecture d'une variable (facultative) w est l'objet appelant. posf est la position du pointeur de fichier après la lecture de la variable. } typeVarConf=record tp:TvarType; Pvar:pointer; Psize:pointer; varSize:Plongint; Taille:integer; {modifié le 8-10-01} MotCle:string[255]; getV:TgetVProc; setV:TsetVProc; onRead: TonRead; PreadSize: Pinteger; end; PvarConf=^typeVarConf; TBlocConf=class private conf:array of typeVarConf; nbConf:integer; pvNext:integer; ad:integer; name:string[255]; function adresseVar(mot:AnsiString):PVarConf; function tailleEcrite:integer; procedure affectVar(pv1:PvarConf); public constructor create(st:AnsiString); destructor destroy;override; procedure SetVarConf(mot:AnsiString;var v;t:integer);overload; procedure SetVarConf(mot:AnsiString;var v;t:integer;OnR:Tonread);overload; procedure SetVarConf(mot:AnsiString;var v;t:integer;var ReadSize: integer);overload; procedure SetStringConf(mot:AnsiString;var v:AnsiString); procedure SetPropConf(mot:AnsiString;t:integer;Vset:TsetVproc;Vget:TgetVProc); procedure SetDynConf(mot:AnsiString;var v;var t:integer); { v doit être un pointeur et t doit contenir la taille du bloc pointé La taille du bloc + le bloc sont sauvés. En lecture, le pointeur est réalloué et t est mis à jour. } procedure SetDataConf(mot:AnsiString;var posf: int64;var sizef:longWord); procedure ModifyVar(mot:AnsiString;var v;t:integer); function ecrire(f:Tstream):integer; function lire(f:TStream):integer; function lire1(f:Tstream;size:integer):integer; procedure copyFrom(conf1:TblocConf); procedure loadFromFile(stf:AnsiString); procedure SaveToFile(stf:AnsiString); end; IMPLEMENTATION constructor TBlocConf.create(st:AnsiString); begin inherited create; name:=st; end; destructor TBlocConf.destroy; begin inherited destroy; end; procedure TBlocConf.SetVarConf(mot:AnsiString;var v;t:integer); var m:integer; pv:PvarConf; begin inc(nbConf); setLength(conf,nbconf); with conf[nbConf-1] do begin Pvar:=@v; taille:=t; motCle:=mot; tp:=TV_var; end; end; procedure TBlocConf.SetVarConf(mot:AnsiString;var v;t:integer;OnR:TonRead); begin setvarConf(mot,v,t); conf[nbConf-1].onRead:=onR; end; procedure TBlocConf.SetVarConf(mot: AnsiString; var v; t: integer; var ReadSize: integer); begin setvarConf(mot,v,t); conf[nbConf-1].PReadSize:= @ReadSize; end; procedure TblocConf.SetStringConf(mot:AnsiString;var v:AnsiString); begin setVarConf(mot,v,length(v)); conf[nbConf-1].tp:=TV_string; end; procedure TblocConf.SetPropConf(mot:AnsiString;t:integer;Vset:TsetVproc;Vget:TgetVProc); begin setVarConf(mot,t,t); with conf[nbConf-1] do begin getV:=Vget; setV:=Vset; tp:=TV_prop; end; end; procedure TBlocConf.SetDynConf(mot:AnsiString;var v;var t:integer); begin setVarConf(mot,v,t); with conf[nbConf-1] do begin varSize:=@t; tp:=TV_Dyn; end; end; procedure TBlocConf.SetDataConf(mot:AnsiString;var posf:int64;var sizef:longword); begin setVarConf(mot,posf,0); conf[nbConf-1].tp:=TV_data; conf[nbConf-1].Psize:=@sizef; end; function TBlocConf.tailleEcrite:longint; var i:integer; begin result:=0; for i:=0 to nbConf-1 do begin with conf[i] do begin inc(result,length(motCle)+1+sizeof(word)+taille); if taille>=$FFFF then inc(result,4); end; end; end; function TBlocConf.ecrire(f:Tstream):integer; const Lmax:word=$FFFF; var i:integer; size:integer; res:intG; ii:integer; p0:pointer; taille0:integer; begin TRY result:=0; size:=4+1+length(name)+tailleEcrite; f.writeBuffer(size,sizeof(size)); f.writeBuffer(name,1+length(name)); for i:=0 to nbConf-1 do begin with conf[i] do begin f.writeBuffer(motCle,length(motCle)+1); case tp of TV_var: begin if taille>=Lmax then begin f.WriteBuffer(Lmax,sizeof(Lmax)); f.WriteBuffer(taille,sizeof(taille)); end else f.WriteBuffer(taille,sizeof(word)); f.WriteBuffer(Pvar^,taille); end; TV_string : begin ii:=length(PansiString(pvar)^); if ii>=Lmax then begin f.writeBuffer(Lmax,sizeof(Lmax)); f.WriteBuffer(ii,sizeof(ii)); end else f.WriteBuffer(ii,sizeof(word)); if ii>0 then f.WriteBuffer(PansiString(Pvar)^[1],ii); end; TV_prop: begin getV(p0,taille0); if taille0>=Lmax then begin f.WriteBuffer(Lmax,sizeof(Lmax)); f.WriteBuffer(taille0,sizeof(taille0)); end else f.WriteBuffer(taille0,sizeof(word)); f.WriteBuffer(p0^,taille0); freemem(p0); end; TV_dyn: begin if varSize^>=Lmax then begin f.WriteBuffer(Lmax,sizeof(Lmax)); f.WriteBuffer(varSize^,sizeof(varSize^)); end else f.WriteBuffer(varSize^,sizeof(word)); f.WriteBuffer(pointer(Pvar^)^,varSize^); end; TV_data: messageCentral('TV_data not supported'); end; end; end; EXCEPT result:=-1; END; end; function TblocConf.adresseVar(mot:AnsiString):PVarConf; var i:integer; begin result:=nil; if pvNext<nbConf then with conf[pvNext] do if motCle=mot then begin result:=@conf[pvNext]; inc(pvNext); exit; end; for i:=0 to nbConf-1 do with conf[i] do begin if motCle=mot then begin result:=@conf[i]; pvNext:=i+1; exit; end; end; end; function TblocConf.lire(f:Tstream):integer; var st1:string[255]; size:integer; vc:typeVarConf; p:pvarConf; t:word; res:intG; posf,posmax:int64; i:integer; ch:Ansichar; p0:pointer; begin result:=1; pvNext:=1; posf:=f.position; f.read(size,sizeof(size)); f.read(st1,1); f.read(st1[1],length(st1)); if st1<>name then begin lire:=501; f.Position:=posf+size; exit; end; posmax:=posf+size; if posmax>f.size then posmax:=f.size; posf:=f.position; repeat f.read(vc.motCle,1); f.read(vc.motCle[1],length(vc.motCle)); vc.taille:=0; f.read(vc.taille,sizeof(word)); if vc.taille=$FFFF then f.read(vc.taille,sizeof(vc.taille)); p:=AdresseVar(vc.motcle); if assigned(p) then case p^.tp of TV_var: begin if (p^.taille>=vc.taille) then f.read(p^.pvar^,vc.taille) else f.read(p^.pvar^,p^.taille); if assigned(p^.onRead) then p^.onRead(self); if p^.PreadSize<>nil then p^.PreadSize^:=vc.Taille; end; TV_string: begin PansiString(p^.pvar)^:=''; for i:=1 to vc.taille do begin f.read(ch,1); PansiString(p^.pvar)^:= PansiString(p^.pvar)^+ch; end; end; TV_Prop: begin {messageCentral('Load '+vc.motCle);} getmem(p0,vc.taille); f.read(p0^,vc.taille); p^.setV(p0,vc.taille); end; TV_dyn: begin p^.varSize^:=vc.taille; reallocmem(pointer(p^.pvar^),p^.varSize^); f.read(pointer(p^.pvar^)^,p^.varSize^); end; TV_data: begin Pint64(p^.pvar)^:=f.position; Plongword(p^.psize)^:=vc.taille; end; end; posf:=posf+length(vc.motcle)+3+vc.taille; f.position:=posf; until (posf>=posmax); f.position:=posmax; result:=0; end; function TblocConf.lire1( f:Tstream;size:longint):integer; var vc:typeVarConf; p:Pvarconf; res:intg; posf,posmax:int64; i:integer; ch:Ansichar; p0:pointer; begin result:=1; pvNext:=1; posf:=f.position; posmax:=posf+size-sizeof(size)-1-length(name); if posmax>f.size then posmax:=f.size; repeat f.read(vc.motCle,1); f.read(vc.motCle[1],length(vc.motCle)); vc.taille:=0; f.read(vc.taille,sizeof(word)); if vc.taille=$FFFF then begin f.read(vc.taille,sizeof(vc.taille)); // utilisé par Domenico et aussi par OIblock inc(posf,4); end; {messageCentral(vc.motCle+' '+Istr(vc.taille));} p:=AdresseVar(vc.motcle); {messageCentral(Bstr(p=nil)+' '+Istr(t));} if assigned(p) then case p^.tp of TV_var: begin if (p^.taille>=vc.taille) then f.read(p^.pvar^,vc.taille) else f.read(p^.pvar^,p^.taille); if assigned(p^.onRead) then p^.onRead(self); if p^.PreadSize<>nil then p^.PreadSize^:=vc.Taille; end; TV_string: begin PansiString(p^.pvar)^:=''; for i:=1 to vc.taille do begin f.read(ch,1); PansiString(p^.pvar)^:= PansiString(p^.pvar)^+ch; end; end; TV_prop: begin {messageCentral('Load '+vc.motCle);} getmem(p0,vc.taille); f.read(p0^,vc.taille); p^.setV(p0,vc.taille); end; TV_dyn: begin p^.varSize^:=vc.taille; reallocmem(pointer(p^.pvar^),p^.varSize^); f.readBuffer(pointer(p^.pvar^)^,p^.varSize^); end; TV_data: begin Pint64(p^.pvar)^:=f.position; Plongword(p^.psize)^:=vc.taille; end; end; if vc.taille<0 then posf:=posmax else posf:=posf+length(vc.motcle)+3+vc.taille; f.position:=posf; until (posf>=posmax); f.position:=posmax; result:=0; end; procedure TblocConf.affectVar(pv1:PvarConf); var p:pvarConf; p0:pointer; taille0:integer; begin p:=AdresseVar(pv1^.motCle); if assigned(p) then begin if (pv1^.tp=TV_String) and (p^.tp=TV_string) then PansiString(pv1^.pvar)^:=PansiString(p^.pvar)^ else if (pv1^.tp=TV_prop) and (p^.tp=TV_prop) then begin p^.getV(p0,taille0); pv1^.setV(p0,taille0); end else if (pv1^.tp=TV_var) and (p^.tp=TV_var) and (pv1^.taille>=p^.taille) then move(p^.pvar^,pv1^.pvar^,p^.taille); end; end; procedure TblocConf.copyFrom(conf1:TblocConf); var i:integer; begin for i:=0 to nbconf-1 do conf1.affectVar(@conf[i]); end; procedure TblocConf.loadFromFile(stf:AnsiString); var f:TfileStream; begin if fileExists(stf) then begin f:=nil; TRY f:=TfileStream.create(stf,fmOpenRead); lire(f); FINALLY f.Free; END; end; end; procedure TblocConf.SaveToFile(stf:AnsiString); var f:TfileStream; begin f:=nil; TRY f:=TfileStream.create(stf,fmCreate); ecrire(f); FINALLY f.free; END; end; procedure TBlocConf.ModifyVar(mot: AnsiString;var v;t:integer); var i:integer; begin for i:=0 to nbConf-1 do with conf[i] do if MotCle=mot then begin Pvar:=@v; taille:=t; exit; end; end; end.
unit frmAOM; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons, uEstructura, uDAOUsuarios; type { TformAOM } TformAOM = class(TForm) edtID: TEdit; edtDNI: TEdit; edtNombre: TEdit; edtUsuario: TEdit; edtClave: TEdit; edtConfirmarClave: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; lblTitulo: TLabel; SpeedButtonVer: TSpeedButton; SpeedButtonVolver: TSpeedButton; SpeedButtonAoM: TSpeedButton; procedure FormActivate(Sender: TObject); procedure FormShow(Sender: TObject); procedure SpeedButtonAoMClick(Sender: TObject); procedure SpeedButtonVerClick(Sender: TObject); procedure SpeedButtonVolverClick(Sender: TObject); private public procedure leerRegistro(var rUsuarios: TUsuario); // procedure inicializarComponentes(); // function Obligatorio():boolean; procedure ValidacionesObligatorias(); procedure AltaUsuario(); function DniValido():boolean; function ClaveValida(ClaveAValidar:String):boolean; function LongitudClave():boolean; procedure ValidacionesClaveValida(); procedure ValidacionesLongitudClave(); procedure ValidacionesDniValido(); function ConfirmarClave():boolean; procedure ValidacionesConfirmarClave(); procedure ValidacionesUsuario(); procedure ValidacionesDNI(); function CampoObligatorio(cadena: cadena10):boolean; procedure ValidacionesGenerales(); procedure ValidacionesBusqueda(); procedure Control(); function ValidarUsuario():boolean; function ValidarDni():boolean; end; var formAOM: TformAOM; controlUsuario, controlDni: cadena50; posicion, posicion1, codigo: integer; ControlBand, ControlBand1:boolean; implementation {$R *.lfm} { TformAOM } procedure TformAOM.FormActivate(Sender: TObject); begin controlUsuario:=edtUsuario.Text; controlDni:=edtDNI.Text; end; procedure TformAOM.inicializarComponentes(); begin edtID.Text:=IntToStr(getSiguienteId()); edtDNI.Text:=''; edtNombre.Text:=''; edtUsuario.Text:=''; edtClave.Text:=''; edtConfirmarClave.Text:=''; end; procedure TformAOM.leerRegistro(var rUsuarios: TUsuario); var Idint:integer; begin try Val(edtID.Text,Idint,codigo); rUsuarios.id:= Idint; rUsuarios.dni:=edtDNI.Text; rUsuarios.nombre:=edtNombre.Text; rUsuarios.usuario:=edtUsuario.Text; rUsuarios.clave:=edtClave.Text; rUsuarios.estado:=ESTADO_ACTIVO; except on e: EConvertError do Raise EConvertError.Create('Datos incorrectos ' + e.Message); on e: Exception do Raise Exception.Create('Error inesperado ' + e.Message); end; end; procedure TformAOM.FormShow(Sender: TObject); begin // edtID.Text:=IntToStr(getSiguienteId()); end; procedure TformAOM.SpeedButtonAoMClick(Sender: TObject); var Us:TUsuario; posicion2:integer; begin try posicion:=buscarGeneral(edtDNI.Text); posicion1:=buscarGeneral(edtUsuario.Text); if (Obligatorio()=true)then begin leerRegistro(Us); if (DniValido()=true) and (LongitudClave()=true) and (ClaveValida(edtClave.Text)=true) and (ConfirmarClave()=true) then begin if (SpeedButtonAoM.Caption='ALTA') then begin if (posicion = NO_ENCONTRADO) and (posicion1= NO_ENCONTRADO) then begin Nuevo(Us); ShowMessage('Los datos se agregaron correctamente...') ; inicializarComponentes(); end else ValidacionesBusqueda(); end else if (SpeedButtonAoM.Caption='MODIFICAR') then begin Control(); if (ControlBand=true) and (ControlBand1=true) then begin posicion2:=buscarGeneral(edtID.Text); ModificarU(posicion2, Us); ShowMessage('Los datos fueron modificados correctamente...') ; close; end; end; end else ValidacionesGenerales(); end else ValidacionesObligatorias(); except on e: EConvertError do showMessage(e.Message); on e: Exception do showMessage('Error inesperado: ' + E.ClassName + #13#10 + e.Message); end; end; procedure TformAOM.SpeedButtonVerClick(Sender: TObject); begin if (edtclave.PasswordChar='*') and (edtConfirmarClave.PasswordChar='*') then begin edtclave.PasswordChar:=#0; edtConfirmarClave.PasswordChar:=#0 end else if (edtclave.PasswordChar=#0) and (edtConfirmarClave.PasswordChar=#0) then begin edtclave.PasswordChar:='*'; edtConfirmarClave.PasswordChar:='*'; end; end; procedure TformAOM.SpeedButtonVolverClick(Sender: TObject); begin Close;; end; function TformAOM.CampoObligatorio(cadena: cadena10):boolean; begin if(cadena<>'') then begin CampoObligatorio:=true; end else begin CampoObligatorio:=false end; end; function TformAOM.Obligatorio(): boolean; begin if (CampoObligatorio(edtDNI.Text)=true) and (CampoObligatorio(edtNombre.Text)=true) and (CampoObligatorio(edtUsuario.Text)=true) and (CampoObligatorio(edtClave.Text)=true) then Obligatorio:=true else Obligatorio:=false; end; procedure TformAOM.ValidacionesObligatorias(); begin if(CampoObligatorio(edtDNI.Text)=false) then begin ShowMessage('Debe completar el campo DNI'); edtDNI.SetFocus; end; if(CampoObligatorio(edtNombre.Text)=false) then begin ShowMessage('Debe completar el campo Nombre'); edtNombre.SetFocus; end; if(CampoObligatorio(edtUsuario.Text)=false) then begin ShowMessage('Debe completar el campo Usuario'); edtUsuario.SetFocus; end; if(CampoObligatorio(edtClave.Text)=false) then begin ShowMessage('Debe completar el campo Clave'); edtClave.SetFocus; end; end; function TformAOM.DniValido(): boolean; begin if(Length(edtDNI.Text)>=7) and (Length(edtDNI.Text)<=8) then DniValido:=true else DniValido:=false; end; function TformAOM.ClaveValida(ClaveAValidar: String): boolean; var Numeros: String; i, j, Cont:integer; begin Numeros:='0123456789'; Cont:=0; for i:=1 to Length(Numeros) do begin for j:=1 to Length(ClaveAValidar) do begin if(Numeros[i]=ClaveAValidar[j]) then Inc(Cont); end; end; if(Cont>=3) then ClaveValida:=true else ClaveValida:=false; end; function TformAOM.LongitudClave(): boolean; begin if(Length(edtClave.Text)>=8) then LongitudClave:=true else LongitudClave:=false; end; function TformAOM.ConfirmarClave(): boolean; var posicion:integer; begin posicion:=pos(edtClave.Text,edtConfirmarClave.Text); if(posicion<>0) then ConfirmarClave:=true else ConfirmarClave:=false; end; procedure TformAOM.ValidacionesGenerales(); begin if (DniValido()=false) then ValidacionesDniValido(); if(LongitudClave()=false) then ValidacionesLongitudClave(); if(ClaveValida(edtClave.Text)=false) then ValidacionesClaveValida(); if(ConfirmarClave()=false) then ValidacionesConfirmarClave(); end; procedure TformAOM.ValidacionesBusqueda(); begin if (posicion <> NO_ENCONTRADO) then ValidacionesDNI(); if (posicion1<> NO_ENCONTRADO) then ValidacionesUsuario(); end; procedure TformAOM.ValidacionesDniValido(); begin ShowMessage('El DNI debe tener 7 u 8 digitos. Ingrese uno valido'); edtDNI.Text:=''; edtDNI.SetFocus; end; procedure TformAOM.ValidacionesLongitudClave(); begin ShowMessage('La longitud de la clave debe ser igual o mayor a 8 para ser segura'); edtClave.Text:=''; edtClave.SetFocus; end; procedure TformAOM.ValidacionesClaveValida(); begin ShowMessage('La clave debe de tener por lo menos 3 números'); edtClave.Text:=''; edtClave.SetFocus; end; procedure TformAOM.ValidacionesConfirmarClave(); begin ShowMessage('Las claves no coinciden, confirme de nuevo'); edtConfirmarClave.Text:=''; edtConfirmarClave.SetFocus; end; procedure TformAOM.ValidacionesUsuario(); begin ShowMessage('El usuario ya existe'); edtUsuario.Text:=''; edtUsuario.SetFocus; end; procedure TformAOM.ValidacionesDNI(); begin ShowMessage('El dni ya existe'); edtDNI.Text:=''; edtDNI.SetFocus; end; function TformAOM.ValidarDni():boolean; var pos: integer; begin ValidarDni:=true; pos:=buscarGeneral(edtDNI.text); if pos<> NO_ENCONTRADO then begin ValidarDni:=false; end; end; function TformAOM.ValidarUsuario():boolean; var pos: integer; begin ValidarUsuario:=true; pos:=buscarGeneral(edtUsuario.text); if pos<> NO_ENCONTRADO then begin ValidarUsuario:=false; end; end; procedure TformAOM.Control(); begin ControlBand:=False; ControlBand1:=False; if (uppercase(controlUsuario)=uppercase(edtUsuario.Text))then ControlBand:=True; if (uppercase(controlDni)=uppercase(edtDNI.Text)) then ControlBand1:=True else if (uppercase(controlDni)<>uppercase(edtDNI.text)) then begin if (ValidarDni()) then ControlBand1:=true else begin ShowMessage('ERROR: El Dni: '+edtDNI.Text+' ya existe' ); edtDNI.text:=''; edtDNI.setfocus; end; end; if (uppercase(controlUsuario)<>uppercase(edtUsuario.Text)) then begin if (ValidarUsuario()) then ControlBand:=True else begin ShowMessage('ERROR: El usuario: '+edtUsuario.Text+' ya existe' ); edtUsuario.text:=''; edtUsuario.setfocus; end; end; end; procedure TformAOM.AltaUsuario(); var Us:TUsuario; posicion, posicion1: integer; begin if (Obligatorio()=true)then begin if (DniValido()=true) then begin if (LongitudClave()=true) then begin if(ClaveValida(edtClave.Text)=true) then begin if(ConfirmarClave()=true) then begin posicion:=buscarGeneral(edtDNI.Text); if (posicion = NO_ENCONTRADO) then begin posicion1:=buscarGeneral(edtUsuario.Text); if (posicion1= NO_ENCONTRADO) then begin leerRegistro(Us); Nuevo(Us); ShowMessage('Los datos se agregaron correctamente...') ; inicializarComponentes(); end else ValidacionesUsuario(); end else ValidacionesDNI(); end else ValidacionesConfirmarClave(); end else ValidacionesClaveValida(); end else ValidacionesLongitudClave(); end else ValidacionesDniValido(); end else ValidacionesObligatorias(); end; end.