text
stringlengths
14
6.51M
unit optionsCalculator; {$mode objfpc}{$H+} interface uses Classes, SysUtils,arrayUtils; type { TOptionsCalculator } TOptionsCalculator = class(TInterfacedObject) private fGameNumbers: TIntArray; //the numbers allowed in this game - default 1..9 public constructor create(gameNumbers:TIntArray=nil); end; implementation { TOptionsCalculator } constructor TOptionsCalculator.create(gameNumbers: TIntArray); begin if gameNumbers <> nil then fGameNumbers:=gameNumbers else fGameNumbers:= TIntArray.create(1,2,3,4,5,6,7,8,9); end; end.
unit demo; { This application demos the TRAS component. While it may be installed in the component library and dropped on a form, this example creates the component in code. Please note this is not intended to be a fully functioning application and may not be distributed as such. Created by Angus Robertson, Magenta Systems Ltd, England in early 1998, delphi@magsys.co.uk, http://www.magsys.co.uk/delphi/ Copyright Magenta Systems Ltd Last updated: 28th March 1999 Compatible with Delphi 2, 3 and 4, tested with Win95, 98 and NT4 Note that Magenta Systems also has available some TAPI functions that allow monitoring on modems and ISDN adaptors using events, avoiding needing to continually poll using the RAS APIs. TAPI also monitors non-RAS modem usage and will monitor incoming calls. A TAPI function is also used to convert the canonical telephone number into a dialable number according to telephony dialling properties. See the web site listed above for more details on the TAPI functions. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, Rascomp32, RAS_API32 ; // the main TRAS component and literals type TMainForm = class(TForm) Status: TStatusBar; ConnList: TListBox; Label1: TLabel; Timer: TTimer; doCreateConn: TButton; doEditConn: TButton; ConnUser: TEdit; ConnPw: TEdit; Label2: TLabel; Label3: TLabel; doLogonUpdate: TButton; doConnect: TButton; doDisConn: TButton; doExit: TButton; Label4: TLabel; doDeleteConn: TButton; doRenameConn: TButton; DeviceName: TLabel; ConnPhone: TLabel; Label7: TLabel; ListDUA: TListBox; Label8: TLabel; Panel1: TPanel; Label5: TLabel; StatXmit: TLabel; StatRecv: TLabel; ConnSpeed: TLabel; Label6: TLabel; IPAddr: TLabel; Memory: TLabel; DeviceList: TListBox; Label9: TLabel; ConnCanonical: TLabel; DeviceType: TLabel; DevicePort: TLabel; procedure FormCreate(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure doConnectClick(Sender: TObject); procedure doDisConnClick(Sender: TObject); procedure doCreateConnClick(Sender: TObject); procedure doEditConnClick(Sender: TObject); procedure doLogonUpdateClick(Sender: TObject); procedure ConnListClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure doExitClick(Sender: TObject); procedure doDeleteConnClick(Sender: TObject); procedure doRenameConnClick(Sender: TObject); private { Private declarations } procedure StateChanged(Sender: TObject); // TRAS event, added manually public { Public declarations } end; var MainForm: TMainForm; RAS: TRAS ; // the main TRAS component CurrConnection: string ; // active connection name, if any StopFlag: boolean ; // if true, stop connection in progress OnlineFlag: boolean ; // if true, connected heap: THeapStatus ; implementation {$R *.DFM} // when a connection is clicked, get Phone book info procedure TMainForm.ConnListClick(Sender: TObject); begin if ConnList.ItemIndex = -1 then exit ; RAS.EntryName := ConnList.Items [ConnList.ItemIndex]; // Connection name ConnUser.Text := '' ; ConnPw.Text := '' ; if RAS.GetDialParams = 0 then // get connection parameters begin ConnUser.Text := RAS.UserName ; // display them ConnPw.Text := RAS.Password ; if RAS.GetEntryProperties = 0 then begin DeviceName.Caption := 'Device Name: ' + RAS.DeviceName ; DeviceType.Caption := 'Device Type: ' + RAS.DeviceType ; DevicePort.Caption := 'Device Port: ' + RAS.DevicePort ; ConnPhone.Caption := 'Phone Number: ' + RAS.PhoneNumber ; ConnCanonical.Caption := 'Canonical Number: ' + RAS.PhoneCanonical ; end ; Timer.Enabled := true ; // not until RAS installed end else Status.Panels[1].Text := RAS.StatusStr ; end; procedure TMainForm.FormCreate(Sender: TObject); var count: integer ; begin OnlineFlag := false ; CurrConnection := '' ; // no active connection, yet RAS := TRAS.Create (Self) ; // create TRAS component RAS.OnStateChanged := StateChanged ; // install event handler if RAS.TestRAS then begin // get list of connections RAS.GetPhoneBookEntries; ConnList.Items.Assign (RAS.PhoneBookEntries); // display it if ConnList.Items.Count <> 0 then ConnList.ItemIndex := 0 ; // set first // get list of RAS capable modems RAS.GetDeviceList ; if RAS.DeviceNameList.Count <> 0 then for count := 0 to RAS.DeviceNameList.Count - 1 do DeviceList.Items.Add (RAS.DeviceNameList [count] + ' (' + RAS.DeviceTypeList [count] + ')') ; // Win95/98 gets performance stats from registry, but the keys may be // translated and there may be more than one dial up adaptor // so get a list and select the first found if NOT RAS.EnablePerfStats (true, true) then begin ListDUA.Items.Assign (RAS.DialUpAdaptors) ; ListDUA.Items.Add ('No Performance Statistics') ; Status.Panels[1].Text := 'No Performance Statistics' ; end else ListDUA.Items.Assign (RAS.DialUpAdaptors) ; // initial settings ConnListClick (self) ; // get connection info Timer.Enabled := true ; StateChanged (self) ; // initial status panel end else begin ConnList.Items.Add (RAS.StatusStr) ; // no RAS available Status.Panels[1].Text := RAS.StatusStr ; end ; end; // event handler called by TRAS when connection status changes procedure TMainform.StateChanged(Sender: TObject); var info: string ; begin if CurrConnection = '' then info := 'DUN: Offline' else info := 'DUN: ' + CurrConnection + ' - ' + RAS.StatusStr ; Status.Panels[0].Text := info ; end; procedure TMainForm.TimerTimer(Sender: TObject); var numconns: integer ; info: string ; begin // check for memory leaks heap := GetHeapStatus ; Memory.Caption := 'Memory: Allocated ' + IntToStr (heap.TotalAllocated) ; // see if any connections are open RAS.GetConnections ; // check for active connections if Ras.Connections.Count = 0 then // no active connections begin OnlineFlag := false ; if CurrConnection <> '' then // just gone offline begin CurrConnection := '' ; RAS.IntDisconnect ; // disconnect, but ignore errors RAS.ResetPerfStats ; // clear stats for next connection StateChanged (self) ; end end else begin // see if new connection if CurrConnection <> RAS.Connections.EntryName (0) then begin CurrConnection := RAS.Connections.EntryName (0) ; RAS.ReOpen (0) ; // allow RAS to use this connection end ; RAS.CurrentStatus ; // triggers StateChanged event if (RAS.ConnectState = RASCS_Connected) then begin RAS.GetPerfStats ; // get performance info if NOT OnlineFlag then begin OnlineFlag := true ; // connections speed not available on NT if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then ConnSpeed.Caption := 'Speed: ' + IntToStr (RAS.StatsConn) + ' bps' ; // dynamic IP addresses if RAS.GetIPAddress = 0 then IPAddr.Caption := RAS.ClientIP + ' > ' + RAS.ServerIP ; end ; // display performance statistics StatXmit.Caption := 'Xmit: ' + IntToStr (RAS.StatsXmit) + ' chars' ; StatRecv.Caption := 'Recv: ' + IntToStr (RAS.StatsRecv) + ' chars' ; end ; end ; end; // this proc waits until a connection is achieved or cancelled procedure TMainForm.doConnectClick(Sender: TObject); begin if ConnList.ItemIndex = -1 then exit ; if CurrConnection <> '' then exit ; // already connected Timer.Enabled := false ; // must stop progress events during connection RAS.EntryName := ConnList.Items [ConnList.ItemIndex]; // Connection name CurrConnection := RAS.EntryName ; // keep it to check later StopFlag := false ; // set if Disconnect button is pressed Status.Panels[1].Text := '' ; Status.Panels[1].Text := CurrConnection + ' - Starting Connection' ; if RAS.AutoConnect <> 0 then // get phone book, start connection begin CurrConnection := '' ; Timer.Enabled := true ; Status.Panels[1].Text := 'Connection Failed - ' + RAS.StatusStr ; beep ; exit ; end ; // need to wait for connection to dial or whatever while (RAS.ConnectState < RASBase) do begin Application.ProcessMessages ; if StopFlag then break ; // see if Disconnect button pressed end ; Timer.Enabled := true ; if (RAS.ConnectState <> RASCS_Connected) or StopFlag then begin Ras.Disconnect; CurrConnection := '' ; StateChanged (self) ; // update panel Status.Panels[1].Text := 'Connection Terminated' ; beep ; exit ; end ; Status.Panels[1].Text := 'Connection Opened OK' ; end; procedure TMainForm.doDisConnClick(Sender: TObject); begin Status.Panels[1].Text := '' ; StopFlag := true ; if NOT Timer.Enabled then exit ; // not while connecting RAS.Disconnect ; // disconnect, returns when done end; procedure TMainForm.doLogonUpdateClick(Sender: TObject); begin Status.Panels[1].Text := '' ; if ConnList.ItemIndex = -1 then exit ; RAS.EntryName := ConnList.Items [ConnList.ItemIndex]; // Connection name RAS.UserName := ConnUser.Text ; RAS.Password := ConnPw.Text ; if RAS.SetDialParams = 0 then Status.Panels[1].Text := 'Connection Updated' else Status.Panels[1].Text := RAS.StatusStr ; end; procedure TMainForm.doExitClick(Sender: TObject); var key: integer ; begin Timer.Enabled := false ; // stop connection checks if RAS.RASConn <> 0 then begin key := MessageDlg ('Close Down Dial-Up Connection?', mtConfirmation, mbYesNoCancel, 0) ; if key = mrCancel then exit ; if key = mrYes then doDisConnClick(Sender) else RAS.LeaveOpen ; // stop destroy closing RAS end ; Application.Terminate ; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin doExitClick (sender) ; Application.Terminate ; end; procedure TMainForm.doCreateConnClick(Sender: TObject); begin Status.Panels[1].Text := '' ; if RAS.CreatePhonebook <> 0 then Status.Panels[1].Text := RAS.StatusStr else begin RAS.GetPhoneBookEntries; // get new list of connections ConnList.Items.Assign (RAS.PhoneBookEntries); // display it if ConnList.Items.Count <> 0 then ConnList.ItemIndex := 0 ; // set first ConnListClick (self) ; // get connection info end ; end; procedure TMainForm.doEditConnClick(Sender: TObject); begin Status.Panels[1].Text := '' ; if ConnList.ItemIndex = -1 then exit ; RAS.EntryName := ConnList.Items [ConnList.ItemIndex]; // Connection name if RAS.EditPhonebook <> 0 then // display Dialog Status.Panels[1].Text := RAS.StatusStr ; end; procedure TMainForm.doDeleteConnClick(Sender: TObject); begin Status.Panels[1].Text := '' ; if ConnList.ItemIndex = -1 then exit ; RAS.EntryName := ConnList.Items [ConnList.ItemIndex]; // Connection name if RAS.DeletePhonebook <> 0 then Status.Panels[1].Text := RAS.StatusStr else begin RAS.GetPhoneBookEntries; // get new list of connections ConnList.Items.Assign (RAS.PhoneBookEntries); // display it if ConnList.Items.Count <> 0 then ConnList.ItemIndex := 0 ; // set first ConnListClick (self) ; // get connection info end ; end; procedure TMainForm.doRenameConnClick(Sender: TObject); var oldname, newname: string ; begin Status.Panels[1].Text := '' ; if ConnList.ItemIndex = -1 then exit ; oldname := ConnList.Items [ConnList.ItemIndex]; // Connection name newname := oldname ; while newname = oldname do begin if NOT InputQuery ('Rename Connection', 'New Connection Name', newname) then exit ; if RAS.ValidateName (newname) <> 0 then begin Status.Panels[1].Text := RAS.StatusStr ; beep ; newname := oldname ; end ; end ; Status.Panels[1].Text := '' ; RAS.EntryName := oldname ; if RAS.RenamePhonebook (newname) <> 0 then Status.Panels[1].Text := RAS.StatusStr else begin RAS.GetPhoneBookEntries; // get new list of connections ConnList.Items.Assign (RAS.PhoneBookEntries); // display it if ConnList.Items.Count <> 0 then ConnList.ItemIndex := 0 ; // set first ConnListClick (self) ; // get connection info end ; end; end.
PROGRAM Maximum; FUNCTION Max2(number_a, number_b: INTEGER): INTEGER; BEGIN IF number_a > number_b THEN BEGIN Max2 := number_a; END ELSE BEGIN Max2 := number_b; END; END; FUNCTION Max3a(a, b, c: INTEGER): INTEGER; VAR max: INTEGER; BEGIN IF a > b THEN BEGIN max := a; END ELSE BEGIN max := b; END; IF c > max THEN BEGIN max := c; END; Max3a := max; END; FUNCTION Max3b(a, b, c: INTEGER): INTEGER; BEGIN Max3b := Max2(Max2(a, b), c); END; BEGIN //WriteLn(Max2(5, 10)); //WriteLn(Max2(500, 50)); //WriteLn(''); WriteLn(Max3a(5, 10, 15)); WriteLn(Max3a(5, 10, 7)); WriteLn(Max3a(15, 10, 8)); WriteLn(Max3a(15, 10, 12)); WriteLn(''); WriteLn(Max3b(5, 10, 15)); WriteLn(Max3b(5, 10, 7)); WriteLn(Max3b(15, 10, 8)); WriteLn(Max3b(15, 10, 12)); END.
unit Extract_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, ShellCtrls, Advanced; type TdlgExtract = class(TForm) BtnOk: TBitBtn; BtnCancel: TBitBtn; MainControl: TPageControl; GeneralSheet: TTabSheet; AdvancedSheet: TTabSheet; cbDestDir: TComboBox; rgUpdateMode: TRadioGroup; Label1: TLabel; DirTree: TShellTreeView; rgExtractMode: TRadioGroup; gbFileTime: TGroupBox; cbUpdateModifyTime: TCheckBox; cbUpdateAccessTime: TCheckBox; rgDeleteArchive: TRadioGroup; procedure DirTreeChange(Sender: TObject; Node: TTreeNode); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var dlgExtract: TdlgExtract; implementation {$R *.dfm} procedure TdlgExtract.DirTreeChange(Sender: TObject; Node: TTreeNode); begin cbDestDir.Text:=DirTree.Path; end; procedure TdlgExtract.FormCreate(Sender: TObject); begin Caption:=ReadFromLanguage('Windows','wndEtract',Caption); GeneralSheet.Caption:=ReadFromLanguage('Tabs','tbGeneral',GeneralSheet.Caption); AdvancedSheet.Caption:=ReadFromLanguage('Tabs','tbAdvanced',AdvancedSheet.Caption); Label1.Caption:=ReadFromLanguage('Labels','lbExtractDir',Label1.Caption); rgUpdateMode.Caption:=ReadFromLanguage('Labels','lbUpdateMode',rgUpdateMode.Caption); rgExtractMode.Caption:=ReadFromLanguage('Labels','lbExtractMode',rgExtractMode.Caption); btnCancel.Caption:=ReadFromLanguage('Buttons','btnCancel',btnCancel.Caption); gbFileTime.Caption:=ReadFromLanguage('Labels','lbFileTime',gbFileTime.Caption); rgDeleteArchive.Caption:=ReadFromLanguage('Labels','lbDeleteArchive',rgDeleteArchive.Caption); cbUpdateModifyTime.Caption:=ReadFromLanguage('Labels','lbUpdateMod',cbUpdateModifyTime.Caption); cbUpdateAccessTime.Caption:=ReadFromLanguage('Labels','lbUpdateAccess',cbUpdateAccessTime.Caption); // rgUpdateMode.Items.Strings[0]:=ReadFromLanguage('Items','itOverwrite',rgUpdateMode.Items.Strings[0]); rgUpdateMode.Items.Strings[1]:=ReadFromLanguage('Items','itSkip',rgUpdateMode.Items.Strings[1]); rgUpdateMode.Items.Strings[2]:=ReadFromLanguage('Items','itOverwritePrompt',rgUpdateMode.Items.Strings[2]); // rgExtractMode.Items.Strings[0]:=ReadFromLanguage('Items','itExtractAll',rgExtractMode.Items.Strings[0]); rgExtractMode.Items.Strings[1]:=ReadFromLanguage('Items','itExtractSelected',rgExtractMode.Items.Strings[1]); // rgDeleteArchive.Items.Strings[0]:=ReadFromLanguage('Items','itNever',rgDeleteArchive.Items.Strings[0]); rgDeleteArchive.Items.Strings[1]:=ReadFromLanguage('Items','itAlways',rgDeleteArchive.Items.Strings[1]); end; end.
unit uFlatBox2DSimulation; interface uses uCustomSimulation, Box2D.Common, Box2D.Collision, Box2D.Dynamics; type TFlatBox2DSimulation = class(TCustomSimulation) private FPositionIterations: integer; FVelocityIterations: integer; procedure SetGravity(const Value: b2Vec2); procedure SetPositionIterations(const Value: integer); procedure SetVelocityIterations(const Value: integer); protected FGravity: b2Vec2; FWorld: b2WorldWrapper; procedure Initialize; override; procedure Step(deltaTime: Double = 1/60); override; procedure Finalize; override; public property Gravity: b2Vec2 read FGravity write SetGravity; property World: b2WorldWrapper read FWorld; property VelocityIterations: integer read FVelocityIterations write SetVelocityIterations; property PositionIterations: integer read FPositionIterations write SetPositionIterations; end; TFlatBox2DSimulationClass = class of TFlatBox2DSimulation; implementation { TFlatBox2DSimulation } procedure TFlatBox2DSimulation.Initialize; begin FVelocityIterations := 6; FPositionIterations := 2; FGravity := b2Vec2.Create(0.0, -10.0); FWorld := b2WorldWrapper.Create(Gravity); end; procedure TFlatBox2DSimulation.Finalize; begin FWorld.Destroy; end; procedure TFlatBox2DSimulation.SetGravity(const Value: b2Vec2); begin FGravity := Value; FWorld.SetGravity(Value); end; procedure TFlatBox2DSimulation.SetPositionIterations(const Value: integer); begin FPositionIterations := Value; end; procedure TFlatBox2DSimulation.SetVelocityIterations(const Value: integer); begin FVelocityIterations := Value; end; procedure TFlatBox2DSimulation.Step(deltaTime: Double); begin FWorld.Step(deltaTime, FVelocityIterations, FPositionIterations); end; end.
unit inventory_unit; { * Author A.Kouznetsov * Rev 1.02 dated 4/6/2015 * Requires CSVdocument.pas http://sourceforge.net/p/lazarus-ccr/svn/2871/tree/components/csvdocument/csvdocument.pas Redistribution and use in source and binary forms, with or without modification, are permitted. 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.} {$mode objfpc}{$H+} // ########################################################################### interface // ########################################################################### uses Classes, SysUtils, Grids, CSVdocument; type { TKicadStock } TKicadStock = class(TStringList) private Doc : TCSVDocument; public FileNames : TStringList; RefNames : TStringList; procedure ToStringGrid(SG : TStringGrid; index : integer); procedure LoadFromFile(const FileName : string); override; constructor Create; destructor Destroy; override; end; // ########################################################################### implementation // ########################################################################### // ################################################## { TKicadStock } // ################################################## // ================================================== // Copy to string grid // ================================================== procedure TKicadStock.ToStringGrid(SG: TStringGrid; index : integer); var i,j, lim : integer; s, fn : string; begin if (index >= 0) and (index < FileNames.Count) then begin fn := FileNames.Strings[index]; Doc.LoadFromFile(fn); // --------------------------------- // Fill headers from row[0] // --------------------------------- lim := Doc.ColCount[0]-1; for j := 0 to lim do begin s := Doc.Cells[j,0]; SG.Columns[j].Title.Caption := s; if j >= SG.ColCount-1 then break; end; // --------------------------------- // Fill grid // --------------------------------- SG.RowCount := Doc.RowCount; lim := Doc.RowCount-1; for i:=1 to lim do begin for j:=0 to SG.ColCount-1 do begin s := Doc.Cells[j,i]; SG.Cells[j,i] := s; end; end; end; end; // ================================================== // Load from file // ================================================== procedure TKicadStock.LoadFromFile(const FileName: string); begin inherited LoadFromFile(FileName); end; // ================================================== // Create // ================================================== constructor TKicadStock.Create; begin FileNames := TStringList.Create; RefNames := TStringList.Create; Doc := TCSVDocument.Create; Doc.Delimiter:=char(9); end; // ================================================== // Destroy // ================================================== destructor TKicadStock.Destroy; begin Doc.Free; FileNames.Free; RefNames.Free; inherited Destroy; end; end.
{ location.pas } program LocationCityAndCountry; const maxId = 2; type location = record id: integer; name_city: string; country_id: integer; end; country = record id: integer; name_country: string; end; fullLocation = record cityName: string; countryName: string; end; cityArray = array [1..maxId] of location; countryArrayId = array[1..maxId] of country; outArray = array [1..maxId] of fullLocation; var i: integer; n: string; c: string; cN: country; f: fullLocation; l: location; ID: integer; countryAr: countryArrayId; cityAr: cityArray; begin for i:= 1 to maxId do begin l.id := i; writeln('Insert city name'); readln(n); l.name_city := n; writeln('Insert country ID'); readln (ID); l.country_id := ID; writeln('Insert country name'); readln(c); cN.name_country := c; writeln(i); cityAr[i].id := l.id; cityAr[i].name_city := l.name_city; cityAr[i].country_id := l.country_id; countryAr[i].id := cN.id; countryAr[i].name_country := cN.name_country; end; for i := 1 to maxId do begin // writeln(cityAr[i].name_city, cityAr[i].country_id); writeln(cityAr[i].name_city,' ', countryAr[i].name_country); end; end. #Pass
unit dxfparseutils; interface uses Classes, SysUtils, dxftypes, dxfparse, dxfclasses; procedure ParseClass(p: TDxfParser; c: TDxfClass); procedure ParseBlockEntity(p: TDxfParser; e: TDxfBlockEntity); procedure ParseBlock(p: TDxfParser; b: TDxfBlock); procedure ParseBlockEnd(p: TDxfParser; b: TDxfBlockEnd); procedure ParsePointDef(p: TDxfParser; var pt: TDxfPoint; const XcodeGroup: Integer; const Def: TDxfPoint); procedure ParsePoint(p: TDxfParser; var pt: TDxfPoint; const XcodeGroup: Integer = CB_X); procedure ParseExtrusionPoint(p: TDxfParser; var pt: TDxfPoint); procedure ParseScale(p: TDxfParser; var pt: TDxfPoint; const XcodeGroup: Integer = CB_X_SCALE); procedure ParseLine(p: TDxfParser; l: TDxfLine); procedure ParseCircle(p: TDxfParser; c: TDxfCircle); procedure ParseSolid(p: TDxfParser; s: TDxfSolid); procedure ParseInsert(p: TDxfParser; i: TDxfInsert); procedure ParsePolyLine(p: TDxfParser; l: TDxfPolyLine); procedure ParseVertex(p: TDxfParser; v: TDxfVertex); procedure ParseEntity(p: TDxfParser; e: TDxfEntity); function ParseEntityFromType(p: TDxfParser; const tp: string): TDxfEntity; // parser must be at 0 / EntityName pair function ParseEntity(p: TDxfParser): TDxfEntity; // parser must be at 0 / EntityName pair procedure ParseVariable(P: TDxfParser; hdr: TDxfHeader); function ParseTableEntryFromType(p: TDxfParser; const tp: string): TDxfTableEntry; procedure ParseAppId(p: TDxfParser; e: TDxfAppIdEntry); procedure ParseBlockRecord(p: TDxfParser; e: TDxfBlockRecordEntry); procedure ParseDimStyle(p: TDxfParser; e: TDxfDimStyleEntry); procedure ParseLayerTableEntry(p: TDxfParser; e: TDxfLayerEntry); procedure ParseLType(p: TDxfParser; e: TDxfLTypeEntry); procedure ParseStyleTableEntry(p: TDxfParser; e: TDxfStyleEntry); procedure ParseUCSTableEntry(p: TDxfParser; e: TDxfUCSEntry); procedure ParseView(p: TDxfParser; e: TDxfViewEntry); procedure ParseVPort(p: TDxfParser; e: TDxfVPortEntry); procedure ParseTableEntry(P: TDxfParser; e: TDxfTableEntry); procedure ParseTable(P: TDxfParser; tbl: TDxfTable); function ParseObjectEntryFromType(p: TDxfParser; const tp: string): TDxfObject; procedure ParseAcDbDictionaryWDFLT(p: TDxfParser; obj: TDxfAcDbDictionaryWDFLT); procedure ParseAcDbPlaceholder(p: TDxfParser; obj: TDxfAcDbPlaceholder); procedure ParseDictionary(p: TDxfParser; obj: TDxfDictionary); procedure ParseDictionaryVar(p: TDxfParser; obj: TDxfDictionaryVar); procedure ParseXRecord(p: TDxfParser; obj: TDxfXRecord); procedure ParsePlotSettings(p: TDxfParser; obj: TDxfPlotSettings); procedure ParseLayout(p: TDxfParser; obj: TDxfLayout); procedure ParseMLineStyle(p: TDxfParser; obj: TDxfMLineStyle); procedure ParseObject(p: TDxfParser; obj: TDxfObject); // used to parse a list of 102... anything ...102 function ParseVarList(p: TDxfParser): TDxfValuesList; procedure ReadFile(const fn: string; dst: TDxfFile); procedure ReadFile(const st: TStream; dst: TDxfFile); procedure ReadFile(p: TDxfParser; dst: TDxfFile); implementation procedure ParseScale(p: TDxfParser; var pt: TDxfPoint; const XcodeGroup: Integer = CB_X_SCALE); begin pt.x := ConsumeFlt(p, XCodeGroup + 0, 0); pt.y := ConsumeFlt(p, XCodeGroup + 1, 0); pt.z := ConsumeFlt(p, XCodeGroup + 2, 0); end; procedure ParsePointDef(p: TDxfParser; var pt: TDxfPoint; const XcodeGroup: Integer; const Def: TDxfPoint); begin pt.x := ConsumeFlt(p, XCodeGroup, def.x); pt.y := ConsumeFlt(p, XCodeGroup + 10, def.y); pt.z := ConsumeFlt(p, XCodeGroup + 20, def.z) end; procedure ParsePoint(p: TDxfParser; var pt: TDxfPoint; const XcodeGroup: Integer = CB_X); begin ParsePointDef(p, pt, XcodeGroup, DefZeroPoint); end; procedure ParseExtrusionPoint(p: TDxfParser; var pt: TDxfPoint); begin ParsePointDef(p, pt, CB_X_EXTRUSION, DefExtrusionPoint); end; procedure ParseBlockEntity(p: TDxfParser; e: TDxfBlockEntity); begin e.Handle := ConsumeStr(p, CB_HANDLE); e.appDefGroup := ''; // todo: collect application defined codes if (p.scanner.CodeGroup = CB_APPDEFNAME) then begin p.Next; // skipping over the initial 102 "{blah" while p.scanner.CodeGroup <> CB_APPDEFNAME do begin // 102 // consumeing initial 102 //e.appDefGroup := e.appDefGroup + p.scanner.ValStr; p.Next; end; p.Next; // skipping over the trailing 102 "}" end; e.Owner := ConsumeStr(p, CB_OWNERHANDLE); e.SubClass := ConsumeStr(p, CB_SUBCLASS); e.SpaceFlag := ConsumeInt(p, CB_SPACEFLAG); e.LayerName := ConsumeStr(p, CB_LAYERNAME); e.Subclass2 := ConsumeStr(p, CB_SUBCLASS); end; procedure ParseBlock(p: TDxfParser; b: TDxfBlock ); begin ParseBlockEntity(p, b); b.BlockName := ConsumeStr(p, CB_NAME); b.BlockFlags := ConsumeInt(p, CB_FLAGS); ParsePoint(p, b.basePoint); b.BlockName2 := ConsumeStr(p, CB_BLOCKNAME); b.XRef := ConsumeStr(p, CB_XREFPATH); b.Descr := ConsumeStr(p, CB_DESCr); end; procedure ParseBlockEnd(p: TDxfParser; b: TDxfBlockEnd); begin ParseBlockEntity(p, b); end; procedure ParseClass(p: TDxfParser; c: TDxfClass); begin c.recName := ConsumeStr(p, CB_DXFRECNAME ); {1 } c.cppName := ConsumeStr(p, CB_CPPNAME ); {2 } c.appName := ConsumeStr(p, CB_APPANME ); {3 } c.ProxyFlags := ConsumeInt(p, CB_PROXYFLAG ); {90 } c.InstCount := ConsumeInt(p, CB_INSTCOUNT ); {91 } c.WasProxy := ConsumeInt(p, CB_WASAPROXY ); {280} c.IsAnEntity := ConsumeInt(p, CB_ISENTITY ); {281} end; procedure ParseEntity(p: TDxfParser; e: TDxfEntity); begin //e.EntityType := ConsumeStr(p, 0); e.Handle := ConsumeStr(p, 5); {appName := ConsumeStr(p, 120); appValues : TDxfValuesList; // 120+custom} {ACAD_Reactors : TDxfValuesList; // 120+330 ACAD_XDict : TDxfValuesList; // 120+360} e.Owner := ConsumeStr(p, 330); e.SubClass := ConsumeStr(p, 100); e.SpaceFlag := ConsumeInt(p, 67); // 67 -- optional!!! (seen on Paper_Source) e.AppTableLayout := ConsumeStr(p, 410); e.LayerName := ConsumeStr(p, 8); e.LineTypeName := ConsumeStr(p, 6, 'BYLAYER'); e.HardPtrId := ConsumeStr(p, 347, 'BYLAYER'); e.ColorNumber := ConsumeInt(p, 62, 256); e.LineWidth := ConsumeInt(p, 370); e.LineScale := ConsumeFlt(p, 48, 1.0); e.isHidden := ConsumeInt(p, 60); e.ProxyBytesCount := ConsumeInt(p, 92); if (e.ProxyBytesCount>0) then begin // e.ProxyGraph := ConsumeInt array of byte; // 310s end; e.Color := ConsumeInt(p, 420); e.ColorName := ConsumeStr(p, 430); e.Transperancy := ConsumeInt(p, 440); e.PlotObj := ConsumeStr(p, 390); e.ShadowMode := ConsumeInt(p, 284); // : string; // 347 // ColorNumber : string; // 62 e.Subclass2 := ConsumeStr(p, 100); end; procedure ParseLine(p: TDxfParser; l: TDxfLine); begin ParseEntity(p, l); l.Thickness := ConsumeFlt(p, CB_THICKNESS); ParsePoint(p, l.StartPoint, CB_X); ParsePoint(p, l.EndPoint, CB_X_ENDPOINT); ParseExtrusionPoint(p, l.Extrusion); end; procedure ParseCircle(p: TDxfParser; c: TDxfCircle); begin ParseEntity(p, c); c.Thickness := ConsumeFlt(p, CB_THICKNESS); ParsePoint(p, c.CenterPoint, CB_X); c.Radius := ConsumeFlt(p, CB_RADIUS); ParseExtrusionPoint(p, c.Extrusion); end; procedure ParseSolid(p: TDxfParser; s: TDxfSolid); begin ParseEntity(p, s); ParsePoint(p, s.Corner1, CB_X0); ParsePoint(p, s.Corner2, CB_X1); ParsePoint(p, s.Corner3, CB_X2); ParsePoint(p, s.Corner4, CB_X3); s.Thickness := ConsumeFlt(p, CB_THICKNESS); ParseExtrusionPoint(p, s.Extrusion); end; procedure ParseInsert(p: TDxfParser; i: TDxfInsert); begin ParseEntity(p, i); i.AttrFlag := ConsumeInt(p, 66); i.BlockName := ConsumeStr(p, 2); ParsePoint(p, i.InsPoint); ParseScale(p, i.Scale); i.Rotation := ConsumeFlt(p, 50); i.ColCount := ConsumeInt(p, 70, 1); i.RowCount := ConsumeInt(p, 71, 1); i.ColSpace := ConsumeFlt(p, 44); i.RowSpace := ConsumeFlt(p, 45); ParseExtrusionPoint(p, i.Extrusion); end; procedure ParsePolyLine(p: TDxfParser; l: TDxfPolyLine); begin ParseEntity(p, l); l.ObsFlag := ConsumeInt(p, 66); ParsePoint(p, l.ElevPoint, CB_X); l.Thickness := ConsumeFlt(p, CB_THICKNESS); l.PolyFlags := ConsumeInt(p, CB_FLAGS); l.StartWidth := ConsumeFlt(p, 40); l.EndWidth := ConsumeFlt(p, 41); l.MCount := ConsumeInt(p, 71); l.NCount := ConsumeInt(p, 72); l.MDensity := ConsumeInt(p, 73); l.NDensity := ConsumeInt(p, 74); l.SurfType := ConsumeInt(p, 75); ParseExtrusionPoint(p, l.Extrusion); end; procedure ParseVertex(p: TDxfParser; v: TDxfVertex); begin ParseEntity(p, v); v.SubClass3 := ConsumeStr(p, 100); ParsePoint(p, v.Location); v.StartWidth := ConsumeFlt(p, 40); v.EndWidth := ConsumeFlt(p, 41); v.Buldge := ConsumeFlt(p, 42); v.Flags := ConsumeInt(p, 70); v.TangentDir := ConsumeFlt(p, 50); v.PolyFace[0] := ConsumeInt(p, 71); v.PolyFace[1] := ConsumeInt(p, 72); v.PolyFace[2] := ConsumeInt(p, 73); v.PolyFace[3] := ConsumeInt(p, 74); v.VertexId := ConsumeInt(p, 91) end; function ParseEntityFromType(p: TDxfParser; const tp: string): TDxfEntity; // parser must be at 0 / EntityName pair var nm : string; begin Result := nil; if tp='' then Exit; nm := upcase(tp); case nm[1] of 'C': if nm = ET_CIRCLE then begin Result := TDxfCircle.Create; ParseCircle(p, TDxfCircle(Result)); end; 'I': if nm = ET_INSERT then begin Result := TDxfInsert.Create; ParseInsert(p, TDxfInsert(Result)); end; 'L': if nm = ET_LINE then begin Result := TDxfLine.Create; ParseLine(p, TDxfLine(Result)); end; 'P': if nm = ET_POLYLINE then begin Result := TDxfPolyLine.Create; ParsePolyLine(p, TDxfPolyLine(Result)); end; 'S': if nm = ET_SOLID then begin Result := TDxfSolid.Create; ParseSolid(p, TDxfSolid(Result)); end; end; end; function ParseEntity(p: TDxfParser): TDxfEntity; // parser must be at 0 / EntityName pair var nm : string; begin if p.scanner.CodeGroup <> CB_CONTROL then begin Result := nil; Exit; end; nm := p.scanner.ValStr; if nm ='' then begin Result := nil; Exit; end; Result := ParseEntityFromType(p, nm); end; procedure ParseVariable(p: TDxfParser; hdr: TDxfHeader); var v : string; begin if not Assigned(p) or not Assigned(hdr) then Exit; v := p.varName; if (v = '') or (length(v)<=2) then Exit; case v[2] of 'A': if v = vACADVER then hdr.acad.Version := ConsumeStr(p, CB_VARVALUE) else if v = vACADMAINTVER then hdr.acad.MaintVer := ConsumeInt(p, CB_VARINT) else if v = vATTMODE then hdr.Base.AttrVisMode := ConsumeInt(p, CB_VARINT) else if v = vAUNITS then hdr.base.AnglesFormat := ConsumeInt(p, CB_VARINT) else if v = vAUPREC then hdr.base.AnglesPrec := ConsumeInt(p, CB_VARINT) else if v = vANGBASE then hdr.base.AngleBase := ConsumeFlt(p, 50) else if v = vANGDIR then hdr.base.isClockWise := ConsumeInt(p, CB_VARINT) ; 'C': if v = vCLAYER then hdr.Sel.Layer := ConsumeStr(p, CB_LAYERNAME) else if v = vCELTYPE then hdr.Sel.EntLineType := ConsumeStr(p, 6) else if v = vCECOLOR then hdr.Sel.EntColor := ConsumeInt(p, 62) else if v = vCELTSCALE then hdr.Sel.EntLineTypeScale := ConsumeFlt(p, CB_VARFLOAT) else if v = vCHAMFERA then hdr.Base.ChamferDist1 := ConsumeFlt(p, CB_VARFLOAT) else if v = vCHAMFERB then hdr.Base.ChamferDist2 := ConsumeFlt(p, CB_VARFLOAT) else if v = vCHAMFERC then hdr.Base.ChamferLen := ConsumeFlt(p, CB_VARFLOAT) else if v = vCHAMFERD then hdr.Base.ChamferAngle := ConsumeFlt(p, CB_VARFLOAT) else if v = vCELWEIGHT then hdr.base.NewObjLineWeight := ConsumeInt (p, 370) else if v = vCEPSNTYPE then hdr.base.PlotStype := ConsumeInt (p, 380) else if v = vCMLSTYLE then hdr.Sel.MultiLineStyle := ConsumeStr (p, 2) else if v = vCMLJUST then hdr.Sel.MultiLineJust := ConsumeInt (p, CB_VARINT) else if v = vCMLSCALE then hdr.Sel.MultiLineScale := ConsumeFlt (p, 40) ; 'D': if v = vDWGCODEPAGE then hdr.base.CodePage := ConsumeStr(p, 3) else if v = vDISPSILH then hdr.Sel.DispSilhMode := ConsumeInt(p, 7) else if v = vDIMSCALE then hdr.Dim.Scale := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMASZ then hdr.Dim.ArrowSize := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMEXO then hdr.Dim.ExtLineOfs := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMDLI then hdr.Dim.DimLineInc := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMRND then hdr.Dim.RoundVal := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMDLE then hdr.Dim.DimLineExt := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMEXE then hdr.Dim.ExtLineExt := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMTP then hdr.Dim.PlusToler := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMTM then hdr.Dim.MinusToler := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMTXT then hdr.Dim.TextHeight := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMCEN then hdr.Dim.CenterSize := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMTSZ then hdr.Dim.TickSize := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMTOL then hdr.Dim.Tolerance := Consumeint(P, CB_VARINT) else if v = vDIMLIM then hdr.Dim.Limits := Consumeint(P, CB_VARINT) else if v = vDIMTIH then hdr.Dim.isTextIns := Consumeint(P, CB_VARINT) else if v = vDIMTOH then hdr.Dim.isTextOut := Consumeint(P, CB_VARINT) else if v = vDIMSE1 then hdr.Dim.isSupExt1 := Consumeint(P, CB_VARINT) else if v = vDIMSE2 then hdr.Dim.isSupExt2 := Consumeint(P, CB_VARINT) else if v = vDIMTAD then hdr.Dim.isTextAbove := Consumeint(P, CB_VARINT) else if v = vDIMZIN then hdr.Dim.SupZeros := Consumeint(P, CB_VARINT) else if v = vDIMBLK then hdr.Dim.ArrowBlock := Consumestr(P, CB_VARVALUE) else if v = vDIMASO then hdr.Dim.isAssocDim := ConsumeInt(P, CB_VARINT) else if v = vDIMSHO then hdr.Dim.isRecompDim := ConsumeInt(P, CB_VARINT) else if v = vDIMPOST then hdr.Dim.Suffix := ConsumeStr(p, CB_VARVALUE) else if v = vDIMAPOST then hdr.Dim.AltSuffix := ConsumeStr(p, CB_VARVALUE) else if v = vDIMALT then hdr.Dim.isUseAltUnit := Consumeint(p, CB_VARINT) else if v = vDIMALTD then hdr.Dim.AltDec := Consumeint(p, CB_VARINT) else if v = vDIMALTF then hdr.Dim.AltScale := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMLFAC then hdr.Dim.LinearScale := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMTOFL then hdr.Dim.isTextOutExt := ConsumeInt(p, CB_VARINT) else if v = vDIMTVP then hdr.Dim.TextVertPos := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMTIX then hdr.Dim.isForceTextIns := ConsumeInt(p, CB_VARINT) else if v = vDIMSOXD then hdr.Dim.isSuppOutExt := ConsumeInt(p, CB_VARINT) else if v = vDIMSAH then hdr.Dim.isUseSepArrow := ConsumeInt(p, CB_VARINT) else if v = vDIMBLK1 then hdr.Dim.ArrowBlock1 := Consumestr(p, CB_VARVALUE) else if v = vDIMBLK2 then hdr.Dim.ArrowBlock2 := Consumestr(p, CB_VARVALUE) else if v = vDIMSTYLE then hdr.Dim.StyleName := Consumestr(p, 2) else if v = vDIMCLRD then hdr.Dim.LineColor := Consumeint(p, CB_VARINT) else if v = vDIMCLRE then hdr.Dim.ExtLineColor := Consumeint(p, CB_VARINT) else if v = vDIMCLRT then hdr.Dim.TextColor := Consumeint(p, CB_VARINT) else if v = vDIMTFAC then hdr.Dim.DispTolerance := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMGAP then hdr.Dim.LineGap := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMJUST then hdr.Dim.HorzTextJust := Consumeint(p, CB_VARINT) else if v = vDIMSD1 then hdr.Dim.isSuppLine1 := ConsumeInt(p, CB_VARINT) else if v = vDIMSD2 then hdr.Dim.isSuppLine2 := ConsumeInt(p, CB_VARINT) else if v = vDIMTOLJ then hdr.Dim.VertJustTol := ConsumeInt(p, CB_VARINT) else if v = vDIMTZIN then hdr.Dim.ZeroSupTol := ConsumeInt(p, CB_VARINT) else if v = vDIMALTZ then hdr.Dim.ZeroSupAltUnitTol := ConsumeInt(p, CB_VARINT) else if v = vDIMALTTZ then hdr.Dim.ZeroSupAltTol := ConsumeInt(p, CB_VARINT) else if v = vDIMUPT then hdr.Dim.isEditCursorText := ConsumeInt(p, CB_VARINT) else if v = vDIMDEC then hdr.Dim.DecPlacesPrim := ConsumeInt(p, CB_VARINT) else if v = vDIMTDEC then hdr.Dim.DecPlacesOther := ConsumeInt(p, CB_VARINT) else if v = vDIMALTU then hdr.Dim.UnitsFormat := ConsumeInt(p, CB_VARINT) else if v = vDIMALTTD then hdr.Dim.DecPlacesAltUnit := ConsumeInt(p, CB_VARINT) else if v = vDIMTXSTY then hdr.Dim.TextStyle := ConsumeStr(p, 7) else if v = vDIMAUNIT then hdr.Dim.AngleFormat := ConsumeInt(p, CB_VARINT) else if v = vDIMADEC then hdr.Dim.AngleDecPlaces := ConsumeInt(p, CB_VARINT) else if v = vDIMALTRND then hdr.Dim.RoundValAlt := ConsumeFlt(p, CB_VARFLOAT) else if v = vDIMAZIN then hdr.Dim.ZeroSupAngUnit := ConsumeInt(p, CB_VARINT) else if v = vDIMDSEP then hdr.Dim.DecSeparator := ConsumeInt(p, CB_VARINT) else if v = vDIMATFIT then hdr.Dim.TextArrowPlace := ConsumeInt(p, CB_VARINT) else if v = vDIMFRAC then hdr.Dim.UnitFrac := ConsumeInt(p, CB_VARINT) else if v = vDIMLDRBLK then hdr.Dim.ArrowBlockLead := ConsumeStr(p, CB_VARVALUE) else if v = vDIMLUNIT then hdr.Dim.Units := ConsumeInt(p, CB_VARINT) else if v = vDIMLWD then hdr.Dim.LineWeight := ConsumeInt(p, CB_VARINT) else if v = vDIMLWE then hdr.Dim.LineWeightExt := ConsumeInt(p, CB_VARINT) else if v = vDIMTMOVE then hdr.Dim.TextMove := ConsumeInt(p, CB_VARINT) ; 'E': if v = vEXTMIN then ParsePoint(p, hdr.Base.ExtLowLeft) else if v = vEXTMAX then ParsePoint(p, hdr.Base.ExtUpRight) else if v = vELEVATION then hdr.Sel.Elev := ConsumeFlt(p, CB_VARFLOAT) else if v = vEXTNAMES then hdr.acad.isExtNames := ConsumeInt(p, 290) else if v = vENDCAPS then hdr.base.LineEndCaps := ConsumeInt(p, 280) ; 'F': if v = vFILLMODE then hdr.Base.isFill := ConsumeInt(p, CB_VARINT) else if v = vFILLETRAD then hdr.Base.FilletRadius := ConsumeFlt(p, CB_VARFLOAT) else if v = vFINGERPRINTGUID then hdr.base.FingerPrintGuid := ConsumeStr(p ,2) ; 'H': if v = vHANDSEED then hdr.Base.NextHandle := ConsumeStr(p, 5) else if v = vHYPERLINKBASE then hdr.base.RelHyperLink := ConsumeStr(p,1) ; 'I': if v = vINSBASE then ParsePoint(p, hdr.Base.InsPoint) else if v = vINSUNITS then hdr.base.DefaultUnits := ConsumeInt(p,CB_VARINT) ; 'J': if v = vJOINSTYLE then hdr.base.LineJointStyle := ConsumeInt(p,280) ; 'L': if v = vLIMMIN then ParsePoint(p, hdr.Base.LimLowLeft) else if v = vLIMMAX then ParsePoint(p, hdr.Base.LimUpRight) else if v = vLTSCALE then hdr.Base.LineTypeScale := ConsumeFlt(p, CB_VARFLOAT) else if v = vLUNITS then hdr.Base.DistFormat := ConsumeInt(p, CB_VARINT) else if v = vLUPREC then hdr.Base.DistPrec := ConsumeInt(p, CB_VARINT) else if v = vLIMCHECK then hdr.Base.isLimCheck := ConsumeInt(p, CB_VARINT) else if v = vLWDISPLAY then hdr.base.isLineShow := ConsumeInt(p,290) ; 'M': if v = vMIRRTEXT then hdr.Base.isMirrText := ConsumeInt(p, CB_VARINT) else if v = vMENU then hdr.Base.MenuName := ConsumeStr(p, CB_VARVALUE) else if v = vMEASUREMENT then hdr.base.MeasureUnits := ConsumeInt(p,CB_VARINT) else if v = vMAXACTVP then hdr.Base.MaxViewPorts := ConsumeInt(p,CB_VARINT) ; 'O': if v = vORTHOMODE then hdr.Base.isOrtho := ConsumeInt(p, CB_VARINT) else if v = vOLESTARTUP then hdr.Base.isOLEStartup := ConsumeInt(p, CB_VARINT) ; 'P': if v = vPUCSBASE then hdr.PUcs.Base := ConsumeStr(p, 2) else if v = vPUCSNAME then hdr.PUcs.Name := ConsumeStr(p, 2) else if v = vPUCSORG then ParsePoint(p, hdr.PUcs.Origin) else if v = vPUCSXDIR then ParsePoint(p, hdr.PUcs.XDir) else if v = vPUCSYDIR then ParsePoint(p, hdr.PUcs.YDir) else if v = vPUCSORTHOREF then hdr.PUcs.OrthoRef := ConsumeStr(p, 2) else if v = vPUCSORTHOVIEW then hdr.PUcs.OrthoView := ConsumeINT(p, CB_VARINT) else if v = vPUCSORGTOP then ParsePoint(p, hdr.PUcs.OriginTop) else if v = vPUCSORGBOTTOM then ParsePoint(p, hdr.PUcs.OriginBottom) else if v = vPUCSORGLEFT then ParsePoint(p, hdr.PUcs.OriginLeft) else if v = vPUCSORGRIGHT then ParsePoint(p, hdr.PUcs.OriginRight) else if v = vPUCSORGFRONT then ParsePoint(p, hdr.PUcs.OriginFront) else if v = vPUCSORGBACK then ParsePoint(p, hdr.PUcs.OriginBack) else if v = vPELEVATION then hdr.Sel.PaperElev := ConsumeFlt(p, CB_VARFLOAT) else if v = vPDMODE then hdr.Base.PtDispMode := ConsumeInt(p, CB_VARINT) else if v = vPDSIZE then hdr.Base.PtDispSize := ConsumeFlt(p, CB_VARFLOAT) else if v = vPLINEWID then hdr.Base.DefPolyWidth := ConsumeFlt(p, CB_VARFLOAT) else if v = vPSVPSCALE then hdr.base.ViewPortScale := ConsumeFlt(p,40) else if v = vPSTYLEMODE then hdr.base.isColorDepmode := ConsumeInt(p,290) else if v = vPROXYGRAPHICS then hdr.base.isProxyImageSave := ConsumeInt(p,CB_VARINT) else if v = vPLINEGEN then hdr.Base.LineTypePatt := ConsumeInt(p,CB_VARINT) else if v = vPSLTSCALE then hdr.Base.PaperLineScaling := ConsumeInt(p,CB_VARINT) else if v = vPINSBASE then ParsePoint(p, hdr.Base.PaperInsPoint) else if v = vPLIMCHECK then hdr.Base.isPaperLimCheck := ConsumeInt(p,CB_VARINT) else if v = vPEXTMIN then ParsePoint(p, hdr.Base.PaperExtLowLeft) else if v = vPEXTMAX then ParsePoint(p, hdr.Base.PaperExtUpRight) else if v = vPLIMMIN then ParsePoint(p, hdr.Base.PaperLimLowLeft) else if v = vPLIMMAX then ParsePoint(p, hdr.Base.PaperLimUpRight) ; 'Q': if v = vQTEXTMODE then hdr.Base.isQText := ConsumeInt(p, CB_VARINT); 'R': if v = vREGENMODE then hdr.Base.isRegen := ConsumeInt(p, CB_VARINT); 'S': if v = vSKETCHINC then hdr.Base.SketchInc := ConsumeFlt(p, CB_VARFLOAT) else if v = vSKPOLY then hdr.Base.isSketchPoly := Consumeint(p, CB_VARINT) else if v = vSPLINETYPE then hdr.Base.SplineCurvType := Consumeint(p, CB_VARINT) else if v = vSPLINESEGS then hdr.Base.LineSegments := Consumeint(p, CB_VARINT) else if v = vSURFTAB1 then hdr.Base.MeshCount1 := Consumeint(p, CB_VARINT) else if v = vSURFTAB2 then hdr.Base.MeshCount2 := Consumeint(p, CB_VARINT) else if v = vSURFTYPE then hdr.Base.SurfType := Consumeint(p, CB_VARINT) else if v = vSURFU then hdr.Base.SurfDensityM := Consumeint(p, CB_VARINT) else if v = vSURFV then hdr.Base.SurfDensityN := Consumeint(p, CB_VARINT) else if v = vSHADEDGE then hdr.Base.ShadeEdge := ConsumeInt(p,CB_VARINT) else if v = vSHADEDIF then hdr.Base.ShadeDiffuse := ConsumeInt(p,CB_VARINT) else if v = vSTYLESHEET then hdr.Base.StyleSheet := ConsumeStr(p, CB_VARVALUE) ; 'T': if v = vTEXTSIZE then hdr.Base.TextHeight := ConsumeFlt(p, CB_VARFLOAT) else if v = vTRACEWID then hdr.Base.TraceWidth := ConsumeFlt(p, CB_VARFLOAT) else if v = vTEXTSTYLE then hdr.Sel.TextStyle := ConsumeStr(p, 7) else if v = vTHICKNESS then hdr.Sel.Thickness := ConsumeFlt(p, CB_VARFLOAT) else if v = vTDCREATE then hdr.Time.CreateTimeLocal := ConsumeFlt(p, CB_VARFLOAT) else if v = vTDUCREATE then hdr.Time.CreateTimeUniv := ConsumeFlt(p, CB_VARFLOAT) else if v = vTDUPDATE then hdr.Time.UpdateTimeLocal := ConsumeFlt(p, CB_VARFLOAT) else if v = vTDUUPDATE then hdr.Time.UpdateTimeUniv := ConsumeFlt(p, CB_VARFLOAT) else if v = vTDINDWG then hdr.Time.TotalTime := ConsumeFlt(p, CB_VARFLOAT) else if v = vTDUSRTIMER then hdr.Time.ElasedTime := ConsumeFlt(p, CB_VARFLOAT) else if v = vTREEDEPTH then hdr.Base.SpaceTreeDepth := ConsumeInt(p,CB_VARINT) else if v = vTILEMODE then hdr.Base.isTileMode := ConsumeInt(p,CB_VARINT) ; 'U': if v = vUSERI1 then hdr.User.I1 := ConsumeInt(p, CB_VARINT) else if v = vUSERI2 then hdr.User.I2 := ConsumeInt(p, CB_VARINT) else if v = vUSERI3 then hdr.User.I3 := ConsumeInt(p, CB_VARINT) else if v = vUSERI4 then hdr.User.I4 := ConsumeInt(p, CB_VARINT) else if v = vUSERI5 then hdr.User.I5 := ConsumeInt(p, CB_VARINT) else if v = vUSERR1 then hdr.User.R1 := ConsumeFlt(p, CB_VARFLOAT) else if v = vUSERR2 then hdr.User.R2 := ConsumeFlt(p, CB_VARFLOAT) else if v = vUSERR3 then hdr.User.R3 := ConsumeFlt(p, CB_VARFLOAT) else if v = vUSERR4 then hdr.User.R4 := ConsumeFlt(p, CB_VARFLOAT) else if v = vUSERR5 then hdr.User.R5 := ConsumeFlt(p, CB_VARFLOAT) else if v = vUSRTIMER then hdr.Time.isTimerOn := ConsumeInt(p, CB_VARINT) else if v = vUNITMODE then hdr.Base.UnitMode := ConsumeInt(p,CB_VARINT) else if v = vUCSBASE then hdr.Ucs.Base := ConsumeStr(p, 2) else if v = vUCSNAME then hdr.Ucs.Name := ConsumeStr(p, 2) else if v = vUCSORG then ParsePoint(p, hdr.Ucs.Origin) else if v = vUCSXDIR then ParsePoint(p, hdr.Ucs.XDir) else if v = vUCSYDIR then ParsePoint(p, hdr.Ucs.YDir) else if v = vUCSORTHOREF then hdr.Ucs.OrthoRef := ConsumeStr(p, 2) else if v = vUCSORTHOVIEW then hdr.Ucs.OrthoView := ConsumeINT(p, CB_VARINT) else if v = vUCSORGTOP then ParsePoint(p, hdr.Ucs.OriginTop) else if v = vUCSORGBOTTOM then ParsePoint(p, hdr.Ucs.OriginBottom) else if v = vUCSORGLEFT then ParsePoint(p, hdr.Ucs.OriginLeft) else if v = vUCSORGRIGHT then ParsePoint(p, hdr.Ucs.OriginRight) else if v = vUCSORGFRONT then ParsePoint(p, hdr.Ucs.OriginFront) else if v = vUCSORGBACK then ParsePoint(p, hdr.Ucs.OriginBack) ; 'V': if v = vVERSIONGUID then hdr.base.VersionGuild := ConsumeStr(p,2) else if v = vVISRETAIN then hdr.Base.isRetainXRefVis := ConsumeInt(p,CB_VARINT) ; 'W': if v = vWORLDVIEW then hdr.Base.isWorldView := ConsumeInt(p,CB_VARINT) ; 'X': if v = vXEDIT then hdr.base.isInPlaceEditin := ConsumeInt(p, 290) ; end; end; procedure ParseTableEntry(p: TDxfParser; e: TDxfTableEntry); begin //e.EntityType := ConsumeStr(p, CB_CONTROL); e.Handle := ConsumeStr(p, CB_HANDLE); // it's either OR, never together if (e.Handle ='') then e.Handle := ConsumeStr(p, CB_DIMHANDLE); e.Owner := ConsumeStr(p, CB_OWNERHANDLE); e.SubClass := ConsumeStr(p, CB_SUBCLASS); end; procedure ParseAppId(p: TDxfParser; e: TDxfAppIdEntry); begin ParseTableEntry(p, e); e.SubClass2 := ConsumeStr(p, CB_SUBCLASS); e.AppData := ConsumeStr(p, CB_NAME); e.Flags := ConsumeInt(p, CB_VARINT); end; procedure ParseBlockRecord(p: TDxfParser; e: TDxfBlockRecordEntry); begin ParseTableEntry(p, e); e.SubClass2 := ConsumeStr(p, CB_SUBCLASS); e.BlockName := ConsumeStr(p, CB_NAME); e.LayoutId := ConsumeStr(p, 340); e.InsertUnit := ConsumeInt(p, CB_VARINT); e.isExplodable := ConsumeInt(p, 280); e.isScalable := ConsumeInt(p, 281); e.PreviewBin := ConsumeStr(p, 310); e.XDataApp := ConsumeStr(p, 1001); end; procedure ParseDimStyle(p: TDxfParser; e: TDxfDimStyleEntry); begin ParseTableEntry(p, e); while p.scanner.CodeGroup<>0 do begin case p.scanner.CodeGroup of CB_SUBCLASS: e.SubClass2 := ConsumeStr(p, CB_SUBCLASS); CB_NAME: e.Dim.StyleName := ConsumeStr(p, CB_NAME); CB_VARINT: e.Flags := ConsumeInt(p, CB_VARINT); 3: e.Dim.Suffix := ConsumeStr(p, 3); // 3 DIMPOST 4: e.Dim.AltSuffix := ConsumeStr(p, 4); // 4 DIMAPOST 5: e.Dim.ArrowBlock := ConsumeStr(p, 5); // 5 DIMBLK (obsolete, now object ID) 6: e.Dim.ArrowBlock1 := ConsumeStr(p, 6); // 6 DIMBLK1 (obsolete, now object ID) 7: e.Dim.ArrowBlock2 := ConsumeStr(p, 7); // 7 DIMBLK2 (obsolete, now object ID) 40: e.Dim.Scale := ConsumeFlt(p, 40); // 40 DIMSCALE 41: e.Dim.ArrowSize := ConsumeFlt(p, 41); // 41 DIMASZ 42: e.Dim.ExtLineOfs := ConsumeFlt(p, 42); // 42 DIMEXO 43: e.Dim.DimLineInc := ConsumeFlt(p, 43); // 43 DIMDLI 44: e.Dim.ExtLineExt := ConsumeFlt(p, 44); // 44 DIMEXE 45: e.Dim.RoundVal := ConsumeFlt(p, 45); // 45 DIMRND 46: e.Dim.DimLineExt := ConsumeFlt(p, 46); // 46 DIMDLE 47: e.Dim.PlusToler := ConsumeFlt(p, 47); // 47 DIMTP 48: e.Dim.MinusToler := ConsumeFlt(p, 48); // 48 DIMTM 140: e.Dim.TextHeight := ConsumeFlt(p, 140); // 140 DIMTXT 141: e.Dim.CenterSize := ConsumeFlt(p, 141); // 141 DIMCEN 142: e.Dim.TickSize := ConsumeFlt(p, 142); // 142 DIMTSZ 143: e.Dim.AltScale := ConsumeFlt(p, 143); // 143 DIMALTF 144: e.Dim.LinearScale := ConsumeFlt(p, 144); // 144 DIMLFAC 145: e.Dim.TextVertPos := ConsumeFlt(p, 145); // 145 DIMTVP 146: e.Dim.DispTolerance := ConsumeFlt(p, 146); // 146 DIMTFAC 147: e.Dim.LineGap := ConsumeFlt(p, 147); // 147 DIMGAP 148: e.Dim.RoundValAlt := ConsumeFlt(p, 148); // 148 DIMALTRND 71: e.Dim.Tolerance := ConsumeInt(p, 71); // 71 DIMTOL 72: e.Dim.Limits := ConsumeInt(p, 72); // 72 DIMLIM 73: e.Dim.isTextIns := ConsumeInt(p, 73); // 73 DIMTIH 74: e.Dim.isTextOut := ConsumeInt(p, 74); // 74 DIMTOH 75: e.Dim.isSupExt1 := ConsumeInt(p, 75); // 75 DIMSE1 76: e.Dim.isSupExt2 := ConsumeInt(p, 76); // 76 DIMSE2 77: e.Dim.isTextAbove := ConsumeInt(p, 77); // 77 DIMTAD 78: e.Dim.SupZeros := ConsumeInt(p, 78); // 78 DIMZIN 79: e.Dim.ZeroSupAngUnit := ConsumeInt(p, 79); // 79 DIMAZIN 170: e.Dim.isUseAltUnit := ConsumeInt(p, 170); // 170 DIMALT 171: e.Dim.AltDec := ConsumeInt(p, 171); // 171 DIMALTD 172: e.Dim.isTextOutExt := ConsumeInt(p, 172); // 172 DIMTOFL 173: e.Dim.isUseSepArrow := ConsumeInt(p, 173); // 173 DIMSAH 174: e.Dim.isForceTextIns := ConsumeInt(p, 174); // 174 DIMTIX 175: e.Dim.isSuppOutExt := ConsumeInt(p, 175); // 175 DIMSOXD 176: e.Dim.LineColor := ConsumeInt(p, 176); // 176 DIMCLRD 177: e.Dim.ExtLineColor := ConsumeInt(p, 177); // 177 DIMCLRE 178: e.Dim.TextColor := ConsumeInt(p, 178); // 178 DIMCLRT 179: e.Dim.AngleDecPlaces := ConsumeInt(p, 179); // 179 DIMADEC 270: e.Dim.__Units := ConsumeInt(p, 270); // 270 DIMUNIT (obsolete, now use DIMLUNIT AND DIMFRAC) 271: e.Dim.DecPlacesPrim := ConsumeInt(p, 271); // 271 DIMDEC 272: e.Dim.DecPlacesOther := ConsumeInt(p, 272); // 272 DIMTDEC 273: e.Dim.UnitsFormat := ConsumeInt(p, 273); // 273 DIMALTU 274: e.Dim.DecPlacesAltUnit := ConsumeInt(p, 274); // 274 DIMALTTD 275: e.Dim.AngleFormat := ConsumeInt(p, 275); // 275 DIMAUNIT 276: e.Dim.UnitFrac := ConsumeInt(p, 276); // 276 DIMFRAC 277: e.Dim.Units := ConsumeInt(p, 277); // 277 DIMLUNIT 278: e.Dim.DecSeparator := ConsumeInt(p, 278); // 278 DIMDSEP 279: e.Dim.TextMove := ConsumeInt(p, 279); // 279 DIMTMOVE 280: e.Dim.HorzTextJust := ConsumeInt(p, 280); // 280 DIMJUST 281: e.Dim.isSuppLine1 := ConsumeInt(p, 281); // 281 DIMSD1 282: e.Dim.isSuppLine2 := ConsumeInt(p, 282); // 282 DIMSD2 283: e.Dim.VertJustTol := ConsumeInt(p, 283); // 283 DIMTOLJ 284: e.Dim.ZeroSupTol := ConsumeInt(p, 284); // 284 DIMTZIN 285: e.Dim.ZeroSupAltUnitTol := ConsumeInt(p, 285); // 285 DIMALTZ 286: e.Dim.ZeroSupAltTol := ConsumeInt(p, 286); // 286 DIMALTTZ 287: e.Dim.__TextArrowPlace := ConsumeInt(p, 287); // 287 DIMFIT (obsolete, now use DIMATFIT and DIMTMOVE) 288: e.Dim.isEditCursorText := ConsumeInt(p, 288); // 288 DIMUPT 289: e.Dim.TextArrowPlace := ConsumeInt(p, 289); // 289 DIMATFIT 340: e.Dim.TextStyle := ConsumeStr(p, 340); // 340 DIMTXSTY (handle of referenced STYLE) 341: e.Dim.ArrowBlockLead := ConsumeStr(p, 341); // 341 DIMLDRBLK (handle of referenced BLOCK) 342: e.Dim.ArrowBlockId := ConsumeStr(p, 342); // DIMBLK (handle of referenced BLOCK) 343: e.Dim.ArrowBlockId1 := ConsumeStr(p, 343); // DIMBLK1 (handle of referenced BLOCK) 344: e.Dim.ArrowBlockId2 := ConsumeStr(p, 344); // DIMBLK2 (handle of referenced BLOCK) 371: e.Dim.LineWeight := ConsumeInt(p, 371); // DIMLWD (lineweight enum value) 372: e.Dim.LineWeightExt := ConsumeInt(p, 372); // DIMLWE (lineweight enum value) else p.Next; end; end; end; procedure ParseLayerTableEntry(p: TDxfParser; e: TDxfLayerEntry); begin ParseTableEntry(p, e); e.SubClass2 := ConsumeStr(p, 100); e.LayerName := ConsumeStr(p, 2); e.Flags := ConsumeInt(p, 70); e.ColorNum := ConsumeInt(p, 62); e.LineType := ConsumeStr(p, 6); e.isPlotting := ConsumeInt(p, 290); e.Lineweight := ConsumeInt(p, 370); e.PlotStyleID := ConsumeStr(p, 390); e.MatObjID := ConsumeStr(p, 347); end; procedure ParseLType(p: TDxfParser; e: TDxfLTypeEntry); begin ParseTableEntry(p, e); e.SubClass2 := ConsumeStr(p, 100); e.LineType := ConsumeStr(p, 2); e.Flags := ConsumeInt(p, 70); e.Descr := ConsumeStr(p, 3); e.AlignCode := ConsumeInt(p, 72); e.LineTypeElems := ConsumeInt(p, 73); e.TotalPatLen := ConsumeFlt(p, 40); e.Len := ConsumeFlt(p, 49); e.Flags2 := ConsumeInt(p, 74); e.ShapeNum := ConsumeInt(p, 75); e.StyleObjId := ConsumeStr(p, 340); SetLength(e.ScaleVal, 1); SetLength(e.RotateVal, 1); SetLength(e.XOfs, 1); SetLength(e.YOfs, 1); e.ScaleVal[0] := ConsumeFlt(p, 46); e.RotateVal[0] := ConsumeFlt(p, 50); e.XOfs[0] := ConsumeFlt(p, 44); e.YOfs[0] := ConsumeFlt(p, 45); e.TextStr := ConsumeStr(p, 9) end; procedure ParseStyleTableEntry(p: TDxfParser; e: TDxfStyleEntry); begin ParseTableEntry(p, e); e.SubClass2 := ConsumeStr(p, 100); e.StyleName := ConsumeStr(p, 2); e.Flags := ConsumeInt(p, 70); e.FixedHeight := ConsumeFlt(p, 40); e.WidthFactor := ConsumeFlt(p, 41); e.Angle := ConsumeFlt(p, 50); e.TextFlags := ConsumeInt(p, 71); e.LastHeight := ConsumeFlt(p, 42); e.FontName := ConsumeStr(p, 3); e.BigFontName := ConsumeStr(p, 4); e.FullFont := ConsumeStr(p, 1071); end; procedure ParseUCSTableEntry(p: TDxfParser; e: TDxfUCSEntry); begin ParseTableEntry(p, e); e.SubClass2 := ConsumeStr(p, 100); e.UCSName := ConsumeStr(p, 2); e.Flags := ConsumeInt(p, 70); ParsePoint(p, e.Origin, 10); ParsePoint(p, e.XDir, 11); ParsePoint(p, e.YDir, 12); e.Zero := ConsumeInt(p, 79); e.Elev := ConsumeFlt(p, 146); e.BaseUCS := ConsumeStr(p, 346); e.OrthType := ConsumeInt(p, 71); ParsePoint(p, e.UCSRelOfs, 13); end; procedure ParseView(p: TDxfParser; e: TDxfViewEntry); begin ParseTableEntry(p, e); e.SubClass2 := ConsumeStr(p, 100); e.ViewName := ConsumeStr(p, 2); e.Flags := ConsumeInt(p, 70); e.Height := ConsumeFlt(p, 40); ParsePoint(p, e.CenterPoint, 10); e.Width := ConsumeFlt(p, 41); ParsePoint(p, e.ViewDir, 11); ParsePoint(p, e.TargetPoint, 12); e.LensLen := ConsumeFlt(p, 42); e.FontClipOfs := ConsumeFlt(p, 43); e.BackClipOfs := ConsumeFlt(p, 44); e.TwistAngle := ConsumeFlt(p, 50); e.ViewMode := ConsumeInt(p, 71); e.RenderMode := ConsumeInt(p, 281); e.isUcsAssoc := ConsumeInt(p, 72); e.isCameraPlot:= ConsumeInt(p, 73); e.BackObjId := ConsumeStr(p, 332); e.LiveSectId := ConsumeStr(p, 334); e.StyleId := ConsumeStr(p, 348); e.OwnerId := ConsumeStr(p, 361); // The following codes appear only if code 72 is set to 1. if e.isUcsAssoc <> 0 then begin ParsePoint(p, e.UCSOrig , 110); ParsePoint(p, e.UCSXAxis , 111); ParsePoint(p, e.UCSYAxis , 112); e.OrthType := ConsumeInt(p, 79); e.UCSElev := ConsumeFlt(p, 146); e.UCSID := ConsumeStr(p, 345); e.UCSBaseID := ConsumeStr(p, 346); end; end; procedure ParseVPort(p: TDxfParser; e: TDxfVPortEntry); var c70: integer; begin ParseTableEntry(p, e); c70:=0; while p.token in [prTableAttr, prTableEntryAttr] do begin case p.scanner.CodeGroup of 100: e.SubClass2 := ConsumeStr(p, 100); 2: e.ViewName := ConsumeStr(p, 2); 70: begin case c70 of 0: e.Flags := ConsumeInt(p, 70); 1: e.PerspFlag := ConsumeInt(p, 70); else p.Next; end; inc(c70); end; 10: ParsePoint(p, e.LeftLow , 10); 11: ParsePoint(p, e.UpRight , 11); 12: ParsePoint(p, e.ViewCenter , 12); 13: ParsePoint(p, e.SnapBase , 13); 14: ParsePoint(p, e.SnapSpace , 14); 15: ParsePoint(p, e.GridSpace , 15); 16: ParsePoint(p, e.ViewDir , 16); 17: ParsePoint(p, e.ViewTarget , 17); 40: e._40 := ConsumeFlt(p, 40); 41: e._41 := ConsumeFlt(p, 41); 42: e.LensLen := ConsumeFlt(p, 42); 43: e.FrontClipOfs := ConsumeFlt(p, 43); 44: e.BackClipOfs := ConsumeFlt(p, 44); 45: e.Height := ConsumeFlt(p, 45); 50: e.RotateAngle := ConsumeFlt(p, 50); 51: e.TwistAngle := ConsumeFlt(p, 51); 72: e.CircleSides := ConsumeInt(p, 72); 331: e.FrozeLayerId := ConsumeStr(p, 331); 441: e.FrozeLayerId := ConsumeStr(p, 441); 1: e.PlotStyle := ConsumeStr(p, 1); 281: e.RenderMode := ConsumeInt(p, 281); 71: e.ViewMode := ConsumeInt(p, 71); 74: e.UCSICON := ConsumeInt(p, 74); 110: ParsePoint(p, e.UCSOrigin, 110); 111: ParsePoint(p, e.UCSXAxis , 111); 112: ParsePoint(p, e.UCSYAxis , 112); 345: e.UCSId := ConsumeStr(p, 345); 346: e.UCSBaseId := ConsumeStr(p, 346); 79: e.OrthType := ConsumeInt(p, 79); 146: e.Elevation := ConsumeFlt(p, 146); 170: e.PlotShade := ConsumeInt(p, 170); 61: e.GridLines := ConsumeInt(p, 61); 332: e.BackObjId := ConsumeStr(p, 332); 333: e.ShadePlotId := ConsumeStr(p, 333); 348: e.VisualStyleId := ConsumeStr(p, 348); 292: e.isDefLight := ConsumeInt(p, 292); 282: e.DefLightType := ConsumeInt(p, 282); 141: e.Brightness := ConsumeFlt(p, 141); 142: e.Contract := ConsumeFlt(p, 142); 63: e.Color1 := ConsumeInt(p, 63); 421: e.Color2 := ConsumeInt(p, 421); 431: e.Color3 := ConsumeInt(p, 431); else p.Next; end; end; end; function ParseTableEntryFromType(p: TDxfParser; const tp: string): TDxfTableEntry; var nm : string; begin Result := nil; if tp='' then Exit; nm := upcase(tp); case nm[1] of 'A': if nm = TE_APPID then begin Result := TDxfAppIdEntry.Create; ParseAppId(p, TDxfAppIdEntry(Result)); end; 'B': if nm = TE_BLOCK_RECORD then begin Result := TDxfBlockRecordEntry.Create; ParseBlockRecord(p, TDxfBlockRecordEntry(Result)); end; 'D': if nm = TE_DIMSTYLE then begin Result := TDxfDimStyleEntry.Create; ParseDimStyle(p, TDxfDimStyleEntry(Result)); end; 'L': if nm = TE_LAYER then begin Result := TDxfLayerEntry.Create; ParseLayerTableEntry(p, TDxfLayerEntry(Result)) end else if nm = TE_LTYPE then begin Result := TDxfLTypeEntry.Create; ParseLType(p, TDxfLTypeEntry(Result)) end; 'S': if nm = TE_STYLE then begin Result := TDxfStyleEntry.Create; ParseStyleTableEntry(p, TDxfStyleEntry(Result)); end; 'U': if nm = TE_UCS then begin Result := TDxfUCSEntry.Create; ParseUCSTableEntry(p, TDxfUCSEntry(Result)); end; 'V': if nm = TE_VIEW then begin Result := TDxfViewEntry.Create; ParseView(p, TDxfViewEntry(Result)); end else if nm = TE_VPORT then begin Result := TDxfVPortEntry.Create; ParseVPort(p, TDxfVPortEntry(Result)); end; end; if Assigned(Result) and (Result.EntryType='') then Result.EntryType := tp; end; procedure ParseTable(P: TDxfParser; tbl: TDxfTable); begin tbl.Name := ConsumeStr(p, CB_NAME); tbl.Handle := ConsumeStr(p, CB_HANDLE); tbl.Owner := ConsumeStr(p, CB_OWNERHANDLE); tbl.SubClass := ConsumeStr(p, CB_SUBCLASS); tbl.MaxNumber := ConsumeInt(p, CB_VARINT); // DIMSTYLE only tbl.SubClass2 := ConsumeStr(p, CB_SUBCLASS); tbl.IntVal2 := ConsumeInt(p, 71); tbl.Owner2 := ConsumeStr(p, 340); end; procedure ParseAcDbDictionaryWDFLT(p: TDxfParser; obj: TDxfAcDbDictionaryWDFLT); var id : string; owner : string; begin ParseObject(p, obj); obj.SubClass2 := ConsumeStr(p, CB_SUBCLASS); obj.CloneFlag := ConsumeInt(p, 281); while p.scanner.CodeGroup = CB_DICT_ENTRYNAME do begin id := ConsumeStr(p, CB_DICT_ENTRYNAME); owner := ConsumeStr(p, CB_DICT_ENTRYOWNER); obj.AddEntry(id, owner); end; obj.SubClass3 := ConsumeStr(p, CB_SUBCLASS); obj.DefaultID := ConsumeStr(p, 340); end; procedure ParseAcDbPlaceholder(p: TDxfParser; obj: TDxfAcDbPlaceholder); begin ParseObject(p, obj); end; procedure ParseDictionary(p: TDxfParser; obj: TDxfDictionary); var id : string; owner : string; begin ParseObject(p, obj); obj.SubClass2 := ConsumeStr(p, CB_SUBCLASS); obj.isHardOwner := ConsumeInt(p, 280); obj.CloneFlag := ConsumeInt(p, 281); while p.scanner.CodeGroup = CB_DICT_ENTRYNAME do begin id := ConsumeStr(p, CB_DICT_ENTRYNAME); owner := ConsumeStr(p, CB_DICT_ENTRYOWNER); if owner = '' then owner := ConsumeStr(p, 360); // possible obj.AddEntry(id, owner); end; end; procedure ParseDictionaryVar(p: TDxfParser; obj: TDxfDictionaryVar); begin ParseObject(p, obj); obj.SubClass2 := ConsumeStr(p, CB_SUBCLASS); obj.SchemaNum := ConsumeInt(p, 280); obj.Value := ConsumeStr(p, 1); end; procedure ParseTableStyle(p: TDxfParser; obj: TDxfTableStyle); var c : TDxfTableCell; c280: integer; begin c := nil; c280 := 0; ParseObject(p, obj); while p.scanner.CodeGroup <> 0 do begin case p.scanner.CodeGroup of CB_SUBCLASS: obj.SubClass2 := ConsumeStr(p, CB_SUBCLASS); 3: obj.Descr := ConsumeStr(p, 3); 70: obj.FlowDir := ConsumeInt(p, 70); 71: obj.Flags := ConsumeInt(p, 71); 40: obj.HorzMargin := ConsumeFlt(p, 40); 41: obj.VertMargin := ConsumeFlt(p, 41); 280: begin if c280 = 0 then obj.VerNum := ConsumeInt(p, 280) else if c280 = 1 then obj.isTitleSupp := ConsumeInt(p, 280); inc(c280); end; 281: obj.isColHeadSupp := ConsumeInt(p, 281); 7: begin c := obj.AddCell; c.StyleName := ConsumeStr(p, 7); end; 140: if Assigned(c) then c.Height := ConsumeFlt(p, 140) else p.Next; 170: if Assigned(c) then c.Align := ConsumeInt(p, 170) else p.Next; 62: if Assigned(c) then c.Color := ConsumeInt(p, 62) else p.Next; 63: if Assigned(c) then c.FillColor := ConsumeInt(p, 63) else p.Next; 283: if Assigned(c) then c.isUseFillColor := ConsumeInt(p, 283) else p.Next; 90: if Assigned(c) then c.CellDataType := ConsumeInt(p, 90) else p.Next; 91: if Assigned(c) then c.CellUnit := ConsumeInt(p, 91) else p.Next; 274: if Assigned(c) then c.BordType1 := ConsumeInt(p, 274) else p.Next; 275: if Assigned(c) then c.BordType2 := ConsumeInt(p, 275) else p.Next; 276: if Assigned(c) then c.BordType3 := ConsumeInt(p, 276) else p.Next; 277: if Assigned(c) then c.BordType4 := ConsumeInt(p, 277) else p.Next; 278: if Assigned(c) then c.BordType5 := ConsumeInt(p, 278) else p.Next; 279: if Assigned(c) then c.BordType6 := ConsumeInt(p, 279) else p.Next; 284: if Assigned(c) then c.isBordVis1 := ConsumeInt(p, 284) else p.Next; 285: if Assigned(c) then c.isBordVis2 := ConsumeInt(p, 285) else p.Next; 286: if Assigned(c) then c.isBordVis3 := ConsumeInt(p, 286) else p.Next; 287: if Assigned(c) then c.isBordVis4 := ConsumeInt(p, 287) else p.Next; 288: if Assigned(c) then c.isBordVis5 := ConsumeInt(p, 288) else p.Next; 289: if Assigned(c) then c.isBordVis6 := ConsumeInt(p, 289) else p.Next; 64: if Assigned(c) then c.BordColor1 := ConsumeInt(p, 64) else p.Next; 65: if Assigned(c) then c.BordColor2 := ConsumeInt(p, 65) else p.Next; 66: if Assigned(c) then c.BordColor3 := ConsumeInt(p, 66) else p.Next; 67: if Assigned(c) then c.BordColor4 := ConsumeInt(p, 67) else p.Next; 68: if Assigned(c) then c.BordColor5 := ConsumeInt(p, 68) else p.Next; 69: if Assigned(c) then c.BordColor6 := ConsumeInt(p, 69) else p.Next; else p.Next; end; end; end; procedure ScannerToVarList(sc: TDxfScanner; dst: TDxfValuesList); begin case DxfDataType(sc.CodeGroup) of dtInt16, dtInt32: dst.AddInt(sc.CodeGroup, sc.ValInt); dtInt64: dst.AddInt(sc.CodeGroup, sc.ValInt64); dtDouble: dst.AddFloat(sc.CodeGroup, sc.ValFloat); else dst.AddStr(sc.CodeGroup, sc.ValStr); end; end; procedure ParseXRecord(p: TDxfParser; obj: TDxfXRecord); begin ParseObject(p, obj); obj.SubClass2 := ConsumeStr(p, CB_SUBCLASS); obj.CloneFlag := ConsumeInt(p, 280); while (p.scanner.CodeGroup <> 0) do begin ScannerToVarList(p.Scanner, obj.XRec); p.Next; end; end; procedure AssignList(obj: TDxfObject; l :TDxfValuesList); var old : TDxfValuesList; begin if not assigned(obj) or not assigned(l) then Exit; old := nil; if l.Name = GROUPLIST_REACTORS then begin old := obj.Reactors; obj.Reactors := l; end else if l.Name = GROUPLIST_XDICTIONARY then begin old := obj.XDict; obj.XDict := l; end else begin old := obj.AppCodes; obj.AppCodes := l; end; old.Free; end; procedure ParseObject(p: TDxfParser; obj: TDxfObject); var l : TDxfValuesList; begin obj.Handle := ConsumeStr(p, CB_HANDLE); l:=ParseVarList(p); if Assigned(l) then AssignList(obj, l); l:=ParseVarList(p); if Assigned(l) then AssignList(obj, l); l:=ParseVarList(p); if Assigned(l) then AssignList(obj, l); obj.Owner := ConsumeStr(p, CB_OWNERHANDLE); end; function ParseObjectEntryFromType(p: TDxfParser; const tp: string): TDxfObject; var nm : string; begin Result := nil; if tp='' then Exit; nm := upcase(tp); case nm[1] of 'A': if nm = OT_ACDBDICTIONARYWDFLT then begin Result := TDxfAcDbDictionaryWDFLT.Create; ParseAcDbDictionaryWDFLT(p, TDxfAcDbDictionaryWDFLT(Result)); end else if nm = OT_ACDBPLACEHOLDER then begin Result := TDxfAcDbPlaceholder.Create; ParseAcDbPlaceholder(p, TDxfAcDbPlaceholder(Result)); end; 'D': if nm = OT_DICTIONARY then begin Result := TDxfDictionary.Create; ParseDictionary(p, TDxfDictionary(Result)); end else if nm = OT_DICTIONARYVAR then begin Result := TDxfDictionaryVar.Create; ParseDictionaryVar(p, TDxfDictionaryVar(Result)); end; 'L': if nm = OT_LAYOUT then begin Result := TDxfLayout.Create; ParseLayout(p, TDxfLayout(Result)); end; 'M': if nm = OT_MLINESTYLE then begin Result := TDxfMLineStyle.Create; ParseMLineStyle(p, TDxfMLineStyle(Result)); end; 'T': if nm = OT_TABLESTYLE then begin Result := TDxfTableStyle.Create; ParseTableStyle(p, TDxfTableStyle(Result)); end; 'X': if nm = OT_XRECORD then begin Result := TDxfXRecord.Create; ParseXRecord(p, TDxfXRecord(Result)); end; end; if Assigned(Result) and (Result.ObjectType='') then Result.ObjectType := tp; end; procedure ParsePlotSettings(p: TDxfParser; obj: TDxfPlotSettings); var i100 : integer; begin ParseObject(p, obj); i100:=0; while p.scanner.CodeGroup<>0 do begin case p.scanner.CodeGroup of 100: begin if i100 > 0 then break else obj.SubClass2 := Consumestr(p, 100); inc(i100); end; 1: obj.PageName := Consumestr(p, 1); 2: obj.PrinterName := Consumestr(p, 2); 4: obj.PaperSize := Consumestr(p, 4); 6: obj.PlotViewName := Consumestr(p, 6); 40: obj.MarginLeftMm := ConsumeFlt(p, 40); 41: obj.MarginBottomMm := ConsumeFlt(p, 41); 42: obj.MarginRightMm := ConsumeFlt(p, 42); 43: obj.MarginTopMm := ConsumeFlt(p, 43); 44: obj.WidthMm := ConsumeFlt(p, 44); 45: obj.HeightMm := ConsumeFlt(p, 45); 46: obj.OffsetX := ConsumeFlt(p, 46); 47: obj.OffsetY := ConsumeFlt(p, 47); 48: obj.PlotX := ConsumeFlt(p, 48); 49: obj.PlotY := ConsumeFlt(p, 49); 140: obj.PlotX2 := ConsumeFlt(p, 140); 141: obj.PlotY2 := ConsumeFlt(p, 141); 142: obj.Numerator := ConsumeFlt(p, 142); 143: obj.Denominator := ConsumeFlt(p, 143); 70: obj.Flags := Consumeint(p, 70); 72: obj.PlotUnits := Consumeint(p, 72); 73: obj.PlotRotation := Consumeint(p, 73); 74: obj.PlotType := Consumeint(p, 74); 7: obj.StyleSheet := ConsumeStr(p, 7); 75: obj.StdScale := Consumeint(p, 75); 76: obj.ShadePlotMode := Consumeint(p, 76); 77: obj.ShadePlotRes := Consumeint(p, 77); 78: obj.ShadePlotDPI := Consumeint(p, 78); 147: obj.ViewScale := ConsumeFlt(p, 147); 148: obj.PaperImgOrigX := ConsumeFlt(p, 148); 149: obj.PaperImgOrigY := ConsumeFlt(p, 149); 333: obj.ShadePlotID := Consumestr(p, 333); else p.Next; end; end; end; procedure ParseLayout(p: TDxfParser; obj: TDxfLayout); begin ParsePlotSettings(p, obj); obj.SubClass3 := ConsumeStr(p, 100); obj.LayoutName := ConsumeStr(p, 1); obj.LayoutFlags := ConsumeInt(p, 70); obj.TabOrder := ConsumeInt(p, 71); ParsePoint(p, obj.MinLim , 10); ParsePoint(p, obj.MaxLim , 11); ParsePoint(p, obj.InsBase , 12); ParsePoint(p, obj.ExtMin , 14); ParsePoint(p, obj.ExtMax , 15); obj.Elevation := ConsumeFlt(p, 146); ParsePoint(p, obj.UCSOrig , 13); ParsePoint(p, obj.UCSXAxis, 16); ParsePoint(p, obj.UCSYAxis, 17); obj.OrthoTypes := ConsumeInt(p, 76); obj.PaperId := ConsumeStr(p, 330); obj.LastVPortId := ConsumeStr(p, 331); obj.UcsId := ConsumeStr(p, 345); obj.UcsOrthoId := ConsumeStr(p, 346); obj.ShadePlotId3 := ConsumeStr(p, 333); end; procedure ParseMLineStyle(p: TDxfParser; obj: TDxfMLineStyle); var e : TDxfMLineStyleEntry; begin ParseObject(p, obj); obj.SubClass2 := Consumestr(p, 100); obj.StyleName := Consumestr(p, 2); obj.Flags := ConsumeInt(p, 70); obj.Descr := ConsumeStr(p, 3); obj.FillColor := ConsumeInt(p, 62); obj.StAngle := ConsumeFlt(p, 51); obj.EndAngle := ConsumeFlt(p, 52); obj.NumElems := ConsumeInt(p, 71); e:=nil; while p.scanner.CodeGroup <> 0 do begin case p.scanner.CodeGroup of 49: begin e:=obj.AddEntry; e.Offset := ConsumeFlt(p, 49); end; 62: if Assigned(e) then e.Color := ConsumeInt(p, 62) else p.Next; 6: if Assigned(e) then e.LineType := ConsumeStr(p, 6, 'BYLAYER') else p.Next; else p.Next; end end; end; function ParseVarList(p: TDxfParser): TDxfValuesList; begin Result := nil; if not Assigned(p) then Exit; if p.scanner.CodeGroup <> CB_GROUPSTART then Exit; Result := TDxfValuesList.Create; Result.Name := p.scanner.ValStr; p.Next; if p.scanner.CodeGroup=CB_GROUPSTART then Exit; while p.scanner.CodeGroup<>CB_GROUPSTART do begin ScannerToVarList(p.scanner, Result); p.Next; end; p.Next; end; procedure ReadFile(const fn: string; dst: TDxfFile); var f : TFileStream; begin f := TFileStream.Create(fn, fmOpenRead or fmShareDenyNone); try ReadFile(f, dst); finally f.Free; end; end; procedure ReadFile(const st: TStream; dst: TDxfFile); var sc : TDxfScanner; p : TDxfParser; begin sc := DxfAllocScanner(st, false); p := TDxfParser.Create; try p.scanner := sc; ReadFile(p, dst); finally p.Free; sc.Free; end; end; procedure ReadFile(p: TDxfParser; dst: TDxfFile); var res : TDxfParseToken; done : boolean; tbl : TDxfTable; te : TDxfTableEntry; ent : TDxfEntity; //ln, ofs: integer; b : TDxfFileBlock; dummyEnd : TDxfBlockEnd; cls : TDxfClass; obj : TDxfObject; begin if not Assigned(p) or not Assigned(dst) then Exit; b:=nil; done := false; dummyEnd := TDxfBlockEnd.Create; try while not done do begin res := p.Next; case res of prVarName: begin ParseVariable(p, dst.header); end; prTableStart: begin tbl := dst.AddTable; ParseTable(p, tbl) end; prTableEntry: if Assigned(tbl) then begin te := ParseTableEntryFromType(p, tbl.Name); tbl.AddItem(te); end; prTableEnd: begin tbl := nil; end; prBlockStart: begin b := dst.AddBlock; ParseBlock(p, b); end; prBlockEnd: begin if b<>nil then ParseBlockEnd(p, b._blockEnd) else ParseBlockEnd(p, dummyEnd); b := nil; end; prEntityStart, prEntityInBlock: begin ent := ParseEntityFromType(p, p.EntityType); if Assigned(b) then b.AddEntity(ent) else dst.AddEntity(ent); end; prClassStart: begin cls := dst.AddClass; ParseClass(p, cls); end; prObjStart: begin obj := ParseObjectEntryFromType(p, p.EntityType); if Assigned(obj) then dst.AddObject(obj); end; prSecEnd: begin tbl := nil; ent := nil; end; prError: begin done := true; end; prEof: begin done := true; end; else // prEntityAttr - we should never get this one! end; end; finally dummyEnd.Free; end; end; end.
unit UTransEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TTransparentMemo = class(TMemo) private { Private declarations } procedure WMPaint(var Message: TWMPaint); message WM_PAINT; protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; public { Public declarations } BGBitmap : TBitmap; BGX,BGY,BGW,BGH : integer; // for test TestCanvas : TCanvas; x1,y1,x2,y2 : integer; // end test ABrush : HBrush; constructor Create(AOwner:TComponent);override; destructor Destroy; override; procedure PaintBackGround(DC : HDC); published { Published declarations } end; procedure Register; implementation uses myUtils; procedure Register; begin RegisterComponents('users', [TTransparentMemo]); end; { TTransparentEdit } constructor TTransparentMemo.Create(AOwner: TComponent); var LogBrush : TLogBrush; begin inherited Create(AOwner); ControlStyle := ControlStyle - [csOpaque]; autoselect := false; LogBrush.lbStyle := BS_NULL; ABrush := CreateBrushIndirect(LogBrush); end; procedure TTransparentMemo.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT; Params.Style := Params.Style and not WS_CLIPSIBLINGS; Params.WindowClass.hbrBackground:=ABrush; end; destructor TTransparentMemo.Destroy; begin deleteObject(ABrush); inherited destroy; end; procedure TTransparentMemo.PaintBackGround(DC: HDC); var oldPalette : HPalette; begin try oldPalette:=SelectPalette(DC,BGBitmap.Palette,true); RealizePalette(DC); //copy Background bitmap to DC StretchBlt(DC,0,0,ClientRect.Right, ClientRect.Bottom, BGBitmap.Canvas.handle,BGX,BGY,BGW,BGH,SRCCOPY); finally SelectPalette(DC,OldPalette,false); end; end; (* procedure TTransparentMemo.WMPaint(var Message: TWMPaint); var DC, MemDC,saveDC: HDC; MemBitmap, OldBitmap: HBITMAP; NoDC : boolean; begin NoDC := Message.DC=0; SaveDC := Message.DC; DC := GetDC(0); MemBitmap := CreateCompatibleBitmap(DC, ClientRect.Right, ClientRect.Bottom); ReleaseDC(0, DC); if NoDC then //DC := BeginPaint(Handle, PS) DC := GetDC(handle) else DC:=SaveDC; MemDC := CreateCompatibleDC(0); OldBitmap := SelectObject(MemDC, MemBitmap); try // paint to MemDC BitBlt(MemDC,0,0,ClientRect.Right, ClientRect.Bottom,0,0,0,Whiteness); Message.DC := MemDC; defaultHandler(Message); Message.DC := 0; PaintBackGround(DC); { // for test BitBlt(TestCanvas.handle,x1,y2,width,height,BGBitmap.Canvas.handle,0,0,SRCCOPY); BitBlt(TestCanvas.handle,x1,y1,width,height,DC,0,0,SRCCOPY); BitBlt(TestCanvas.handle,x2,y2,width,height,MemDC,0,0,SRCCOPY); // end test } StretchBltTransparent(DC,0,0,width,height,MemDC,0,0,width,height,0,color); ValidateRect(handle,nil); if NoDC then //EndPaint(Handle, PS); releaseDC(handle,DC); finally SelectObject(MemDC, OldBitmap); DeleteDC(MemDC); DeleteObject(MemBitmap); end; end; *) (* procedure TTransparentMemo.WMPaint(var Message: TWMPaint); var DC, MemDC,saveDC: HDC; MemBitmap, OldBitmap: HBITMAP; NoDC : boolean; OldBrush : HBrush; begin inherited; { NoDC := Message.DC=0; SaveDC := Message.DC; if NoDC then //DC := BeginPaint(Handle, PS) DC := GetDC(handle) else DC:=SaveDC; try PaintBackGround(DC); setBKMode(DC,transparent); oldBrush := SelectObject(DC,ABrush); Message.DC := DC; defaultHandler(Message); Message.DC := 0; ValidateRect(handle,nil); if NoDC then //EndPaint(Handle, PS); finally SelectObject(DC,OldBrush); releaseDC(handle,DC); end;} end; *) end.
unit uUSBNotifier; interface uses Windows,Messages,Classes,DBT; type TUSBNotifyEvent=procedure(Sender:TObject; dwEvent:longword; sUSBName:AnsiString)of object; const GUID_DEVINTERFACE_COMPORT:TGUID='{86E0D1E0-8089-11D0-9CE4-08003E301F73}'; //'{4d36e978-e325-11ce-bfc1-08002be10318}'; GUID_DEVINTERFACE_USB_DEVICE:TGUID='{A5DCBF10-6530-11D2-901F-00C04FB951ED}'; type TUSBnotifier=class(TComponent) private hWindow:HWND; hNotify:HDEVNOTIFY; fOnUSBNotify:TUSBNotifyEvent; procedure SetOnUSBNotify(const ne:TUSBNotifyEvent); procedure USBRegister; procedure USBUnregister; protected procedure WMDeviceChange(var M:TMessage); virtual; procedure WndProc(var M:TMessage); virtual; public constructor Create(aOwner:TComponent); override; destructor Destroy; override; published property OnUSBNotify:TUSBNotifyEvent read FOnUSBNotify write SetOnUSBNotify; end; function GetComPortName(sUSBInfo:AnsiString):AnsiString; implementation uses Registry; {$BOOLEVAL OFF} {$RANGECHECKS OFF} {$OVERFLOWCHECKS OFF} function GetComPortName(sUSBInfo:AnsiString):AnsiString; var r:TRegistry; s:AnsiString; ndx:integer; begin r:=nil; try try r:=TRegistry.Create; r.RootKey:=HKEY_LOCAL_MACHINE; s:=sUSBInfo; ndx:=Pos('USB',s); if ndx<>0then Delete(s,1,ndx+2); if r.OpenKeyReadOnly('System\ControlSet001\Enum\USB')then begin ndx:=Pos('#',s); if ndx<>0then begin Delete(s,1,ndx); ndx:=Pos('#',s); if ndx<>0then begin if r.OpenKeyReadOnly(Copy(s,1,ndx-1))then begin Delete(s,1,ndx); ndx:=Pos('#',s); if ndx<>0then begin r.OpenKeyReadOnly(Copy(s,1,ndx-1)); // if r.ValueExists('FriendlyName')then s:=r.ReadString('FriendlyName'); // FriendlyName - дополнительная информация по порту if r.OpenKeyReadOnly('Device Parameters')then if r.ValueExists('PortName')then begin s:=r.ReadString('SymbolicName'); sUSBInfo:=r.ReadString('PortName'); end; end; end; end; end; end; finally r.Free; end; except end; Result:=sUSBInfo; end; { TUSBnotifier } constructor TUSBnotifier.Create(aOwner:TComponent); begin inherited Create(aOwner); hWindow:=AllocateHWnd(WndProc); USBRegister; end; destructor TUSBnotifier.Destroy; begin USBUnregister; DeallocateHWnd(hWindow); inherited Destroy; end; procedure TUSBnotifier.SetOnUSBNotify(const ne:TUSBNotifyEvent); begin fOnUSBNotify:=ne; end; procedure TUSBnotifier.USBregister; var dbi:DEV_BROADCAST_DEVICEINTERFACE_A; begin ZeroMemory(@dbi,SizeOf(dbi)); dbi.dbcc_size:=SizeOf(dbi); dbi.dbcc_devicetype:=DBT_DEVTYP_DEVICEINTERFACE; dbi.dbcc_reserved:=0; dbi.dbcc_classguid:=GUID_DEVINTERFACE_USB_DEVICE; hNotify:=RegisterDeviceNotification(hWindow,@dbi,DEVICE_NOTIFY_WINDOW_HANDLE); end; procedure TUSBnotifier.USBunregister; begin UnregisterDeviceNotification(hNotify); end; procedure TUSBnotifier.WMDeviceChange(var M:TMessage); var lpdb:PDevBroadcastHdr; Device:PDevBroadcastDeviceInterface; sName:AnsiString; i:integer; begin if(M.WParam=DBT_DEVICEARRIVAL)or(M.WParam=DBT_DEVICEREMOVECOMPLETE) or(M.WParam=DBT_DEVICEREMOVEPENDING)or(M.WParam=DBT_DEVICEQUERYREMOVE)or(M.WParam=DBT_DEVICEQUERYREMOVEFAILED)then begin lpdb:=PDevBroadcastHdr(M.LParam); if lpdb.dbch_devicetype<>DBT_DEVTYP_DEVICEINTERFACE then exit; Device:=PDevBroadcastDeviceInterface(M.LParam); i:=lpdb.dbch_size-SizeOf(lpdb^)+1; SetLength(sName,i); CopyMemory(@sName[1],@Device^.dbcc_name[0],i); if@fOnUSBNotify<>nil then fOnUSBNotify(Self,M.WParam,sName); end; end; procedure TUSBnotifier.WndProc(var M:TMessage); begin if(M.Msg=WM_DEVICECHANGE)then WMDeviceChange(M)else M.Result:=DefWindowProc(hWindow,M.Msg,M.WParam,M.LParam); end; end.
unit tadconjunto; interface const max = 101; type elemento = longint; conjunto = array [0..MAX+1] of elemento; (* Uma vez tque o tipo elemento eh longint, a posicao zero do vetor (c[0]) contera o tamanho do vetor, se os elementos fossem de outro tipo isto poderia ser feito. Os elementos propriamente ditos iniciam na posicao 1 e terminam na posicao MAX. A ultima posicao (c[MAX+1]) eh utilizada como sentinela em algumas funcoes. *) procedure inicializar_conjunto(var c: conjunto); function eh_vazio(var c: conjunto):boolean; function cardinalidade (var c: conjunto): longint; function pertence (x: elemento; var c: conjunto): boolean; procedure uniao (var c1, c2, uni: conjunto); procedure intersecao (var c1, c2, intersec: conjunto); function contido (var c1, c2: conjunto): boolean; procedure inserir (x: elemento; var c: conjunto); procedure remover (x: elemento; var c: conjunto); procedure ler_conjunto (var c: conjunto); (*----------------------------TAD Conjunto -------------------------------*) implementation procedure inicializar_conjunto (var c: conjunto); (* cria as estruturas necessarias para o tipo conjunto. custo: constante. *) begin c[0]:= 0; end; function eh_vazio (var c: conjunto): boolean; (* retorna true se o conjunto c eh vazio. custo: constante. *) begin eh_vazio:= c[0] = 0; end; function cardinalidade (var c: conjunto): longint; (* retorna a cardinalidade do conjunto c custo: constante. *) begin cardinalidade:= c[0]; end; function pertence (x: elemento; var c: conjunto): boolean; (* retorna true se x pertence ao conjunto c e false caso contrario. como a estrutura esta ordenada é feita uma busca binária. custo: proporcial ao logaritmo do tamanho do conjunto, ja que ha ordenacao. *) var ini, fim, meio: longint; begin ini:= 1; fim:= c[0]; meio:= (ini + fim) div 2; while (ini <= fim) and (x <> c[meio]) do begin if x < c[meio] then fim:= meio - 1 else ini:= meio + 1; meio:= (ini + fim) div 2; end; if x = c[meio] then pertence:= true else pertence:= false; end; procedure uniao (var c1, c2, uni: conjunto); (* obtem a uniao dos conjuntos c1 e c2. Lembrar que eles estao ordenados. custo: proporcial a soma dos tamanhos dos vetores (tem que percorrer os dois). *) var i,j,k,l: longint; begin i:= 1; j:= 1; k:= 0; while (i <= c1[0]) and (j <= c2[0]) do begin if c1[i] < c2[j] then begin k:= k + 1; uni[k]:= c1[i]; i:= i + 1; end else if c1[i] > c2[j] then begin k:= k + 1; uni[k]:= c2[j]; j:= j + 1; end else (* descarta um dos repetidos *) begin k:= k + 1; uni[k]:= c1[i]; i:= i + 1; j:= j + 1; end; end; (* while *) (* acrescenta o que sobrou do maior conjunto *) for l:= i to c1[0] do begin k:= k + 1; uni[k]:= c1[i]; i:= i + 1; end; for l:= j to c2[0] do begin k:= k + 1; uni[k]:= c2[j]; j:= j + 1; end; uni[0]:= k; end; procedure intersecao (var c1, c2, intersec: conjunto); (* obtem a intersecao dos conjuntos c1 e c2. Lembrar que eles estao ordenados. custo: proporcional ao tamanho do vetor c1. obs.: voce pode depois modificar para que o custo seja proporcional ao tamanho do menor conjunto. *) var i,j,k: longint; begin i:= 1; j:= 1; k:= 0; while (i <= c1[0]) and (j <= c2[0]) do if c1[i] < c2[j] then i:= i + 1 else if c1[i] > c2[j] then j:= j + 1 else (* elemento nos dois conjuntos *) begin k:= k + 1; intersec[k]:= c1[i]; i:= i + 1; j:= j + 1; end; intersec[0]:= k; end; function contido (var c1, c2: conjunto): boolean; (* retorna true se o conjunto c1 esta contido no conjunto c2 e false caso contrario. custo: proporcional ao tamanho do conjunto c1. *) var i,j: longint; ok: boolean; begin if c1[0] > c2[0] then contido:= false else begin ok:= true; i:= 1; j:= 1; while (i <= c1[0]) and (j <= c2[0] ) and ok do if c1[i] < c2[j] then ok:= false else if c1[i] > c2[j] then j:= j + 1 else begin i:= i + 1; j:= j + 1; end; if not ok then contido:= false else if i > c1[0] then contido:= true else contido:= false; end; end; procedure inserir (x: elemento; var c: conjunto); (* insere o elemento x no conjunto c, mantem os elementos ordenados. custo: para garantir o conjunto ordenado, proporcional ao tamanho do conjunto. *) var i: longint; begin if not pertence (x,c) then begin i:= c[0]; while (i >= 1) and (x <= c[i]) do begin c[i+1]:= c[i]; i:= i - 1; end; (* agora pode inserir x *) c[i+1]:= x; c[0]:= c[0] + 1; end; end; procedure remover (x: elemento; var c: conjunto); (* remove o elemento x do conjunto c. usa uma sentinela na posicao posterior a ultima. custo: para garantir o conjunto ordenado, proporcional ao tamanho do conjunto. *) var i, indice: longint; begin (* primeiro acha a posicao do elemento *) indice:= 1; c[c[0]+1]:= x; while x <> c[indice] do indice:= indice + 1; if indice < c[0] + 1 then (* achou o elemento *) begin (* compahttp://www.inf.ufpr.br/carmem/ci055/aulas/tad-conjunto/conjunto.pascta o vetor *) for i:= indice to c[0]-1 do c[i]:= c[i+1]; c[0]:= c[0] - 1; end; end; procedure ler_conjunto (var c: conjunto); (* cria um conjunto, a posicao zero contem o tamanho dele. custo: proporcional ao tamanho do conjunto.http://www.inf.ufpr.br/carmem/ci055/aulas/tad-conjunto/conjunto.pas *) var i: longint; x: elemento; begin read (x); i:= 0; while x <> 0 do begin inserir (x,c); i:= i + 1; read (x); end; end; procedure imprimir_conjunto (var c: conjunto); (* imprime um conjunto. custo: proporcional ao tamanho do conjunto *) var i: longint; begin for i:= 1 to c[0]-1 do write (c[i],' '); writeln (c[c[0]]); end; end.
unit AqDrop.Core.Manager.Intf; interface type /// ------------------------------------------------------------------------------------------------------------------ /// <summary> /// EN-US: /// Interface that must be implemented by object manager classes. /// PT-BR: /// Interface que deve ser implementada por classes gerenciadoras. /// </summary> /// ------------------------------------------------------------------------------------------------------------------ IAqManager<T: class> = interface ['{82232845-E30C-4411-8B73-4234E1898564}'] procedure _AddDependent(const pDependent: T); procedure _RemoveDependent(const pDependent: T); end; implementation end.
unit TableViewFilterFormFilterBuilderUnit; interface uses SysUtils, Classes, TableViewFilterFormUnit, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPC3Painter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Grids; type TFilterCondition = ( fcEqual, fcNotEqual, fcLess, fcGreater, fcLessEqual, fcGreaterEqual, fcLike, fcNotLike, fcBetween, fcNotBetween ); TTableViewFilterFormFilterBuilder = class abstract (TObject) strict protected FTableViewFilterForm: TTableViewFilterForm; public destructor Destroy; override; constructor Create(ATableViewFilterForm: TTableViewFilterForm); procedure AddFilterExpression( AItem: TObject; const ACondition: TFilterCondition; const AValue ); virtual; abstract; procedure ApplyFilter; virtual; abstract; end; implementation { TTableViewFilterFormFilterBuilder } constructor TTableViewFilterFormFilterBuilder.Create( ATableViewFilterForm: TTableViewFilterForm); begin inherited Create; FTableViewFilterForm := ATableViewFilterForm; end; destructor TTableViewFilterFormFilterBuilder.Destroy; begin inherited; end; end.
unit zLSP; interface uses Windows, SysUtils, winsock, registry, Variants, Classes, zSharedFunctions, RxVerInf, zutil, zHTMLTemplate; const LSP_Reg_Key = 'SYSTEM\CurrentControlSet\Services\WinSock2\Parameters'; type // Информация о пространсте имен TNameSpaceInfo = record Found : boolean; // Признак того, что соотв. CLSID найден IsCorrect : boolean; // Признак корректности NSProviderId : TGUID; // CLSID провайдера dwNameSpace : DWord; fActive : Boolean; // Признак активности dwVersion : DWord; // Версия lpszIdentifier : String; // Текстовый идентификатор BinFileName : string; // Имя исполняемого файла BinFileExists : boolean; // Признак существования файла на диске BinFileInfo : string; // Информация о исполняемом файле RegKey : string; // Ключ реестра CheckResults : integer; // Результаты проверки end; // Информация о протоколе TProtocolInfo = record Found : boolean; IsCorrect : boolean; lpszIdentifier : String; BinFileName : string; BinFileExists : boolean; BinFileInfo : string; RegKey : string; CheckResults : integer; // Результаты проверки end; // Прототипы функций TWSAEnumNameSpaceProviders = function (lpdwBufferLength : LPDWORD; lpNameSpaceBuffer : pointer) : LongInt; stdcall; TWSCUnInstallNameSpace = function(NSProviderId : PGUID) : LongInt; stdcall; TWSCEnableNSProvider = function(NSProviderId : PGUID; Enabled : bool) : LongInt; stdcall; TWSAEnumProtocols = function (lpiProtocols: PInt; lpProtocolBuffer: pointer; lpdwBufferLength: PDWORD): longint; stdcall; TWSARemoveServiceClass = function(NSProviderId : PGUID) : LongInt; stdcall; TWSCDeinstallProvider = function(NSProviderId : pointer; ErrorCode : PLongInt) : LongInt; stdcall; // Класс для работы с LSP TLSPManager = class private FCurrent_NameSpace_Catalog: string; FCurrent_Protocol_Catalog: string; protected hLib : THandle; WSAEnumNameSpaceProviders : TWSAEnumNameSpaceProviders; WSARemoveServiceClass : TWSARemoveServiceClass; WSCDeinstallProvider : TWSCDeinstallProvider; WSAEnumProtocols : TWSAEnumProtocols; WSCUnInstallNameSpace : TWSCUnInstallNameSpace; WSCEnableNSProvider : TWSCEnableNSProvider; function RefreshCatalogNames : boolean; function RefreshNameSpaceListReg : boolean; function RefreshNameSpaceListWS : boolean; function RefreshProtocolInfo : boolean; // Поиск имени файла по реестру function SearchLSPFileByRegistry(ANameSpaceCatalog: string; AGUID: TGUID): string; public // Списки пространств имен NameSpaceListReg : array of TNameSpaceInfo; // По данным реестра NameSpaceListWS : array of TNameSpaceInfo; // По данным WinSock // Списки протоколов ProtocolListReg : array of TProtocolInfo; // По данным реестра constructor Create; // Обновление списков function Refresh : boolean; function SetNameSpaceActive(ID : integer; NewStatus : boolean) : boolean; // **** Удаление пространства имен **** // По GUID function DeleteNameSpaceByGUID(AGUID : TGUID) : boolean; // По имени function DeleteNameSpaceByName(AName : string) : boolean; // По имени DLL файла function DeleteNameSpaceByBinaryName(AName : string; ANameCompare : boolean) : boolean; // Сортировка по имени ключа function SortNameSpaceRegList : boolean; // Перенумерация ключей, устранение пропусков в нумерации, корректура кол-ва провайдеров function RenumberNameSpace : boolean; // Автоматическое восстановление function AutoRepairNameSpace : boolean; // **** Удаление протокола **** // По GUID function DeleteProtocolByID(ID : integer) : boolean; // По имени function DeleteProtocolByName(AName : string) : boolean; // По имени DLL файла function DeleteProtocolByBinaryName(AName : string; ANameCompare : boolean) : boolean; // Сортировка по имени ключа function SortProtocolRegList : boolean; // Перенумерация ключей, устранение пропусков в нумерации, корректура кол-ва провайдеров function RenumberProtocol : boolean; // Автоматическое восстановление function AutoRepairProtocol : boolean; // **** Диагностика и полное автовосстановление **** // Поиск ошибок function SearchErrors(AList : TStrings) : integer; // Создание HTML отчета function CreateHTMLReport(ALines : TStrings; HideGoodFiles: boolean) : integer; function FullAutoRepair(ABackUpPath : string) : boolean; destructor Destroy; override; property Current_NameSpace_Catalog : string read FCurrent_NameSpace_Catalog; property Current_Protocol_Catalog : string read FCurrent_Protocol_Catalog; end; implementation uses zTranslate; const MAX_PROTOCOL_CHAIN = 7; WSAPROTOCOL_LEN = 255; type LPINT = ^longint; // Описание LPS TWSANameSpaceInfo = packed record NSProviderId : TGUID; dwNameSpace : DWord; fActive : bool; dwVersion : DWord; lpszIdentifier : LPSTR; end; TWSAProtocolChain = record ChainLen: Integer; // the length of the chain, // length = 0 means layered protocol, // length = 1 means base protocol, // length > 1 means protocol chain ChainEntries: Array[0..MAX_PROTOCOL_CHAIN-1] of LongInt; // a list of dwCatalogEntryIds end; TWSAProtocol_InfoA = record dwServiceFlags1: LongInt; dwServiceFlags2: LongInt; dwServiceFlags3: LongInt; dwServiceFlags4: LongInt; dwProviderFlags: LongInt; ProviderId: TGUID; dwCatalogEntryId: LongInt; ProtocolChain: TWSAProtocolChain; iVersion: Integer; iAddressFamily: Integer; iMaxSockAddr: Integer; iMinSockAddr: Integer; iSocketType: Integer; iProtocol: Integer; iProtocolMaxOffset: Integer; iNetworkByteOrder: Integer; iSecurityScheme: Integer; dwMessageSize: LongInt; dwProviderReserved: LongInt; szProtocol: Array[0..WSAPROTOCOL_LEN+1-1] of Char; end; TProtocolPackedCatalogItem = packed record BinFileName : array[0..$FF] of char; Unc1 : array[0..$77] of char; ProtocolName : array[0..$FF] of char; Unc2 : array[0..2000] of char; end; { TLSPManager } constructor TLSPManager.Create; var WSAData : TWSAData; begin // Очистка таблиц NameSpaceListWS := nil; NameSpaceListReg := nil; ProtocolListReg := nil; WSAEnumNameSpaceProviders := nil; // Попытка загрузки библиотеки hLib := LoadLibrary('ws2_32.dll'); // Инициализация Winsock WSAStartup($0202, WSAData); // Поиск необходимых функций if hLib <> NULL then begin WSAEnumNameSpaceProviders := GetProcAddress(hLib, 'WSAEnumNameSpaceProvidersA'); WSARemoveServiceClass := GetProcAddress(hLib, 'WSARemoveServiceClass'); WSCDeinstallProvider := GetProcAddress(hLib, 'WSCDeinstallProvider'); WSCUnInstallNameSpace := GetProcAddress(hLib, 'WSCUnInstallNameSpace'); WSAEnumProtocols := GetProcAddress(hLib, 'WSAEnumProtocolsA'); WSCEnableNSProvider := GetProcAddress(hLib, 'WSCEnableNSProvider'); end; // Определение текущих каталогов в реестре RefreshCatalogNames; end; destructor TLSPManager.Destroy; begin NameSpaceListWS := nil; NameSpaceListReg := nil; ProtocolListReg := nil; inherited; end; function TLSPManager.SearchLSPFileByRegistry(ANameSpaceCatalog : string; AGUID: TGUID): string; var Reg : TRegistry; Lines : TStringList; TmpGUID : TGUID; i : integer; begin Result := ''; Lines := TStringList.Create; // Поиск имени бинарного файла Reg := TRegistry.Create; try try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(LSP_Reg_Key+'\'+ANameSpaceCatalog+'\Catalog_Entries', false) then begin Reg.GetKeyNames(Lines); Reg.CloseKey; for i := 0 to Lines.Count - 1 do if Reg.OpenKey(LSP_Reg_Key+'\'+ANameSpaceCatalog+'\Catalog_Entries\'+Lines[i], false) then begin if Reg.ReadBinaryData('ProviderId', TmpGUID, SizeOf(TmpGUID)) = SizeOf(TmpGUID) then if GUIDToString(TmpGUID) = GUIDToString(AGUID) then begin Result := NTFileNameToNormalName(Reg.ReadString('LibraryPath')); Reg.CloseKey; Break; end; Reg.CloseKey; end; end; finally Reg.Free; end; except // Подавили все ошибки end; Lines.Free; end; function TLSPManager.RefreshNameSpaceListWS: boolean; var buf : array[0..200] of TWSANameSpaceInfo; BufSize : DWORD; i, Res : integer; Current_NameSpace_Catalog : string; VersionInfo : TVersionInfo; begin Result := false; // Очистка таблицы NameSpaceListWS := nil; if @WSAEnumNameSpaceProviders = nil then exit; if Current_NameSpace_Catalog = '' then exit; // Построение списка LSP провайдеров BufSize := sizeof(Buf); ZeroMemory(@buf, BufSize); Res := WSAEnumNameSpaceProviders(@BufSize, @Buf[0]); SetLength(NameSpaceListWS, Res); // Заполнение списка for i := 0 to Res-1 do begin NameSpaceListWS[i].NSProviderId := Buf[i].NSProviderId; NameSpaceListWS[i].dwNameSpace := Buf[i].dwNameSpace; NameSpaceListWS[i].fActive := Buf[i].fActive; NameSpaceListWS[i].dwVersion := Buf[i].dwVersion; NameSpaceListWS[i].lpszIdentifier := Trim(Buf[i].lpszIdentifier); NameSpaceListWS[i].BinFileName := SearchLSPFileByRegistry(Current_NameSpace_Catalog, NameSpaceListWS[i].NSProviderId); NameSpaceListWS[i].BinFileExists := FileExists(NameSpaceListWS[i].BinFileName); // Определение версии файла try VersionInfo := TVersionInfo.Create(NameSpaceListWS[i].BinFileName); NameSpaceListWS[i].BinFileInfo := VersionInfo.LegalCopyright + '('+VersionInfo.FileVersion+')'; VersionInfo.Free; except end; end; Result := true; end; function TLSPManager.Refresh: boolean; begin // Обновление данных о каталогах RefreshCatalogNames; // Получение данных о LSP через WinSock RefreshNameSpaceListWS; // Получение данных о LSP через реестр RefreshNameSpaceListReg; // Получение данных о протоколах через реестр RefreshProtocolInfo; end; function TLSPManager.RefreshNameSpaceListReg: boolean; var Reg : TRegistry; Lines : TStringList; i : integer; VersionInfo : TVersionInfo; begin Result := false; NameSpaceListReg := nil; // Если текущий каталог не определен, то выход if Current_NameSpace_Catalog = '' then exit; Lines := TStringList.Create; // Поиск имени бинарного файла Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(LSP_Reg_Key+'\'+Current_NameSpace_Catalog+'\Catalog_Entries', false) then begin // Получение списка вложенных ключей Reg.GetKeyNames(Lines); Reg.CloseKey; SetLength(NameSpaceListReg, Lines.Count); // Сброс признаков "Найден" и "Корретен" for i := 0 to Lines.Count - 1 do begin NameSpaceListReg[i].Found := false; NameSpaceListReg[i].IsCorrect := false; end; // Заполнение массива for i := 0 to Lines.Count - 1 do // Вложенный ключ удалось открыть ?? if Reg.OpenKey(LSP_Reg_Key+'\'+Current_NameSpace_Catalog+'\Catalog_Entries\'+Lines[i], false) then begin // Чтение GUID Reg.ReadBinaryData('ProviderId', NameSpaceListReg[i].NSProviderId, SizeOf(TGUID)); NameSpaceListReg[i].Found := true; NameSpaceListReg[i].dwNameSpace := Reg.ReadInteger('SupportedNameSpace'); NameSpaceListReg[i].fActive := Reg.ReadBool('Enabled'); NameSpaceListReg[i].dwVersion := Reg.ReadInteger('Version'); NameSpaceListReg[i].lpszIdentifier := Trim(Reg.ReadString('DisplayString')); NameSpaceListReg[i].BinFileName := NTFileNameToNormalName(Reg.ReadString('LibraryPath')); // ?? Проверка, не является ли путь относительным if pos(':', NameSpaceListReg[i].BinFileName) = 0 then begin if FileExists(NormalDir(GetSystemDirectoryPath) + NameSpaceListReg[i].BinFileName) then NameSpaceListReg[i].BinFileName := NormalDir(GetSystemDirectoryPath) + NameSpaceListReg[i].BinFileName; end; NameSpaceListReg[i].BinFileExists := FileExists(NameSpaceListReg[i].BinFileName); NameSpaceListReg[i].IsCorrect := (NameSpaceListReg[i].BinFileName <> '') and (NameSpaceListReg[i].lpszIdentifier <> '') ; NameSpaceListReg[i].RegKey := Lines[i]; NameSpaceListReg[i].CheckResults := -1; // Определение версии файла try VersionInfo := TVersionInfo.Create(NameSpaceListReg[i].BinFileName); NameSpaceListReg[i].BinFileInfo := VersionInfo.LegalCopyright + '('+VersionInfo.FileVersion+')'; VersionInfo.Free; except end; Reg.CloseKey; end; end; except end; // Разрушение классов Reg.Free; Lines.Free; Result := true; end; function TLSPManager.RefreshCatalogNames: boolean; begin // Определение текущих каталогов в реестре FCurrent_NameSpace_Catalog := Trim(RegKeyReadString(HKEY_LOCAL_MACHINE, LSP_Reg_Key, 'Current_NameSpace_Catalog')); FCurrent_Protocol_Catalog := Trim(RegKeyReadString(HKEY_LOCAL_MACHINE, LSP_Reg_Key, 'Current_Protocol_Catalog')); end; function TLSPManager.RefreshProtocolInfo: boolean; var Reg : TRegistry; Tmp : TProtocolPackedCatalogItem; Lines : TStringList; i, Res : integer; S : string; VersionInfo : TVersionInfo; begin Result := false; ProtocolListReg := nil; // Если текущий каталог не определен, то выход if Current_NameSpace_Catalog = '' then exit; Lines := TStringList.Create; // Поиск имени бинарного файла Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(LSP_Reg_Key+'\'+Current_Protocol_Catalog+'\Catalog_Entries', false) then begin // Получение списка вложенных ключей Reg.GetKeyNames(Lines); Reg.CloseKey; SetLength(ProtocolListReg, Lines.Count); // Сброс признаков "Найден" и "Корретен" for i := 0 to Lines.Count - 1 do begin ProtocolListReg[i].Found := false; ProtocolListReg[i].IsCorrect := false; end; // Заполнение массива for i := 0 to Lines.Count - 1 do // Вложенный ключ удалось открыть ?? if Reg.OpenKey(LSP_Reg_Key+'\'+Current_Protocol_Catalog+'\Catalog_Entries\'+Lines[i], false) then begin Reg.ReadBinaryData('PackedCatalogItem', Tmp, SizeOf(Tmp)); ProtocolListReg[i].Found := true; ProtocolListReg[i].BinFileName := NTFileNameToNormalName(Trim(Tmp.BinFileName)); // ?? Проверка, не является ли путь относительным if pos(':', ProtocolListReg[i].BinFileName) = 0 then begin if FileExists(NormalDir(GetSystemDirectoryPath) + ProtocolListReg[i].BinFileName) then ProtocolListReg[i].BinFileName := NormalDir(GetSystemDirectoryPath) + ProtocolListReg[i].BinFileName; end; SetLength(S, 255); Res := UnicodeToUtf8(@S[1], @Tmp.ProtocolName[0], length(S)); ProtocolListReg[i].lpszIdentifier := Trim(copy(S, 1, Res)); ProtocolListReg[i].IsCorrect := (ProtocolListReg[i].BinFileName <> '') and (ProtocolListReg[i].lpszIdentifier <> '') ; // ?? Проверка, не является ли путь относительным if pos(':', ProtocolListReg[i].BinFileName) = 0 then begin if FileExists(NormalDir(GetSystemDirectoryPath) + ProtocolListReg[i].BinFileName) then ProtocolListReg[i].BinFileName := NormalDir(GetSystemDirectoryPath) + ProtocolListReg[i].BinFileName; end; ProtocolListReg[i].BinFileExists := FileExists(ProtocolListReg[i].BinFileName); ProtocolListReg[i].RegKey := Lines[i]; ProtocolListReg[i].CheckResults := -1; // Определение версии файла try VersionInfo := TVersionInfo.Create( ProtocolListReg[i].BinFileName ); ProtocolListReg[i].BinFileInfo := VersionInfo.LegalCopyright + '('+VersionInfo.FileVersion+')'; VersionInfo.Free; except end; Reg.CloseKey; end; end; except end; // Разрушение классов Reg.Free; Lines.Free; Result := true; end; function TLSPManager.DeleteNameSpaceByGUID(AGUID: TGUID): boolean; var i, Res : integer; Reg : TRegistry; begin Result := false; // Обновление списка RefreshNameSpaceListReg; Res := -1; // Поиск пространства имен for i := 0 to Length(NameSpaceListReg)-1 do if GUIDToString(NameSpaceListReg[i].NSProviderId) = GUIDToString(AGUID) then begin Res := i; Break; end; // Запись найдена ? if Res = -1 then exit; Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; // Удаление ключа реестра Reg.DeleteKey(LSP_Reg_Key+'\'+Current_NameSpace_Catalog+'\Catalog_Entries\'+NameSpaceListReg[Res].RegKey); Reg.CloseKey; Reg.Free; RenumberNameSpace; Result := true; end; function TLSPManager.DeleteNameSpaceByBinaryName(AName: string; ANameCompare: boolean): boolean; var i : integer; begin // Обновление списка RefreshNameSpaceListReg; // Поиск пространства имен for i := 0 to Length(NameSpaceListReg)-1 do if (not(ANameCompare) and (AnsiUpperCase(NameSpaceListReg[i].BinFileName) = AnsiUpperCase(AName))) or (ANameCompare and (ExtractFileName(AnsiUpperCase(NameSpaceListReg[i].BinFileName)) = ExtractFileName(AnsiUpperCase(AName)))) then begin Result := DeleteNameSpaceByGUID(NameSpaceListReg[i].NSProviderId); Break; end; end; function TLSPManager.DeleteNameSpaceByName(AName: string): boolean; var i : integer; begin // Обновление списка RefreshNameSpaceListReg; // Поиск пространства имен for i := 0 to Length(NameSpaceListReg)-1 do if AnsiUpperCase(NameSpaceListReg[i].lpszIdentifier) = AnsiUpperCase(AName) then begin Result := DeleteNameSpaceByGUID(NameSpaceListReg[i].NSProviderId); Break; end; end; function TLSPManager.SortNameSpaceRegList: boolean; var i, j : integer; Tmp : TNameSpaceInfo; begin for i := 0 to Length(NameSpaceListReg) - 2 do for j := i+1 to Length(NameSpaceListReg) - 1 do if NameSpaceListReg[i].RegKey > NameSpaceListReg[j].RegKey then begin Tmp := NameSpaceListReg[i]; NameSpaceListReg[i] := NameSpaceListReg[j]; NameSpaceListReg[j] := Tmp; end; end; function TLSPManager.RenumberNameSpace: boolean; var i, KeyNameDigits, LastKeyNum : integer; KeyNameMask : string; Reg : TRegistry; begin Result := false; // Обновление списка ключей RefreshNameSpaceListReg; // Выполнение сортировки по имени ключа SortNameSpaceRegList; // Поиск максимальной длинны ключа (только для ключей с числовым именем) KeyNameDigits := 1; for i := 0 to Length(NameSpaceListReg)-1 do if StrToIntDef(NameSpaceListReg[i].RegKey, -1) >= 0 then if Length(NameSpaceListReg[i].RegKey) > KeyNameDigits then KeyNameDigits := Length(NameSpaceListReg[i].RegKey); // Максимальная длинна ключа найдена, логическая проверка if (KeyNameDigits < 4) or (KeyNameDigits > 14) then KeyNameDigits := 12; // Создание форматной маски KeyNameMask := ''; for i := 1 to KeyNameDigits do KeyNameMask := KeyNameMask + '0'; LastKeyNum := 0; // Цикл перенумерации ключей для созданиянепрерывнйо цепочки Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; for i := 0 to Length(NameSpaceListReg)-1 do begin if StrToIntDef(NameSpaceListReg[i].RegKey, 0) <> (LastKeyNum + 1) then Reg.MoveKey(LSP_Reg_Key+'\'+Current_NameSpace_Catalog+'\Catalog_Entries\'+NameSpaceListReg[i].RegKey, LSP_Reg_Key+'\'+Current_NameSpace_Catalog+'\Catalog_Entries\'+FormatFloat(KeyNameMask,LastKeyNum + 1), true); inc(LastKeyNum); end; // Запись реального количества ключей в Num_Catalog_Entries if Reg.OpenKey(LSP_Reg_Key+'\'+Current_NameSpace_Catalog, false) then begin Reg.WriteInteger('Num_Catalog_Entries', Length(NameSpaceListReg)); Reg.CloseKey; end; Reg.Free; Result := true; end; function TLSPManager.AutoRepairNameSpace: boolean; var i : integer; begin RefreshNameSpaceListReg; // Удаление записей, для которых нет файла i := 0; while i <= Length(NameSpaceListReg) - 1 do if not(NameSpaceListReg[i].BinFileExists) then DeleteNameSpaceByGUID(NameSpaceListReg[i].NSProviderId) else inc(i); // Перенумерация RenumberNameSpace; end; function TLSPManager.AutoRepairProtocol: boolean; var i : integer; begin RefreshProtocolInfo; i := 0; while i <= Length(ProtocolListReg) - 1 do if not(ProtocolListReg[i].BinFileExists) then DeleteProtocolByID(i) else inc(i); end; function TLSPManager.DeleteProtocolByID(ID: integer): boolean; var Reg : TRegistry; begin Result := false; // Запись найдена ? if not((ID >= 0) and (ID < Length(ProtocolListReg))) then exit; Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; // Удаление ключа реестра Reg.DeleteKey(LSP_Reg_Key+'\'+Current_Protocol_Catalog+'\Catalog_Entries\'+ProtocolListReg[ID].RegKey); Reg.CloseKey; Reg.Free; RenumberProtocol; Result := true; end; function TLSPManager.DeleteProtocolByBinaryName(AName: string; ANameCompare: boolean): boolean; var i : integer; begin for i := 0 to Length(ProtocolListReg)-1 do if (not(ANameCompare) and (AnsiUpperCase(ProtocolListReg[i].lpszIdentifier) = AnsiUpperCase(AName))) or (ANameCompare and (ExtractFileName(AnsiUpperCase(ProtocolListReg[i].lpszIdentifier)) = ExtractFileName(AnsiUpperCase(AName)))) then DeleteProtocolByID(i); end; function TLSPManager.DeleteProtocolByName(AName: string): boolean; var i : integer; begin for i := 0 to Length(ProtocolListReg)-1 do if AnsiUpperCase(ProtocolListReg[i].lpszIdentifier) = AnsiUpperCase(AName) then DeleteProtocolByID(i); end; function TLSPManager.RenumberProtocol: boolean; var i, KeyNameDigits, LastKeyNum : integer; KeyNameMask : string; Reg : TRegistry; begin Result := false; // Обновление списка ключей RefreshProtocolInfo; // Выполнение сортировки по имени ключа SortProtocolRegList; // Поиск максимальной длинны ключа (только для ключей с числовым именем) KeyNameDigits := 1; for i := 0 to Length(ProtocolListReg)-1 do if StrToIntDef(ProtocolListReg[i].RegKey, -1) >= 0 then if Length(ProtocolListReg[i].RegKey) > KeyNameDigits then KeyNameDigits := Length(ProtocolListReg[i].RegKey); // Максимальная длинна ключа найдена, логическая проверка if (KeyNameDigits < 4) or (KeyNameDigits > 14) then KeyNameDigits := 12; // Создание форматной маски KeyNameMask := ''; for i := 1 to KeyNameDigits do KeyNameMask := KeyNameMask + '0'; LastKeyNum := 0; // Цикл перенумерации ключей для создания непрерывной цепочки Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; for i := 0 to Length(ProtocolListReg)-1 do begin if StrToIntDef(ProtocolListReg[i].RegKey, 0) <> (LastKeyNum + 1) then Reg.MoveKey(LSP_Reg_Key+'\'+Current_Protocol_Catalog+'\Catalog_Entries\'+ProtocolListReg[i].RegKey, LSP_Reg_Key+'\'+Current_Protocol_Catalog+'\Catalog_Entries\'+FormatFloat(KeyNameMask,LastKeyNum + 1), true); inc(LastKeyNum); end; // Запись реального количества ключей в Num_Catalog_Entries if Reg.OpenKey(LSP_Reg_Key+'\'+Current_Protocol_Catalog, false) then begin Reg.WriteInteger('Num_Catalog_Entries', Length(ProtocolListReg)); Reg.CloseKey; end; Reg.Free; Result := true; end; function TLSPManager.SortProtocolRegList: boolean; var i, j : integer; Tmp : TProtocolInfo; begin for i := 0 to Length(ProtocolListReg) - 2 do for j := i+1 to Length(ProtocolListReg) - 1 do if ProtocolListReg[i].RegKey > ProtocolListReg[j].RegKey then begin Tmp := ProtocolListReg[i]; ProtocolListReg[i] := ProtocolListReg[j]; ProtocolListReg[j] := Tmp; end; end; function TLSPManager.SearchErrors(AList: TStrings): integer; var i, Num_Catalog_Entries : integer; Reg : TRegistry; begin Refresh; Result := 0; Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(LSP_Reg_Key+'\'+Current_NameSpace_Catalog, false) then begin Num_Catalog_Entries := -1; try Num_Catalog_Entries := Reg.ReadInteger('Num_Catalog_Entries'); except end; if Num_Catalog_Entries = -1 then begin AList.Add(TranslateStr('$AVZ0638')); inc(Result); end else if Length(NameSpaceListReg) <> Num_Catalog_Entries then begin AList.Add(TranslateStr('$AVZ0639 '+IntToStr(Num_Catalog_Entries)+' $AVZ0487 '+IntToStr(Length(NameSpaceListReg)))); inc(Result); end; Reg.CloseKey; end; // Пространства имен for i := 0 to Length(NameSpaceListReg) - 1 do begin if not(NameSpaceListReg[i].BinFileExists) then begin AList.Add(TranslateStr('$AVZ0637: "'+NameSpaceListReg[i].lpszIdentifier+'" --> $AVZ0623 ')+NameSpaceListReg[i].BinFileName); inc(Result); end; if StrToIntDef(NameSpaceListReg[i].RegKey, -1) = -1 then begin AList.Add(TranslateStr('$AVZ0637: "'+NameSpaceListReg[i].lpszIdentifier+'" --> $AVZ0509 ')+NameSpaceListReg[i].RegKey); inc(Result); end else begin if (i=0) and (StrToIntDef(NameSpaceListReg[i].RegKey, -1) <> 1) then begin AList.Add(TranslateStr('$AVZ0637: "'+NameSpaceListReg[i].lpszIdentifier+'" --> $AVZ0528 (')+NameSpaceListReg[i].RegKey+')'); inc(Result); end; if (i>0) and (StrToIntDef(NameSpaceListReg[i].RegKey, -1) - StrToIntDef(NameSpaceListReg[i-1].RegKey, -1) <> 1) then begin AList.Add(TranslateStr('$AVZ0637: "'+NameSpaceListReg[i].lpszIdentifier+'" --> $AVZ0939')); inc(Result); end; end; end; // ***** Протоколы ***** if Reg.OpenKey(LSP_Reg_Key+'\'+Current_Protocol_Catalog, false) then begin Num_Catalog_Entries := -1; try Num_Catalog_Entries := Reg.ReadInteger('Num_Catalog_Entries'); except end; if Num_Catalog_Entries = -1 then begin AList.Add(TranslateStr('$AVZ0640: $AVZ0092')); inc(Result); end else if Length(ProtocolListReg) <> Num_Catalog_Entries then begin AList.Add(TranslateStr('$AVZ0640: $AVZ0349 '+IntToStr(Num_Catalog_Entries)+' $AVZ0487 ')+IntToStr(Length(ProtocolListReg))); inc(Result); end; Reg.CloseKey; end; for i := 0 to Length(ProtocolListReg) - 1 do begin if not(ProtocolListReg[i].BinFileExists) then begin AList.Add(TranslateStr('$AVZ0640 = "'+ProtocolListReg[i].lpszIdentifier+'" --> $AVZ0623 ')+ProtocolListReg[i].BinFileName); inc(Result); end; if StrToIntDef(ProtocolListReg[i].RegKey, -1) = -1 then begin AList.Add(TranslateStr('$AVZ0640 = "'+ProtocolListReg[i].lpszIdentifier+'" --> $AVZ0509 ')+ProtocolListReg[i].RegKey); inc(Result); end else begin if (i=0) and (StrToIntDef(ProtocolListReg[i].RegKey, -1) <> 1) then begin AList.Add(TranslateStr('$AVZ0640: "'+ProtocolListReg[i].lpszIdentifier+'" --> $AVZ0528 ('+ProtocolListReg[i].RegKey+')')); inc(Result); end; if (i>0) and (StrToIntDef(ProtocolListReg[i].RegKey, -1) - StrToIntDef(ProtocolListReg[i-1].RegKey, -1) <> 1) then begin AList.Add(TranslateStr('$AVZ0640: "'+ProtocolListReg[i].lpszIdentifier+'" --> $AVZ0939')); inc(Result); end; end; end; Reg.Free; end; function TLSPManager.FullAutoRepair(ABackUpPath : string): boolean; var Lines : TStrings; begin Result := false; ABackUpPath := Trim(ABackUpPath); if ABackUpPath <> '' then begin NormalDir(ABackUpPath); zForceDirectories(ABackUpPath); Lines := TStringList.Create; Lines.Add('REGEDIT4'); Lines.Add(''); Lines.Add('[-'+LSP_Reg_Key+']'); ExpRegKey(HKEY_LOCAL_MACHINE, LSP_Reg_Key, Lines); try Lines.SaveToFile(ABackUpPath+'SPI_'+FormatDateTime('YYYYMMDD_HHNNSS', Now)+'.reg'); except end; Lines.Free; end; // Автоматическое восстановление AutoRepairNameSpace; AutoRepairProtocol; Result := true; end; function TLSPManager.SetNameSpaceActive(ID: integer; NewStatus: boolean): boolean; var Reg : TRegistry; begin Result := false; // Запись найдена ? if not((ID >= 0) and (ID < Length(NameSpaceListReg))) then exit; Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; // Удаление ключа реестра if Reg.OpenKey(LSP_Reg_Key+'\'+Current_NameSpace_Catalog+'\Catalog_Entries\'+NameSpaceListReg[ID].RegKey, false) then begin; Reg.WriteBool('Enabled', NewStatus); Reg.CloseKey; end; Reg.Free; RenumberProtocol; Result := true; end; function TLSPManager.CreateHTMLReport(ALines: TStrings; HideGoodFiles: boolean): integer; var i, Res, GoodFiles : integer; S, ST, FileInfoStr : string; begin ALines.Add('<TABLE '+HTML_TableFormat1+'>'); ALines.Add(TranslateStr('<B>$AVZ0788')); ALines.Add('<TR '+HTMP_TableHeader+'>'+HTML_TableHeaderTD+'$AVZ0787'+HTML_TableHeaderTD+'$AVZ1051'+HTML_TableHeaderTD+'$AVZ0317'+HTML_TableHeaderTD+'$AVZ0581'+HTML_TableHeaderTD+'GUID'); GoodFiles := 0; for i := 0 to Length(NameSpaceListReg)-1 do begin if NameSpaceListReg[i].CheckResults = 0 then begin S := 'bgColor='+HTMP_BgColorTrusted; inc(GoodFiles); end else S := 'bgColor='+HTMP_BgColor2; if not(HideGoodFiles and (NameSpaceListReg[i].CheckResults = 0)) then begin FileInfoStr := FormatFileInfo(NameSpaceListReg[i].BinFileName, ', '); ALines.Add('<TR '+S+'>'+ '<TD>'+HTMLNVL(NameSpaceListReg[i].lpszIdentifier)+ '<TD>'+ST+ '<TD>'+'<a href="" title="'+FileInfoStr+'">'+HTMLNVL(NameSpaceListReg[i].BinFileName)+'</a>'+GenScriptTxt(NameSpaceListReg[i].BinFileName)+ '<TD>'+HTMLNVL(NameSpaceListReg[i].BinFileInfo)+ '<TD>'+HTMLNVL(GUIDToString(NameSpaceListReg[i].NSProviderId)) ); end; end; ALines.Add('<TR bgColor='+HTMP_BgColorFt+'><TD colspan=7>$AVZ0538 - '+IntToStr(Length(NameSpaceListReg))+', $AVZ0586 - '+IntToStr(GoodFiles)); ALines.Add('</TABLE>'); // ALines.Add('<B>$AVZ0789'); ALines.Add('<TABLE '+HTML_TableFormat1+'>'); ALines.Add('<TR '+HTMP_TableHeader+'>'+HTML_TableHeaderTD+'$AVZ0787'+HTML_TableHeaderTD+'$AVZ0317'+HTML_TableHeaderTD+'$AVZ0581'); GoodFiles := 0; for i := 0 to Length(ProtocolListReg)-1 do begin if ProtocolListReg[i].CheckResults = 0 then begin S := 'bgColor='+HTMP_BgColorTrusted; inc(GoodFiles); end else S := 'bgColor='+HTMP_BgColor2; if not(HideGoodFiles and (ProtocolListReg[i].CheckResults = 0)) then begin FileInfoStr := FormatFileInfo(ProtocolListReg[i].BinFileName, ', '); ALines.Add('<TR '+S+'>'+ '<TD>'+HTMLNVL(ProtocolListReg[i].lpszIdentifier)+ '<TD>'+'<a href="" title="'+FileInfoStr+'">'+HTMLNVL(ProtocolListReg[i].BinFileName)+'</a>'+GenScriptTxt(ProtocolListReg[i].BinFileName)+ '<TD>'+HTMLNVL(ProtocolListReg[i].BinFileInfo) ); end; end; ALines.Add('<TR bgColor='+HTMP_BgColorFt+'><TD colspan=7>$AVZ0538 - '+IntToStr(Length(ProtocolListReg))+', $AVZ0586 - '+IntToStr(GoodFiles)); ALines.Add('</TABLE>'); ALines.Add('<B>$AVZ0930'); ALines.Add('<TABLE '+HTML_TableFormat1+'><pre>'); Res := SearchErrors(ALines); if Res > 0 then begin ALines.Add('$AVZ0117 - '+IntToStr(Res)); ALines.Add('$AVZ0132'); end else begin ALines.Add(TranslateStr('$AVZ0463')); end; ALines.Add('</pre></TABLE>'); // Перевод протокола TranslateLines(ALines); end; end.
unit win.timer; interface uses Windows; // Windows中7种定时器 { 1. WM_TIMER SetTimer 精度非常低 最小计时精度仅为30ms CPU占用低 且定时器消息在多任务操作系统中的优先级很低 不能得到及时响应 2. sleep 3. COleDateTime 4. GetTickCount 以ms为单位的计算机启动后经历的时间间隔 精度比WM_TIMER消息映射高 在较短的定时中其计时误差为15ms 5. DWORD timeGetTime(void) 多媒体定时器函数 定时精 度为ms级 6. timeSetEvent() 多媒体定时器 函数定时精度为ms级 利用该函数可以实现周期性的函数调用 7. QueryPerformanceFrequency()和 QueryPerformanceCounter() 对于精确度要求更高的定时操作 则应该使用 其定时误差不超过1微秒,精度与CPU等机器配置有关 } type { 高精度 计时器 } PPerfTimer = ^TPerfTimer; TPerfTimer = record Frequency : Int64; Start : Int64; Stop : Int64; end; PWinTimer = ^TWinTimer; TWinTimer = record Wnd : HWND; TimerID : UINT; EventID : UINT; Elapse : UINT; TimerFunc : TFNTimerProc; end; procedure PerfTimerStart(APerfTimer: PPerfTimer); function PerfTimerReadValue(APerfTimer: PPerfTimer): Int64; function PerfTimerReadNanoSeconds(APerfTimer: PPerfTimer): AnsiString; function PerfTimerReadMilliSeconds(APerfTimer: PPerfTimer): AnsiString; function PerfTimerReadSeconds(APerfTimer: PPerfTimer): AnsiString; function GetTickCount: Cardinal; procedure StartWinTimer(ATimer: PWinTimer); procedure EndWinTimer(ATimer: PWinTimer); implementation uses Sysutils; procedure PerfTimerStart(APerfTimer: PPerfTimer); begin Windows.QueryPerformanceCounter(APerfTimer.Start); end; function PerfTimerReadValue(APerfTimer: PPerfTimer): Int64; begin QueryPerformanceCounter(APerfTimer.Stop); QueryPerformanceFrequency(APerfTimer.Frequency); Assert(APerfTimer.Frequency > 0); Result := Round(1000000 * (APerfTimer.Stop - APerfTimer.Start) / APerfTimer.Frequency); end; function PerfTimerReadNanoseconds(APerfTimer: PPerfTimer): string; begin QueryPerformanceCounter(APerfTimer.Stop); QueryPerformanceFrequency(APerfTimer.Frequency); Assert(APerfTimer.Frequency > 0); Result := IntToStr(Round(1000000 * (APerfTimer.Stop - APerfTimer.Start) / APerfTimer.Frequency)); end; function PerfTimerReadMilliseconds(APerfTimer: PPerfTimer): string; begin QueryPerformanceCounter(APerfTimer.Stop); QueryPerformanceFrequency(APerfTimer.Frequency); Assert(APerfTimer.Frequency > 0); Result := FloatToStrF(1000 * (APerfTimer.Stop - APerfTimer.Start) / APerfTimer.Frequency, ffFixed, 15, 3); end; function PerfTimerReadSeconds(APerfTimer: PPerfTimer): String; begin QueryPerformanceCounter(APerfTimer.Stop); QueryPerformanceFrequency(APerfTimer.Frequency); Result := FloatToStrF((APerfTimer.Stop - APerfTimer.Start) / APerfTimer.Frequency, ffFixed, 15, 3); end; function GetTickCount: Cardinal; begin Result := Windows.GetTickCount; end; procedure StartWinTimer(ATimer: PWinTimer); begin ATimer.TimerID := Windows.SetTimer(ATimer.Wnd, ATimer.EventID, ATimer.Elapse, ATimer.TimerFunc); end; procedure EndWinTimer(ATimer: PWinTimer); begin Windows.KillTimer(ATimer.Wnd, ATimer.TimerId); end; end.
unit DW.Notifications.iOS; // ***************** NOTE ************************** // THIS UNIT IS CURRENTLY EXPERIMENTAL // USE AT YOUR OWN RISK! // // It may or may not be removed from the Kastri Free library {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses iOSapi.Foundation, Macapi.ObjectiveC, DW.Notifications, DW.iOSapi.UserNotifications; type TPlatformNotifications = class; TUserNotificationCenterDelegate = class(TOCLocal, UNUserNotificationCenterDelegate) private FNotifications: TNotifications; procedure ProcessLocalNotification(request: UNNotificationRequest); procedure ProcessNotificationRequest(request: UNNotificationRequest); procedure ProcessRemoteNotification(request: UNNotificationRequest); protected property Notifications: TNotifications read FNotifications write FNotifications; public { UNUserNotificationCenterDelegate } [MethodName('userNotificationCenter:willPresentNotification:withCompletionHandler:')] procedure userNotificationCenterWillPresentNotificationWithCompletionHandler(center: UNUserNotificationCenter; willPresentNotification: UNNotification; withCompletionHandler: Pointer); cdecl; [MethodName('userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:')] procedure userNotificationCenterDidReceiveNotificationResponseWithCompletionHandler(center: UNUserNotificationCenter; didReceiveNotificationResponse: UNNotificationResponse; withCompletionHandler: Pointer); cdecl; end; TAuthorizationCallback = reference to procedure(const AGranted: Boolean); TPlatformNotifications = class(TCustomPlatformNotifications) private class var FNotificationCenterDelegate: TUserNotificationCenterDelegate; class constructor CreateClass; class destructor DestroyClass; private procedure AddNotificationRequestCompletionHandler(error: NSError); function GetNotificationContent(ANotification: TNotification): UNMutableNotificationContent; function GetNotificationTrigger(ANotification: TNotification; const AImmediate: Boolean): UNCalendarNotificationTrigger; procedure IssueNotification(const ANotification: TNotification; const AImmediate: Boolean); procedure RequestAuthorization; procedure RequestAuthorizationCompletionHandler(granted: Boolean; error: NSError); protected procedure CancelAll; override; procedure CancelNotification(const AName: string); override; procedure PresentNotification(const ANotification: TNotification); override; procedure ScheduleNotification(const ANotification: TNotification); override; public constructor Create(const ANotifications: TNotifications); override; destructor Destroy; override; end; implementation uses System.SysUtils, System.Messaging, System.DateUtils, Macapi.Helpers, Macapi.ObjCRuntime, iOSapi.CocoaTypes, FMX.Platform, DW.OSLog, DW.Macapi.ObjCRuntime, DW.iOSapi.Helpers, DW.Macapi.Helpers; type TOpenNotifications = class(TNotifications); function NotificationCenter: UNUserNotificationCenter; begin Result := TUNUserNotificationCenter.OCClass.currentNotificationCenter; end; // Non-buggy version (as opposed to the one in Macapi.Helpers) function GetGMTDateTime(const ADateTime: TDateTime): TDateTime; begin Result := IncSecond(ADateTime, -TNSTimeZone.Wrap(TNSTimeZone.OCClass.localTimeZone).secondsFromGMT); end; { TUserNotificationCenterDelegate } procedure TUserNotificationCenterDelegate.ProcessNotificationRequest(request: UNNotificationRequest); begin if request.trigger.isKindOfClass(objc_getClass('UNPushNotificationTrigger')) then ProcessRemoteNotification(request) else ProcessLocalNotification(request); end; procedure TUserNotificationCenterDelegate.ProcessRemoteNotification(request: UNNotificationRequest); var LJSON: string; begin LJSON := TiOSHelperEx.NSDictionaryToJSON(request.content.userInfo); TMessageManager.DefaultManager.SendMessage(nil, TPushRemoteNotificationMessage.Create(TPushNotificationData.Create(LJSON))); end; procedure TUserNotificationCenterDelegate.ProcessLocalNotification(request: UNNotificationRequest); var LNotification: TNotification; LContent: UNNotificationContent; LUserInfo: TNSDictionaryHelper; begin if FNotifications = nil then Exit; // <====== LContent := request.content; LNotification.Name := NSStrToStr(request.identifier); LNotification.AlertBody := NSStrToStr(LContent.body); LNotification.Title := NSStrToStr(LContent.title); LNotification.Subtitle := NSStrToStr(LContent.subtitle); LNotification.EnableSound := LContent.sound <> nil; // Result.SoundName := ? LNotification.HasAction := LContent.categoryIdentifier <> nil; LUserInfo := TNSDictionaryHelper.Create(LContent.userInfo); LNotification.RepeatInterval := TRepeatInterval(LUserInfo.GetValue('RepeatInterval', 0)); TOpenNotifications(FNotifications).DoNotificationReceived(LNotification); end; procedure TUserNotificationCenterDelegate.userNotificationCenterDidReceiveNotificationResponseWithCompletionHandler(center: UNUserNotificationCenter; didReceiveNotificationResponse: UNNotificationResponse; withCompletionHandler: Pointer); var LBlockImp: procedure; cdecl; begin TOSLog.d('TUserNotificationCenterDelegate.userNotificationCenterDidReceiveNotificationResponseWithCompletionHandler'); ProcessNotificationRequest(didReceiveNotificationResponse.notification.request); @LBlockImp := imp_implementationWithBlock(withCompletionHandler); LBlockImp; imp_removeBlock(@LBlockImp); end; procedure TUserNotificationCenterDelegate.userNotificationCenterWillPresentNotificationWithCompletionHandler(center: UNUserNotificationCenter; willPresentNotification: UNNotification; withCompletionHandler: Pointer); var LBlockImp: procedure(options: UNNotificationPresentationOptions); cdecl; LOptions: UNNotificationPresentationOptions; begin TOSLog.d('TUserNotificationCenterDelegate.userNotificationCenterWillPresentNotificationWithCompletionHandler'); ProcessNotificationRequest(willPresentNotification.request); @LBlockImp := imp_implementationWithBlock(withCompletionHandler); LOptions := UNNotificationPresentationOptionAlert; LBlockImp(LOptions); imp_removeBlock(@LBlockImp); end; { TPlatformNotifications } class constructor TPlatformNotifications.CreateClass; begin FNotificationCenterDelegate := TUserNotificationCenterDelegate.Create; NotificationCenter.setDelegate(FNotificationCenterDelegate.GetObjectID); end; class destructor TPlatformNotifications.DestroyClass; begin FNotificationCenterDelegate.Free; end; constructor TPlatformNotifications.Create(const ANotifications: TNotifications); begin inherited; FNotificationCenterDelegate.Notifications := ANotifications; RequestAuthorization; end; destructor TPlatformNotifications.Destroy; begin // inherited; end; procedure TPlatformNotifications.RequestAuthorizationCompletionHandler(granted: Boolean; error: NSError); begin // end; procedure TPlatformNotifications.RequestAuthorization; var LOptions: UNAuthorizationOptions; begin LOptions := UNAuthorizationOptionSound or UNAuthorizationOptionAlert or UNAuthorizationOptionBadge or UNAuthorizationOptionCarPlay; NotificationCenter.requestAuthorizationWithOptions(LOptions, RequestAuthorizationCompletionHandler); end; procedure TPlatformNotifications.CancelAll; begin NotificationCenter.removeAllPendingNotificationRequests; end; procedure TPlatformNotifications.CancelNotification(const AName: string); begin NotificationCenter.removePendingNotificationRequestsWithIdentifiers(StringArrayToNSArray([AName])); end; function TPlatformNotifications.GetNotificationContent(ANotification: TNotification): UNMutableNotificationContent; var LSound: Pointer; LUserInfo: TNSMutableDictionaryHelper; begin Result := TUNMutableNotificationContent.Create; Result.setTitle(StrToNSStr(ANotification.Title)); Result.setSubtitle(StrToNSStr(ANotification.SubTitle)); Result.setBody(StrToNSStr(ANotification.AlertBody)); Result.setBadge(TNSNumber.Wrap(TNSNumber.OCClass.numberWithInteger(ANotification.Number))); if ANotification.EnableSound then begin if ANotification.SoundName.IsEmpty then LSound := TUNNotificationSound.OCClass.defaultSound else LSound := TUNNotificationSound.OCClass.soundNamed(StrToNSStr(ANotification.SoundName)); Result.setSound(TUNNotificationSound.Wrap(LSound)); end else Result.setSound(nil); LUserInfo := TNSMutableDictionaryHelper.Create(TNSMutableDictionary.Create); LUserInfo.SetValue(Ord(ANotification.RepeatInterval), 'RepeatInterval'); Result.setUserInfo(LUserInfo.Dictionary); end; function TPlatformNotifications.GetNotificationTrigger(ANotification: TNotification; const AImmediate: Boolean): UNCalendarNotificationTrigger; const cDayDateUnits = NSHourCalendarUnit or NSMinuteCalendarUnit or NSSecondCalendarUnit; cAllDateUnits = NSYearCalendarUnit or NSMonthCalendarUnit or NSDayCalendarUnit or cDayDateUnits; cRepeatingDateUnits: array[TRepeatInterval] of NSUInteger = ( cDayDateUnits, { None } NSSecondCalendarUnit, { Second } NSMinuteCalendarUnit or NSSecondCalendarUnit, { Minute } cDayDateUnits, { Hour } NSDayCalendarUnit or cDayDateUnits, { Day } NSWeekCalendarUnit or cDayDateUnits, { Week } NSWeekdayCalendarUnit or NSMonthCalendarUnit or NSDayCalendarUnit or cDayDateUnits, { Weekday } NSMonthCalendarUnit or NSDayCalendarUnit or cDayDateUnits, { Month } NSQuarterCalendarUnit or NSDayCalendarUnit or cDayDateUnits, { Quarter - according to Apple: "largely unimplemented" } NSYearCalendarUnit or NSDayCalendarUnit or NSMonthCalendarUnit or cDayDateUnits, { Year } cDayDateUnits { Era - why would you use a notification with this repeat interval??? } ); var LTrigger: Pointer; LCalendar: NSCalendar; LTriggerDate: NSDateComponents; LDateUnits: NSUInteger; LRepeating: Boolean; LDate: TDateTime; begin LCalendar := TNSCalendar.Wrap(TNSCalendar.OCClass.currentCalendar); LDateUnits := cDayDateUnits; // Does not seem to consistently allow immediate within a second of the current time LDate := IncSecond(Now); if not AImmediate then begin LDateUnits := cRepeatingDateUnits[ANotification.RepeatInterval]; LDate := ANotification.FireDate; end; LDate := GetGMTDateTime(LDate); LTriggerDate := LCalendar.components(LDateUnits, DateTimeToNSDate(LDate)); LRepeating := (ANotification.RepeatInterval <> TRepeatInterval.None) and not AImmediate; LTrigger := TUNCalendarNotificationTrigger.OCClass.triggerWithDateMatchingComponents(LTriggerDate, LRepeating); Result := TUNCalendarNotificationTrigger.Wrap(LTrigger); end; procedure TPlatformNotifications.IssueNotification(const ANotification: TNotification; const AImmediate: Boolean); var LContent: UNMutableNotificationContent; LTrigger: UNCalendarNotificationTrigger; LPointer: Pointer; LRequest: UNNotificationRequest; LName: string; begin LName := ANotification.Name; if LName.IsEmpty then LName := 'ImmediateNotification'; LContent := GetNotificationContent(ANotification); LTrigger := GetNotificationTrigger(ANotification, AImmediate); LPointer := TUNNotificationRequest.OCClass.requestWithIdentifier(StrToNSStr(LName), LContent, LTrigger); LRequest := TUNNotificationRequest.Wrap(LPointer); NotificationCenter.addNotificationRequest(LRequest, AddNotificationRequestCompletionHandler); end; procedure TPlatformNotifications.PresentNotification(const ANotification: TNotification); begin IssueNotification(ANotification, True); end; procedure TPlatformNotifications.ScheduleNotification(const ANotification: TNotification); begin IssueNotification(ANotification, False); end; procedure TPlatformNotifications.AddNotificationRequestCompletionHandler(error: NSError); begin // If error = nil: all good :-) Note: May be in a separate thread end; end.
unit unCadImagem; interface uses Windows, Messages, ShellAPI, SysUtils, Variants, StrUtils, Math, Classes, Mask, Buttons, MaskUtils, Registry, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, ImgList, jpeg, StdCtrls, Menus, ExtCtrls, Grids, DB, AdvObj, BaseGrid, AdvGrid, AdvCGrid, ZAbstractRODataset, ZAbstractDataset, ZDataset, AdvAppStyler, Vcl.ExtDlgs, AdvGlowButton, AdvEdit, AdvPanel, unMaterial, unDocumento; type TfmCadImagem = class(TForm) QueryGeral: TZQuery; OpenPictureDialog: TOpenPictureDialog; FormStyler: TAdvFormStyler; PanelGeral: TAdvPanel; LabelImagem: TLabel; LabelDescricao: TLabel; LabelAlterarDescricao: TLabel; ColumnGridImagens: TAdvColumnGrid; PanelBotoes: TAdvPanel; EditCadastroDEIMAGEM: TAdvEdit; EditCadastroNMIMAGEM: TAdvEdit; ButtonIncluirImagem: TAdvGlowButton; ButtonExcluirImagem: TAdvGlowButton; ButtonSelecionarImagem: TAdvGlowButton; ButtonFechar: TAdvGlowButton; ButtonSalvar: TAdvGlowButton; ButtonExcluir: TAdvGlowButton; ImageList: TImageList; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ButtonFecharClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure LabelAlterarDescricaoClick(Sender: TObject); procedure ButtonIncluirImagemClick(Sender: TObject); procedure ButtonExcluirImagemClick(Sender: TObject); procedure ColumnGridImagensClickCell(Sender: TObject; ARow, ACol: Integer); procedure ButtonSalvarClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure ButtonExcluirClick(Sender: TObject); procedure ButtonSelecionarImagemClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } pId: TGUID; pOpcao: char; pcdMaterial: integer; pUltimoLocalSelecionado: string; pMaterial: TMaterial; pDocumento: TDocumento; procedure limpaGrid; procedure limpaImagem; procedure desabilitaAcoes; procedure carregaImagensBotoes; procedure carregaImagensGrid; public { Public declarations } procedure setacdMaterial(prmcdMaterial: integer); procedure carregaImagensMaterial; end; var fmCadImagem: TfmCadImagem; implementation uses undmPrincipal, unPrincipal, unAplVisualizaImagem, undmEstilo; {$R *.dfm} procedure TfmCadImagem.ButtonExcluirClick(Sender: TObject); var vcdImagem: integer; begin vcdImagem := 0; desabilitaAcoes; try with ColumnGridImagens do begin if Row > 0 then vcdImagem := ColumnByName['CDIMAGEM'].Ints[Row]; if vcdImagem = 0 then Exit; // Valida se realmente o usuário quer realizar a exclusão. if MessageBox(fmPrincipal.Handle, PWideChar('Deseja realmente realizar a exclusão da imagem?'), cTituloMensagemConfirmacao, MB_YESNO or MB_ICONQUESTION or MB_DEFBUTTON2) = IDNO then Exit; try pMaterial.Codigo := pcdMaterial; pMaterial.Documento := vcdImagem; if pMaterial.excluiMaterialImagem = 0 then raise exception.Create('Imagem do material a ser excluída não foi encontrada.'); pDocumento.Codigo := vcdImagem; if pDocumento.exclui = 0 then raise exception.Create('Imagem ser excluída não foi encontrada.'); // Exclui o documento fisicamente. SysUtils.DeleteFile(ColumnByName['NMIMAGEM'].Rows[Row]); carregaImagensMaterial; fmPrincipal.apresentaResultadoCadastro('Cadastro excluído com sucesso.'); except on E: exception do begin fmPrincipal.apresentaResultadoCadastro(E.Message); fmPrincipal.manipulaExcecoes(Sender,E); end; end; end; finally ButtonSelecionarImagem.Enabled := true; ButtonSalvar.Enabled := true; ButtonExcluir.Enabled := true; ButtonFechar.Enabled := true; ActiveControl := ColumnGridImagens; end; end; procedure TfmCadImagem.ButtonExcluirImagemClick(Sender: TObject); begin with ColumnGridImagens do if Enabled then if RowCount > 2 then RemoveRows(Row,1) else ClearRows(Row,1); end; procedure TfmCadImagem.ButtonFecharClick(Sender: TObject); begin Close; end; procedure TfmCadImagem.ButtonIncluirImagemClick(Sender: TObject); var i: integer; vlcImagem: string; begin // Realiza validações. if EditCadastroNMIMAGEM.Text = EmptyStr then Exit; vlcImagem := StringReplace(EditCadastroNMIMAGEM.Text,'"',EmptyStr,[rfReplaceAll]); if not FileExists(vlcImagem) then begin fmPrincipal.apresentaResultadoCadastro('Imagem inexistente, favor verificar o nome ou local da Imagem informada.'); Exit; end; try // Validação dos itens antes de inserir na grid. with ColumnGridImagens do if Enabled then for i := 1 to RowCount -1 do begin if AnsiCompareText(ColumnByName['NMIMAGEM'].Rows[i],vlcImagem) = 0 then begin fmPrincipal.apresentaResultadoCadastro('Esta Imagem já foi inserida na tabela, favor informar uma outra imagem.'); Exit; end; end; try with ColumnGridImagens do begin BeginUpdate; if Enabled then begin if ColumnByName['DEIMAGEM'].Rows[RowCount-1] <> EmptyStr then begin AddRow; Row := RowCount -1; end; ColumnByName['NMIMAGEM'].Rows[Row] := vlcImagem; if RowCount = 2 then AddRadioButton(1,Row,true) else AddRadioButton(1,Row,false); ColumnByName['DEIMAGEM'].Rows[Row] := EditCadastroDEIMAGEM.Text; AddImageIdx(3,RowCount-1,1,haCenter,vaCenter); AddImageIdx(4,Row,2,haCenter,vaCenter); ColumnByName['CDIMAGEM'].Ints[Row] := 0; end else begin Enabled := true; ColumnByName['NMIMAGEM'].Rows[Row] := vlcImagem; ColumnByName['DEIMAGEM'].Rows[Row] := EditCadastroDEIMAGEM.Text; AddImageIdx(3,RowCount-1,1,haCenter,vaCenter); AddImageIdx(4,Row,2,haCenter,vaCenter); end; EndUpdate; end; except on E: exception do fmPrincipal.manipulaExcecoes(Sender,E); end; finally limpaImagem; end; end; procedure TfmCadImagem.ButtonSalvarClick(Sender: TObject); var i, vStatus, vcdImagem: integer; vImagem, vcsImagem, vflPadrao: string; begin try try with ColumnGridImagens do begin BeginUpdate; for i := 1 to RowCount -1 do begin // Associa a imagem cadastrada ao material. if IsRadioButtonChecked(1,i) then vflPadrao := 'S' else vflPadrao := 'N'; if ColumnByName['NMIMAGEM'].Rows[i] <> EmptyStr then begin // Para novos registros. if ColumnByName['CDIMAGEM'].Ints[i] = 0 then begin vImagem := ExtractFileName(ColumnByName['NMIMAGEM'].Rows[i]); // Obtem o checksum do arquivo. vcsImagem := fmPrincipal.fnGeral.obtemCheckSumArquivo(ColumnByName['NMIMAGEM'].Rows[i]); pDocumento.Nome := vImagem; pDocumento.Descricao := ColumnByName['DEIMAGEM'].Rows[i]; pDocumento.Tipo := 'I'; // Padrão para Imagem. pDocumento.Documento := ColumnByName['NMIMAGEM'].Rows[i]; pDocumento.Checksum := vcsImagem; vcdImagem := pDocumento.insere; if vcdImagem = 0 then raise exception.Create('Não foi possível incluir a imagem.'); ColumnByName['CSIMAGEM'].Rows[i] := vcsImagem; ColumnByName['CDIMAGEM'].Ints[i] := vcdImagem; pMaterial.Codigo := pcdMaterial; pMaterial.Documento := vcdImagem; pMaterial.ImagemPadrao := vflPadrao; vStatus := pMaterial.insereMaterialImagem; if vStatus = 0 then begin // Se não puder associar, exclui a imagem cadastrada. pDocumento.Codigo := vcdImagem; pDocumento.exclui; raise exception.Create('Não foi possível associar a imagem ao material.'); end; end else begin pDocumento.Codigo := ColumnByName['CDIMAGEM'].Ints[i]; pDocumento.Descricao := ColumnByName['DEIMAGEM'].Rows[i]; if pDocumento.atualiza = 0 then raise exception.Create('Imagem a ser atualizada não foi encontrada.'); pMaterial.Codigo := pcdMaterial; pMaterial.Documento := ColumnByName['CDIMAGEM'].Ints[i]; pMaterial.ImagemPadrao := vflPadrao; if pMaterial.atualizaMaterialImagem = 0 then raise exception.Create('Imagem do material a ser atualizada não foi encontrada.'); end; end; end; EndUpdate; end; fmPrincipal.apresentaResultadoCadastro('Cadastro realizado com sucesso.'); carregaImagensMaterial; ButtonExcluir.Enabled := true; except on E: exception do begin fmPrincipal.apresentaResultadoCadastro(E.Message); fmPrincipal.manipulaExcecoes(Sender,E); end; end; finally ButtonSelecionarImagem.Enabled := true; ButtonSalvar.Enabled := true; ButtonExcluir.Enabled := true; ButtonFechar.Enabled := true; ActiveControl := ButtonFechar; end; end; procedure TfmCadImagem.carregaImagensBotoes; begin ButtonSelecionarImagem.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'browser-e-16.png'); ButtonSelecionarImagem.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'browser-h-16.png'); ButtonSelecionarImagem.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'browser-d-16.png'); ButtonIncluirImagem.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'add-image-e-16.png'); ButtonIncluirImagem.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'add-image-h-16.png'); ButtonIncluirImagem.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'add-image-d-16.png'); ButtonExcluirImagem.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'remove-image-e-16.png'); ButtonExcluirImagem.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'remove-image-h-16.png'); ButtonExcluirImagem.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'remove-image-d-16.png'); end; procedure TfmCadImagem.carregaImagensGrid; begin fmPrincipal.fnGeral.insereImageList(ImageList,fmPrincipal.LocalIcones + 'picture-e-16.png'); fmPrincipal.fnGeral.insereImageList(ImageList,fmPrincipal.LocalIcones + 'picture-d-16.png'); fmPrincipal.fnGeral.insereImageList(ImageList,fmPrincipal.LocalIcones + 'edit-image-e-16.png'); fmPrincipal.fnGeral.insereImageList(ImageList,fmPrincipal.LocalIcones + 'edit-image-d-16.png'); fmPrincipal.fnGeral.insereImageList(ImageList,fmPrincipal.LocalIcones + 'edit-image-green-16.png'); ColumnGridImagens.GridImages := ImageList; end; procedure TfmCadImagem.carregaImagensMaterial; var vQuery: TZQuery; begin try ColumnGridImagens.BeginUpdate; limpaGrid; vQuery := TZQuery.Create(Self); with vQuery do begin SQL.Text := 'SELECT cddocumento,nmdocumento,dedocumento,flpadrao'; SQL.Add('FROM ' + cSchema + '.vw_materialimagem'); SQL.Add('WHERE cdmaterial = :CDMATERIAL'); Params.ParamByName('CDMATERIAL').AsInteger := pcdMaterial; dmPrincipal.executaConsulta(vQuery); while not Eof do begin with ColumnGridImagens do begin if Fields.FieldByName('FLPADRAO').AsString = 'S' then AddRadioButton(1,RowCount-1,true) else AddRadioButton(1,RowCount-1,false); ColumnByName['DEIMAGEM'].Rows[RowCount-1] := Fields.FieldByName('DEDOCUMENTO').AsString; AddImageIdx(3,RowCount-1,0,haCenter,vaCenter); AddImageIdx(4,RowCount-1,3,haCenter,vaCenter); ColumnByName['NMIMAGEM'].Rows[RowCount-1] := Fields.FieldByName('NMDOCUMENTO').AsString; ColumnByName['CDIMAGEM'].Ints[RowCount-1] := Fields.FieldByName('CDDOCUMENTO').AsInteger; Next; if not Eof then RowCount := RowCount +1; end; end; Active := false; end; finally ColumnGridImagens.EndUpdate; ColumnGridImagens.Row := 1; FreeAndNil(vQuery); pOpcao := 'A'; ButtonExcluir.Enabled := true; end; end; procedure TfmCadImagem.ColumnGridImagensClickCell(Sender: TObject; ARow, ACol: Integer); var vImagem: string; begin with ColumnGridImagens do begin // Realiza validações if (ColumnByName['NMIMAGEM'].Rows[ARow] = EmptyStr) or (ARow = 0) then Exit; if not Enabled then Exit; // Se clicou na coluna de visualizar a imagem. if ACol = 3 then if ColumnByName['CDIMAGEM'].Ints[Row] > 0 then begin vImagem := fmPrincipal.LocalTemporario + ColumnByName['NMIMAGEM'].Rows[Row]; pDocumento.Codigo := ColumnByName['CDIMAGEM'].Ints[Row]; if not pDocumento.salvaDocumentoDisco(vImagem) then begin fmPrincipal.pLogSistema.Error('A imagem ' + vImagem + ' não pode ser obtida da tabela. A imagem não será apresentada.'); Exit; end; fmAplVisualizaImagem := TfmAplVisualizaImagem.Create(Self); with fmAplVisualizaImagem do begin setaImagem(vImagem, ColumnByName['DEIMAGEM'].Rows[ARow]); ShowModal; end; end; // Se clicou na coluna de editar seta para edição. if ACol = 4 then if ColumnByName['CDIMAGEM'].Ints[Row] = 0 then begin limpaImagem; EditCadastroNMIMAGEM.Text := ColumnByName['NMIMAGEM'].Rows[Row]; EditCadastroDEIMAGEM.Text := ColumnByName['DEIMAGEM'].Rows[Row]; AddImageIdx(3,RowCount-1,2,haCenter,vaCenter); AddImageIdx(4,ARow,4,haCenter,vaCenter); Enabled := false; end; end; end; procedure TfmCadImagem.desabilitaAcoes; begin ButtonSelecionarImagem.Enabled := false; ButtonIncluirImagem.Enabled := false; ButtonExcluirImagem.Enabled := false; ButtonSalvar.Enabled := false; ButtonExcluir.Enabled := false; ButtonFechar.Enabled := false; end; procedure TfmCadImagem.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfmCadImagem.FormCreate(Sender: TObject); var i: integer; begin try CreateGUID(pId); Color := Self.Color; FormStyler.AutoThemeAdapt := false; pOpcao := 'I'; pMaterial := TMaterial.Create; pDocumento := TDocumento.Create; carregaImagensBotoes; carregaImagensGrid; limpaGrid; ActiveControl := ButtonSelecionarImagem; // Configura a Grid. with ColumnGridImagens do begin DrawingStyle := gdsThemed; AutoThemeAdapt := false; for i := 0 to ColCount -1 do Columns[i].ShowBands := true; Bands.Active := true; end; FormResize(Sender); except on E: Exception do begin fmPrincipal.manipulaExcecoes(Sender,E); Close; end; end; end; procedure TfmCadImagem.FormDestroy(Sender: TObject); begin FreeAndNil(pMaterial); FreeAndNil(pDocumento); end; procedure TfmCadImagem.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Exit; end; procedure TfmCadImagem.FormResize(Sender: TObject); begin ButtonFechar.Left := PanelBotoes.Width - ButtonFechar.Width - fmPrincipal.EspacamentoFinalBotao; ButtonExcluir.Left := ButtonFechar.Left - ButtonExcluir.Width - fmPrincipal.EspacamentoEntreBotoes; ButtonSalvar.Left := ButtonExcluir.Left - ButtonSalvar.Width - fmPrincipal.EspacamentoEntreBotoes; end; procedure TfmCadImagem.LabelAlterarDescricaoClick(Sender: TObject); begin if EditCadastroDEIMAGEM.Text <> EmptyStr then EditCadastroDEIMAGEM.Text := InputBox('Alterar a Descrição da Imagem', 'Informe uma nova descrição para a imagem:', EditCadastroDEIMAGEM.Text); end; procedure TfmCadImagem.limpaGrid; begin with ColumnGridImagens do begin ClearRows(1,RowCount-1); Row := 1; RowCount := 2; Columns[0].Width := 0; Columns[1].Width := 40; Columns[2].Width := 500; Columns[3].Width := 30; Columns[4].Width := 35; Columns[5].Width := 0; Columns[6].Width := 0; Columns[7].Width := 0; HideColumns(5,7); end; end; procedure TfmCadImagem.limpaImagem; begin EditCadastroNMIMAGEM.Clear; EditCadastroDEIMAGEM.Clear; end; procedure TfmCadImagem.setacdMaterial(prmcdMaterial: integer); begin pcdMaterial := prmcdMaterial; end; procedure TfmCadImagem.ButtonSelecionarImagemClick(Sender: TObject); var vNomeArquivo, vExtensao: string; vPosicao: integer; begin try Screen.Cursor := crHourGlass; desabilitaAcoes; with OpenPictureDialog do begin Title := 'Abrir Imagem'; DefaultExt := EmptyStr; if pUltimoLocalSelecionado = EmptyStr then InitialDir := fmPrincipal.fnGeral.obtemDiretorioUsuario('My Pictures') else InitialDir := pUltimoLocalSelecionado; Filter := 'Todos (*.png;*.jpeg;*.jpg;*.bmp;*.tif;*.tiff)|*.png;*.jpeg;*.jpg;*.bmp;*.tif;*.tiff|'; Filter := Filter + 'Imagens PNG (*.png)|*.png|'; Filter := Filter + 'Imagens JPEG (*.jpeg;*.jpg)|*.jpeg;*.jpg|'; Filter := Filter + 'Bitmaps (*.bmp)|*.bmp|'; Filter := Filter + 'Imagens TIFF (*.tiff;*.tif)|*.tiff;*.tif'; FilterIndex := 1; if Execute then begin pUltimoLocalSelecionado := ExtractFilePath(FileName); EditCadastroNMIMAGEM.Text := FileName; vNomeArquivo := ExtractFileName(FileName); vExtensao := ExtractFileExt(FileName); // Monta o nome da Imagem com base no nome do arquivo da Imagem. if vExtensao <> EmptyStr then begin vPosicao := Pos(vExtensao,vNomeArquivo); if vPosicao > 0 then Delete(vNomeArquivo,vPosicao,Length(vExtensao)); end; EditCadastroDEIMAGEM.Text := vNomeArquivo; ButtonIncluirImagem.Enabled := true; ButtonExcluirImagem.Enabled := true; end; end; finally ButtonSelecionarImagem.Enabled := true; ButtonSalvar.Enabled := true; ButtonExcluir.Enabled := true; ButtonFechar.Enabled := true; Screen.Cursor := crDefault; end; end; end.
{******************************************************************************} { } { Delphi SwagDoc Library } { Copyright (c) 2018 Marcelo Jaloto } { https://github.com/marcelojaloto/SwagDoc } { } {******************************************************************************} { } { 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 Json.Schema.Field.Arrays; interface uses System.Json, Json.Schema.Field, Json.Schema.Common.Types; type [ASchemaType(skArray)] TJsonFieldArray = class(TJsonField) strict private fItemFieldType: TJsonField; fMinLength: Integer; fMaxLength: Integer; public constructor Create; override; destructor Destroy; override; function Clone: TJsonField; override; function ToJsonSchema: TJsonObject; override; property ItemFieldType: TJsonField read fItemFieldType write fItemFieldType; property MinLength: Integer read fMinLength write fMinLength; property MaxLength: Integer read fMaxLength write fMaxLength; end; implementation uses System.Classes, Json.Commom.Helpers; { TJsonFieldArray } function TJsonFieldArray.Clone: TJsonField; begin Result := inherited Clone; TJsonFieldArray(Result).MinLength := Self.MinLength; TJsonFieldArray(Result).MaxLength := Self.MaxLength; TJsonFieldArray(Result).ItemFieldType := Self.ItemFieldType.Clone; end; constructor TJsonFieldArray.Create; begin inherited Create; fItemFieldType := nil; fMinLength := 0; fMaxLength := 0; end; destructor TJsonFieldArray.Destroy; begin if Assigned(fItemFieldType) then fItemFieldType.Free; inherited Destroy; end; function TJsonFieldArray.ToJsonSchema: TJsonObject; begin Result := inherited ToJsonSchema; if Assigned(fItemFieldType) then Result.AddPair('items', fItemFieldType.ToJsonSchema); if (fMinLength > 0) then Result.AddPair('minLength', fMinLength); if (fMaxLength > 0) then Result.AddPair('maxLength', fMaxLength); end; initialization RegisterClass(TJsonFieldArray); end.
unit Form1; interface uses SmartCL.System, SmartCL.Graphics, SmartCL.Components, SmartCL.Forms, SmartCL.Fonts, SmartCL.Borders, SmartCL.Application, System.Colors, uMyListBox, SmartCL.Controls.Listbox, SmartCL.Controls.Button, SmartCL.Controls.Label, SmartCL.Controls.SimpleLabel, SmartCL.Controls.EditBox; type TForm1 = class(TW3Form) private {$I 'Form1:intf'} MyListBox1 : TMyListBox; protected procedure InitializeForm; override; procedure InitializeObject; override; procedure Resize; override; procedure DeleteFrom(listbox: TW3ListBox); function GetTextChild(lb: TW3ListBox; idx: integer): TW3Label; procedure AddItem(Name: string); end; implementation { TForm1 } procedure TForm1.InitializeForm; begin inherited; // this is a good place to initialize components end; procedure TForm1.AddItem(Name: string); begin var item := W3ListBox1[W3ListBox1.Add]; var lbl := TW3SimpleLabel.Create(item); lbl.StyleClass := 'TW3SimpleLabel'; lbl.Font.Name := "'Arial Black', arial, sans-serif"; lbl.Font.Color := clBlue; lbl.Caption := name; lbl.Autosize := false; w3_setStyle(lbl.Handle, 'text-align', 'center'); lbl.SetBounds(0, 0, item.ClientWidth, item.ClientHeight); end; procedure TForm1.InitializeObject; begin inherited; {$I 'Form1:impl'} (*--------------------------------------*) MyListBox1 := TMyListBox.Create(self); MyListBox1.SetBounds(8,60,304,176); MyListBox1.Styles.SelectedColor := clLime; MyListBox1.Styles.HighlightedColor := clAquamarine; MyListBox1.Styles.MovingColor := clBurlyWood; MyListBox1.AllowMoving := true; W3btnLB1Add.OnClick := procedure(sender: TObject) begin MyListBox1.Add('- ' + IntToStr(MyListBox1.Count) + ' -'); MyListBox1.GetTextChild(MyListBox1.Count-1).Container.Font.Name := "'Arial Black', arial, sans-serif"; MyListBox1.GetTextChild(MyListBox1.Count-1).AlignText := taCenter; MyListBox1.GetTextChild(MyListBox1.Count-1).Container.Font.Color := clBlue; end; W3btnLB1Delete.OnClick := lambda DeleteFrom(MyListBox1); end; (*-----------*) W3listbox1.Styles.SelectedColor := clLime; W3listbox1.Styles.HighlightedColor := clAquamarine; W3listbox1.Styles.MovingColor := clBurlyWood; W3listbox1.AllowMoving := true; B1Delete.OnClick := lambda DeleteFrom(W3listbox1); end; B1Add.OnClick := lambda AddItem(IntToStr(W3listbox1.Count)); end; end; procedure TForm1.DeleteFrom(listbox: TW3ListBox); begin if listbox.SelectedIndex >= 0 then listbox.Delete(listbox.SelectedIndex); end; function TForm1.GetTextChild(lb: TW3ListBox; idx: integer): TW3Label; begin Result := nil; var item := lb.Items[idx]; for var iChild := 0 to item.GetChildCount - 1 do begin var obj := item.GetChildObject(iChild); if Assigned(obj) and (obj is TW3Label) then Exit(TW3Label(obj)); end; end; procedure TForm1.Resize; begin inherited; end; initialization Forms.RegisterForm({$I %FILE%}, TForm1); end.
unit AT.ShortName.DX.TabFrameChild; interface uses AT.ShortName.Intf, cxPC, Vcl.Forms, System.Classes, Vcl.Controls; type TATdxTabFrameChild = class(TcxTabSheet, IATTabFrameChildUI, IATFrameCaptionChanged) strict private FFrame: TCustomFrame; FLinkForm: TCustomForm; strict protected function GetText: TCaption; function GetFrame: TCustomFrame; function GetNonClosing: Boolean; procedure SetText(const Value: TCaption); procedure _SetFrameAndProperties(AFrame: TCustomFrame; ALinkForm: TCustomForm; ANonClosing: Boolean); public constructor Create(AOwner: TComponent; AFrame: TCustomFrame; ALinkForm: TCustomForm = NIL; ANonClosing: Boolean = False); reintroduce; overload; virtual; constructor Create(AOwner: TComponent; AFrameClass: TCustomFrameClass; ALinkForm: TCustomForm = NIL; ANonClosing: Boolean = False); reintroduce; overload; virtual; procedure FrameCaptionChanged(const AValue: String); property Caption read GetText write SetText; property Frame: TCustomFrame read GetFrame; property NonClosing: Boolean read GetNonClosing; end; implementation uses System.SysUtils; constructor TATdxTabFrameChild.Create(AOwner: TComponent; AFrame: TCustomFrame; ALinkForm: TCustomForm = NIL; ANonClosing: Boolean = False); begin inherited Create(AOwner); _SetFrameAndProperties(AFrame, ALinkForm, ANonClosing); end; constructor TATdxTabFrameChild.Create(AOwner: TComponent; AFrameClass: TCustomFrameClass; ALinkForm: TCustomForm = NIL; ANonClosing: Boolean = False); begin inherited Create(AOwner); _SetFrameAndProperties(AFrameClass.Create(Self), ALinKForm, ANonClosing); end; procedure TATdxTabFrameChild.FrameCaptionChanged(const AValue: String); begin Caption := AValue; end; function TATdxTabFrameChild.GetText: TCaption; var Len: Integer; begin Len := GetTextLen; SetString(Result, PChar(nil), Len); if Len <> 0 then begin Len := Len - GetTextBuf(PChar(Result), Len + 1); if Len > 0 then SetLength(Result, Length(Result) - Len); end; end; function TATdxTabFrameChild.GetFrame: TCustomFrame; begin Result := FFrame; end; function TATdxTabFrameChild.GetNonClosing: Boolean; var AIntf: IATTabFrameNonClosing; begin if (Assigned(Frame)) then begin Result := (Supports(Frame, IATTabFrameNonClosing, AIntf)); if (Result) then Result := AIntf.IsNonClosing; end else Result := False; end; procedure TATdxTabFrameChild.SetText(const Value: TCaption); var AIntf: IATTabCaptionChanged; begin if (GetText <> Value) then SetTextBuf(PChar(Value)); if (Supports(FLinkForm, IATTabCaptionChanged, AIntf)) then AIntf.TabCaptionChanged(Value); end; procedure TATdxTabFrameChild._SetFrameAndProperties(AFrame: TCustomFrame; ALinkForm: TCustomForm; ANonClosing: Boolean); var ANCIntf: IATTabFrameNonClosing; ACapIntf: IATFrameCaption; begin FLinkForm := ALinkForm; FFrame := AFrame; if (Assigned(FFrame)) then begin if (Supports(FFrame, IATTabFrameNonClosing, ANCIntf)) then AllowCloseButton := (NOT ANCIntf.IsNonClosing); FFrame.Name := EmptyStr; FFrame.Parent := Self; FFrame.Align := alClient; FFrame.AlignWithMargins := True; FFrame.Margins.Left := 8; FFrame.Margins.Top := 8; FFrame.Margins.Right := 8; FFrame.Margins.Bottom := 8; FFrame.Show; if (Supports(FFrame, IATFrameCaption, ACapIntf)) then Caption := ACapIntf.Caption else Caption := 'New Child Tab'; end else begin Caption := 'New Child Tab'; end; end; end.
unit Model.Entity.CADASTRO_CARREGAMENTO; interface uses System.Generics.Collections, System.Classes, Rest.Json, System.JSON, SimpleAttributes; type [Tabela('CADASTRO_CARREGAMENTO')] TCADASTRO_CARREGAMENTO = class private FCODIGO: integer; FDATA_CARREGAMENTO: TDate; FLOCAL_CARREGAMENTO: string; FPESO_LIQ_CARGA: Double; FFRETE_TONELADA: Double; FTOTAL_FRETE: Double; FKM_INICIO: Double; FKM_CHEGADA: Double; FTOTAL_KM_RODADOS: Double; FPRODUTO_CARREGADO: string; public constructor Create; destructor Destroy; override; published {verificar os atributos do campo de chave primária} {Exemplo: [Campo('NOME_CAMPO'), PK, AutoInc] } [Campo('CODIGO'), PK] property CODIGO: integer read FCODIGO write FCODIGO; [Campo('DATA_CARREGAMENTO')] property DATA_CARREGAMENTO: TDate read FDATA_CARREGAMENTO write FDATA_CARREGAMENTO; [Campo('LOCAL_CARREGAMENTO')] property LOCAL_CARREGAMENTO: string read FLOCAL_CARREGAMENTO write FLOCAL_CARREGAMENTO; [Campo('PESO_LIQ_CARGA')] property PESO_LIQ_CARGA: Double read FPESO_LIQ_CARGA write FPESO_LIQ_CARGA; [Campo('FRETE_TONELADA')] property FRETE_TONELADA: Double read FFRETE_TONELADA write FFRETE_TONELADA; [Campo('TOTAL_FRETE')] property TOTAL_FRETE: Double read FTOTAL_FRETE write FTOTAL_FRETE; [Campo('KM_INICIO')] property KM_INICIO: Double read FKM_INICIO write FKM_INICIO; [Campo('KM_CHEGADA')] property KM_CHEGADA: Double read FKM_CHEGADA write FKM_CHEGADA; [Campo('TOTAL_KM_RODADOS')] property TOTAL_KM_RODADOS: Double read FTOTAL_KM_RODADOS write FTOTAL_KM_RODADOS; [Campo('PRODUTO_CARREGADO')] property PRODUTO_CARREGADO: string read FPRODUTO_CARREGADO write FPRODUTO_CARREGADO; function ToJSONObject: TJsonObject; function ToJsonString: string; end; implementation constructor TCADASTRO_CARREGAMENTO.Create; begin end; destructor TCADASTRO_CARREGAMENTO.Destroy; begin inherited; end; function TCADASTRO_CARREGAMENTO.ToJSONObject: TJsonObject; begin Result := TJson.ObjectToJsonObject(Self); end; function TCADASTRO_CARREGAMENTO.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; end.
unit ICONT; interface uses Vcl.Graphics, Winapi.Windows, System.Classes; type TIconDir = record idReserved: Word; idType: Word; idCount: Word; end; TIconDirEntry = record bWidth: Byte; bHeight: Byte; bColorCount: Byte; bReserved: Byte; wPlanes: Word; wBitCount: Word; dwBytesInRes: DWORD; dwImageOffset: DWORD; end; type TTNIcon = class(TIcon) public Count: Integer; public procedure AddIconImage(source: TGraphic); procedure LoadFromStream(Stream: TStream); override; end; implementation procedure TTNIcon.LoadFromStream(Stream: TStream); var Image: TMemoryStream; IconDir: TIconDir; IconDirEntry: TIconDirEntry; I: Integer; begin Image := TMemoryStream.Create; try Image.SetSize(Stream.Size - Stream.Position); Stream.ReadBuffer(Image.Memory^, Image.Size); Image.ReadBuffer(IconDir, SizeOf(IconDir)); if not (IconDir.idType in [RC3_STOCKICON, RC3_ICON]) then InvalidIcon; for I := 0 to IconDir.idCount - 1 do begin Image.ReadBuffer(IconDirEntry^, SizeOf(IconDirEntry)); end; //NewImage(0, Image); except Image.Free; raise; end; Changed(Self); end; end.
unit PluginUtil; interface uses Classes, Logger, CommonTypes, ProgressFormUnit, DataClass, Config; type RPluginDescriptor = record pluginHandle: HModule; pluginInstance: pointer; pluginName: string; className: string; fileName: string; end; TPlugin = class( TPersistent ) private procedure LoadConfig( ); protected fPluginName: string; fLogger: TLogger; // стандартный логгер fListParam: TStringList; //список параметров плагина fIntParam0: integer; fObjectParam: TObject; fDataItems: TItemArray; fCommonConfig: TAppConfig; fPluginConfig: TStringList; fProgressForm: TProgressForm; fOnRefreshGraphic: TNotifyEvent; public fDataClass: TDataClass; constructor Create( aPluginName: string; aConfig: TAppConfig; aLogLevel: enmLogLevel ); destructor Destroy( ); override; class function PluginName: string; virtual; abstract; procedure Init( ); virtual; abstract; procedure SetListParam( aParams: TStringList ); procedure SetIntParam0( aIntParam: integer ); procedure SetObject( aObject: TObject ); procedure SetDataClass( aDataClass: TDataClass ); procedure BeginWork; virtual; abstract; procedure EndWork; virtual; abstract; procedure UpdateWork( aObjectId: string ); virtual; abstract; procedure SetOnRefreshGraphic( aEvent: TNotifyEvent ); procedure FireOnRefreshGraphic( ); end; TPluginUtil = class private fApplicationName: string; //наименовние приложения, для определения ветки в регистри, откудова читать параметры fPluginList: array of RPluginDescriptor; fLogger: TLogger; function ListInstalledPlugins( ): string; public constructor Create( aAppName: string; aLogger: TLogger ); destructor Destroy( ); override; procedure LoadPlugins( ); function PluginCount( ): integer; function GetPluginName( aPluginIdx: integer ): string; function ListPluginNames( var aNames: TStringList ): boolean; function GetPluginByName( aPluginName: string; var aPlugin: TPlugin ): boolean; function GetPluginByIdx( aPluginIdx: integer ): TPlugin; end; TPluginClass = class of TPlugin; implementation uses Forms, Windows, SysUtils, StrUtils, RegistryUtil; constructor TPluginUtil.Create( aAppName: string; aLogger: TLogger ); var i: integer; fname: string; strs: TStringList; begin fApplicationName := aAppName; fLogger := aLogger; strs := TStringList.Create; strs.Delimiter := ';'; try strs.DelimitedText := ListInstalledPlugins( ); for i := 0 to strs.Count - 1 do begin SetLength( fPluginList, Length( fPluginList ) + 1 ); fname := strs.Names[i]; fPluginList[high( fPluginList )].fileName := fname; fPluginList[high( fPluginList )].className := strs.Values[fname]; end; finally strs.Free; end; end; destructor TPluginUtil.Destroy; var i: integer; value: string; pluginModule: HModule; plugin: TPlugin; begin for i := 0 to high( fPluginList ) do begin fLogger.Debug( ClassName, 'Unloading package: ' + fPluginList[i].className + ' - ' + fPluginList[i].pluginName ); if fPluginList[i].pluginInstance <> nil then begin FreeAndNil( fPluginList[i].pluginInstance ); UnloadPackage( fPluginList[i].pluginHandle ); end; end; SetLength( fPluginList, 0 ); inherited; end; function TPluginUtil.GetPluginByIdx( aPluginIdx: integer ): TPlugin; begin Result := fPluginList[aPluginIdx].pluginInstance; end; function TPluginUtil.GetPluginByName( aPluginName: string; var aPlugin: TPlugin ): boolean; var i: integer; begin Result := false; for i := 0 to high( fPluginList ) do begin if aPluginName = fPluginList[i].pluginName then begin aPlugin := fPluginList[i].pluginInstance; Result := true; Break; end; end; end; function TPluginUtil.GetPluginName( aPluginIdx: integer ): string; begin Result := fPluginList[aPluginIdx].pluginName; end; function TPluginUtil.ListInstalledPlugins: string; begin try Result := GetStringParam( 'installedPlugins', 'Software\DSCTool\' + fApplicationName ); except Result := ''; end; end; function TPluginUtil.ListPluginNames( var aNames: TStringList ): boolean; var i: integer; begin Result := false; if Length( fPluginList ) > 0 then begin for i := 0 to high( fPluginList ) do aNames.Add( fPluginList[i].pluginName ); Result := true; end; end; procedure TPluginUtil.LoadPlugins; var i: integer; fname: string; AClass: TPluginClass; plugin: TPlugin; begin for i := 0 to high( fPluginList ) do begin try fname := fPluginList[i].fileName; fname := ExtractFilePath( ParamStr( 0 ) ) + 'plugins\' + fname; fLogger.Debug( ClassName, 'Loading package: ' + fPluginList[i].className ); fPluginList[i].pluginHandle := LoadPackage( fname ); AClass := TPluginClass( FindClass( fPluginList[i].className ) ); plugin := AClass.Create( fPluginList[i].className, gConfig, fLogger.fLogLevel ); fPluginList[i].pluginInstance := plugin; fPluginList[i].pluginName := plugin.pluginName; except on E: Exception do raise Exception.Create( 'Произошла ошибка при загрузке плагина ' + fname + ': ' + E.message ); end; end; end; function TPluginUtil.PluginCount: integer; begin Result := Length( fPluginList ); end; constructor TPlugin.Create( aPluginName: string; aConfig: TAppConfig; aLogLevel: enmLogLevel ); begin if StartsStr( 'T', aPluginName ) then fPluginName := RightStr( aPluginName, Length( aPluginName ) - 1 ) else fPluginName := aPluginName; fCommonConfig := aConfig; fLogger := TLogger.Create( fPluginName, aLogLevel, fCommonConfig.fProgramDataPath ); fProgressForm := TProgressForm.Create( Application ); LoadConfig( ); end; destructor TPlugin.Destroy; begin if fPluginConfig <> nil then fPluginConfig.Free; if fLogger <> nil then begin fLogger.Debug( ClassName, 'Main destory called' ); FreeAndNil( fLogger ); end; inherited; end; procedure TPlugin.FireOnRefreshGraphic; begin if Assigned( fOnRefreshGraphic ) then fOnRefreshGraphic( Self ); end; procedure TPlugin.SetDataClass( aDataClass: TDataClass ); begin fDataClass := aDataClass; end; procedure TPlugin.SetIntParam0( aIntParam: integer ); begin fIntParam0 := aIntParam; end; procedure TPlugin.SetListParam( aParams: TStringList ); begin fListParam := aParams; end; procedure TPlugin.SetObject( aObject: TObject ); begin fObjectParam := aObject; end; procedure TPlugin.SetOnRefreshGraphic( aEvent: TNotifyEvent ); begin fOnRefreshGraphic := aEvent; end; procedure TPlugin.LoadConfig; var fileName: string; begin fileName := fCommonConfig.fProgramDataPath + fPluginName + '.ini'; if FileExists( fileName ) then begin fPluginConfig := TStringList.Create( ); fPluginConfig.LoadFromFile( fileName ); fLogger.Debug( ClassName, 'PluginConfig loaded from file: ' + fileName ); end; end; initialization finalization end.
unit SystemAuthentificationFormViewModelPropertiesINIFile; interface uses SystemAuthentificationFormViewModel, AbstractSystemAuthentificationFormViewModelPropertiesStorage, PropertiesIniFileUnit, SysUtils, Classes; const LOG_ON_INFO_SECTION_NAME = 'LogOnInfo'; LOGIN_PROPERTY_NAME = 'Login'; type TSystemAuthentificationFormViewModelPropertiesINIFile = class ( TAbstractSystemAuthentificationFormViewModelPropertiesStorage ) protected FPropertiesINIFile: TPropertiesIniFile; protected procedure SaveSystemAuthentificationFormViewModelProperties( ViewModel: TSystemAuthentificationFormViewModel ); override; procedure RestoreSystemAuthentificationFormViewModelProperties( ViewModel: TSystemAuthentificationFormViewModel ); override; public destructor Destroy; override; constructor Create(const PropertiesINIFilePath: String); end; implementation { TSystemAuthentificationFormViewModelPropertiesINIFile } constructor TSystemAuthentificationFormViewModelPropertiesINIFile.Create( const PropertiesINIFilePath: String); begin inherited Create; FPropertiesINIFile := TPropertiesIniFile.Create(PropertiesINIFilePath); end; destructor TSystemAuthentificationFormViewModelPropertiesINIFile.Destroy; begin FreeAndNil(FPropertiesINIFile); inherited; end; procedure TSystemAuthentificationFormViewModelPropertiesINIFile. RestoreSystemAuthentificationFormViewModelProperties( ViewModel: TSystemAuthentificationFormViewModel ); begin inherited; FPropertiesINIFile.GoToSection(LOG_ON_INFO_SECTION_NAME); ViewModel.ClientLogin := FPropertiesINIFile.ReadValueForProperty(LOGIN_PROPERTY_NAME, varString, ''); end; procedure TSystemAuthentificationFormViewModelPropertiesINIFile. SaveSystemAuthentificationFormViewModelProperties( ViewModel: TSystemAuthentificationFormViewModel ); begin inherited; FPropertiesINIFile.GoToSection(LOG_ON_INFO_SECTION_NAME); FPropertiesINIFile.WriteValueForProperty( LOGIN_PROPERTY_NAME, ViewModel.ClientLogin ); end; end.
unit zAVKernel; interface uses Types, Classes, SysUtils, Windows, zAVZArcKernel, // Модули связи с драйверами zAVZDriver, zAVZDriverN, zAVZDriverRK, zAVZDriverBC, WIZARDNN, zAntivirus, zVirFileList, zESScripting, zLogSystem, zXMLLogger; threadvar // Антивирус MainAntivirus : TAntivirus; // Система проверки сигнатур FileSignCheck : TFileSignCheck; // Главная нейросеть WizardNeuralNetwork : TWizardNeuralNetwork; // Настроки антикейлоггера KeyloggerBase : TKeyloggerBase; // Найстройки антируткита RootkitBase : TRootkitBase; // Макровирусы в документах Office OfficeMacroBase : TOfficeMacroBase; // Настройки проверки системы SystemCheck : TSystemCheck; // Настройки проверки системы - искатель пот. уязвимостей SystemIPU : TSystemIPU; // Настройки восстановления системы SystemRepair : TSystemRepair; // Стандартные скрипты StdScripts : TStdScripts; // Скрипты Backup BackupScripts : TBackupScripts; // База кода kernel-mode KMBase : TKMBase; // Драйвер AVZDriver : TAVZDriver; // Распаковщик архивов AVZDecompress : TAVZDecompress; // Модуль переводчика TranslateSys : TTranslate; // Эвристический анализатор памяти ESSystem : TESSystem; ESUserScript : TESUserScript; // База сканера памяти MemScanBase : TMemScanBase; // Список наденных файлов для индивидуальной обработки VirFileList : TVirFileList; // XML логгер для доп-данных, собираемых в ходе исследования системы XMLLogger : TXMLLogger; // Boot Cleaner AVZDriverBC : TAVZDriverBC; var // папка, в которой размещены базы AVPath : string; // папка, в которой размещен карантин QuarantineBaseFolder : string; // Признак того, что AVZ работает по сети NetWorkMode : boolean = false; // Признак того, что требуется перезагрузка RebootNeed : boolean; DeletedVirusList : TStrings; // папка, в которой размещаются временные файлы AVZTempDirectoryPath : string; // Режим именования папко для KAV KAVQuarantineMode : boolean = false; // Инициализация ядра function InitAVKernel(ALangId : string; AKavMode : byte = 0) : boolean; // Получение пути к папке карантина function GetQuarantineDirName(ASubFolder : string; ABaseFolder : boolean = false) : string; implementation uses zutil, zTranslate; function InitAVKernel(ALangId : string; AKavMode : byte = 0) : boolean; begin Result := false; ALangId := Trim(UpperCase(ALangId)); KMBase := nil; // Создание класса "Антивирус" MainAntivirus := TAntivirus.Create(AVPath);//#DNL // Система проверки сигнатур FileSignCheck := TFileSignCheck.Create(AVPath); //#DNL // Создание главного нейроэмулятора WizardNeuralNetwork := TWizardNeuralNetwork.Create; // Режим 0 - драйвера берутся из базы AVZ if AKavMode = 0 then begin // Инициализация хранилища драйверов KMBase := TKMBase.Create(AVPath);//#DNL KMBase.LoadBinDatabase; // Создание класса для управления драйвером AVZDriver := TAVZDriver.Create; AVZDriver.KMBase := KMBase; AVZDriver.DriverPath := GetSystemDirectoryPath+'Drivers\'; // Настройка AVZDriverSG AVZDriverSG.KMBase := KMBase; AVZDriverSG.DriverPath := GetSystemDirectoryPath+'Drivers\'; // Драйвер расширенного мониторинга AVZDriverRK := TAVZDriverRK.Create; AVZDriverRK.KMBase := KMBase; AVZDriverRK.DriverPath := AVZDriverSG.DriverPath; // Драйвер Boot Cleaner AVZDriverBC := TAVZDriverBC.Create; AVZDriverBC.KMBase := KMBase; AVZDriverBC.DriverPath := AVZDriverSG.DriverPath; end; // Режим 1 - драйвер KIS if AKavMode = 1 then begin // Инициализация хранилища драйверов (у нас его нет - заглушка) KMBase := nil; // Создание класса для управления драйвером AVZDriver := TAVZDriverKIS.Create; AVZDriver.KMBase := nil; // Настройка AVZDriverSG AVZDriverSG.KMBase := nil; AVZDriverSG.DriverPath := '-'; // Драйвер Boot Cleaner AVZDriverBC := TAVZDriverBCKIS.Create; AVZDriverBC.KMBase := nil; AVZDriverBC.DriverPath := '-'; end; ESUserScript := TESUserScript.Create; // Создание настроек кейлоггера KeyloggerBase := TKeyloggerBase.Create(AVPath);//#DNL // Создание настроек антируткита RootkitBase := TRootkitBase.Create(AVPath);//#DNL // Создание класса для поиска макровирусов в документах Office OfficeMacroBase := TOfficeMacroBase.Create(AVPath);//#DNL // Создание класса проверки системы SystemCheck := TSystemCheck.Create(AVPath);//#DNL // Создание класса поиска потенциальных уязвимостей SystemIPU := TSystemIPU.Create(AVPath);//#DNL // Настройки восстановления системы SystemRepair := TSystemRepair.Create(AVPath);//#DNL // База сканирования памяти MemScanBase := TMemScanBase.Create(AVPath);//#DNL // База стандартных скриптов StdScripts := TStdScripts.Create(AVPath);//#DNL // База скриптов backup BackupScripts := TBackupScripts.Create(AVPath);//#DNL // Создание класса-декомпрессора AVZDecompress := TAVZDecompress.Create(AVPath);//#DNL AVZDecompress.LoadBinDatabase; // Эвритисческая проверка ESSystem := TESSystem.Create(AVPath);//#DNL // Переводчик TranslateSys := TTranslate.Create(AVPath);//#DNL TranslateSys.LoadBinDatabase(ALangId); LangCode := ALangId; // Создание класса "Список вирусов" VirFileList := TVirFileList.Create; DeletedVirusList := TStringList.Create; // Создание XML логгера XMLLogger := TXMLLogger.Create; end; // Получение пути к папке карантина function GetQuarantineDirName(ASubFolder : string; ABaseFolder : boolean = false) : string; var Year, Month, Day : word; S : string; StrSize : dword; begin if KAVQuarantineMode then begin if ASubFolder = 'Quarantine' then ASubFolder := 'AVZ_Quarantine' else if ASubFolder = 'Infected' then ASubFolder := 'AVZ_Infected' else if ASubFolder = 'Backup' then ASubFolder := 'AVZ_Backup'; end; // Формирование базового пути Result := QuarantineBaseFolder + ASubFolder + '\'; // Добавление в сетевом режиме имени ПК в путь if NetWorkMode then begin SetLength(S, 200); StrSize := length(s); GetComputerName(PChar(S), StrSize); Result := Result + copy(S, 1, StrSize) + '\'; end; // Формирование динамической части (год-месяц-день) DecodeDate(Now, Year, Month, Day); if not(ABaseFolder) then Result := Result + IntToStr(Year) + '-' + FormatFloat('00', Month) + '-' + FormatFloat('00', Day)+'\'; Result := NormalDir(Result); end; end.
// Real (as in "Float") Color Library // // efg, September 1998 // September 2001, HLStoRGB error corrected. UNIT RealColorLibrary; INTERFACE USES Windows, // TRGBQuad Graphics, // TBitmap ImageProcessingPrimitives; // TReal, pRGBQuadArray TYPE TRealToRGBConversion = PROCEDURE (CONST x: TReal; VAR R,G,B: BYTE); TRealColorMatrix = // pf32bit Bitmap, or matrix of single float values CLASS(TBitmap) PRIVATE FUNCTION GetReal(i,j: Integer): TReal; PROCEDURE SetReal(i,j: Integer; value: TReal); PUBLIC CONSTRUCTOR Create; Override; PROCEDURE ConvertRealMatrixToRGBImage(ConversionFunction: TRealToRGBConversion); PROPERTY Element[i,j: Integer]: TReal READ GetReal Write SetReal; DEFAULT; END; // Color Conversions // HLS PROCEDURE HLStoRGB(CONST H,L,S: TReal; VAR R,G,B: TReal); PROCEDURE RGBToHLS(CONST R,G,B: TReal; VAR H,L,S: TReal); // HSV PROCEDURE HSVtoRGB(CONST H,S,V: TReal; VAR R,G,B: TReal); PROCEDURE RGBToHSV(CONST R,G,B: TReal; VAR H,S,V: TReal); // CMY PROCEDURE CMYtoRGB(CONST C,M,Y: TReal; VAR R,G,B: TReal); PROCEDURE RGBToCMY(CONST R,G,B: TReal; VAR C,M,Y: TReal); // CMYK PROCEDURE CMYKtoRGB(CONST C,M,Y,K: TReal; VAR R,G,B : TReal); PROCEDURE RGBToCMYK(CONST R,G,B : TReal; VAR C,M,Y,K: TReal); // Color Matrices: All Bitmap parameters are pf24bit bitmaps PROCEDURE BitmapToRGBMatrices(CONST Bitmap: TBitmap; VAR Red,Green,Blue: TRealColorMatrix); FUNCTION RGBMatricesToBitmap(CONST Red,Green,Blue: TRealColorMatrix): TBitmap; PROCEDURE RGBMatricesToHSVMatrices(CONST Red,Green,Blue: TRealColorMatrix; VAR Hue,Saturation,Value: TRealColorMatrix); PROCEDURE HSVMatricesToRGBMatrices(CONST Hue,Saturation,Value: TRealColorMatrix; VAR Red,Green,Blue: TRealColorMatrix); IMPLEMENTATION USES Math, // MaxValue IEEE754, // NAN (not a number) SysUtils; // Exception TYPE EColorError = CLASS(Exception); // == TColorMatrix ==================================================== // CONSTRUCTOR TRealColorMatrix.Create; BEGIN ASSERT (SizeOf(TRGBQuad) = SizeOf(TReal)); // to be sure Inherited Create; PixelFormat := pf32bit; // Each "pixel" is a "single" END {Create}; PROCEDURE TRealColorMatrix.ConvertRealMatrixToRGBImage(ConversionFunction: TRealToRGBConversion); VAR FloatRow: pSingleArray; i : INTEGER; j : INTEGER; PixelRow: pRGBQuadArray; R,G,B : BYTE; BEGIN FOR j := 0 TO Height-1 DO BEGIN PixelRow := Scanline[j]; FloatRow := Scanline[j]; FOR i := 0 TO Width-1 DO BEGIN ConversionFunction(FloatRow[i], R,G,B); WITH PixelRow[i] DO BEGIN rgbRed := R; rgbGreen := G; rgbBlue := B; rgbReserved := 0 END END END END {ConvertSingleToRGB}; FUNCTION TRealColorMatrix.GetReal(i,j: Integer): TReal; BEGIN RESULT := pSingleArray(Scanline[j])[i] END {GetSingle}; PROCEDURE TRealColorMatrix.SetReal(i,j: Integer; value: TReal); BEGIN pSingleArray(Scanline[j])[i] := value END {SetSingle}; // == HLS / RGB ======================================================= // // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 596. PROCEDURE HLStoRGB(CONST H,L,S: TReal; VAR R,G,B: TReal); VAR m1: TReal; m2: TReal; FUNCTION Value(CONST n1,n2: TReal; hue: TReal): TReal; BEGIN IF hue > 360.0 THEN hue := hue - 360.0 ELSE IF hue < 0.0 THEN hue := hue + 360.0; IF hue < 60.0 THEN RESULT := n1 + (n2 - n1)*hue / 60.0 ELSE IF hue < 180 THEN RESULT := n2 ELSE IF hue < 240.0 THEN RESULT := n1 + (n2-n1)*(240.0 - hue) / 60.0 ELSE RESULT := n1 END {Value}; BEGIN // There is an error in Computer Graphics Principles and Practice, // Foley, et al, 1996, pp. 592-596. The formula uses a lower case // "el", "l", and defines in C: // // m2 = (l < 0.5) ? (l * (l+s)):(l+s-l*s) // // This is a perfect example of why "l" (a lower case "el") should // NEVER be used as a variable name, and why a programming convention -- // to use lower case letters in variable names -- should not override // the problem definition, which defines the color space using an "L". // The 1982 version of the book, in Pascal, shows the correct formula // (but alas, also used a lower case "l"): // // if l <= 0.5 // then m2 := l*(1+s) // NOTE the one, in "1+s", here // else m2 := l + s - l*s  // // [Thanks to Gary Freestone, IBM Global Services Australia, for // bringing this to my attention. efg, Sept. 2001] IF L <= 0.5 THEN m2 := L * (1 + S) ELSE m2 := L + S - L*S; m1 := 2.0 * L - m2; IF S = 0.0 THEN BEGIN // achromatic -- no hue IF IsNAN(H) THEN BEGIN R := L; G := L; B := L END ELSE RAISE EColorError.Create('HLStoRGB: S = 0 and H has a value'); END ELSE BEGIN // Chromatic case -- there is a hue R := Value(m1, m2, H + 120.0); G := Value(m1, m2, H); B := Value(m1, m2, H - 120.0) END END {HLStoRGB}; // H = 0 to 360 (corresponding to 0..360 degrees around hexcone) // L = 0.0 (shade of gray) to 1.0 (pure color) // S = 0.0 (black) to 1.0 {white) // // R, G, B each in [0,1] // // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 595. PROCEDURE RGBToHLS (CONST R,G,B: TReal; VAR H,L,S: TReal); VAR Delta: TReal; Max : TReal; Min : TReal; BEGIN Max := MaxValue( [R, G, B] ); Min := MinValue( [R, G, B] ); L := (Max + Min) / 2.0; // Lightness IF Max = Min // Achromatic case since r = g = b THEN BEGIN S := 0.0; H := NAN; // Undefined END ELSE BEGIN Delta := Max - Min; IF L <= 0.5 THEN S := Delta / (Max + Min) ELSE S := Delta / (2.0 - (Max + Min)); IF R = Max THEN // degrees between yellow and magenta H := (60.0*(G - B)) / Delta ELSE IF G = Max THEN // degrees between cyan and yellow H := 120.0 + (60.0*(B - R)) / Delta ELSE IF B = Max THEN // degrees between magenta and cyan H := 240.0 + (60.0*(R - G)) / Delta; IF H < 0 THEN H := H + 360.0; // Keep in interval [0, 360) END END {RGBtoHLS}; // == HSV / RGB ======================================================= // // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 593. // // H = 0.0 to 360.0 (corresponding to 0..360 degrees around hexcone) // NaN (undefined) for S = 0 // S = 0.0 (shade of gray) to 1.0 (pure color) // V = 0.0 (black) to 1.0 (white) PROCEDURE HSVtoRGB (CONST H,S,V: TReal; VAR R,G,B: TReal); VAR f : TReal; i : INTEGER; hTemp: TReal; // since H is CONST parameter p,q,t: TReal; BEGIN IF S = 0.0 // color is on black-and-white center line THEN BEGIN IF IsNaN(H) THEN BEGIN R := V; // achromatic: shades of gray G := V; B := V END ELSE RAISE EColorError.Create('HSVtoRGB: S = 0 and H has a value'); END ELSE BEGIN // chromatic color IF H = 360.0 // 360 degrees same as 0 degrees THEN hTemp := 0.0 ELSE hTemp := H; hTemp := hTemp / 60; // h is now IN [0,6) i := TRUNC(hTemp); // largest integer <= h f := hTemp - i; // fractional part of h p := V * (1.0 - S); q := V * (1.0 - (S * f)); t := V * (1.0 - (S * (1.0 - f))); CASE i OF 0: BEGIN R := V; G := t; B := p END; 1: BEGIN R := q; G := V; B := p END; 2: BEGIN R := p; G := V; B := t END; 3: BEGIN R := p; G := q; B := V END; 4: BEGIN R := t; G := p; B := V END; 5: BEGIN R := V; G := p; B := q END END END END {HSVtoRGB}; // RGB, each 0 to 255, to HSV. // H = 0.0 to 360.0 (corresponding to 0..360.0 degrees around hexcone) // S = 0.0 (shade of gray) to 1.0 (pure color) // V = 0.0 (black) to 1.0 {white) // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 592. Floating point fractions, 0..1, replaced with // integer values, 0..255. PROCEDURE RGBToHSV (CONST R,G,B: TReal; VAR H,S,V: TReal); VAR Delta: TReal; Min : TReal; BEGIN Min := MinValue( [R, G, B] ); V := MaxValue( [R, G, B] ); Delta := V - Min; // Calculate saturation: saturation is 0 if r, g and b are all 0 IF V = 0.0 THEN S := 0 ELSE S := Delta / V; IF S = 0.0 THEN H := NAN // Achromatic: When s = 0, h is undefined ELSE BEGIN // Chromatic IF R = V THEN // between yellow and magenta [degrees] H := 60.0 * (G - B) / Delta ELSE IF G = V THEN // between cyan and yellow H := 120.0 + 60.0 * (B - R) / Delta ELSE IF B = V THEN // between magenta and cyan H := 240.0 + 60.0 * (R - G) / Delta; IF H < 0.0 THEN H := H + 360.0 END END {RGBtoHSV}; // == CMY / RGB ======================================================= // // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 588 // R, G, B, C, M, Y each IN [0.0 .. 1.0] PROCEDURE CMYtoRGB(CONST C,M,Y: TReal; VAR R,G,B: TReal); BEGIN R := 1.0 - C; G := 1.0 - M; B := 1.0 - Y END {CMYtoRGB}; // R, G, B, C, M, Y each IN [0.0 .. 1.0] PROCEDURE RGBtoCMY(CONST R,G,B: TReal; VAR C,M,Y: TReal); BEGIN C := 1.0 - R; M := 1.0 - G; Y := 1.0 - B END {RGBtoCMY}; // == CMYK / RGB ====================================================== // // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 589 // R, G, B, C, M, Y, K each IN [0.0 .. 1.0] PROCEDURE CMYKtoRGB(CONST C,M,Y,K: TReal; VAR R,G,B: TReal); BEGIN R := 1.0 - (C + K); G := 1.0 - (M + K); B := 1.0 - (Y + K) END {CMYtoRGB}; // R, G, B, C, M, Y each IN [0.0 .. 1.0] PROCEDURE RGBToCMYK(CONST R,G,B: TReal; VAR C,M,Y,K: TReal); BEGIN RGBtoCMY(R,G,B, C,M,Y); K := MinValue([C, M, Y]); C := C - K; M := M - K; Y := Y - K END {RGBtoCMYK}; // == Color Matrices ================================================= // PROCEDURE BitmapToRGBMatrices(CONST Bitmap: TBitmap; VAR Red,Green,Blue: TRealColorMatrix); VAR i,j: INTEGER; row: pRGBTripleArray; BEGIN ASSERT (Bitmap.PixelFormat = pf24bit); Red := TRealColorMatrix.Create; Red.Width := Bitmap.Width; Red.Height := Bitmap.Height; Green := TRealColorMatrix.Create; Green.Width := Bitmap.Width; Green.Height := Bitmap.Height; Blue := TRealColorMatrix.Create; Blue.Width := Bitmap.Width; Blue.Height := Bitmap.Height; FOR j := 0 TO Bitmap.Height-1 DO BEGIN row := Bitmap.Scanline[j]; FOR i := 0 TO Bitmap.Width-1 DO BEGIN Red[i,j] := row[i].rgbtRed / 255; // 0.0 to 1.0 Green[i,j] := row[i].rgbtGreen / 255; Blue[i,j] := row[i].rgbtBlue / 255; END END END {BitmapToRGBMatrices}; FUNCTION RGBMatricesToBitmap(CONST Red,Green,Blue: TRealColorMatrix): TBitmap; VAR i,j: INTEGER; row: pRGBTripleArray; BEGIN ASSERT( (Red.Width = Green.Width) AND (Red.Width = Blue.Width) AND (Red.Height = Green.Height) AND (Red.Height = Blue.Height) ); RESULT := TBitmap.Create; RESULT.Width := Red.Width; RESULT.Height := Red.Height; RESULT.PixelFormat := pf24bit; FOR j := 0 TO Red.Height-1 DO BEGIN row := RESULT.Scanline[j]; FOR i := 0 TO Red.Width-1 DO BEGIN WITH row[i] DO BEGIN rgbtRed := TRUNC(Red[i,j] * 255 + 0.5); rgbtGreen := TRUNC(Green[i,j] * 255 + 0.5); rgbtBlue := TRUNC(Blue[i,j] * 255 + 0.5); END END END END {RGBMatricesToBitmap}; PROCEDURE RGBMatricesToHSVMatrices(CONST Red,Green,Blue: TRealColorMatrix; VAR Hue,Saturation,Value: TRealColorMatrix); VAR i,j : INTEGER; H,S,V: TReal; BEGIN ASSERT( (Red.Width = Green.Width) AND (Red.Width = Blue.Width) AND (Red.Height = Green.Height) AND (Red.Height = Blue.Height) AND (Hue.Width = Saturation.Width) AND (Hue.Width = Value.Width) AND (Hue.Height = Saturation.Height) AND (Hue.Height = Value.Height) ); FOR j := 0 TO Red.Height-1 DO BEGIN FOR i := 0 TO Red.Width-1 DO BEGIN RGBToHSV(Red[i,j], Green[i,j], Blue[i,j], H, S, V); Hue[i,j] := H; Saturation[i,j] := S; Value[i,j] := V END END END {RGBMatricesToHSVMatrices}; PROCEDURE HSVMatricesToRGBMatrices(CONST Hue,Saturation,Value: TRealColorMatrix; VAR Red,Green,Blue: TRealColorMatrix); VAR i,j : INTEGER; R,G,B: TReal; BEGIN ASSERT( (Red.Width = Green.Width) AND (Red.Width = Blue.Width) AND (Red.Height = Green.Height) AND (Red.Height = Blue.Height) AND (Hue.Width = Saturation.Width) AND (Hue.Width = Value.Width) AND (Hue.Height = Saturation.Height) AND (Hue.Height = Value.Height) ); FOR j := 0 TO Red.Height-1 DO BEGIN FOR i := 0 TO Red.Width-1 DO BEGIN HSVToRGB(Hue[i,j], Saturation[i,j], Value[i,j], R, G, B); Red[i,j] := R; Green[i,j] := G; Blue[i,j] := B END END END {HSVMatriceesToRGBMatrices}; END.
unit uInterfaceObjeto; interface uses uCalculadoraEventos; type iCalculadora = interface; iOperacoesDisplay = interface; iOperacoes = interface ['{DF845E6B-AEC8-4670-97E9-165A9831B298}'] function Executar: string; function Display : iOperacoesDisplay; end; iOperacoesDisplay = interface ['{1B7B9644-935D-42AC-9FFA-4324029E0DDD}'] function Resultado(Value: TEventoDisplay): iOperacoesDisplay; function EndDisplay : iOperacoes; end; iCalculadoraDisplay = interface ['{241BB46F-82DC-41C7-B3F3-09B37FC2BF39}'] function Resultado(Value: TEventoDisplay): iCalculadoraDisplay; function EndDisplay: iCalculadora; end; iCalculadora = interface ['{41DC5E6A-44D3-4C98-AF75-C265AC72C083}'] function Add(Value: String): iCalculadora; overload; function Add(Value: Integer): iCalculadora; overload; function Add(Value: Currency): iCalculadora; overload; function Somar: iOperacoes; function Subtrair: iOperacoes; function Multiplicar: iOperacoes; function Dividir: iOperacoes; function Display: iCalculadoraDisplay; end; implementation end.
unit frm_TileEditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GR32, GR32_Image, GR32_layers,StdCtrls; type Tfrm8x8TileEditor = class(TForm) imgTile: TImage32; imgAvailPal: TImage32; cmdOK: TButton; cmdCancel: TButton; procedure FormShow(Sender: TObject); procedure imgTileMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure imgTileMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure imgAvailPalMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure cmdOKClick(Sender: TObject); private SelPalLeft,SelPalRight : Byte; procedure Draw8x8Tile; procedure DisplayPalette; { Private declarations } public TileID : Integer; { Public declarations } end; var frm8x8TileEditor: Tfrm8x8TileEditor; implementation uses unit_global, classes_Graphics; var DaTile : T8x8Graphic; {$R *.dfm} procedure Tfrm8x8TileEditor.FormShow(Sender: TObject); begin DaTile := RNAROM.Export8x8Pat(TileID); // showmessage(IntToStr(DaTile.Pixels[0,0])); Draw8x8Tile(); DisplayPalette(); end; procedure Tfrm8x8TileEditor.DisplayPalette(); var TempBitmap : TBitmap32; begin TempBitmap := TBitmap32.Create; try TempBitmap.Width := 40; TempBitmap.Height := 25; TempBitmap.FillRect(0,0,10,25, RNAROM.ReturnColor32NESPal(RNAROM.Palette[RNAOptions.LastPaletteTileEditor,0])); TempBitmap.FillRect(10,0,20,25, RNAROM.ReturnColor32NESPal(RNAROM.Palette[RNAOptions.LastPaletteTileEditor,1])); TempBitmap.FillRect(20,0,30,25, RNAROM.ReturnColor32NESPal(RNAROM.Palette[RNAOptions.LastPaletteTileEditor,2])); TempBitmap.FillRect(30,0,40,25, RNAROM.ReturnColor32NESPal(RNAROM.Palette[RNAOptions.LastPaletteTileEditor,3])); if SelPalLeft = SelPalRight then begin TempBitmap.Line(SelPalLeft*10,0,SelPalLeft*10, 25,RNAOptions.LeftTextColour); TempBitmap.Line(SelPalLeft*10,0,SelPalLeft*10 + 10,0,RNAOptions.LeftTextColour); TempBitmap.Line(SelPalRight*10 + 9,1,SelPalRight*10 + 9,25,RNAOptions.MiddleTextColour); TempBitmap.Line(SelPalRight*10,24,SelPalRight*10 + 9,24,RNAOptions.MiddleTextColour); // TempBitmap.Line(SelPalRight*10 + 0,SelPalRight*32+31,32,SelPalRight* 32+31,RNAOptions.MiddleTextColour); // TempBitmap.FrameRectS(SelPalLeft * 10,0,SelPalLeft * 10 + 10,25,RNAOptions.LeftTextColour); // TempBitmap.FrameRectS(SelPalRight * 10,0,SelPalRight * 10 + 10,25,RNAOptions.MiddleTextColour); end else begin TempBitmap.FrameRectS(SelPalLeft * 10,0,SelPalLeft * 10 + 10,25,RNAOptions.LeftTextColour); TempBitmap.FrameRectS(SelPalRight * 10,0,SelPalRight * 10 + 10,25,RNAOptions.MiddleTextColour); end; imgAvailPal.Bitmap := TempBitmap; finally FreeAndNil(TempBitmap); end; end; procedure Tfrm8x8TileEditor.Draw8x8Tile(); var i,x : Integer; TempBitmap : TBitmap32; begin TempBitmap := TBitmap32.Create; try TempBitmap.Width := 8; TempBitmap.Height := 8; for x := 0 to 7 do for i := 0 to 7 do TempBitmap.Pixel[x,i] := RNAROM.ReturnColor32NESPal(RNAROM.Palette[RNAOptions.LastPaletteTileEditor,DaTile.Pixels[i,x]]); imgTile.Bitmap := TempBitmap; finally FreeAndNil(TempBitmap); end; end; procedure Tfrm8x8TileEditor.imgTileMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin if Button = mbLeft then begin if (y div 20 > 7) or (x div 20 > 7) then exit; DaTile.Pixels[Y div 20,X div 20] := SelPalLeft; Draw8x8Tile(); end else if Button = mbRight then begin if (y div 20 > 7) or (x div 20 > 7) then exit; DaTile.Pixels[Y div 20,X div 20] := SelPalRight; Draw8x8Tile(); end; end; procedure Tfrm8x8TileEditor.imgTileMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin if ssLeft in Shift then begin if x < 0 then exit; if (y div 20 > 7) or (x div 20 > 7) then exit; DaTile.Pixels[Y div 20,X div 20] := SelPalLeft; Draw8x8Tile(); end else if ssRight in Shift then begin if x < 0 then exit; if (y div 20 > 7) or (x div 20 > 7) then exit; DaTile.Pixels[Y div 20,X div 20] := SelPalRight; Draw8x8Tile(); end; end; procedure Tfrm8x8TileEditor.imgAvailPalMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin if button = mbLeft then begin SelPalLeft := X div 20; DisplayPalette(); end else if Button = mbRight then begin SelPalRight := X div 20; DisplayPalette(); end else if Button = mbMiddle then begin if RNAOptions.LastPaletteTileEditor = 3 then RNAOptions.LastPaletteTileEditor := 0 else RNAOptions.LastPaletteTileEditor := RNAOptions.LastPaletteTileEditor +1; DisplayPalette; Draw8x8Tile(); end; end; procedure Tfrm8x8TileEditor.cmdOKClick(Sender: TObject); begin RNAROM.Import8x8Pat(TileID,DaTile); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 2001-2002 Borland Software Corporation } { } {*******************************************************} unit AMHelp; interface uses Classes, ActnList, ActnMan; type TAMHelp = class(TComponent) private FAction: TCustomAction; FActionManager: TCustomActionManager; FCaption: string; FCompareProc: TActionProc; FFoundClient: TActionClientItem; procedure CompareCaption(AClient: TActionClient); procedure CompareAction(AClient: TActionClient); function FindItem: TActionClientItem; protected procedure FindClient(AClient: TActionClient); procedure Notification(AComponent: TComponent; Operation: TOperation); override; public function AddAction(AnAction: TCustomAction; AClient: TActionClient; After: Boolean = True): TActionClientItem; function AddCategory(ACategory: string; AClient: TActionClient; After: Boolean = True): TActionClientItem; function AddSeparator(AnItem: TActionClientItem; After: Boolean = True): TActionClientItem; procedure DeleteActionItems(Actions: array of TCustomAction); procedure DeleteItem(Caption: string); function FindItemByCaption(ACaption: string): TActionClientItem; function FindItemByAction(Action: TCustomAction): TActionClientItem; published property ActionManager: TCustomActionManager read FActionManager write FActionManager; end; procedure Register; implementation uses SysUtils; { TAMHelp } { AddAction adds AnAction to an ActionBand either before or after AClient. Use this method to insert a new action into an existing ActionBand. Use one of the FindItemxxx methods to locate the position at which you want to insert the new item. } function TAMHelp.AddAction(AnAction: TCustomAction; AClient: TActionClient; After: Boolean): TActionClientItem; begin Result := nil; if (FActionManager = nil) or (AClient = nil) or (AClient.Collection = nil) then exit; Result := TActionClientItem(AClient.Collection.Add); Result.Index := AClient.Index + Integer(After); Result.Action := AnAction; end; type TActionManagerClass = class(TCustomActionManager); TActionArray = array of TContainedAction; function AddActions(var Actions: TActionArray; ActionList: TCustomActionList; ACategory: string): Integer; var I: Integer; begin Result := Length(Actions); if ActionList = nil then exit; SetLength(Actions, Result + ActionList.ActionCount); for I := 0 to ActionList.ActionCount - 1 do if CompareText(ActionList[I].Category, ACategory) = 0 then begin Actions[Result] := ActionList[I]; Inc(Result); end; SetLength(Actions, Result); end; { AddCategory adds all of the actions from ACategory to an ActionBand inserting it either before or after the AClient item. } function TAMHelp.AddCategory(ACategory: string; AClient: TActionClient; After: Boolean): TActionClientItem; var I: Integer; Actions: TActionArray; begin Result := nil; if (FActionManager = nil) or (AClient = nil) then exit; AddActions(Actions, FActionManager, ACategory); for I := 0 to FActionManager.LinkedActionLists.Count - 1 do AddActions(Actions, FActionManager.LinkedActionLists[I].ActionList, ACategory); with AClient as TActionClient do begin Result := TActionManagerClass(ActionManager).GetActionClientItemClass.Create(nil); Result.Caption := ACategory; Result.Collection := AClient.Collection; Result.Index := AClient.Index + Integer(After); for I := 0 to Length(Actions) - 1 do Result.Items.Add.Action := Actions[I]; Result.Control.Enabled := True; end; end; { AddSeparator adds a separator to an ActionBand following AnItem. Use the FindItemxxx methods to locate the item you want to instert a separator either before or after. } function TAMHelp.AddSeparator( AnItem: TActionClientItem; After: Boolean = True): TActionClientItem; begin Result := nil; if (FActionManager = nil) or (AnItem = nil) or (AnItem.ActionClients = nil) then exit; Result := AnItem.ActionClients.Add; Result.Caption := '|'; Result.Index := AnItem.Index + Integer(After); end; procedure TAMHelp.CompareAction(AClient: TActionClient); begin if AClient is TActionClientItem then with AClient as TActionClientItem do if Action = FAction then FFoundClient := TActionClientItem(AClient); end; procedure TAMHelp.CompareCaption(AClient: TActionClient); begin if AClient is TActionClientItem then with AClient as TActionClientItem do if CompareText(Caption, FCaption) = 0 then FFoundClient := TActionClientItem(AClient); end; { DeleteActionItems removes items from the ActionBars collection which are linked to the Actions specified. } procedure TAMHelp.DeleteActionItems(Actions: array of TCustomAction); var I: Integer; Item: TActionClientItem; begin if FActionManager = nil then exit; for I := Low(Actions) to High(Actions) do begin Item := FindItemByAction(Actions[I]); if Assigned(Item) then Item.Free; end; end; { DeleteItem deletes an ActionBand item after locating it based on it's Caption. } procedure TAMHelp.DeleteItem(Caption: string); var Item: TActionClientItem; begin FFoundClient := nil; FCaption := Caption; Item := FindItemByCaption(Caption); if Assigned(Item) then Item.Free; end; procedure TAMHelp.FindClient(AClient: TActionClient); begin if Assigned(AClient) and Assigned(FCompareProc) and Assigned(FFoundClient) then exit; // Only find the first occurance FCompareProc(AClient); end; function TAMHelp.FindItem: TActionClientItem; begin Result := nil; if FActionManager = nil then exit; FFoundClient := nil; ActionManager.ActionBars.IterateClients(ActionManager.ActionBars, FindClient); Result := FFoundClient; end; { FindItemByAction takes an Action and returns the first item that is linked to that action. } function TAMHelp.FindItemByAction( Action: TCustomAction): TActionClientItem; begin FCompareProc := CompareAction; FAction := Action; Result := FindItem; end; { FindItemByCaption takes ACaption and returns the first item with a matching caption. } function TAMHelp.FindItemByCaption( ACaption: string): TActionClientItem; begin FCompareProc := CompareCaption; FCaption := ACaption; Result := FindItem; end; procedure TAMHelp.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (FActionManager = AComponent) then FActionManager := nil; end; procedure Register; begin RegisterComponents('mtkComponents', [TAMHelp]); end; end.
unit SimThyrCLIServices; { SimThyr Project } { A numerical simulator of thyrotropic feedback control } { Version 5.0.0 (Mirage) } { (c) J. W. Dietrich, 1994 - 2022 } { (c) Ludwig Maximilian University of Munich 1995 - 2002 } { (c) Ruhr University of Bochum 2005 - 2022 } { This unit provides some global functions for use by other units } { Source code released under the BSD License } { See http://simthyr.sourceforge.net for details } {$mode objfpc}{$R+} {$IFDEF LCLCocoa} {$modeswitch objectivec1} {$ENDIF} interface uses Classes, SysUtils, StrUtils, CRT, UnitConverter, SimThyrTypes, SimThyrResources; const kLength = 8; kScale = 160; minWidth = 4; var gLength: integer; procedure SetParameterUnits; procedure SetConversionFactors; procedure WriteTableHeader; procedure WriteTableLine(theLine: tResultContent); procedure ShowErrorMessage(theMessage: String); procedure ShowFileError; procedure ShowVersionError; procedure ShowFormatError; implementation procedure SetParameterUnits; begin gParameterUnit[t_pos] := 'day h:m:s'; gParameterUnit[TRH_pos] := 'ng/L'; gParameterUnit[pTSH_pos] := 'mIU/L'; gParameterUnit[TSH_pos] := gParameterUnit[pTSH_pos]; gParameterUnit[TT4_pos] := 'nmol/L'; gParameterUnit[FT4_pos] := 'pmol/L'; gParameterUnit[TT3_pos] := 'nmol/L'; gParameterUnit[FT3_pos] := 'pmol/L'; gParameterUnit[cT3_pos] := gParameterUnit[FT3_pos]; end; procedure SetConversionFactors; begin gParameterFactor[TRH_pos] := 1; gParameterFactor[pTSH_pos] := 1; gParameterFactor[TSH_pos] := gParameterFactor[pTSH_pos]; gParameterFactor[TT4_pos] := ConvertedValue(1, T4_MOLAR_MASS, 'ng/dl', gParameterUnit[TT4_pos]); gParameterFactor[FT4_pos] := ConvertedValue(1, T4_MOLAR_MASS, 'ng/dl', gParameterUnit[FT4_pos]); gParameterFactor[TT3_pos] := ConvertedValue(1, T3_MOLAR_MASS, 'pg/ml', gParameterUnit[TT3_pos]); gParameterFactor[FT3_pos] := ConvertedValue(1, T3_MOLAR_MASS, 'pg/ml', gParameterUnit[FT3_pos]); gParameterFactor[cT3_pos] := ConvertedValue(1, T3_MOLAR_MASS, 'pg/ml', gParameterUnit[cT3_pos]); end; procedure WriteTableHeader; var termWidth: integer; begin {$IFDEF Windows} termWidth := WindMaxX; {$ELSE} termWidth := ScreenWidth; {$ENDIF} if termWidth > kScale then gLength := kLength else gLength := minWidth + termWidth div kScale * kLength; writeln; write(AddChar(' ', 'i', gLength) + kTab + AddChar(' ', 't', gLength) + kTab); write(AddChar(' ', 'TRH', gLength) + kTab + AddChar(' ', 'pTSH', gLength) + kTab); write(AddChar(' ', 'TSH', gLength) + kTab + AddChar(' ', 'TT4', gLength) + kTab); write(AddChar(' ', 'FT4', gLength) + kTab + AddChar(' ', 'TT3', gLength) + kTab); write(AddChar(' ', 'FT3', gLength) + kTab + AddChar(' ', 'cT3', gLength) + kTab); writeln(); write(AddChar(' ', ' ', gLength) + kTab); write(AddChar(' ', gParameterUnit[t_pos], gLength) + kTab); write(AddChar(' ', gParameterUnit[TRH_pos], gLength) + kTab); write(AddChar(' ', gParameterUnit[pTSH_pos], gLength) + kTab); write(AddChar(' ', gParameterUnit[TSH_pos], gLength) + kTab); write(AddChar(' ', gParameterUnit[TT4_pos], gLength) + kTab); write(AddChar(' ', gParameterUnit[FT4_pos], gLength) + kTab); write(AddChar(' ', gParameterUnit[TT3_pos], gLength) + kTab); write(AddChar(' ', gParameterUnit[FT3_pos], gLength) + kTab); write(AddChar(' ', gParameterUnit[cT3_pos], gLength) + kTab); writeln(); end; procedure WriteTableLine(theLine: tResultContent); {Writes contents of table line to the console (SimThyr CLI only)} var i: integer; begin for i := 0 to length(theLine) - 1 do begin if i = 2 then write(AddChar(' ', theLine[i], 10)) else write(AddChar(' ', theLine[i], gLength)); write(kTab); end; writeln; end; procedure ShowErrorMessage(theMessage: String); begin writeln(theMessage); end; procedure ShowFileError; begin writeln(FILE_FORMAT_ERROR_MESSAGE); end; procedure ShowVersionError; begin writeln(FILE_VERSION_MESSAGE); end; procedure ShowFormatError; begin writeln(FORMAT_MESSAGE); end; end.
program main; { TITLE: PROGRAMMING II LABS SUBTITLE: Practical 2 AUTHOR 1: Carlos Torres Paz LOGIN 1: carlos.torres@udc.es AUTHOR 2: Daniel Sergio Vega Rodriguez LOGIN 2: d.s.vega@udc.es GROUP: 5.4 DATE: 03/05/2019 } uses sysutils,Manager,SharedTypes,RequestQueue; procedure Create(cName: tCenterName; numVotes: tNumVotes; var Mng: tManager); begin if insertCenter(cName,numVotes,Mng) then (* Si fue posible la inserción *) writeln('* Create: center ',cName,' totalvoters ',numVotes:0) else writeln('+ Error: Create not possible'); end; procedure New(cName: tCenterName; pName: tPartyName; var Mng: tManager); begin if insertPartyInCenter(cName, pName,Mng) then (* Si fue posible la inserción *) writeln('* New: center ',cName, ' party ',pName) else writeln('+ Error: New not possible'); end; procedure Vote(cName : tCenterName; pName : tPartyName; var Mng: tManager); begin if voteInCenter(cName, pName, Mng) then writeln('* Vote: center ',cName,' party ',pName) else begin write('+ Error: Vote not possible.'); (*En caso de no encontrar el partido o el centro da error, en el primer caso error el voto se suma a NULLVOTES *) if voteInCenter(cName,NULLVOTE, Mng) then writeln(' Party ',pName, ' not found in center ',cName, '. NULLVOTE') else writeln; end; end; procedure Remove(var Mng : tManager); begin if deleteCenters(Mng) = 0 then writeln('* Remove: No centers removed'); end; procedure Stats(var Mng: tManager); begin ShowStats(Mng); end; {----------------------------------------} procedure RunTasks(var Queue: tQueue); forward; procedure readTasks(filename:string); VAR usersFile : text; line : string; QItem : tItemQ; Queue : tQueue; begin {proceso de lectura del fichero filename } {$i-} { Deactivate checkout of input/output errors} Assign(usersFile, filename); Reset(usersFile); {$i+} { Activate checkout of input/output errors} if (IoResult <> 0) then begin writeln('**** Error reading '+filename); halt(1) end; createEmptyQueue(Queue); while not EOF(usersFile) do begin { Read a line in the file and save it in different variables} ReadLn(usersFile, line); QItem.code := trim(copy(line,1,2)); QItem.request:= line[4]; QItem.param1 := trim(copy(line,5,10)); { trim removes blank spaces of the string} { copy(s, i, j) copies j characters of string s } { from position i } QItem.param2 := trim(copy(line,15,10)); if not enqueue(QItem,Queue) then begin writeln('**** Queue is full ****'); break; end; end; Close(usersFile); RunTasks(Queue); end; procedure RunTasks(var Queue: tQueue); var QItem : tItemQ; (* Variable que guarda un nodo de la cola para la extracción de sus datos*) Mng : tManager; (* La multilista que se usará a continuación*) begin CreateEmptyManager(Mng); (* Inicialización *) while not isEmptyQueue(Queue) do (* Las operaciones acaban cuando la cola está vacía *) begin QItem:= front(Queue); writeln('********************'); with QItem do begin (* Case que discrimina cada comando con su correspondiente subrutina y formato *) case request of /// Create 'C': begin writeln(code,' ', request, ': center ', param1,' totalvoters ',param2); writeln; Create(param1,strToInt(param2),Mng); end; /// New 'N': begin writeln(code,' ', request, ': center ', param1,' party ',param2); writeln; new(param1,param2,Mng); end; /// Vote 'V': begin writeln(code,' ', request, ': center ', param1,' party',param2); writeln; vote(param1,param2,Mng); end; /// Remove 'R': begin writeln(code,' ', request,': '); writeln; Remove(Mng); end; /// Stats 'S': begin writeln(code,' ', request,': '); writeln; Stats(Mng); end; otherwise writeln(' + Not a valid request'); (* En caso de algún error con el input *) end; end; dequeue(Queue); (* Borrado del comienzo de la cola (la operación ya ejecutada) *) end; deleteManager(Mng); (* Borrado de la memoria ocupada por la multilista *) end; {Main program} begin if (paramCount>0) then readTasks(ParamStr(1)) else readTasks('create.txt'); end.
unit UPhysicalPerson; interface uses SysUtils, UPerson; type TPhysicalPerson = class(TPerson) private id: integer; email: string; name: string; status: integer; comment: string; createAt: TDateTime; cpf: string; salary: currency; birthday: TDateTime; gender: char; public Constructor Create( id: integer; cpf: string; name: string; email: string; status: integer; comment: string; salary: currency; birthday: TDateTime; gender: char; createAt: TDateTime ); procedure setID(id: integer); override; function getID: integer; override; procedure setName(name: string); override; function getName: string; override; procedure setEmail(email: string); override; function getEmail: string; override; procedure setStatus(status: integer); override; function getStatus: integer; override; procedure setComment(comment: string); override; function getComment: string; override; procedure setCreateAt(createAt: TDateTime); override; function getCreateAt: TDateTime; override; procedure setCPF(cpf: string); function getCPF: string; procedure setSalary(salary: currency); function getSalary: currency; procedure setBirthday(birthday: TDateTime); function getBirthday: TDateTime; procedure setGender(gender: char); function getGender: char; end; implementation { TPhysicalPerson } Constructor TPhysicalPerson.Create( id: integer; cpf: string; name: string; email: string; status: integer; comment: string; salary: currency; birthday: TDateTime; gender: char; createAt: TDateTime ); begin self.id := id; self.cpf := cpf; self.name := name; self.email := email; self.status := status; self.comment := comment; self.salary := salary; self.birthday := birthday; self.gender := gender; self.createAt := createAt; end; { PERSON } procedure TPhysicalPerson.setID(id: integer); begin self.id := id; end; function TPhysicalPerson.getID: integer; begin result := self.id; end; procedure TPhysicalPerson.setName(name: string); begin self.name := name; end; function TPhysicalPerson.getName: string; begin result := self.name; end; procedure TPhysicalPerson.setEmail(email: string); begin self.email := email; end; function TPhysicalPerson.getEmail: string; begin result := self.email; end; procedure TPhysicalPerson.setStatus(status: integer); begin self.status := status; end; function TPhysicalPerson.getStatus: integer; begin result := self.status; end; procedure TPhysicalPerson.setComment(comment: string); begin self.comment := comment; end; function TPhysicalPerson.getComment: string; begin result := self.comment; end; procedure TPhysicalPerson.setCreateAt(createAt: TDateTime); begin self.createAt := createAt; end; function TPhysicalPerson.getCreateAt: TDateTime; begin result := self.createAt; end; { PHYSICALPERSON } procedure TPhysicalPerson.setCPF(cpf: string); begin self.cpf := cpf; end; function TPhysicalPerson.getCPF: string; begin result := self.cpf; end; procedure TPhysicalPerson.setSalary(salary: currency); begin self.salary := salary; end; function TPhysicalPerson.getSalary: currency; begin result := self.salary; end; procedure TPhysicalPerson.setBirthday(birthday: TDateTime); begin self.birthday := birthday; end; function TPhysicalPerson.getBirthday: TDateTime; begin result := self.birthday; end; function TPhysicalPerson.getGender: char; begin result := self.gender; end; procedure TPhysicalPerson.setGender(gender: char); begin self.gender := gender; end; end.
unit ImagesMan; {********************************************** Kingstar Delphi Library Copyright (C) Kingstar Corporation <Unit>ImagesMan <What>¹ÜÀíͼÏñ×ÊÔ´ <Written By> Huang YanLai <History> **********************************************} interface uses SysUtils, Classes, UIStyles, Controls, extctrls, Buttons, Graphics; const BtnDefaultWidth = 75; BtnDefaultHeight = 25; type TCommandImages = class; TCommandImage = class(TUICustomStyleItem) private FCaption: String; FCommandImages: TCommandImages; FImageIndex: integer; FHeight: Integer; FWidth: Integer; FHint: string; procedure SetCaption(const Value: String); procedure SetImageIndex(const Value: integer); function GetImageAvailable: Boolean; procedure SetHeight(const Value: Integer); procedure SetWidth(const Value: Integer); protected public constructor Create(Collection: TCollection); override; property CommandImages : TCommandImages read FCommandImages; property ImageAvailable : Boolean read GetImageAvailable; published property ImageIndex : integer read FImageIndex write SetImageIndex default -1; property Caption : String read FCaption write SetCaption; property Width : Integer read FWidth write SetWidth default BtnDefaultWidth; property Height : Integer read FHeight write SetHeight default BtnDefaultHeight; property Hint : string read FHint write FHint; end; TCommandImages = class(TUICustomStyle) private FImages: TImageList; FFrameColor: TColor; FBackgroundColor: TColor; FShadowColor: TColor; FDisabledColor: TColor; FBrightColor: TColor; FFont: TFont; procedure SetImages(const Value: TImageList); procedure SetBackgroundColor(const Value: TColor); procedure SetDisabledColor(const Value: TColor); procedure SetFrameColor(const Value: TColor); procedure SetShadowColor(const Value: TColor); procedure SetBrightColor(const Value: TColor); procedure SetFont(const Value: TFont); procedure FontChanged(Sender : TObject); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner : TComponent); override; class function GetItemClass : TUICustomStyleItemClass; override; published property Items; property Images : TImageList read FImages write SetImages; property FrameColor : TColor read FFrameColor write SetFrameColor default clWindowFrame; property BackgroundColor : TColor read FBackgroundColor write SetBackgroundColor default clBtnFace; property ShadowColor : TColor read FShadowColor write SetShadowColor default clBtnShadow; property DisabledColor : TColor read FDisabledColor write SetDisabledColor default clBtnHighlight; property BrightColor : TColor read FBrightColor write SetBrightColor default clBtnHighlight; property Font : TFont read FFont write SetFont; end; TCommandImageLink = class(TUICustomStyleItemLink) private function GetImageAvailable: Boolean; function GetCommandImage: TCommandImage; procedure SetCommandImage(const Value: TCommandImage); protected public constructor Create; property ImageAvailable : Boolean read GetImageAvailable; property CommandImage : TCommandImage read GetCommandImage write SetCommandImage; end; TUIImages = class; TUIImageItem = class(TUICustomStyleItem) private FPicture: TPicture; FImages: TUIImages; procedure SetPicture(const Value: TPicture); procedure PictureChanged(Sender : TObject); protected public constructor Create(Collection: TCollection); override; destructor Destroy;override; property Images : TUIImages read FImages; published property Picture : TPicture read FPicture write SetPicture; end; TUIImages = class(TUICustomStyle) private protected public class function GetItemClass : TUICustomStyleItemClass; override; published property Items; end; TUIImageLink = class(TUICustomStyleItemLink) private function GetImage: TUIImageItem; procedure SetImage(const Value: TUIImageItem); protected public constructor Create; property Image : TUIImageItem read GetImage write SetImage; end; implementation uses Windows; { TCommandImage } constructor TCommandImage.Create(Collection: TCollection); begin inherited; assert(Style is TCommandImages); FCommandImages := TCommandImages(Style); FImageIndex := -1; FHeight := BtnDefaultHeight; FWidth := BtnDefaultWidth; end; function TCommandImage.GetImageAvailable: Boolean; begin Assert(FCommandImages is TCommandImages); if FCommandImages.Images<>nil then OutputDebugString(Pchar(IntToStr(FCommandImages.Images.Count))); Result := (FCommandImages.Images<>nil) and (FImageIndex>=0) and (FImageIndex<FCommandImages.Images.Count); end; procedure TCommandImage.SetCaption(const Value: String); begin if FCaption <> Value then begin FCaption := Value; Changed(false); end; end; procedure TCommandImage.SetHeight(const Value: Integer); begin if FHeight <> Value then begin FHeight := Value; Changed(false); end; end; procedure TCommandImage.SetImageIndex(const Value: integer); begin if FImageIndex <> Value then begin FImageIndex := Value; Changed(false); end; end; procedure TCommandImage.SetWidth(const Value: Integer); begin if FWidth <> Value then begin FWidth := Value; Changed(false); end; end; { TCommandImages } constructor TCommandImages.Create(AOwner: TComponent); begin inherited; FImages := nil; FFrameColor := clWindowFrame; FBackgroundColor := clBtnFace; FShadowColor := clBtnShadow; FDisabledColor := clBtnHighlight; FBrightColor := clBtnHighlight; FFont := TFont.Create; FFont.OnChange := FontChanged; end; procedure TCommandImages.FontChanged(Sender: TObject); begin UIStyleChanged(Self); end; class function TCommandImages.GetItemClass: TUICustomStyleItemClass; begin Result := TCommandImage; end; procedure TCommandImages.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent=FImages) and (Operation=opRemove) then Images := nil; end; procedure TCommandImages.SetBackgroundColor(const Value: TColor); begin if FBackgroundColor <> Value then begin FBackgroundColor := Value; UIStyleChanged(Self); end; end; procedure TCommandImages.SetBrightColor(const Value: TColor); begin if FBrightColor <> Value then begin FBrightColor := Value; UIStyleChanged(Self); end; end; procedure TCommandImages.SetDisabledColor(const Value: TColor); begin if FDisabledColor <> Value then begin FDisabledColor := Value; UIStyleChanged(Self); end; end; procedure TCommandImages.SetFont(const Value: TFont); begin FFont.Assign(Value); end; procedure TCommandImages.SetFrameColor(const Value: TColor); begin if FFrameColor <> Value then begin FFrameColor := Value; UIStyleChanged(Self); end; end; procedure TCommandImages.SetImages(const Value: TImageList); begin if FImages <> Value then begin FImages := Value; if FImages<>nil then FImages.FreeNotification(self); end; end; procedure TCommandImages.SetShadowColor(const Value: TColor); begin if FShadowColor <> Value then begin FShadowColor := Value; UIStyleChanged(Self); end; end; { TCommandImageLink } constructor TCommandImageLink.Create; begin inherited Create(TCommandImage); end; function TCommandImageLink.GetImageAvailable: Boolean; begin Result := IsAvailable and CommandImage.ImageAvailable; end; function TCommandImageLink.GetCommandImage: TCommandImage; begin Result := TCommandImage(StyleItem); end; procedure TCommandImageLink.SetCommandImage(const Value: TCommandImage); begin StyleItem := Value; end; { TUIImageItem } constructor TUIImageItem.Create(Collection: TCollection); begin inherited; assert(Style is TUIImages); FImages := TUIImages(Style); FPicture := TPicture.Create; FPicture.OnChange := PictureChanged; end; destructor TUIImageItem.Destroy; begin FPicture.OnChange := nil; FreeAndNil(FPicture); inherited; end; procedure TUIImageItem.PictureChanged(Sender: TObject); begin UIStyleChanged(Self); end; procedure TUIImageItem.SetPicture(const Value: TPicture); begin FPicture.Assign(Value); end; { TUIImages } class function TUIImages.GetItemClass: TUICustomStyleItemClass; begin Result := TUIImageItem; end; { TUIImageLink } constructor TUIImageLink.Create; begin inherited Create(TUIImageItem); end; function TUIImageLink.GetImage: TUIImageItem; begin Result := TUIImageItem(StyleItem); end; procedure TUIImageLink.SetImage(const Value: TUIImageItem); begin StyleItem := Value; end; end.
unit CommandList; interface uses System.Classes, System.SysUtils, ThothTypes, ThothObjects, ThothCommands; type /////////////////////////////////////////////////////// // Command List TThCommandList = class(TThInterfacedObject, IThObserver) private FSubject: IThSubject; FUndoList: TInterfaceList; FRedoList: TInterfaceList; FOnChange: TNotifyEvent; FLimit: Integer; procedure ResizeUndoList(ASize: Integer); procedure ClearRedo; function ExchangeCommand(ACommand: IThCommand): IThCommand; // function ExchangeUndoCommand(ACommand: IThCommand): IThCommand; // function ExchangeRedoCommand(ACommand: IThCommand): IThCommand; protected procedure DoChange; public constructor Create; destructor Destroy; override; procedure Notifycation(ACommand: IThCommand); procedure SetSubject(ASubject: IThSubject); property OnChange: TNotifyEvent read FOnChange write FOnChange; procedure Undo; procedure Redo; function HasUndo: Boolean; function HasRedo: Boolean; property UndoLimit: Integer read FLimit write FLimit; end; implementation uses Winapi.Windows, System.Math; { TThCommandList } constructor TThCommandList.Create; begin FLimit := High(Word) div 2; FUndoList := TInterfaceList.Create; FRedoList := TInterfaceList.Create; // FList. end; destructor TThCommandList.Destroy; var I: Integer; begin FUndoList.Free; FRedoList.Free; inherited; end; procedure TThCommandList.SetSubject(ASubject: IThSubject); begin FSubject := ASubject; ASubject.RegistObserver(Self); end; procedure TThCommandList.Notifycation(ACommand: IThCommand); begin OutputDebugSTring(PChar('TCommandList - ' + TThShapeCommand(ACommand).ClassName)); // 새로운 커맨드가 들어오면 Undo 불가(Redo초기화) if ACommand is TThInsertShapeCommand then ClearRedo; FUndoList.Add(ACommand); if FUndoList.Count > FLimit then ResizeUndoList(FLimit); end; procedure TThCommandList.ClearRedo; var I: Integer; begin for I := 0 to FRedoList.Count - 1 do if FRedoList[I] is TThInsertShapeCommand then FSubject.Subject(Self, TThRemoveShapeCommand.Create(TThShapeCommand(FRedoList[I]).List)); // 기존 리스트에 담겨져 있던 객체들은 어카지?? // 1, 커맨드를 돌며 삭제한다. // 2, 처리할때마다 확인하고 처리한다. FRedoList.Clear; end; procedure TThCommandList.ResizeUndoList(ASize: Integer); var I: Integer; begin for I := FUndoList.Count - 1 - ASize downto 0 do begin // Delete한 객체는 해제하기 위해 RemoveShape 커맨드 전송 if FUndoList[I] is TThDeleteShapeCommand then FSubject.Subject(Self, TThRemoveShapeCommand.Create(TThShapeCommand(FUndoList[I]).List)); end; end; procedure TThCommandList.DoChange; begin end; function TThCommandList.ExchangeCommand(ACommand: IThCommand): IThCommand; begin if ACommand is TThInsertShapeCommand then Result := TThDeleteShapeCommand.Create(TThShapeCommand(ACommand).List) else if ACommand is TThDeleteShapeCommand then Result := TThRestoreShapeCommand.Create(TThShapeCommand(ACommand).List) else if ACommand is TThMoveShapeCommand then Result := TThMoveShapeCommand.Create(TThShapeCommand(ACommand).List, TThMoveShapeCommand(ACommand).AfterPos, TThMoveShapeCommand(ACommand).BeforePos) ; end; function TThCommandList.HasRedo: Boolean; begin Result := FRedoList.Count > 0; if Result then OutputDebugString(PChar('TThCommandList.HasRedo')); end; function TThCommandList.HasUndo: Boolean; begin Result := FUndoList.Count > 0; end; //function TThCommandList.ExchangeRedoCommand(ACommand: IThCommand): IThCommand; //begin // //end; //procedure TThCommandList.MoveCommand(ASrc, ADest: TInterfaceList); //var // Command, Command2: IThCommand; //begin // if ASrc.Count <= 0 then // Exit; // // Command := IThCommand(ASrc.Last); // Command2 := ExchangeCommand(Command); // // FSubject.Subject(Command2); // // ASrc.Delete(ASrc.Count - 1); // ADest.Add(Command2); //end; procedure TThCommandList.Undo; var Command: IThCommand; begin if FUndoList.Count <= 0 then Exit; Command := IThCommand(FUndoList.Last); // Command2 := ExchangeCommand(Command); FUndoList.Delete(FUndoList.Count - 1); FRedoList.Add(Command); FSubject.Subject(Self, ExchangeCommand(Command)); OutputDebugSTring(PChar(Format('TCommandList - Un: %d, Re: %d', [FUndoList.Count, FRedoList.Count]))); end; procedure TThCommandList.Redo; var Command: IThCommand; begin if FRedoList.Count <= 0 then Exit; Command := IThCommand(FRedoList.Last); // TThCommand(Command).Source := Self; FRedoList.Delete(FRedoList.Count - 1); FUndoList.Add(Command); FSubject.Subject(Self, Command); if FUndoList.Count > FLimit then ResizeUndoList(FLimit); end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} unit IdOpenSSLHeaders_cmac; interface // Headers for OpenSSL 1.1.1 // cmac.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts, IdOpenSSLHeaders_evp, IdOpenSSLHeaders_ossl_typ; //* Opaque */ type CMAC_CTX_st = type Pointer; CMAC_CTX = CMAC_CTX_st; PCMAC_CTX = ^CMAC_CTX; var function CMAC_CTX_new: PCMAC_CTX; procedure CMAC_CTX_cleanup(ctx: PCMAC_CTX); procedure CMAC_CTX_free(ctx: PCMAC_CTX); function CMAC_CTX_get0_cipher_ctx(ctx: PCMAC_CTX): PEVP_CIPHER_CTX; function CMAC_CTX_copy(out_: PCMAC_CTX; const in_: PCMAC_CTX): TIdC_INT; function CMAC_Init(ctx: PCMAC_CTX; const key: Pointer; keylen: TIdC_SIZET; const cipher: PEVP_Cipher; impl: PENGINe): TIdC_INT; function CMAC_Update(ctx: PCMAC_CTX; const data: Pointer; dlen: TIdC_SIZET): TIdC_INT; function CMAC_Final(ctx: PCMAC_CTX; out_: PByte; poutlen: PIdC_SIZET): TIdC_INT; function CMAC_resume(ctx: PCMAC_CTX): TIdC_INT; implementation end.
unit uGoogleMapsClass; interface uses Generics.Collections; type TDistance = class private FText: String; FValue: Double; published property Text: String read FText write FText; property Value: Double read FValue write FValue; end; TDuration = class private FValue: Double; FText: String; published property Text: String read FText write FText; property Value: Double read FValue write FValue; end; TLatLng = class private FXa: Double; FYa: Double; published property Xa: Double read FXa write FXa; property Ya: Double read FYa write FYa; end; TDirectionsStep = class private FDistance: TDistance; FDuration: TDuration; FPath: TObjectList<TLatLng>; FTravelMode: string; FStartLocation: TLatLng; FInstructions: string; FEndLocation: TLatLng; published constructor Create; destructor Destroy; override; property Distance: TDistance read FDistance write FDistance; property Duration: TDuration read FDuration write FDuration; property EndLocation: TLatLng read FEndLocation write FEndLocation; property Instructions: string read FInstructions write FInstructions; property StartLocation: TLatLng read FStartLocation write FStartLocation; property Path: TObjectList<TLatLng> read FPath write FPath; property TravelMode : string read FTravelMode write FTravelMode; end; TDirectionsLeg = class private FDistance: TDistance; FDepartureTime: TDuration; FStartAddress: string; FDuration: TDuration; FSteps: TObjectList<TDirectionsStep>; FStartLocation: TLatLng; FViaWaypoints: TObjectList<TLatLng>; FEndAddress: string; FArrivalTime: TDistance; FEndLocation: TLatLng; published constructor Create; destructor Destroy; override; property ArrivalTime: TDistance read FArrivalTime write FArrivalTime; property DepartureTime: TDuration read FDepartureTime write FDepartureTime; property Distance: TDistance read FDistance write FDistance; property Duration: TDuration read FDuration write FDuration; property EndAddress: string read FEndAddress write FEndAddress; property EndLocation: TLatLng read FEndLocation write FEndLocation; property StartAddress: string read FStartAddress write FStartAddress; property StartLocation: TLatLng read FStartLocation write FStartLocation; property Steps: TObjectList<TDirectionsStep> read FSteps write FSteps; property ViaWaypoints: TObjectList<TLatLng> read FViaWaypoints write FViaWaypoints; end; TDirectionsRoute = class private FLegs : TObjectList<TDirectionsLeg>; public constructor Create; destructor Destroy; override; property Legs: TObjectList<TDirectionsLeg> read FLegs write FLegs; end; implementation { TDirectionsRoute } constructor TDirectionsRoute.Create; begin FLegs := TObjectList<TDirectionsLeg>.Create; end; destructor TDirectionsRoute.Destroy; begin FLegs.Free; inherited; end; { TDirectionsLeg } constructor TDirectionsLeg.Create; begin FDistance := TDistance.Create; FDepartureTime:= TDuration.Create; FDuration := TDuration.Create; FStartLocation:= TLatLng.Create; FArrivalTime := TDistance.Create; FEndLocation := TLatLng.Create; FSteps := TObjectList<TDirectionsStep>.Create; FViaWaypoints := TObjectList<TLatLng>.Create; end; destructor TDirectionsLeg.Destroy; begin FDistance.Free; FDepartureTime.Free; FDuration.Free; FStartLocation.Free; FArrivalTime.Free; FEndLocation.Free; FSteps.Free; FViaWaypoints.Free; inherited; end; { TDirectionsStep } constructor TDirectionsStep.Create; begin FDistance := TDistance.Create; FDuration := TDuration.Create; FPath := TObjectList<TLatLng>.Create; FStartLocation:= TLatLng.Create; FEndLocation := TLatLng.Create; end; destructor TDirectionsStep.Destroy; begin FDistance.Free; FDuration.Free; FPath.Free; FStartLocation.Free; FEndLocation.Free; inherited; end; end.
unit uPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, filectrl; type TfPrincipal = class(TForm) BitBtnDir: TBitBtn; Memo1: TMemo; FileListBox: TFileListBox; procedure BitBtnDirClick(Sender: TObject); private { Private declarations } public { Public declarations } end; type PSearchRec = ^TSearchRec; TSearchDirCallBack = Procedure(FileName: string; Rec: PSearchRec; lpData: pointer; count, depth: cardinal; var Cancel: Boolean); function SearchDir(Dir: String; lpFunc: TSearchDirCallBack; lpData: pointer) : cardinal; var fPrincipal: TfPrincipal; implementation {$R *.dfm} function SearchDir(Dir: String; lpFunc: TSearchDirCallBack; lpData: pointer) : cardinal; var depth, count: cardinal; Cancel: Boolean; function vldir(dr: string): Boolean; begin result := ((trim(dr) <> '..') and (trim(dr) <> '.')); end; procedure Search(dirname: string); var Rec: TSearchRec; begin if (Cancel) then exit; inc(depth); if (FindFirst(dirname + '\*', faReadOnly or faanyfile or favolumeid or faHidden or faSysFile or faDirectory or faArchive, Rec) <> 0) then begin System.SysUtils.FindClose(Rec); dec(depth); exit; end; repeat if ((Rec.Attr and faDirectory) <> 0) then begin if vldir(Rec.Name) then Search(dirname + '\' + Rec.Name); end; inc(count); if (vldir(Rec.Name)) then lpFunc(dirname + '\' + Rec.Name, @Rec, lpData, count, depth, Cancel); if (Cancel) then break; until (findnext(Rec) <> 0); System.SysUtils.FindClose(Rec); dec(depth); end; begin if (@lpFunc = nil) then exit; Cancel := false; count := 0; depth := 0; while (Dir[length(Dir)] = '\') or (Dir[length(Dir)] = '/') do delete(Dir, length(Dir), 1); if not(Directoryexists(Dir)) then begin result := 1; exit; end; Search(Dir); if (count = 0) then result := 2 else result := 0; end; Function isFolderEmpty(szPath: String): Boolean; var res: TSearchRec; begin szPath := IncludeTrailingBackslash(szPath); result := (FindFirst(szPath + '*.*', faanyfile - faDirectory, res) <> 0); FindClose(res); end; Procedure CallBack(FileName: string; Rec: PSearchRec; lpData: pointer; count, depth: cardinal; var Cancel: Boolean); var I: Integer; flb: TFileListBox; tsl: TStringList; begin tsl := TStringList.Create(); tsl.Add('# Ignore everything in this directory'); tsl.Add('*'); tsl.Add('# Except this file'); tsl.Add('!.gitignore'); if Directoryexists(FileName) then begin fPrincipal.FileListBox.FileName := FileName; if fPrincipal.FileListBox.Items.count = 0 then begin fPrincipal.Memo1.Lines.Add(FileName); tsl.SaveToFile(FileName + '\.gitgnore'); end; end; fPrincipal.Caption := 'depth = ' + inttostr(depth) + ' count = ' + inttostr(count); end; procedure TfPrincipal.BitBtnDirClick(Sender: TObject); const SELDIRHELP = 1000; var Dir: string; begin Dir := 'C:'; if SelectDirectory(Dir, [sdAllowCreate, sdPerformCreate, sdPrompt], SELDIRHELP) then BitBtnDir.Caption := Dir; SearchDir(Dir, @CallBack, nil); end; end.
unit frm_scriptsequence; {$mode objfpc}{$H+} interface uses SysUtils, Classes, fpg_base, fpg_main, fpg_form, fpg_label, fpg_button, fpg_edit, fpg_memo, fpg_editbtn; type TRunScriptSequenceForm = class(TfpgForm) private {@VFD_HEAD_BEGIN: RunScriptSequenceForm} Label1: TfpgLabel; edtDirectory: TfpgDirectoryEdit; edtStart: TfpgEditInteger; lblStart: TfpgLabel; lblEnd: TfpgLabel; edtEnd: TfpgEditInteger; Memo1: TfpgMemo; btnCheck: TfpgButton; btnRun: TfpgButton; btnCancel: TfpgButton; {@VFD_HEAD_END: RunScriptSequenceForm} function GetScripts: TStrings; procedure btnCheckClicked(Sender: TObject); procedure btnRunClicked(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); public constructor Create(AOwner: TComponent); override; procedure AfterCreate; override; procedure GenerateScriptList; property Scripts: TStrings read GetScripts; end; {@VFD_NEWFORM_DECL} implementation uses tiConstants, tiUtils, tiINI, tiGUIINI, tiDialogs; {@VFD_NEWFORM_IMPL} procedure TRunScriptSequenceForm.AfterCreate; begin {%region 'Auto-generated GUI code' -fold} {@VFD_BODY_BEGIN: RunScriptSequenceForm} Name := 'RunScriptSequenceForm'; SetPosition(344, 149, 550, 401); WindowTitle := 'Script Sequence'; Hint := ''; Label1 := TfpgLabel.Create(self); with Label1 do begin Name := 'Label1'; SetPosition(8, 8, 312, 16); FontDesc := '#Label1'; Hint := ''; Text := 'Script Directory'; end; edtDirectory := TfpgDirectoryEdit.Create(self); with edtDirectory do begin Name := 'edtDirectory'; SetPosition(8, 24, 536, 24); Anchors := [anLeft,anRight,anTop]; Directory := ''; ExtraHint := ''; RootDirectory := ''; TabOrder := 2; end; edtStart := TfpgEditInteger.Create(self); with edtStart do begin Name := 'edtStart'; SetPosition(8, 72, 120, 24); FontDesc := '#Edit1'; Hint := ''; TabOrder := 3; Value := 0; end; lblStart := TfpgLabel.Create(self); with lblStart do begin Name := 'lblStart'; SetPosition(8, 56, 196, 16); FontDesc := '#Label1'; Hint := ''; Text := 'Starting sequence'; end; lblEnd := TfpgLabel.Create(self); with lblEnd do begin Name := 'lblEnd'; SetPosition(284, 60, 156, 16); FontDesc := '#Label1'; Hint := ''; Text := 'Ending Sequence'; end; edtEnd := TfpgEditInteger.Create(self); with edtEnd do begin Name := 'edtEnd'; SetPosition(284, 76, 120, 24); FontDesc := '#Edit1'; Hint := ''; TabOrder := 6; Value := 0; end; Memo1 := TfpgMemo.Create(self); with Memo1 do begin Name := 'Memo1'; SetPosition(8, 144, 388, 204); FontDesc := '#Edit1'; Hint := ''; TabOrder := 7; end; btnCheck := TfpgButton.Create(self); with btnCheck do begin Name := 'btnCheck'; SetPosition(408, 144, 80, 24); Text := 'Check'; FontDesc := '#Label1'; Hint := ''; ImageName := ''; TabOrder := 8; OnClick := @btnCheckClicked; end; btnRun := TfpgButton.Create(self); with btnRun do begin Name := 'btnRun'; SetPosition(356, 372, 92, 24); Text := 'Run'; FontDesc := '#Label1'; Hint := ''; ImageName := ''; TabOrder := 9; OnClick := @btnRunClicked; end; btnCancel := TfpgButton.Create(self); with btnCancel do begin Name := 'btnCancel'; SetPosition(452, 372, 92, 24); Text := 'Cancel'; FontDesc := '#Label1'; Hint := ''; ImageName := ''; ModalResult := mrCancel; TabOrder := 10; end; {@VFD_BODY_END: RunScriptSequenceForm} {%endregion} end; function TRunScriptSequenceForm.GetScripts: TStrings; begin Result := Memo1.Lines; end; procedure TRunScriptSequenceForm.btnCheckClicked(Sender: TObject); begin GenerateScriptList; end; procedure TRunScriptSequenceForm.btnRunClicked(Sender: TObject); begin if edtEnd.Value < edtStart.Value then begin tiAppError('Ending sequence must be equal or larger than starting sequence number'); Exit; end; GenerateScriptList; ModalResult := mrOK; end; procedure TRunScriptSequenceForm.GenerateScriptList; var sl: TStringList; i: integer; s: string; begin s := ''; sl := TStringList.Create; Memo1.Clear; for i := edtStart.Value to edtEnd.Value do begin tiFilesToStringList(edtDirectory.Directory + Format('%3.3d', [i]), '*.sql', sl, True); Memo1.Text := Memo1.Text + s + sl.Text; s := cLineEnding; end; sl.Free; end; procedure TRunScriptSequenceForm.FormShow(Sender: TObject); begin gGUIINI.ReadFormState(self); edtDirectory.Directory := gGUIINI.ReadString(name, 'ScriptDirectory', ''); edtStart.Value := gGUIINI.ReadInteger(name, 'StartSequence', 1); edtEnd.Value := gGUIINI.ReadInteger(name, 'StopSequence', 1); end; procedure TRunScriptSequenceForm.FormClose(Sender: TObject; var Action: TCloseAction); begin gGUIINI.WriteFormState(self); gGUIINI.WriteString(name, 'ScriptDirectory', edtDirectory.Directory); gGUIINI.WriteInteger(name, 'StartSequence', edtStart.Value); gGUIINI.WriteInteger(name, 'StopSequence', edtEnd.Value); end; constructor TRunScriptSequenceForm.Create(AOwner: TComponent); begin inherited Create(AOwner); OnShow := @FormShow; OnClose := @FormClose; end; end.
unit uDM_ModuloEnvio; interface uses System.SysUtils, System.Classes, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile; type TDM_ModuloEnvio = class(TDataModule) TetheringAppProfile1: TTetheringAppProfile; TetheringManager1: TTetheringManager; procedure TetheringManager1RequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); procedure TetheringManager1EndManagersDiscovery(const Sender: TObject; const ARemoteManagers: TTetheringManagerInfoList); procedure DataModuleCreate(Sender: TObject); private { Private declarations } Connected : Boolean; FNFCe: TStringList; FListaServers: TStringList; procedure SetNFCe(const Value: TStringList); procedure SetListaServers(const Value: TStringList); public { Public declarations } procedure FindWalls; function Send : Boolean; function CheckServers : Boolean; procedure Refresh; property NFCe : TStringList read FNFCe write SetNFCe; property ListaServers : TStringList read FListaServers write SetListaServers; end; var DM_ModuloEnvio: TDM_ModuloEnvio; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses System.Tether.NetworkAdapter; { TDM_ModuloEnvio } function TDM_ModuloEnvio.CheckServers: Boolean; begin if FListaServers.Count > 0 then Result := True else begin Result := False; end; end; procedure TDM_ModuloEnvio.DataModuleCreate(Sender: TObject); begin Connected := False; FListaServers := TStringList.Create; FNFCe := TStringList.Create; //FindWalls; end; procedure TDM_ModuloEnvio.FindWalls; var I: Integer; begin //TetheringManager1.AutoConnect(); { FListaServers.Clear; for I := (TetheringManager1.PairedManagers.Count)-1 downto 0 do TetheringManager1.UnPairManager(TetheringManager1.PairedManagers[I]); TetheringManager1.DiscoverManagers; } end; procedure TDM_ModuloEnvio.Refresh; var I: Integer; begin { FListaServers.Clear; for I := 0 to TetheringManager1.RemoteProfiles.Count - 1 do if (TetheringManager1.RemoteProfiles[I].ProfileText = 'ServidorTether') then FListaServers.Add(TetheringManager1.RemoteProfiles[I].ProfileText); if FListaServers.Count > 0 then begin Connected := TetheringAppProfile1.Connect(TetheringManager1.RemoteProfiles[0]); end; } end; function TDM_ModuloEnvio.Send: Boolean; var LStream: TMemoryStream; begin if not Connected then Connected := TetheringAppProfile1.Connect(TetheringManager1.RemoteProfiles[0]); LStream := TMemoryStream.Create; try NFCe.SaveToStream(LStream); Result := TetheringAppProfile1.SendStream(TetheringManager1.RemoteProfiles[0], 'NFCe', LStream); finally LStream.Free; end; end; procedure TDM_ModuloEnvio.SetListaServers(const Value: TStringList); begin FListaServers := Value; end; procedure TDM_ModuloEnvio.SetNFCe(const Value: TStringList); begin FNFCe := Value; end; procedure TDM_ModuloEnvio.TetheringManager1EndManagersDiscovery( const Sender: TObject; const ARemoteManagers: TTetheringManagerInfoList); var i : integer; begin {for I := 0 to ARemoteManagers.Count-1 do if (ARemoteManagers[I].ManagerText = 'ServidorTether') then TetheringManager1.PairManager(ARemoteManagers[I]); } end; procedure TDM_ModuloEnvio.TetheringManager1RequestManagerPassword( const Sender: TObject; const ARemoteIdentifier: string; var Password: string); begin Password := '1234'; end; end.
unit GMJson; interface uses System.JSON.Serializers, System.Rtti, System.TypInfo; type IJson = interface ['{EA6737C1-4C53-44D5-BC98-5C13A590E084}'] function Serialize(aObject: TObject): string; overload; function Serialize(aObject: TObject; ExcludeProp: array of string): string; overload; function Deserialize(aClass: TClass; Json: string): TObject; end; TGMJson = class(TInterfacedObject, IJson) public function Serialize(aObject: TObject): string; overload; function Serialize(aObject: TObject; ExcludeProp: array of string): string; overload; function Deserialize(aClass: TClass; Json: string): TObject; end; TMyJsonDynamicContractResolver = class(TJsonDynamicContractResolver) protected function CreateObjectContract(ATypeInf: PTypeInfo): TJsonObjectContract; override; end; implementation uses System.SysUtils, Rest.Json, System.JSON, System.JSONConsts, REST.JsonReflect; { TGMJson } function TGMJson.Deserialize(aClass: TClass; Json: string): TObject; var JSONValue: TJsonValue; JSONObject: TJSONObject; begin Result := aClass.Create; JSONValue := TJSONObject.ParseJSONValue(Json); try if not Assigned(JSONValue) then Exit; if (JSONValue is TJSONArray) then begin with TJSONUnMarshal.Create do try SetFieldArray(Result, 'Items', (JSONValue as TJSONArray)); finally Free; end; Exit; end; if (JSONValue is TJSONObject) then JSONObject := JSONValue as TJSONObject else begin Json := Json.Trim; if (Json = '') and not Assigned(JSONValue) or (Json <> '') and Assigned(JSONValue) and JSONValue.Null then Exit else raise EConversionError.Create(SCannotCreateObject); end; TJson.JsonToObject(Result, JSONObject, []); finally JSONValue.Free; end; end; function TGMJson.Serialize(aObject: TObject{; ExcludeProp: array of string}): string; begin Result := TJson.ObjectToJsonString(aObject, []); end; function TGMJson.Serialize(aObject: TObject; ExcludeProp: array of string): string; var Serializer: TJsonSerializer; Resolver: TMyJsonDynamicContractResolver; begin Resolver := nil; Serializer := nil; try Resolver := TMyJsonDynamicContractResolver.Create; Serializer := TJsonSerializer.Create; Serializer.ContractResolver := Resolver; Result := Serializer.Serialize(aObject); finally //if Assigned(Resolver) then Resolver.Free; if Assigned(Serializer) then Serializer.Free; end; end; { TMyJsonDynamicContractResolver } function TMyJsonDynamicContractResolver.CreateObjectContract( ATypeInf: PTypeInfo): TJsonObjectContract; var LContract: TJsonObjectContract; LProperty: TJsonProperty; begin LContract := inherited CreateObjectContract(ATypeInf); // Iterate through the properties of the object for LProperty in LContract.Properties do begin // If the property is part of the TPerson class and its name is 'Age', exclude it if (LProperty.Name = 'FOwner') then LProperty.Ignored := True; end; Result := LContract; end; end.
unit dmMapaValores; interface uses SysUtils, Classes, DB, IBCustomDataSet, IBQuery, kbmMemTable, dmUltimGridSorter; type TMapaValores = class(TUltimGridSorter) qValores: TIBQuery; Valores: TkbmMemTable; ValoresOID_VALOR: TSmallintField; ValoresNOMBRE: TIBStringField; ValoresSIMBOLO: TIBStringField; ValoresDINERO: TIBBCDField; ValoresPAPEL: TIBBCDField; ValoresZONA: TIBStringField; ValoresPAIS: TIBStringField; ValoresSELECCIONADO: TBooleanField; qValoresOR_VALOR: TSmallintField; qValoresDINERO: TIBBCDField; qValoresPAPEL: TIBBCDField; qValoresZONA: TIBStringField; procedure DataModuleCreate(Sender: TObject); procedure ValoresFilterRecord(DataSet: TDataSet; var Accept: Boolean); private procedure SetOIDSesion(const Value: integer); function GetVerSeleccionados: boolean; procedure SetVerSeleccionados(const Value: boolean); public procedure Seleccionar; procedure SeleccionarZona(const zona: string); procedure DiaSiguiente; procedure DiaAnterior; property OIDSesion: integer write SetOIDSesion; property VerSeleccionados: boolean read GetVerSeleccionados write SetVerSeleccionados; end; implementation uses dmBD, dmData, UtilDB, dmDataComun; {$R *.dfm} { TMapaValores } procedure TMapaValores.DataModuleCreate(Sender: TObject); begin OIDSesion := Data.OIDSesion; DefaultField := ValoresSELECCIONADO; end; procedure TMapaValores.DiaAnterior; begin Data.dsCotizacion.DataSet.Next; OIDSesion := Data.OIDSesion; end; procedure TMapaValores.DiaSiguiente; begin Data.dsCotizacion.DataSet.Prior; OIDSesion := Data.OIDSesion; end; function TMapaValores.GetVerSeleccionados: boolean; begin result := Valores.Filtered; end; procedure TMapaValores.Seleccionar; begin Valores.Edit; ValoresSELECCIONADO.Value := not ValoresSELECCIONADO.Value; Valores.Post; end; procedure TMapaValores.SeleccionarZona(const zona: string); var inspect: TInspectDataSet; filtered: boolean; begin filtered := Valores.Filtered; if filtered then begin inspect := StartInspectDataSet(Valores); Valores.Filtered := false; end; SeleccionarCampo(zona, ValoresZONA); if filtered then begin EndInspectDataSet(inspect); Valores.Filtered := true; end; end; procedure TMapaValores.SetOIDSesion(const Value: integer); var OIDsValores: TStringList; events: TDataSetEvents; pDataComun: PDataComunValor; OIDValor: integer; begin events := DisableEventsDataSet(Valores); try if Valores.Active then begin OIDsValores := TStringList.Create; Valores.First; while not Valores.Eof do begin if ValoresSELECCIONADO.Value then OIDsValores.Add(ValoresOID_VALOR.AsString); Valores.Next; end; end else OIDsValores := nil; qValores.Close; qValores.ParamByName('OID_SESION').AsInteger := Value; qValores.Open; qValores.First; Valores.Close; Valores.Open; while not qValores.Eof do begin Valores.Append; OIDValor := qValoresOR_VALOR.Value; pDataComun := DataComun.FindValor(OIDValor); ValoresOID_VALOR.Value := OIDValor; ValoresNOMBRE.Value := pDataComun^.Nombre; ValoresSIMBOLO.Value := pDataComun^.Simbolo; ValoresDINERO.Value := qValoresDINERO.Value; ValoresPAPEL.Value := qValoresPAPEL.Value; ValoresZONA.Value := DataComun.FindZona(qValoresZONA.AsInteger); ValoresPAIS.Value := pDataComun^.Mercado^.Pais; ValoresSELECCIONADO.Value := (OIDsValores = nil) or (OIDsValores.IndexOf(qValoresOR_VALOR.AsString) > -1); Valores.Post; qValores.Next; end; qValores.Close; Valores.First; finally EnableEventsDataSet(Valores, events); FreeAndNil(OIDsValores); end; end; procedure TMapaValores.SetVerSeleccionados(const Value: boolean); begin Valores.Filtered := Value; end; procedure TMapaValores.ValoresFilterRecord(DataSet: TDataSet; var Accept: Boolean); begin inherited; Accept := ValoresSELECCIONADO.Value; end; end.
unit MakeDataRule; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,StrUtils, Vcl.ComCtrls, Vcl.ToolWin, System.ImageList, Vcl.ImgList, Vcl.Grids, UMakeRuleClass,UMainDataModule, Vcl.Menus ; type TForm_MakeRule = class(TForm) ImageList1: TImageList; ToolBar1: TToolBar; AddButton: TToolButton; EditButton: TToolButton; SaveButton: TToolButton; DeleteButton: TToolButton; ExitButton: TToolButton; GroupBox1: TGroupBox; Splitter1: TSplitter; ListBox1: TListBox; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; GroupBox2: TGroupBox; Label1: TLabel; Edit_Rule_name: TEdit; Label2: TLabel; CB_FileSuffix: TComboBox; Label3: TLabel; CB_Split_Flag: TComboBox; Label4: TLabel; Edit_Sup_Flag: TEdit; Label5: TLabel; Edit_Time_Flag: TEdit; RG_Sup_Upper: TRadioGroup; RG_Time_Upper: TRadioGroup; Label6: TLabel; Edit_DT_String: TEdit; Memo1: TMemo; Label7: TLabel; CB_DataType: TComboBox; CB_Data_Unit: TComboBox; Label8: TLabel; Label9: TLabel; Label10: TLabel; Edit_Data_Flag: TEdit; RG_Data_Upper: TRadioGroup; StringGrid1: TStringGrid; But_AddData: TButton; But_DelData: TButton; StatusBar1: TStatusBar; GroupBox3: TGroupBox; GroupBox5: TGroupBox; Memo_Source: TMemo; PopMemu_Memo: TPopupMenu; GroupBox6: TGroupBox; Memo_Result: TMemo; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; ImageList2: TImageList; Button1: TButton; RG_MoveSupp: TRadioGroup; GB_MoveSup: TGroupBox; Label11: TLabel; Edit_MoveSup_ProFlag: TEdit; RG_MoveSup_Upper: TRadioGroup; Label12: TLabel; CB_Equal: TComboBox; Edit_MoveSuP_Value: TEdit; Label13: TLabel; CB_Mult_Max_AGV: TComboBox; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure But_AddDataClick(Sender: TObject); procedure But_DelDataClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure ListBox1Click(Sender: TObject); procedure SaveButtonClick(Sender: TObject); procedure Edit_Rule_nameClick(Sender: TObject); procedure CB_FileSuffixClick(Sender: TObject); procedure CB_Split_FlagClick(Sender: TObject); procedure CB_Data_UnitClick(Sender: TObject); procedure Edit_Data_FlagClick(Sender: TObject); procedure Edit_Sup_FlagClick(Sender: TObject); procedure Edit_Time_FlagClick(Sender: TObject); procedure Edit_DT_StringClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure N2Click(Sender: TObject); procedure Memo_SourceMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure N4Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure ExitButtonClick(Sender: TObject); procedure RG_MoveSuppClick(Sender: TObject); procedure Edit_MoveSup_ProFlagClick(Sender: TObject); procedure Edit_MoveSuP_ValueClick(Sender: TObject); procedure Memo_SourceClick(Sender: TObject); private { Private declarations } SaveLx:String; Selected_Ruleid:integer; SelectedStringRow:Integer; MyDataSet:TMYDataSet; MyCommand:TMyCommand; MyRule:TMakeRuleClass; procedure ClearEdit; procedure GetInputEdit; function CheckInputEdit:Boolean; procedure AddDataType; //---------------------- procedure InitDataTypeStrinGrid; function SaveIntoDataBase(Sav:String) :Boolean; function SelectMaxId:Integer; procedure OptionTip(Str:String); procedure FillListBox(ListB:TListBox) ; function FillMyRuleData(id:Integer;Rule:TMakeRuleClass):Boolean; function FillSelectEditData(Rule:TMakeRuleClass):Boolean; procedure SelectComboBoxText(CB:TComboBox;Str:String); // procedure DispMemoCopySource(Px,Py:Integer);//显示Memo控制快捷菜单 procedure CopyToPhaseIntoMemoSource; public { Public declarations } end; var Form_MakeRule: TForm_MakeRule; function CreateMakeRule_inn(AHandle:THandle;ACaption:string;Wid,Hi:integer):THandle;stdcall; implementation {$R *.dfm} uses Lu_Public_BasicModual,Vcl.Clipbrd, PStope_GzmGuidClass; function CreateMakeRule_inn(AHandle:THandle;ACaption:string;Wid,Hi:integer):THandle;stdcall; begin if Assigned(Form_MakeRule) then FreeAndNil(Form_MakeRule); Application.Handle:=AHandle; Form_MakeRule:=TForm_MakeRule.Create(Application); try with Form_MakeRule do begin Caption:=ACaption; WindowState:= wsNormal; ParentWindow:=Ahandle; if Hi >Height then Top :=Round((Hi-Height)/3) else Top :=0; if Wid> Width then Left:=Round((Wid-Width)/2) else Left:=0; Show; SetFocus; Result:=Form_MakeRule.Handle ;//函数值 end ; except FreeAndNil(Form_MakeRule); end; end; procedure TForm_MakeRule.AddButtonClick(Sender: TObject); begin ClearEdit; SaveLx:='Insert'; SaveButton.Enabled :=true; GroupBox2.Enabled :=true; end; procedure TForm_MakeRule.AddDataType; var tmp:TBasicDataParm; begin tmp.DataName :=self.CB_DataType.Text; tmp.DataBh:=self.CB_DataType.ItemIndex +1; if CB_DataType.ItemIndex=5 then begin tmp.DataType:=TSupportDataType(9); end else begin tmp.DataType:=TSupportDataType(CB_DataType.ItemIndex +1); end; tmp.TagStr :=self.Edit_Data_Flag.Text ; tmp.UpperCase :=self.RG_Data_Upper.ItemIndex ; tmp.DataUnit :=Self.CB_Data_Unit.Text ; MyRule.AddBasicDataS(tmp); end; procedure TForm_MakeRule.Button1Click(Sender: TObject); var i,j:integer; s_tmp:string; tmp: TInputData; begin for I := 0 to self.Memo_Source.Lines.Count -1 do begin tmp:=MyRule.AnalySisData(Memo_Source.Lines[i] ) ; if tmp.DataCount >0 then MyRule.Add_Anal_DataS(tmp); end; //分解后 组合成一个完整的字符串在 Memo 中显示 for I := 0 to MyRule.Anal_DataNumber -1 do begin s_tmp:=''; s_tmp:= MyRule.SupProRec.TagStr + ' ' ; s_tmp:=s_tmp + intTostr(MyRule.Anal_DataS[i].support ) + ' '; if MyRule.MoveSuppFlag then begin s_tmp:=s_tmp+ MyRule.MoveProRec.TagStr + ' ' ; if MyRule.Anal_DataS[i].MoveSupportTag then s_tmp:=s_tmp + 'true' + ' ' else s_tmp:=s_tmp + 'False' + ' ' ; end; s_tmp:=s_tmp + MyRule.DTProRec.TagStr + ' '; s_tmp:=s_tmp + FormatDateTime('YYYY-MM-DD/HH:NN:SS', MyRule.Anal_DataS[i].GenerateTime) + ' '; for j := 0 to MyRule.Anal_DataS[i].DataCount-1 do begin s_tmp:=s_tmp + MyRule.Anal_DataS[i].InputDataS[j].TagStr + ' '; s_tmp:=s_tmp + FormatFloat('0.00',MyRule.Anal_DataS[i].InputDataS[j].Data )+ ' '; end; // s_tmp:=s_tmp + 'U '+ FormatFloat('0.00',MyRule.Anal_DataS[i].Useddata ) ; self.Memo_Result.Lines.Add(s_tmp) ; end; end; procedure TForm_MakeRule.But_AddDataClick(Sender: TObject); begin if Trim(Edit_Data_Flag.Text)='' then begin messagebox(self.Handle,'请标记数据的前导字符!','系统提示',mb_iconerror+mb_ok); exit; end; AddDataType; InitDataTypeStrinGrid; MyRule.FillDataToStrGrid(Self.StringGrid1); self.Edit_Data_Flag.Text :=''; end; procedure TForm_MakeRule.But_DelDataClick(Sender: TObject); begin if (SelectedStringRow >0 ) and (trim(StringGrid1.Cells[0,SelectedStringRow] )<> '') then begin MyRule.DeleteBasicDataS(SelectedStringRow-1); InitDataTypeStrinGrid; MyRule.FillDataToStrGrid(StringGrid1); end; end; procedure TForm_MakeRule.CB_Data_UnitClick(Sender: TObject); begin CB_Data_Unit.SetFocus; end; procedure TForm_MakeRule.CB_FileSuffixClick(Sender: TObject); begin CB_FileSuffix.SetFocus ; end; procedure TForm_MakeRule.CB_Split_FlagClick(Sender: TObject); begin CB_Split_Flag.SetFocus; end; function TForm_MakeRule.CheckInputEdit: Boolean; begin Result:=False; if Trim(self.Edit_Rule_name.Text)= '' then begin messagebox(self.Handle,'请填写规则的名称!','系统提示',mb_iconerror+mb_ok); exit; end; if Trim(self.Edit_Sup_Flag.Text)= '' then begin messagebox(self.Handle,'请标记支架的前导字符!','系统提示',mb_iconerror+mb_ok); exit; end; if Trim(self.Edit_Time_Flag.Text)= '' then begin messagebox(self.Handle,'请标记时间的前导字符!','系统提示',mb_iconerror+mb_ok); exit; end; if Trim(self.Edit_DT_String.Text)= '' then begin messagebox(self.Handle,'请录入时间格式!','系统提示',mb_iconerror+mb_ok); exit; end; Result:=true; end; procedure TForm_MakeRule.ClearEdit; begin self.Edit_Rule_name.Text :=''; self.Edit_Sup_Flag.text:=''; self.Edit_Time_Flag.Text:=''; self.Edit_DT_String.Text :=''; self.Edit_Data_Flag.Text :=''; self.CB_Split_Flag.ItemIndex :=0; self.CB_Data_Unit.ItemIndex :=0; self.CB_FileSuffix.ItemIndex :=1; self.RG_Sup_Upper.ItemIndex :=0; self.RG_Time_Upper.ItemIndex:=0; self.RG_Data_Upper.ItemIndex :=0; self.RG_MoveSupp.ItemIndex :=0; Edit_MoveSuP_Value.Text :=''; self.Edit_MoveSup_ProFlag.Text:=''; MyRule.ClearDataS ; // 清理SringGrid1 InitDataTypeStrinGrid; end; procedure TForm_MakeRule.CopyToPhaseIntoMemoSource; var arr: array[0..99999] of Char; begin Clipboard.GetTextBuf(arr, Length(arr)); self.Memo_Source.Text :=Arr; end; procedure TForm_MakeRule.DeleteButtonClick(Sender: TObject); var sql:string; t_s:string; begin if Selected_Ruleid <=0 then exit; t_s:='你确定要删除【'+Edit_Rule_name.Text+'】的数据么?'; if Application.MessageBox(Pwidechar(t_s),'提示',MB_OKCANCEL+MB_ICONQUESTION) =2 then exit; sql:='delete from inputRule where id= '+IntTostr(Selected_Ruleid) ; MyCommand.CommandText :=sql; MyCommand.Execute ; // 清除数据 Sql:='delete from InputRule_DataType where Ruleid =' +IntTostr(Selected_Ruleid) ; MyCommand.CommandText :=sql; MyCommand.Execute ; //刷新ListBox FillListBox(ListBox1); OptionTip('数据删除成功!'); DeleteButton.Enabled :=false; end; procedure TForm_MakeRule.DispMemoCopySource(Px, Py: Integer); begin PopMemu_Memo.Popup(px,py); end; procedure TForm_MakeRule.EditButtonClick(Sender: TObject); begin SaveLx:='Update'; SaveButton.Enabled :=true; end; procedure TForm_MakeRule.Edit_Data_FlagClick(Sender: TObject); begin Edit_Data_Flag.SetFocus; end; procedure TForm_MakeRule.Edit_DT_StringClick(Sender: TObject); begin Edit_DT_String.SetFocus; end; procedure TForm_MakeRule.Edit_MoveSup_ProFlagClick(Sender: TObject); begin Edit_MoveSup_ProFlag.SetFocus; end; procedure TForm_MakeRule.Edit_MoveSuP_ValueClick(Sender: TObject); begin Edit_MoveSuP_Value.SetFocus; end; procedure TForm_MakeRule.Edit_Rule_nameClick(Sender: TObject); begin Edit_Rule_name.SetFocus; end; procedure TForm_MakeRule.Edit_Sup_FlagClick(Sender: TObject); begin Edit_Sup_Flag.SetFocus; end; procedure TForm_MakeRule.Edit_Time_FlagClick(Sender: TObject); begin Edit_Time_Flag.SetFocus; end; procedure TForm_MakeRule.ExitButtonClick(Sender: TObject); begin Close; end; procedure TForm_MakeRule.FillListBox(ListB: TListBox); var Sql:String; begin ListB.Clear ; try sql:='select id,RuleName from inputRule '; MyDataSet.Close ; MyDataSet.CommandText :=sql; if MyDataSet.Open then while not MyDataSet.Eof do begin ListB.Items.Add(MyDataSet.FieldByName('id').AsString + '_' + MyDataSet.FieldByName('RuleName').AsString ); MyDataSet.Next ; end; finally MyDataSet.Close ; end; end; function TForm_MakeRule.FillMyRuleData(id: Integer; Rule: TMakeRuleClass): Boolean; var Sql:string; tmp:TBasicDataParm; begin { inputRule RuleName,FileSufix,LineSplitStr,SupProFlag,SupUpper, ' + ' TimeProFlag,TimeUpper,TimeString ) InputRule_DataType Ruleid,DataType,DataBh,DataProFlag,DataUpper) values ( '; } try sql:='select * from inputRule where id= ' +IntTostr(id); Rule.ClearDataS ; MyDataSet.Close ; MyDataSet.CommandText :=sql; if MyDataSet.Open then begin Rule.RuleId:=MyDataSet.FieldByName('id').AsInteger; Rule.RuleName :=MyDataSet.FieldByName('RuleName').AsString; Rule.FileSuffix :=MyDataSet.FieldByName('FileSufix').AsString; Rule.LineSplitTag :=MyDataSet.FieldByName('LineSplitStr').AsString; Rule.SupProRec.TagStr :=MyDataSet.FieldByName('SupProFlag').AsString; Rule.SupProRec.UpperCase :=MyDataSet.FieldByName('SupUpper').AsInteger; Rule.DTProRec.TagStr :=MyDataSet.FieldByName('TimeProFlag').AsString; Rule.DTProRec.UpperCase :=MyDataSet.FieldByName('TimeUpper').AsInteger; Rule.DataTimeStr :=MyDataSet.FieldByName('TimeString').AsString; if MyDataSet.FieldByName('MoveSupTag').AsInteger=1 then begin Rule.MoveSuppFlag:=true; Rule.MoveProRec.UpperCase:=MyDataSet.FieldByName('MoveSuP_Upper').AsInteger; Rule.MoveSupp_Equal :=MyDataSet.FieldByName('MoveSup_Equal').AsString; Rule.MoveProRec.TagStr :=MyDataSet.FieldByName('MoveSup_ProFlag').AsString; Rule.MoveSupp_Value:=MyDataSet.FieldByName('MoveSup_Value').AsInteger; end else begin Rule.MoveSuppFlag:=False; Rule.MoveProRec.UpperCase:=0; Rule.MoveSupp_Equal :=''; Rule.MoveProRec.TagStr :=''; Rule.MoveSupp_Value:=0; end; Rule.MuleData_MAX_AGV:= MyDataSet.FieldByName('Mult_Max_AGV').AsInteger; end; MyDataSet.Close ; sql:='select * from InputRule_DataType where Ruleid= ' +IntTostr(Rule.RuleId); MyDataSet.CommandText :=sql; if MyDataSet.Open then while not MyDataSet.Eof do begin tmp.DataName :=MyDataSet.FieldByName('DataType').AsString; tmp.DataBh :=MyDataSet.FieldByName('DataBh').AsInteger ; tmp.DataType:=TSupportDataType(tmp.DataBh); tmp.TagStr :=MyDataSet.FieldByName('DataProFlag').AsString; tmp.UpperCase :=MyDataSet.FieldByName('DataUpper').AsInteger ; tmp.DataUnit:=MyDataSet.FieldByName('DataUnit').AsString; Rule.AddBasicDataS(tmp); MyDataSet.Next ; end; finally MyDataSet.Close ; end; end; function TForm_MakeRule.FillSelectEditData(Rule: TMakeRuleClass): Boolean; var i:integer; begin Edit_Rule_name.Text :=Rule.RuleName ; SelectComboBoxText(CB_FileSuffix,Rule.FileSuffix); SelectComboBoxText(self.CB_Split_Flag,Rule.LineSplitTag); self.Edit_Sup_Flag.Text :=Rule.SupProRec.TagStr; Self.RG_Sup_Upper.ItemIndex:=Rule.SupProRec.UpperCase; self.Edit_Time_Flag.Text :=Rule.DTProRec.TagStr; Self.RG_Time_Upper.ItemIndex:=Rule.DTProRec.UpperCase; self.Edit_DT_String.Text:=Rule.DataTimeStr; if Rule.MoveSuppFlag then begin self.RG_MoveSupp.ItemIndex := 0 ; self.Edit_MoveSup_ProFlag.Text :=Rule.MoveProRec.TagStr ; self.Edit_MoveSuP_Value.Text :=IntToStr(Rule.MoveSupp_Value ); self.RG_MoveSup_Upper.ItemIndex :=Rule.MoveProRec.UpperCase ; SelectComboBoxText(self.CB_Equal ,Rule.MoveSupp_Equal); end else begin self.RG_MoveSupp.ItemIndex := 1; self.GB_MoveSup.Enabled :=False; self.Edit_MoveSup_ProFlag.Text :=''; self.Edit_MoveSuP_Value.Text :=''; self.RG_MoveSup_Upper.ItemIndex :=0; end; self.CB_Mult_Max_AGV.ItemIndex :=Rule.MuleData_MAX_AGV; //更新stringGrid1 InitDataTypeStrinGrid; MyRule.FillDataToStrGrid(Self.StringGrid1); end; procedure TForm_MakeRule.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin {关闭窗体,还得需要发出Close命令} if Assigned(Form_MakeRule) then FreeAndNil(Form_MakeRule); end; procedure TForm_MakeRule.FormCreate(Sender: TObject); begin if not Assigned(MyRule) then MyRule:=TMakeRuleClass.Create(MainDataModule.ExConn) ; SelectedStringRow:=0; MyDataSet:=TMYDataSet.Create(nil); MyCommand:=TMyCommand.Create(nil); MyDataSet.MySqlConnection :=MainDataModule.ExConn; MyCommand.MySqlConnection :=MainDataModule.ExConn; // Selected_Ruleid:=-1; TabSheet2.Enabled :=false; end; procedure TForm_MakeRule.FormDestroy(Sender: TObject); begin if Assigned(MyRule) then FreeAndNil(MyRule); FreeAndNil(MyDataSet); FreeAndNil(MyCommand); end; procedure TForm_MakeRule.FormShow(Sender: TObject); begin Public_Basic.InitStatusBar(self.StatusBar1 ); ClearEdit; FillListBox(ListBox1); end; procedure TForm_MakeRule.GetInputEdit; begin MyRule.RuleName:=self.Edit_Rule_name.Text ; MyRule.FileSuffix:=self.CB_FileSuffix.Text ; MyRule.LineSplitTag:=self.CB_Split_Flag.Text; MyRule.SupProRec.TagStr :=Self.Edit_Sup_Flag.Text; MyRule.SupProRec.UpperCase:=self.RG_Sup_Upper.ItemIndex; MyRule.DTProRec.TagStr:=self.Edit_Time_Flag.Text; MyRule.DTProRec.UpperCase:=self.RG_Time_Upper.ItemIndex; MyRule.DataTimeStr:=self.Edit_DT_String.Text; if RG_MoveSupp.ItemIndex =0 then begin MYRule.MoveSuppFlag:=true; MYRule.MoveProRec.UpperCase:=self.RG_MoveSup_Upper.ItemIndex ; MYRule.MoveSupp_Equal :=self.CB_Equal.Text ; MYRule.MoveProRec.TagStr :=self.Edit_MoveSup_ProFlag.Text ; MYRule.MoveSupp_Value:=public_Basic.StrToInt_lu(Edit_MoveSuP_Value.Text) ; end else begin MYRule.MoveSuppFlag:=False; MYRule.MoveProRec.UpperCase:=0 ; MYRule.MoveSupp_Equal :=self.CB_Equal.Text ; MYRule.MoveProRec.TagStr :='' ; MYRule.MoveSupp_Value:=0 ; end; MyRule.MuleData_MAX_AGV:=self.CB_Mult_Max_AGV.ItemIndex ; end; procedure TForm_MakeRule.InitDataTypeStrinGrid; var i:integer; begin for i := 0 to StringGrid1.RowCount - 1 do begin StringGrid1.Rows[i].Clear ; StringGrid1.RowHeights[i]:=18; end; StringGrid1.ColCount :=6; StringGrid1.RowCount :=3; StringGrid1.Font.Size:=8; StringGrid1.FixedRows :=1; StringGrid1.Cells [0,0]:='序号'; StringGrid1.ColWidths[0]:=30; StringGrid1.Cells [1,0]:='数据名称'; StringGrid1.ColWidths[1]:=60; StringGrid1.Cells [2,0]:='前导标识'; StringGrid1.ColWidths[2]:=60; StringGrid1.Cells [3,0]:='数据单位'; StringGrid1.ColWidths[3]:=60; StringGrid1.Cells [4,0]:='大小写'; StringGrid1.ColWidths[4]:=60; end; procedure TForm_MakeRule.ListBox1Click(Sender: TObject); var LinStr:String; begin if listBox1.itemindex <0 then exit; LinStr:= ListBox1.items[listBox1.itemindex]; Selected_Ruleid:=public_Basic.StrToInt_lu(LeftStr(LinStr,pos('_',LinStr)-1)); if Selected_Ruleid >0 then begin FillMyRuleData(Selected_Ruleid,MyRule); FillSelectEditData(MyRule); TabSheet2.Enabled :=true; end; self.DeleteButton.Enabled :=True; self.EditButton.Enabled :=true; GroupBox2.Enabled :=true; end; procedure TForm_MakeRule.Memo_SourceClick(Sender: TObject); begin Memo_Source.SetFocus; end; procedure TForm_MakeRule.Memo_SourceMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var pt:TPoint; begin if Button=mbRight then begin pt:= self.Memo_Source.ClientToScreen(Point(0,0)); DispMemoCopySource(pt.X +x,Pt.y+y); end; end; procedure TForm_MakeRule.N2Click(Sender: TObject); begin self.Memo_Source.Clear ; end; procedure TForm_MakeRule.N4Click(Sender: TObject); begin CopyToPhaseIntoMemoSource; end; procedure TForm_MakeRule.OptionTip(Str: String); begin StatusBar1.Panels[0].Text :=str; end; procedure TForm_MakeRule.RG_MoveSuppClick(Sender: TObject); begin if self.RG_MoveSupp.ItemIndex =0 then begin self.GB_MoveSup.Enabled :=true; end else begin self.GB_MoveSup.Enabled :=False; end; end; procedure TForm_MakeRule.SaveButtonClick(Sender: TObject); begin if SaveIntoDataBase(Savelx) then begin //刷新ListBox FillListBox(ListBox1); // SaveButton.Enabled :=false; end; end; function TForm_MakeRule.SaveIntoDataBase(Sav:String):Boolean; var sql,Sql2:string; Ruleid,i:integer; Move_Tag:Integer; begin Result:=False; if not self.CheckInputEdit then exit; GetInputEdit; if MyRule.Basic_DataNumber <1 then begin messagebox(self.Handle,'请填充数据规则!','系统提示',mb_iconerror+mb_ok); exit; end; if MyRule.MoveSuppFlag then Move_Tag:=1 else Move_Tag:=0; if Sav='Insert' then begin try sql:='insert into inputRule (RuleName,FileSufix,LineSplitStr,SupProFlag,SupUpper, ' + ' TimeProFlag,TimeUpper,TimeString,MoveSupTag,MoveSup_ProFlag,MoveSup_Upper, ' + ' Movesup_Equal,Movesup_Value,Mult_Max_AGV ) Values ( ' + '''' + MyRule.RuleName + ''',''' + MyRule.FileSuffix + ''',' + '''' + MyRule.LineSplitTag +''',''' + MyRule.SupProRec.TagStr + ''',' + IntToStr(MyRule.SupProRec.UpperCase) +',''' + MyRule.DTProRec.TagStr + ''',' + IntTostr(MyRule.DTProRec.UpperCase ) +',''' + MyRule.DataTimeStr + ''',' + IntTostr(Move_Tag ) +',''' + MyRule.MoveProRec.TagStr + ''',' + IntTostr(MyRule.MoveProRec.UpperCase ) +',''' + MyRule.MoveSupp_Equal + ''',' + IntTostr(MyRule.MoveSupp_Value ) + ',' + IntTostr(MyRule.MuleData_MAX_AGV ) + ') '; MyCommand.CommandText :=sql; MyCommand.Execute ; Ruleid:=self.SelectMaxId ; if Ruleid >0 then begin Sql2:='insert into InputRule_DataType (Ruleid,DataType,DataBh,DataProFlag,DataUpper,DataUnit) values ( '; for I := 0 to MyRule.Basic_DataNumber -1 do begin sql:=Sql2 +IntTostr(Ruleid) + ',''' + MyRule.BasicDataS[i].DataName +''',' + IntTostr(MyRule.BasicDataS[i].DataBh) + ',''' +MyRule.BasicDataS[i].TagStr + ''',' + IntTostr(MyRule.BasicDataS[i].UpperCase ) +','''+MyRule.BasicDataS[i].DataUnit + '''' + ')'; MyCommand.CommandText :=sql; MyCommand.Execute ; end; end; finally OptionTip('数据保存成功!'); end; end else if Sav='Update' then begin try if Selected_Ruleid <=0 then exit; sql:='Update inputRule set RuleName = ''' + MyRule.RuleName + ''', ' + ' FileSufix = ''' + MyRule.FileSuffix +''', ' + ' LineSplitStr= ''' + MyRule.LineSplitTag + ''', ' + ' SupProFlag= '''+ MyRule.SupProRec.TagStr + ''',' + ' SupUpper =' + IntToStr(MyRule.SupProRec.UpperCase) +', ' + ' TimeProFlag= '''+ MyRule.DTProRec.TagStr + ''',' + ' TimeUpper =' + IntToStr(MyRule.DTProRec.UpperCase) +', ' + ' TimeString =''' + MyRule.DataTimeStr +''', ' + ' MoveSupTag = ' + IntTostr(Move_Tag ) +', '+ ' MoveSup_ProFlag = ''' + MyRule.MoveProRec.TagStr + ''',' + ' MoveSup_Upper = ' + IntTostr(MyRule.MoveProRec.UpperCase ) +', '+ ' Movesup_Equal = ''' + MyRule.MoveSupp_Equal + ''',' + ' Movesup_Value = ' + IntTostr(MyRule.MoveSupp_Value ) + ',' + ' Mult_Max_AGV = ' + IntTostr(MyRule.MuleData_MAX_AGV ) + ' where id= '+IntTostr(Selected_Ruleid) ; MyCommand.CommandText :=sql; MyCommand.Execute ; // 清除数据 Sql2:='delete from InputRule_DataType where Ruleid =' +IntTostr(Selected_Ruleid) ; MyCommand.CommandText :=sql2; MyCommand.Execute ; Sql2:='insert into InputRule_DataType (Ruleid,DataType,DataBh,DataProFlag,DataUpper,DataUnit) values ( '; for I := 0 to MyRule.Basic_DataNumber -1 do begin sql:=Sql2 +IntTostr(Selected_Ruleid) + ',''' + MyRule.BasicDataS[i].DataName +''',' + IntTostr(MyRule.BasicDataS[i].DataBh) + ',''' +MyRule.BasicDataS[i].TagStr + ''',' + IntTostr(MyRule.BasicDataS[i].UpperCase ) +','''+MyRule.BasicDataS[i].DataUnit + '''' + ')'; MyCommand.CommandText :=sql; MyCommand.Execute ; end; finally OptionTip('数据编辑成功!'); end; end; Result:=true; end; procedure TForm_MakeRule.SelectComboBoxText(CB: TComboBox; Str: String); var i:integer; Selected:Boolean; begin Selected:=False; for I := 0 to CB.Items.Count -1 do if cb.Items.Strings[i]=str then begin cb.ItemIndex :=i; Selected :=true; break; end; if not Selected then begin cb.Items.Add(str); cb.ItemIndex := CB.Items.Count -1; end; end; function TForm_MakeRule.SelectMaxId: Integer; var sql:string; begin Result:=-1; try sql:='select MAX(id) as MD from inputRule '; MyDataSet.Close ; MyDataSet.CommandText :=sql; if MyDataSet.Open then Result:=MyDataSet.FieldByName('MD').AsInteger ; finally MyDataSet.Close ; end; end; procedure TForm_MakeRule.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin SelectedStringRow:= ARow; end; end. // end unit
unit CarTest; interface uses dbTest, dbObjectTest, TestFramework, ObjectTest; type TCarTest = class(TdbObjectTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TCar = class(TObjectTest) function InsertDefault: integer; override; public function InsertUpdateCar(const Id, Code : integer; Name, RegistrationCertificateId: string; CarModelId: Integer): integer; constructor Create; override; end; implementation uses ZDbcIntfs, SysUtils, Storage, DBClient, XMLDoc, CommonData, Forms, UtilConvert, UtilConst, ZLibEx, zLibUtil, JuridicalTest, DB, CarModelTest; constructor TCar.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_Car'; spSelect := 'gpSelect_Object_Car'; spGet := 'gpGet_Object_Car'; end; function TCar.InsertDefault: integer; var CarModelId: Integer; begin CarModelId := TCarModel.Create.GetDefault; result := InsertUpdateCar(0, -1, 'Автомобиль', 'АЕ НЕ', CarModelId); inherited; end; function TCar.InsertUpdateCar; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inCode', ftInteger, ptInput, Code); FParams.AddParam('inName', ftString, ptInput, Name); FParams.AddParam('RegistrationCertificateId', ftString, ptInput, RegistrationCertificateId); FParams.AddParam('inCarModelId', ftInteger, ptInput, CarModelId); FParams.AddParam('inUnitId', ftInteger, ptInput, 0); FParams.AddParam('inPersonalDriverId', ftInteger, ptInput, 0); FParams.AddParam('inFuelMasterId', ftInteger, ptInput, 0); FParams.AddParam('inFuelChildId', ftInteger, ptInput, 0); result := InsertUpdate(FParams); end; { TBranchTest } procedure TCarTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'OBJECTS\Car\'; inherited; end; procedure TCarTest.Test; var Id: integer; RecordCount: Integer; ObjectTest: TCar; begin ObjectTest := TCar.Create; // Получим список RecordCount := ObjectTest.GetDataSet.RecordCount; // Вставка Автомобиля Id := ObjectTest.InsertDefault; try // Получение данных о Филиале with ObjectTest.GetRecord(Id) do Check((FieldByName('Name').AsString = 'Автомобиль'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; initialization TestFramework.RegisterTest('Объекты', TCarTest.Suite); end.
unit UFMenu; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, Client.VO, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Edit, System.RegularExpressions, Winapi.Windows, FMX.ListBox, REST.Types, Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Data.Bind.Components, REST.Client, Data.Bind.ObjectScope, System.JSON, System.Generics.Collections, Xml.xmldom, Xml.XMLIntf, Xml.XMLDoc, XML.Controller, IdMessage, IdBaseComponent, IdText, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdServerIOHandler, IdSSL, IdSSLOpenSSL, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdAttachmentFile; type TFMenu = class(TForm) Panel1: TPanel; Label1: TLabel; edtCliNome: TEdit; edtCliIdentidade: TEdit; edtCliCPF: TEdit; edtCliTelefone: TEdit; edtCliEmail: TEdit; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; gbEndereco: TGroupBox; edtEndCEP: TEdit; edtEndLogradouro: TEdit; edtEndNumero: TEdit; edtEndComplemento: TEdit; edtEndBairro: TEdit; edtEndCidade: TEdit; edtEndPais: TEdit; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Bairro: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Panel2: TPanel; btnNovo: TButton; btnSalvar: TButton; btnSair: TButton; btnConsultaCEP: TButton; edtEndEstado: TComboBox; RESTRequest: TRESTRequest; RESTClient: TRESTClient; RESTResponse: TRESTResponse; BindingsList: TBindingsList; IdSMTP: TIdSMTP; IdMessage: TIdMessage; IdServerIOHandlerSSLOpenSSL: TIdServerIOHandlerSSLOpenSSL; IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL; procedure btnNovoClick(Sender: TObject); procedure btnSairClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnConsultaCEPClick(Sender: TObject); procedure edtEndCEPKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); private { Private declarations } vCliente : TClientVO; vEndereco : TAddressVO; vListaCliente : TObjectList<TClientVO>; procedure LimparControles; procedure LimpaEstanciaObjeto; procedure ValidarNumeros(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure ValidarEmail(Sender: TObject); procedure ValidarControles; procedure PreencherObjeto; procedure EnviarEmail; public { Public declarations } end; var FMenu: TFMenu; implementation {$R *.fmx} uses Client.Controller, JSon.Controller, JSon.VO; procedure TFMenu.btnNovoClick(Sender: TObject); begin LimparControles; LimpaEstanciaObjeto; end; procedure TFMenu.btnSairClick(Sender: TObject); begin Application.Terminate; end; procedure TFMenu.btnSalvarClick(Sender: TObject); begin ValidarControles; PreencherObjeto; EnviarEmail; end; procedure TFMenu.edtEndCEPKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if key = 13 then btnConsultaCEPClick(Sender); end; procedure TFMenu.EnviarEmail; var vXML : string; TextoMsg: TidText; begin try vXML := TXMLController.GetInstance.ObjectToXML(vCliente); IdSMTP.ConnectTimeout := 10000; IdSMTP.ReadTimeout := 10000; IdMessage.Clear; IdMessage.CharSet := 'iso-8859-1'; IdMessage.Encoding := MeMIME; IdMessage.ContentType := 'multipart/related' ; IdMessage.subject := 'Assunto'; IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23; IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient; IdSMTP.IOHandler := IdSSLIOHandlerSocket; IdSMTP.UseTLS := utUseImplicitTLS; IdSMTP.AuthType := satDefault; IdSMTP.Port := 465; IdSMTP.Host := 'smtp.gmail.com'; IdSMTP.Username := InputBox('Digite seu Email (gmail)', 'Email: ', '');// 'usuario@gmail.com'; IdSMTP.Password := InputBox('Digite sua senha', 'Senha: ', ''); IdMessage.From.Address := InputBox('Email do remetente', 'Email: ', ''); IdMessage.From.Name := InputBox('Nome do remetente', 'Nome: ', ''); IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address; IdMessage.Recipients.Add.Text := 'adrianogalvao@agbtecnologia.com.br'; IdMessage.Subject := InputBox('Assunto do email', 'Assunto: ', '');; IdMessage.Encoding := meMIME; TextoMsg := TIdText.Create(IdMessage.MessageParts); TextoMsg.Body.Add(vXML); TextoMsg.ContentType := 'text/plain; charset=iso-8859-1'; TIdAttachmentFile.Create(IdMessage.MessageParts, GetCurrentDir + '\Cliente.xml'); try IdSMTP.Connect; IdSMTP.Authenticate; except on E:Exception do begin ShowMessage('Erro na conexão ou autenticação: ' + E.Message); Exit; end; end; try IdSMTP.Send(IdMessage); ShowMessage('Mensagem enviada com sucesso!'); except On E:Exception do begin ShowMessage('Erro ao enviar a mensagem: ' + E.Message); end; end; finally UnLoadOpenSSLLibrary; end; end; procedure TFMenu.btnConsultaCEPClick(Sender: TObject); procedure ResetRESTConnection; begin RESTClient.ResetToDefaults; RESTRequest.ResetToDefaults; RESTResponse.ResetToDefaults; end; var vJSONVO : TJsonVO; vJSON : TJSONObject; vOk : Boolean; begin try ResetRESTConnection; RESTClient.BaseURL := 'https://viacep.com.br/ws/'; RESTRequest.Resource := edtEndCEP.Text + '/json/'; RESTRequest.Method := TRESTRequestMethod.rmGET; RESTRequest.Execute; vJSON := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(RESTResponse.Content),0) as TJSONObject; vJSONVO := TJsonVO.Create; vJSONVO := TJsonController.GetInstance.JSONToObject(vJSON); edtEndLogradouro.Text := vJSONVO.logradouro; edtEndComplemento.Text := vJSONVO.complemento; edtEndBairro.Text := vJSONVO.bairro; edtEndCidade.Text := vJSONVO.localidade; edtEndEstado.ItemIndex := Integer(TClientController.GetInstance.StrToTState(vOk, vJSONVO.uf)); finally FreeAndNil(vJSONVO); FreeAndNil(vJSON); end; end; procedure TFMenu.FormCreate(Sender: TObject); begin edtCliCPF.OnKeyDown := ValidarNumeros; edtCliTelefone.OnKeyDown := ValidarNumeros; edtEndCEP.OnKeyDown := ValidarNumeros; edtEndNumero.OnKeyDown := ValidarNumeros; edtCliIdentidade.OnKeyDown := ValidarNumeros; edtCliEmail.OnExit := ValidarEmail; LimparControles; LimpaEstanciaObjeto; vListaCliente := TObjectList<TClientVO>.Create; end; procedure TFMenu.LimpaEstanciaObjeto; begin if Assigned(vCliente) then begin FreeAndNil(vCliente); end; if Assigned(vEndereco) then begin FreeAndNil(vEndereco); end; vCliente := TClientVO.Create; vEndereco := TAddressVO.Create; end; procedure TFMenu.LimparControles; begin edtCliNome.Text := ''; edtCliIdentidade.Text := ''; edtCliCPF.Text := ''; edtCliTelefone.Text := ''; edtCliEmail.Text := ''; edtEndCEP.Text := ''; edtEndLogradouro.Text := ''; edtEndNumero.Text := ''; edtEndComplemento.Text := ''; edtEndBairro.Text := ''; edtEndCidade.Text := ''; edtEndEstado.ItemIndex := -1; edtEndPais.Text := ''; end; procedure TFMenu.PreencherObjeto; var vOk : Boolean; begin try vCliente.Nome := edtCliNome.Text; vCliente.Identidade := StrToInt(edtCliIdentidade.Text); vCliente.CPF := StrToInt64(edtCliCPF.Text); vCliente.Telefone := edtCliTelefone.Text; vCliente.Email := edtCliEmail.Text; vEndereco.Cep := StrToInt(edtEndCEP.Text); vEndereco.Logradouro := edtEndLogradouro.Text; vEndereco.Numero := edtEndNumero.Text; vEndereco.Complemento := edtEndComplemento.Text; vEndereco.Bairro := edtEndBairro.Text; vEndereco.Cidade := edtEndCidade.Text; vEndereco.Estado := TClientController.GetInstance.StrToTState(vOk, edtEndEstado.Items[edtEndEstado.ItemIndex]); vEndereco.Pais := edtEndPais.Text; vCliente.Endereco := vEndereco; vListaCliente.Add(vCliente); except on e : exception do begin raise Exception.Create('Erro ao preencher objeto.' + e.Message); end; end; end; procedure TFMenu.ValidarControles; procedure MensagemValidar(Sender : TObject); begin ShowMessage('O Campo não pode ser vazio: ' + TEdit(Sender).TextPrompt); Abort; end; begin if edtCliNome.Text = '' then MensagemValidar(edtCliNome); if edtCliIdentidade.Text = '' then MensagemValidar(edtCliIdentidade); if edtCliCPF.Text = '' then MensagemValidar(edtCliCPF); if edtCliTelefone.Text = '' then MensagemValidar(edtCliTelefone); if edtCliEmail.Text = '' then MensagemValidar(edtCliEmail); if edtEndCEP.Text = '' then MensagemValidar(edtEndCEP); if edtEndLogradouro.Text = '' then MensagemValidar(edtEndLogradouro); if edtEndNumero.Text = '' then MensagemValidar(edtEndNumero); if edtEndComplemento.Text = '' then MensagemValidar(edtEndComplemento); if edtEndBairro.Text = '' then MensagemValidar(edtEndBairro); if edtEndCidade.Text = '' then MensagemValidar(edtEndCidade); if edtEndEstado.ItemIndex = -1 then ShowMessage('O Campo não pode ser vazio: Estado'); if edtEndPais.Text = '' then MensagemValidar(edtEndPais); end; procedure TFMenu.ValidarEmail(Sender: TObject); var RegEx: TRegEx; begin if TEdit(Sender).Text <> '' then begin RegEx := TRegex.Create('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]*[a-zA-Z0-9]+$'); if not RegEx.Match(TEdit(Sender).Text).Success then begin ShowMessage('Email inválido.'); TEdit(Sender).Text := ''; TEdit(Sender).SetFocus; end; end; end; procedure TFMenu.ValidarNumeros(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if (KeyChar In ['A'..'Z', 'a'..'z', '@','!','#','$', '%','^', '&','`','~','*','(',')','-','_','=','+','|','/','<','>', '"',';',':','[',']','{','}']) then begin Key := 0; Abort; end; end; end.
program readtest; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} SysUtils, Classes, dxfparse, dxftypes { you can add units after this }; var fs : TFileStream; bs : TDxfScanner; begin if ParamCount=0 then begin writeln('please specify input file name'); Exit; end; fs := TFileStream.Create(ParamStr(1), fmOpenRead or fmShareDenyNone); try bs := DxfAllocScanner(fs, false); try while bs.Next <> scEof do begin if bs.LastScan = scError then begin writeln('err: ', bs.ErrStr); Exit; end; case bs.datatype of dtUnknown: writeln('unknown'); dtInt16, dtInt32: writeln(' value: ', bs.ValInt); dtInt64: writeln(' value: ', bs.ValInt64); dtStr2049, dtStr255, dtStrHex : writeln(' value: ', bs.ValStr); dtDouble: writeln(' value: ', bs.ValFloat); dtBoolean: writeln(' value: ', bs.ValInt); dtBin1: writeln(' value length: ', bs.ValBinLen); end; end; finally bs.Free; end; finally fs.Free; end; end.
{ TBatteryInfo Component Version 1.1 - Suite GLib Copyright (©) 2009, by Germán Estévez (Neftalí) Acceso a los atributos de la batería conectada al equipo. Utilización/Usage: Basta con "soltar" el componente y activarlo. Place the component in the form and active it. MSDN Info: http://msdn.microsoft.com/en-us/library//aa394074(VS.85).aspx ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia envíame un mail a: german_ral@hotmail.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion send a mail to: german_ral@hotmail.com ========================================================================= @author Germán Estévez (Neftalí) @web http://neftali.clubDelphi.com - http://neftali-mirror.site11.com/ @cat Package GLib } unit CBatteryInfo; { ========================================================================= TBatteryInfo.pas Componente ======================================================================== Historia de las Versiones ------------------------------------------------------------------------ 07/01/2010 * Creación. ========================================================================= Errores detectados no corregidos ========================================================================= } //========================================================================= // // I N T E R F A C E // //========================================================================= interface uses Classes, Controls, CWMIBase; type //: Clase para definir las propiedades del componente. TBatteryProperties = class(TPersistent) private FAvailability:Integer; FAvailabilityAsString:string; FBatteryRechargeTime:Longword; FBatteryStatus:Integer; FBatteryStatusAsString:string; FCaption:string; FChemistry:Integer; FChemistryAsString:string; FConfigManagerErrorCode:Longword; FConfigManagerErrorCodeAsString:string; FConfigManagerUserConfig:boolean; FCreationClassName:string; FDescription:string; FDesignCapacity:Longword; FDesignVoltage:Int64; FDeviceID:string; FErrorCleared:boolean; FErrorDescription:string; FEstimatedChargeRemaining:Integer; FEstimatedRunTime:Longword; FExpectedBatteryLife:Longword; FExpectedLife:Longword; FFullChargeCapacity:Longword; FInstallDate:TDateTime; FLastErrorCode:Longword; FMaxRechargeTime:Longword; FName:string; FPNPDeviceID:string; FPowerManagementCapabilities:TArrInteger; FPowerManagementCapabilitiesCount:integer; FPowerManagementCapabilitiesAsString:string; FPowerManagementSupported:boolean; FSmartBatteryVersion:string; FStatus:string; FStatusInfo:Integer; FStatusInfoAsString:string; FSystemCreationClassName:string; FSystemName:string; FTimeOnBattery:Longword; FTimeToFullCharge:Longword; private function GetPowerManagementCapabilities(index: integer): Integer; public property PowerManagementCapabilities[index:integer]:Integer read GetPowerManagementCapabilities; property PowerManagementCapabilitiesCount:integer read FPowerManagementCapabilitiesCount stored False; // Obtener la propiedad <Availability> como string function GetAvailabilityAsString():string; // Obtener la propiedad <BatteryStatus> como string function GetBatteryStatusAsString():string; // Obtener la propiedad <Chemistry> como string function GetChemistryAsString():string; // Obtener la propiedad <ConfigManagerErrorCode> como string function GetConfigManagerErrorCodeAsString():string; // Obtener la propiedad <StatusInfo> como string function GetStatusInfoAsString():string; published property Availability:Integer read FAvailability write FAvailability stored False; property AvailabilityAsString:string read GetAvailabilityAsString write FAvailabilityAsString stored False; property BatteryRechargeTime:Longword read FBatteryRechargeTime write FBatteryRechargeTime stored False; property BatteryStatus:Integer read FBatteryStatus write FBatteryStatus stored False; property BatteryStatusAsString:string read GetBatteryStatusAsString write FBatteryStatusAsString stored False; property Caption:string read FCaption write FCaption stored False; property Chemistry:Integer read FChemistry write FChemistry stored False; property ChemistryAsString:string read GetChemistryAsString write FChemistryAsString stored False; property ConfigManagerErrorCode:Longword read FConfigManagerErrorCode write FConfigManagerErrorCode stored False; property ConfigManagerErrorCodeAsString:string read GetConfigManagerErrorCodeAsString write FConfigManagerErrorCodeAsString stored False; property ConfigManagerUserConfig:boolean read FConfigManagerUserConfig write FConfigManagerUserConfig stored False; property CreationClassName:string read FCreationClassName write FCreationClassName stored False; property Description:string read FDescription write FDescription stored False; property DesignCapacity:Longword read FDesignCapacity write FDesignCapacity stored False; property DesignVoltage:Int64 read FDesignVoltage write FDesignVoltage stored False; property DeviceID:string read FDeviceID write FDeviceID stored False; property ErrorCleared:boolean read FErrorCleared write FErrorCleared stored False; property ErrorDescription:string read FErrorDescription write FErrorDescription stored False; property EstimatedChargeRemaining:Integer read FEstimatedChargeRemaining write FEstimatedChargeRemaining stored False; property EstimatedRunTime:Longword read FEstimatedRunTime write FEstimatedRunTime stored False; property ExpectedBatteryLife:Longword read FExpectedBatteryLife write FExpectedBatteryLife stored False; property ExpectedLife:Longword read FExpectedLife write FExpectedLife stored False; property FullChargeCapacity:Longword read FFullChargeCapacity write FFullChargeCapacity stored False; property InstallDate:TDateTime read FInstallDate write FInstallDate stored False; property LastErrorCode:Longword read FLastErrorCode write FLastErrorCode stored False; property MaxRechargeTime:Longword read FMaxRechargeTime write FMaxRechargeTime stored False; property Name:string read FName write FName stored False; property PNPDeviceID:string read FPNPDeviceID write FPNPDeviceID stored False; property PowerManagementCapabilitiesAsString:string read FPowerManagementCapabilitiesAsString write FPowerManagementCapabilitiesAsString stored False; property PowerManagementSupported:boolean read FPowerManagementSupported write FPowerManagementSupported stored False; property SmartBatteryVersion:string read FSmartBatteryVersion write FSmartBatteryVersion stored False; property Status:string read FStatus write FStatus stored False; property StatusInfo:Integer read FStatusInfo write FStatusInfo stored False; property StatusInfoAsString:string read GetStatusInfoAsString write FStatusInfoAsString stored False; property SystemCreationClassName:string read FSystemCreationClassName write FSystemCreationClassName stored False; property SystemName:string read FSystemName write FSystemName stored False; property TimeOnBattery:Longword read FTimeOnBattery write FTimeOnBattery stored False; property TimeToFullCharge:Longword read FTimeToFullCharge write FTimeToFullCharge stored False; end; //: Implementación para el acceso vía WMI a la clase Win32_Battery TBatteryInfo = class(TWMIBase) private FBatteryProperties: TBatteryProperties; protected //: Rellenar las propiedades. procedure FillProperties(AIndex:integer); override; // propiedad Active procedure SetActive(const Value: Boolean); override; //: Clase para el componente. function GetWMIClass():string; override; //: Obtener el root. function GetWMIRoot():string; override; //: Limpiar las propiedades procedure ClearProps(); override; public // redefinido el constructor constructor Create(AOwner: TComponent); override; //: destructor destructor Destroy; override; published // propiedades de la Battery property BatteryProperties:TBatteryProperties read FBatteryProperties write FBatteryProperties; end; // Constantes para la propiedad Availability const ENUM_STRING_AVAILABILITY_1 = 'Other'; ENUM_STRING_AVAILABILITY_2 = 'Unknown'; ENUM_STRING_AVAILABILITY_3 = 'Running or Full Power'; ENUM_STRING_AVAILABILITY_4 = 'Warning'; ENUM_STRING_AVAILABILITY_5 = 'In Test'; ENUM_STRING_AVAILABILITY_6 = 'Not Applicable'; ENUM_STRING_AVAILABILITY_7 = 'Power Off'; ENUM_STRING_AVAILABILITY_8 = 'Off Line'; ENUM_STRING_AVAILABILITY_9 = 'Off Duty'; ENUM_STRING_AVAILABILITY_10 = 'Degraded'; ENUM_STRING_AVAILABILITY_11 = 'Not Installed'; ENUM_STRING_AVAILABILITY_12 = 'Install Error'; ENUM_STRING_AVAILABILITY_13 = 'Power Save - Unknown. The device is known to be in a power save mode, but its exact status is unknown.'; ENUM_STRING_AVAILABILITY_14 = 'Power Save - Low Power Mode. The device is in a power save state but still functioning, and may exhibit degraded performance.'; ENUM_STRING_AVAILABILITY_15 = 'Power Save - Standby. The device is not functioning, but could be brought to full power quickly.'; ENUM_STRING_AVAILABILITY_16 = 'Power Cycle'; ENUM_STRING_AVAILABILITY_17 = 'Power Save - Warning. The device is in a warning state, though also in a power save mode.'; // Constantes para la propiedad BatteryStatus const ENUM_STRING_BATTERYSTATUS_1 = 'The battery is discharging.'; ENUM_STRING_BATTERYSTATUS_2 = 'The system has access to AC so no battery is being discharged. However, the battery is not necessarily charging.'; ENUM_STRING_BATTERYSTATUS_3 = 'Fully Charged'; ENUM_STRING_BATTERYSTATUS_4 = 'Low'; ENUM_STRING_BATTERYSTATUS_5 = 'Critical'; ENUM_STRING_BATTERYSTATUS_6 = 'Charging'; ENUM_STRING_BATTERYSTATUS_7 = 'Charging and High'; ENUM_STRING_BATTERYSTATUS_8 = 'Charging and Low'; ENUM_STRING_BATTERYSTATUS_9 = 'Charging and Critical'; ENUM_STRING_BATTERYSTATUS_10 = 'Undefined'; ENUM_STRING_BATTERYSTATUS_11 = 'Partially Charged'; // Constantes para la propiedad Chemistry const ENUM_STRING_CHEMISTRY_1 = 'Other'; ENUM_STRING_CHEMISTRY_2 = 'Unknown'; ENUM_STRING_CHEMISTRY_3 = 'Lead Acid'; ENUM_STRING_CHEMISTRY_4 = 'Nickel Cadmium'; ENUM_STRING_CHEMISTRY_5 = 'Nickel Metal Hydride'; ENUM_STRING_CHEMISTRY_6 = 'Lithium-ion'; ENUM_STRING_CHEMISTRY_7 = 'Zinc air'; ENUM_STRING_CHEMISTRY_8 = 'Lithium Polymer'; // Constantes para la propiedad ConfigManagerErrorCode const ENUM_STRING_CONFIGMANAGERERRORCODE_0 = 'Device is working properly.'; ENUM_STRING_CONFIGMANAGERERRORCODE_1 = 'Device is not configured correctly.'; ENUM_STRING_CONFIGMANAGERERRORCODE_2 = 'Windows cannot load the driver for this device.'; ENUM_STRING_CONFIGMANAGERERRORCODE_3 = 'Driver for this device might be corrupted, or the system may be low on memory or other resources.'; ENUM_STRING_CONFIGMANAGERERRORCODE_4 = 'Device is not working properly. One of its drivers or the registry might be corrupted.'; ENUM_STRING_CONFIGMANAGERERRORCODE_5 = 'Driver for the device requires a resource that Windows cannot manage.'; ENUM_STRING_CONFIGMANAGERERRORCODE_6 = 'Boot configuration for the device conflicts with other devices.'; ENUM_STRING_CONFIGMANAGERERRORCODE_7 = 'Cannot filter.'; ENUM_STRING_CONFIGMANAGERERRORCODE_8 = 'Driver loader for the device is missing.'; ENUM_STRING_CONFIGMANAGERERRORCODE_9 = 'Device is not working properly. The controlling firmware is incorrectly reporting the resources for the device.'; ENUM_STRING_CONFIGMANAGERERRORCODE_10 = 'Device cannot start.'; ENUM_STRING_CONFIGMANAGERERRORCODE_11 = 'Device failed.'; ENUM_STRING_CONFIGMANAGERERRORCODE_12 = 'Device cannot find enough free resources to use.'; ENUM_STRING_CONFIGMANAGERERRORCODE_13 = 'Windows cannot verify the device''s resources.'; ENUM_STRING_CONFIGMANAGERERRORCODE_14 = 'Device cannot work properly until the computer is restarted.'; ENUM_STRING_CONFIGMANAGERERRORCODE_15 = 'Device is not working properly due to a possible re-enumeration problem.'; ENUM_STRING_CONFIGMANAGERERRORCODE_16 = 'Windows cannot identify all of the resources that the device uses.'; ENUM_STRING_CONFIGMANAGERERRORCODE_17 = 'Device is requesting an unknown resource type.'; ENUM_STRING_CONFIGMANAGERERRORCODE_18 = 'Device drivers must be reinstalled.'; ENUM_STRING_CONFIGMANAGERERRORCODE_19 = 'Failure using the VxD loader.'; ENUM_STRING_CONFIGMANAGERERRORCODE_20 = 'Registry might be corrupted.'; ENUM_STRING_CONFIGMANAGERERRORCODE_21 = 'System failure. If changing the device driver is ineffective, see the hardware documentation. Windows is removing the device.'; ENUM_STRING_CONFIGMANAGERERRORCODE_22 = 'Device is disabled.'; ENUM_STRING_CONFIGMANAGERERRORCODE_23 = 'System failure. If changing the device driver is ineffective, see the hardware documentation.'; ENUM_STRING_CONFIGMANAGERERRORCODE_24 = 'Device is not present, not working properly, or does not have all of its drivers installed.'; ENUM_STRING_CONFIGMANAGERERRORCODE_25 = 'Windows is still setting up the device.'; ENUM_STRING_CONFIGMANAGERERRORCODE_26 = 'Windows is still setting up the device.'; ENUM_STRING_CONFIGMANAGERERRORCODE_27 = 'Device does not have valid log configuration.'; ENUM_STRING_CONFIGMANAGERERRORCODE_28 = 'Device drivers are not installed.'; ENUM_STRING_CONFIGMANAGERERRORCODE_29 = 'Device is disabled. The device firmware did not provide the required resources.'; ENUM_STRING_CONFIGMANAGERERRORCODE_30 = 'Device is using an IRQ resource that another device is using.'; ENUM_STRING_CONFIGMANAGERERRORCODE_31 = 'Device is not working properly. Windows cannot load the required device drivers.'; // Constantes para la propiedad StatusInfo const ENUM_STRING_STATUSINFO_1 = 'Other'; ENUM_STRING_STATUSINFO_2 = 'Unknown'; ENUM_STRING_STATUSINFO_3 = 'Enabled'; ENUM_STRING_STATUSINFO_4 = 'Disabled'; ENUM_STRING_STATUSINFO_5 = 'Not Applicable'; //========================================================================= // // I M P L E M E N T A T I O N // //========================================================================= implementation uses {Generales} Forms, Types, Windows, SysUtils, {GLib} UProcedures, UConstantes, Dialogs; { TBattery } {-------------------------------------------------------------------------------} // Limpiar las propiedades procedure TBatteryInfo.ClearProps; begin Self.BatteryProperties.FAvailability := 0; Self.BatteryProperties.FBatteryRechargeTime := 0; Self.BatteryProperties.FBatteryStatus := 0; Self.BatteryProperties.FCaption := STR_EMPTY; Self.BatteryProperties.FChemistry := 0; Self.BatteryProperties.FConfigManagerErrorCode := 0; Self.BatteryProperties.FConfigManagerUserConfig := False; Self.BatteryProperties.FCreationClassName := STR_EMPTY; Self.BatteryProperties.FDescription := STR_EMPTY; Self.BatteryProperties.FDesignCapacity := 0; Self.BatteryProperties.FDesignVoltage := 0; Self.BatteryProperties.FDeviceID := STR_EMPTY; Self.BatteryProperties.FErrorCleared := False; Self.BatteryProperties.FErrorDescription := STR_EMPTY; Self.BatteryProperties.FEstimatedChargeRemaining := 0; Self.BatteryProperties.FEstimatedRunTime := 0; Self.BatteryProperties.FExpectedBatteryLife := 0; Self.BatteryProperties.FExpectedLife := 0; Self.BatteryProperties.FFullChargeCapacity := 0; Self.BatteryProperties.FInstallDate := 0; Self.BatteryProperties.FLastErrorCode := 0; Self.BatteryProperties.FMaxRechargeTime := 0; Self.BatteryProperties.FName := STR_EMPTY; Self.BatteryProperties.FPNPDeviceID := STR_EMPTY; Self.BatteryProperties.FPowerManagementCapabilitiesCount := 0; Self.BatteryProperties.FPowerManagementCapabilitiesAsString := STR_EMPTY; SetLength(Self.BatteryProperties.FPowerManagementCapabilities,0); Self.BatteryProperties.FPowerManagementSupported := False; Self.BatteryProperties.FSmartBatteryVersion := STR_EMPTY; Self.BatteryProperties.FStatus := STR_EMPTY; Self.BatteryProperties.FStatusInfo := 0; Self.BatteryProperties.FSystemCreationClassName := STR_EMPTY; Self.BatteryProperties.FSystemName := STR_EMPTY; Self.BatteryProperties.FTimeOnBattery := 0; Self.BatteryProperties.FTimeToFullCharge := 0; end; //: Constructor del componente constructor TBatteryInfo.Create(AOwner: TComponent); begin inherited; Self.FBatteryProperties := TBatteryProperties.Create(); Self.MSDNHelp := 'http://msdn.microsoft.com/en-us/library//aa394074(VS.85).aspx'; end; // destructor del componente destructor TBatteryInfo.Destroy(); begin // liberar FreeAndNil(Self.FBatteryProperties); inherited; end; // Obtener la clase function TBatteryInfo.GetWMIClass(): string; begin Result := WIN32_BATTERY_CLASS; end; // Obtener Root function TBatteryInfo.GetWMIRoot(): string; begin Result := STR_CIM2_ROOT; end; // Active procedure TBatteryInfo.SetActive(const Value: Boolean); begin // método heredado inherited; end; // Acceso a los elementos de la propiedad <PowerManagementCapabilities> function TBatteryProperties.GetPowerManagementCapabilities(index: integer):Integer; begin if (index >= Self.FPowerManagementCapabilitiesCount) then begin Index := Self.FPowerManagementCapabilitiesCount - 1; end; Result := Self.FPowerManagementCapabilities[index]; end; //: Rellenar las propiedades del componente. procedure TBatteryInfo.FillProperties(AIndex: integer); var v:variant; vNull:boolean; vp:TBatteryProperties; begin // Llamar al heredado (importante) inherited; // Rellenar propiedades... vp := Self.BatteryProperties; GetWMIPropertyValue(Self, 'Availability', v, vNull); vp.FAvailability := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'BatteryRechargeTime', v, vNull); vp.FBatteryRechargeTime := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'BatteryStatus', v, vNull); vp.FBatteryStatus := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'Caption', v, vNull); vp.FCaption := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Chemistry', v, vNull); vp.FChemistry := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'ConfigManagerErrorCode', v, vNull); vp.FConfigManagerErrorCode := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'ConfigManagerUserConfig', v, vNull); vp.FConfigManagerUserConfig := VariantBooleanValue(v, vNull); GetWMIPropertyValue(Self, 'CreationClassName', v, vNull); vp.FCreationClassName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Description', v, vNull); vp.FDescription := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'DesignCapacity', v, vNull); vp.FDesignCapacity := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'DesignVoltage', v, vNull); vp.FDesignVoltage := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'DeviceID', v, vNull); vp.FDeviceID := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'ErrorCleared', v, vNull); vp.FErrorCleared := VariantBooleanValue(v, vNull); GetWMIPropertyValue(Self, 'ErrorDescription', v, vNull); vp.FErrorDescription := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'EstimatedChargeRemaining', v, vNull); vp.FEstimatedChargeRemaining := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'EstimatedRunTime', v, vNull); vp.FEstimatedRunTime := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'ExpectedBatteryLife', v, vNull); vp.FExpectedBatteryLife := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'ExpectedLife', v, vNull); vp.FExpectedLife := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'FullChargeCapacity', v, vNull); vp.FFullChargeCapacity := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'InstallDate', v, vNull); if not vNull then begin vp.FInstallDate := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2))); end; GetWMIPropertyValue(Self, 'LastErrorCode', v, vNull); vp.FLastErrorCode := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'MaxRechargeTime', v, vNull); vp.FMaxRechargeTime := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'Name', v, vNull); vp.FName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'PNPDeviceID', v, vNull); vp.FPNPDeviceID := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'PowerManagementCapabilities', v, vNull); vp.FPowerManagementCapabilitiesAsString := VariantStrValue(v, vNull); // vp.FPowerManagementCapabilities := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'PowerManagementSupported', v, vNull); vp.FPowerManagementSupported := VariantBooleanValue(v, vNull); GetWMIPropertyValue(Self, 'SmartBatteryVersion', v, vNull); vp.FSmartBatteryVersion := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Status', v, vNull); vp.FStatus := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'StatusInfo', v, vNull); vp.FStatusInfo := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'SystemCreationClassName', v, vNull); vp.FSystemCreationClassName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'SystemName', v, vNull); vp.FSystemName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'TimeOnBattery', v, vNull); vp.FTimeOnBattery := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'TimeToFullCharge', v, vNull); vp.FTimeToFullCharge := VariantIntegerValue(v, vNull); end; // Obtener la propiedad como string function TBatteryProperties.GetAvailabilityAsString():string; begin case FAvailability of 1: Result := ENUM_STRING_AVAILABILITY_1; 2: Result := ENUM_STRING_AVAILABILITY_2; 3: Result := ENUM_STRING_AVAILABILITY_3; 4: Result := ENUM_STRING_AVAILABILITY_4; 5: Result := ENUM_STRING_AVAILABILITY_5; 6: Result := ENUM_STRING_AVAILABILITY_6; 7: Result := ENUM_STRING_AVAILABILITY_7; 8: Result := ENUM_STRING_AVAILABILITY_8; 9: Result := ENUM_STRING_AVAILABILITY_9; 10: Result := ENUM_STRING_AVAILABILITY_10; 11: Result := ENUM_STRING_AVAILABILITY_11; 12: Result := ENUM_STRING_AVAILABILITY_12; 13: Result := ENUM_STRING_AVAILABILITY_13; 14: Result := ENUM_STRING_AVAILABILITY_14; 15: Result := ENUM_STRING_AVAILABILITY_15; 16: Result := ENUM_STRING_AVAILABILITY_16; 17: Result := ENUM_STRING_AVAILABILITY_17; else Result := STR_EMPTY; end; end; // Obtener la propiedad como string function TBatteryProperties.GetBatteryStatusAsString():string; begin case FBatteryStatus of 1: Result := ENUM_STRING_BATTERYSTATUS_1; 2: Result := ENUM_STRING_BATTERYSTATUS_2; 3: Result := ENUM_STRING_BATTERYSTATUS_3; 4: Result := ENUM_STRING_BATTERYSTATUS_4; 5: Result := ENUM_STRING_BATTERYSTATUS_5; 6: Result := ENUM_STRING_BATTERYSTATUS_6; 7: Result := ENUM_STRING_BATTERYSTATUS_7; 8: Result := ENUM_STRING_BATTERYSTATUS_8; 9: Result := ENUM_STRING_BATTERYSTATUS_9; 10: Result := ENUM_STRING_BATTERYSTATUS_10; 11: Result := ENUM_STRING_BATTERYSTATUS_11; else Result := STR_EMPTY; end; end; // Obtener la propiedad como string function TBatteryProperties.GetChemistryAsString():string; begin case FChemistry of 1: Result := ENUM_STRING_CHEMISTRY_1; 2: Result := ENUM_STRING_CHEMISTRY_2; 3: Result := ENUM_STRING_CHEMISTRY_3; 4: Result := ENUM_STRING_CHEMISTRY_4; 5: Result := ENUM_STRING_CHEMISTRY_5; 6: Result := ENUM_STRING_CHEMISTRY_6; 7: Result := ENUM_STRING_CHEMISTRY_7; 8: Result := ENUM_STRING_CHEMISTRY_8; else Result := STR_EMPTY; end; end; // Obtener la propiedad como string function TBatteryProperties.GetConfigManagerErrorCodeAsString():string; begin case FConfigManagerErrorCode of 0: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_0; 1: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_1; 2: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_2; 3: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_3; 4: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_4; 5: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_5; 6: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_6; 7: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_7; 8: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_8; 9: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_9; 10: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_10; 11: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_11; 12: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_12; 13: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_13; 14: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_14; 15: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_15; 16: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_16; 17: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_17; 18: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_18; 19: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_19; 20: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_20; 21: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_21; 22: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_22; 23: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_23; 24: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_24; 25: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_25; 26: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_26; 27: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_27; 28: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_28; 29: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_29; 30: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_30; 31: Result := ENUM_STRING_CONFIGMANAGERERRORCODE_31; else Result := STR_EMPTY; end; end; // Obtener la propiedad como string function TBatteryProperties.GetStatusInfoAsString():string; begin case FStatusInfo of 1: Result := ENUM_STRING_STATUSINFO_1; 2: Result := ENUM_STRING_STATUSINFO_2; 3: Result := ENUM_STRING_STATUSINFO_3; 4: Result := ENUM_STRING_STATUSINFO_4; 5: Result := ENUM_STRING_STATUSINFO_5; else Result := STR_EMPTY; end; end; end.
(* Jarrett Yap 97045843 Computer Science 1 Semester 1 1997 Assignment 3 Sales Report *) program SalesFileReader; uses Crt, Printer; const TopTitle = ' MULTI-DISK COMPUTER COMPANY'; Title2 = ' SALES REPORT'; TitleLineOne = 'SALESPERSON SALESPERSON PRODUCT QTY PRICE EXTENSION'; TitleLineTwo = 'NUMBER NAME CODE SOLD AMOUNT'; TotalFor = ' TOTAL FOR'; TotalForReport = ' TOTAL FOR REPORT '; FileName = 'saledata.dat'; { This is the name of the data file. } Type EmployeeID = 1000 .. 9999; ProductCode = 1000 .. 9999; SalesRecord = Record SalespersonNo : EmployeeID; SalespersonName : String [11]; ProductNo : ProductCode; QuantitySold : Integer; UnitPrice : Real; End {SalesRecord}; var Sale: SalesRecord; CurrentNo, PrevNo: integer; { These integers determine whether to calculate the subtotal for each salesperson } PrevName: string; { Used to store the last salesperson's name } SalesTotal, SubTotal: Real; { Used to calculate the total sales } SalesFile: file of SalesRecord; { File variable for the salesfile } Day, Month, Year: shortint; { Store the date typed in by user } Extension: Real; { Stores Price * units sold for each sale } procedure Setup; { This procedure clears the screen, opens the data file for reading, and prompts the user for the date. It also writes the headings of the sales report to the screen. } begin ClrScr; SalesTotal:= 0; SubTotal:= 0; Assign(SalesFile, FileName); Reset(SalesFile); Write('Date: '); Readln(Day, Month, Year); ClrScr; Writeln(Lst, TopTitle); Write(Lst, Day,'/', Month,'/', Year); Writeln(Lst, Title2); Writeln(Lst); Writeln(Lst, TitleLineOne); Writeln(Lst, TitleLineTwo); Writeln(Lst); end; procedure ReadFromFile; begin Read(SalesFile, Sale); end; procedure PrintDetails; { Send sales details to printer } begin Write(Lst,Sale.SalesPersonNo, ' '); Write(Lst,Sale.SalesPersonName, ' ' ); Write(Lst,Sale.ProductNo,' '); Write(Lst,Sale.QuantitySold:2,' '); Write(Lst,Sale.UnitPrice:6:2,' '); Writeln(Lst, Extension:8:2); end; procedure DoTheMaths; { Calculates the extension and sales amount } begin Extension:= Sale.QuantitySold * Sale.UnitPrice; SubTotal:= SubTotal + Extension; end; procedure WriteSubTotal; { Prints the subtotal for each sales person } begin Writeln(Lst); Write(Lst,TotalFor); Write(Lst,PrevName,' '); Writeln(Lst, SubTotal:10:2); Writeln(Lst); end; procedure CleanUp; { Close data file } begin Close(SalesFile); end; begin Setup; ReadFromFile; PrevNo:= Sale.SalesPersonNo; CurrentNo:= Sale.SalesPersonNo; PrevName:= Sale.SalesPersonName; While not Eof(SalesFile) do begin ReadFromFile; CurrentNo:= Sale.SalesPersonNo; If PrevNo <> CurrentNo then begin WriteSubTotal; SalesTotal:= SalesTotal + SubTotal; SubTotal:= 0; PrevNo:= CurrentNo; PrevName:= Sale.SalesPersonName; end; DoTheMaths; PrintDetails; end; { WHILE } WriteSubTotal; SalesTotal:= SalesTotal + SubTotal; Write(Lst, TotalForReport,' ', SalesTotal:10:2); CleanUp; end.
unit Netlist; interface uses SysUtils, Classes; type EneError = class(Exception); TneNode = class; TneComponent = class; TnePin = class private FName : string; FNode : TneNode; FComponent : TneComponent; public property Name : string read FName write FName; property Component : TneComponent read FComponent write FComponent; property Node : TneNode read FNode write FNode; end; TneNode = class private FName : string; FPins : TList; function GetPinCount : integer; function GetPin( index : integer ) : TnePin; public property Name : string read FName write FName; property PinCount : integer read GetPinCount; property Pins[index : integer] : TnePin read GetPin; procedure Sort; constructor Create; destructor Destroy; override; end; TneComponent = class private FName : string; FPins : TList; function GetPinCount : integer; function GetPin( index : integer ) : TnePin; public property Name : string read FName write FName; property PinCount : integer read GetPinCount; property Pins[index : integer] : TnePin read GetPin; procedure SortNodes; procedure SortPinNos; constructor Create; destructor Destroy; override; end; type TneNetList = class private FNodes : TList; FComponents : TList ; // property handlers function GetNodeCount : integer; function GetNode( index : integer ) : TneNode; function GetComponentCount : integer; function GetComponent( index : integer ) : TneComponent; // internal functions function EquivalentNode( SourceNode : TneNode ) : TneNode; public const ColoredNodeCount = 6; var ColoredNodes : array[0..ColoredNodeCount-1] of TneNode; property NodeCount : integer read GetNodeCount; property Nodes[index : integer] : TneNode read GetNode; property ComponentCount : integer read GetComponentCount; property Components[index : integer] : TneComponent read GetComponent; // property PinCount : integer read GetPinCount; // property Pins[index : integer] : TnePin read GetPin; function CreateNode : TneNode; function CreateComponent : TneComponent; function CreatePin( Node : TneNode; Component : TneComponent; const PinName : string ) : TnePin; procedure DeleteNode( value : TneNode ); procedure DeleteComponent( value : TneComponent ); procedure DeletePin( value : TnePin ); function ComponentByName( const Name : string ) : TneComponent; function NodeByName( const Name : string ) : TneNode; procedure Clear; procedure SortNodes; procedure SortComponentsByNode; procedure SortComponentsByPinNo; function Validate( report : TStrings ) : boolean; procedure GetEquivalentColoredNets( SourceNetlist : TneNetlist ); procedure Clone( Source : TneNetlist ); constructor Create; destructor Destroy; override; end; implementation uses SortCompare, Windows; (* A Netlist contains 1. Array of Components[] - each component representing a part on schematic. 2. Array of Nodes[] - each node being a circuit "Net". 3. Array of Pins[] - each pin connecting a component and a node. We add a component with CreateComponent We add a node with CreateNode We add a pin with CreatePin : the pin connects a node to a component and both the node and the component must exist when CreatePin called To remove a component, node or pin, call its destructor via .Free . NO** TneComponent.Free causes any pins connecting the component to be destroyed. YES** TneNode.Free causes any pins connecting the node to be destroyed. NO** TnePin.Free causes the pins to be removed the from Component and Node Pins[] arrays. Locate a Component or Node by name with ComponentByName and NodeByName. *) // ***************************************** // TnePin CLASS // ***************************************** // ***************************************** // TneNode CLASS // ***************************************** function TneNode.GetPinCount : integer; begin result := FPins.Count; end; function TneNode.GetPin( index : integer ) : TnePin; begin result := TnePin( FPins[index] ); end; function NodeComparePinNames( const Name1, Name2 : string ) : integer; begin result := AnsiCompareText( Name1, Name2 ); end; function NodePinCompare( P1, P2 : pointer ) : integer; begin // compare two pins //.. firstly on component name result := CompareDesignators( TnePin(P1).Component.Name, TnePin(P2).Component.Name ); //.. if names match, compare by pin number if result = 0 then begin // result := AnsiCompareText( TnePin(P1).Name, TnePin(P2).Name ); result := NodeComparePinNames( TnePin(P1).Name, TnePin(P2).Name ); end; end; // sort the pins attached to this node, firstly by the component name belonging // to the pin, then by pin number. procedure TneNode.Sort; begin FPins.Sort( NodePinCompare ); end; constructor TneNode.Create; begin FPins := TList.Create; end; destructor TneNode.Destroy; begin FPins.Free; inherited; end; // ***************************************** // TneComponent CLASS // ***************************************** function TneComponent.GetPinCount : integer; begin result := FPins.Count; end; function TneComponent.GetPin( index : integer ) : TnePin; begin result := TnePin( FPins[index] ); end; function ComponentNodeCompare( P1, P2 : pointer ) : integer; begin // compare two pins //.. firstly on node name result := CompareDesignators( TnePin(P1).Node.Name, TnePin(P2).Node.Name ); // if names match, compare by pin name if result = 0 then begin result := AnsiCompareText( TnePin(P1).Name, TnePin(P2).Name ); end; end; function ComponentPinNoCompare( P1, P2 : pointer ) : integer; begin // compare by pin name result := AnsiCompareText( TnePin(P1).Name, TnePin(P2).Name ); end; procedure TneComponent.SortNodes; begin FPins.Sort( ComponentNodeCompare ); end; procedure TneComponent.SortPinNos; begin FPins.Sort( ComponentPinNoCompare ); end; constructor TneComponent.Create; begin FPins := TList.Create; end; destructor TneComponent.Destroy; var i : integer; begin for i := FPins.Count -1 downto 0 do begin TnePin( FPins[i] ).Free; end; FPins.Free; inherited; end; // ***************************************** // TneNetlist CLASS // ***************************************** function TneNetList.GetNodeCount : integer; begin result := FNodes.Count; end; function TneNetList.GetNode( index : integer ) : TneNode; begin result := TneNode(FNodes[index]); end; function TneNetList.GetComponentCount : integer; begin result := FComponents.Count; end; function TneNetList.GetComponent( index : integer ) : TneComponent; begin result := TneComponent(FComponents[index]); end; function TneNetList.CreateNode : TneNode; begin result := TneNode.Create; FNodes.Add( result) ; end; function TneNetList.CreateComponent : TneComponent; begin result := TneComponent.Create; FComponents.Add( result ); end; function TneNetList.CreatePin( Node : TneNode; Component : TneComponent; const PinName : string ) : TnePin; begin // check that node and component exist if (FNodes.IndexOf( Node ) < 0) then begin raise EneError.Create( 'Unknown node' ); end; if (FComponents.IndexOf( Component ) < 0) then begin raise EneError.Create( 'Unknown component' ); end; result := TnePin.Create; result.Node := Node; result.Component := Component; result.FName := PinName; Node.FPins.Add( result ); Component.FPins.Add( result ); end; procedure TneNetList.DeleteNode( value : TneNode ); begin end; procedure TneNetList.DeleteComponent( value : TneComponent ); begin end; procedure TneNetList.DeletePin( value : TnePin ); begin end; function TneNetList.ComponentByName( const Name : string ) : TneComponent; var i : integer; Component : TneComponent; begin for i := 0 to FComponents.Count -1 do begin Component := TneComponent(FComponents[i]); if CompareText( Component.Name, Name) = 0 then begin result := Component; exit; end; end; result := nil; end; function TneNetList.NodeByname( const Name : string ) : TneNode; var i : integer; Node : TneNode; begin for i := 0 to FNodes.Count -1 do begin Node := TneNode(FNodes[i]); if Node.Name = Name then begin result := Node; exit; end; end; result := nil; end; // ** COMPARISON FUNCTIONS FOR SORT OF NODES, COMPONENTS ** function NodeCompare( P1, P2 : pointer ) : integer; begin result := AnsiCompareText( (TneNode(P1)).Name, (TneNode(P2)).Name ); end; function ComponentCompare( P1, P2 : pointer ) : integer; begin // result := AnsiCompareText( (TneComponent(P1)).Name, (TneComponent(P2)).Name ); result := CompareDesignators( (TneComponent(P1)).Name, (TneComponent(P2)).Name ); end; // Sort nodes so node names are in text order // Each Node must sort pins by Component name, then by pin number procedure TneNetList.SortNodes; var i : integer; begin // Sort Nodes by Name FNodes.Sort( NodeCompare ); // Each Node must sort pins by Component name, then by pin number for i := 0 to NodeCount -1 do begin Nodes[i].Sort; end; end; // Sort components so they are in component name order. // Within each component, sort its pins by node name, pin number. procedure TneNetList.SortComponentsByNode; var i : integer; begin FComponents.Sort( ComponentCompare ); // Each component must sort pins by Node name, pin number for i := 0 to ComponentCount -1 do begin Components[i].SortNodes; end; end; procedure TneNetList.SortComponentsByPinNo; var i : integer; begin FComponents.Sort( ComponentCompare ); // Each component must sort pins by pin number for i := 0 to ComponentCount -1 do begin Components[i].SortPinNos; end; end; procedure TneNetList.Clear; var i : integer; begin for i := 0 to ColoredNodeCount -1 do begin ColoredNodes[i] := nil; end; for i := FComponents.Count -1 downto 0 do begin TneComponent( FComponents[i] ).Free; end; FComponents.Clear; for i := FNodes.Count -1 downto 0 do begin TneNode( FNodes[i] ).Free; end; FNodes.Clear; end; // ****************************** // TEST NETLIST VALIDITY // ****************************** (* Call with report = reference to TStrings object which will receive lines of the report. Set report = nil if no report required. Returns True = Netlist valid, no lines added to report. False = Netlist not valid, if report not nil, lines added to report. *) function TneNetList.Validate( report : TStrings ) : boolean; procedure LineOut( s : string ); begin if Assigned( report ) then begin report.Add( s ); end; result := False; end; var i : integer; Node : TneNode; LastNodeName : string; Component : TneComponent; LastComponentName : string; j : integer; Pin : TnePin; LastPin : TnePin; begin // assume will pass tests : any failure detected will change result := True; // * Check that no two nodes have same name * // get nodes in .name order SortNodes; for i := 0 to NodeCount -1 do begin Node := Nodes[i]; // node must have a name if Node.Name = '' then begin LineOut( 'Unnamed node' ); continue; end; // node name must not be same as node before if LastNodeName = Node.Name then begin LineOut( 'Duplicate net Name : "' + LastNodeName + '"' ); end; // keep old nodename ready for next node check LastNodeName := Node.Name; end; // * Warn of Nodes with only one pin * for i := 0 to NodeCount -1 do begin Node := Nodes[i]; if Node.PinCount =1 then begin LineOut( 'Node has only one pin : "' + Node.Name + '"' ); end else if Node.PinCount = 0 then begin LineOut( 'Node has no pins : "' + Node.Name + '"' ); end; end; // * Check that no two components have same name * // get components in .Name order (also by PinNo order within components : // this order is used by test following this one) SortComponentsByPinNo; for i := 0 to ComponentCount -1 do begin Component := Components[i]; // component must have a name if Component.Name = '' then begin LineOut( 'Unnamed component' ); continue; end; // component name must not be same as component before if LastComponentName = Component.Name then begin LineOut( 'Duplicate component Name : "' + LastComponentName + '"' ); end; // keep old component name ready for next component check LastComponentName := Component.Name; end; // * Check that component pin does not appear in more than one node * for i := 0 to ComponentCount -1 do begin Component := Components[i]; // invald pin number will never match a actual pin no LastPin := nil; for j := 0 to Component.PinCount -1 do begin Pin := Component.Pins[j]; // Pin if Pin.Name = '' then begin LineOut( Format( 'Component %s has empty pin name', [Component.Name] ) ); continue; end; // If a pin name in array equals last pin name in array // of pins for this component, then we have 2 pins with same name // which is an error in the netlist. if (LastPin <> nil) and (LastPin.Name = Pin.Name) then begin LineOut( Format( 'Component %s has duplicate Pin "%s" in nets %s and %s', [Component.Name, LastPin.Name, LastPin.Node.Name, Pin.Node.Name] ) ); end; LastPin := Pin; end; end; end; constructor TneNetList.Create; begin FNodes := TList.Create; FComponents := TList.Create; end; destructor TneNetList.Destroy; var i : integer; begin if assigned( FComponents ) then begin for i := FComponents.Count -1 downto 0 do begin TneComponent( FComponents[i] ).Free; end; FComponents.Free; end; if assigned( FNodes ) then begin for i := FNodes.Count -1 downto 0 do begin TneNode( FNodes[i] ).Free; end; FNodes.Free; end; inherited; end; // ** MAKE THIS NETLIST A COPY OF THE SOURCE NETLIST ** procedure TneNetList.Clone( Source : TneNetlist ); var // record equivalent source nodes SourceNodes : array[0..ColoredNodeCount -1] of TneNode; i : integer; SourceComponent, LocalComponent : TneComponent; SourceNode, LocalNode : TneNode; j : integer; SourcePin {, LocalPin} : TnePin; SourcePinNode, LocalPinNode : TneNode; SourceNodeColoredNode : TneNode; SourceNodeName : string; begin // Clear everything - nodes, components, pins Clear; // create new Nodes to match SourceNetlist for i := 0 to Source.NodeCount - 1 do begin SourceNode := Source.Nodes[i]; LocalNode := CreateNode; LocalNode.FName := SourceNode.Name; // if source node is tagged as colored, then set the local copy to colored for j := 0 to ColoredNodeCount - 1 do begin if SourceNodes[j] = SourceNode then begin // store this node in array of nodes that are colored ColoredNodes[j] := SourceNode; end; end; end; // create new Components to match SourceNetlist for i := 0 to Source.ComponentCount - 1 do begin SourceComponent := Source.Components[i]; LocalComponent := CreateComponent; LocalComponent.FName := SourceComponent.FName; // put component pins for j := 0 to SourceComponent.PinCount - 1 do begin SourcePin := SourceComponent.Pins[j]; SourcePinNode := SourcePin.FNode; LocalPinNode := NodeByName( SourcePinNode.Name ); if LocalPinNode = nil then begin raise EneError.Create( 'Missing node in net duplication' ); end; // LocalPin := CreatePin( LocalPinNode, LocalComponent, SourcePin.Name ); CreatePin( LocalPinNode, LocalComponent, SourcePin.Name ); end; end; // copy the colored node list for i := 0 to ColoredNodeCount - 1 do begin SourceNodeColoredNode := Source.ColoredNodes[i]; if SourceNodeColoredNode = nil then begin ColoredNodes[i] := nil; end else begin SourceNodeName := SourceNodeColoredNode.Name; ColoredNodes[i] := NodeByName( SourceNodeName ); end; end; end; // ** EVALUATE EQUIVALENCE OF TWO NODES ** // return the number of matching component pins. 0=no matches, etc function RateNodeMatch( Node1, Node2 : TneNode ) : integer; var Component1, Component2 : TneComponent; Node1PinIndex, Node2PinIndex : integer; Node1PinCount, Node2PinCount : integer; DesignatorCompare : integer; PinCompare : integer; begin // will count number of component pin matches between the two nodes result := 0; // each node sorted by 1.Component Name, then by 2. Pin Name (number) Node1.Sort; Node2.Sort; Node1PinIndex := 0; Node2PinIndex := 0; Node1PinCount := Node1.PinCount; Node2PinCount := Node2.PinCount; // step through pins of Node 1 while (Node1PinIndex < Node1PinCount) and (Node2PinIndex < Node2PinCount) do begin Component1 := Node1.Pins[Node1PinIndex].Component; Component2 := Node2.Pins[Node2PinIndex].Component; // *** move components in sync DesignatorCompare := CompareDesignators( Component1.Name, Component2.Name ); // if Node1 is on an earlier component than Node2, then move Node1 ahead if DesignatorCompare < 0 then begin Inc( Node1PinIndex ); end // if Node2 is on an earlier component than Node1, then move Node2 ahead else if DesignatorCompare > 0 then begin Inc( Node2PinIndex ); end // we are on the same component, so count the number of pins that match else begin PinCompare := NodeComparePinNames( Node1.Pins[Node1PinIndex].Name, Node2.Pins[Node2PinIndex].Name ); // if Node 1 is on earlier pin name than Node2, then move Node 1 ahead if PinCompare < 0 then begin Inc( Node1PinIndex ); end // if Node 2 is on earlier pin name than Node1, then move Node 2 ahead else if PinCompare > 0 then begin Inc( Node2PinIndex ); end // if names match, count that and move to next pins in both lists else begin inc( result ); inc( Node1PinIndex ); inc( Node2PinIndex ); end end; end; end; // ** FIND EQUIVALENT NODE ** // Look through local nodes to find the one that best matches SourceNode // Return reference to the local node. function TneNetList.EquivalentNode( SourceNode : TneNode ) : TneNode; var i : integer; Node : TneNode; NodeRating : integer; BestNode : TneNode; BestNodeRating : integer; begin // can't match empty node if SourceNode = nil then begin result := nil; exit; end; // stop uninitialised variable compiler warning BestNode := nil; // look for node with maximum number of pin matches with Source Node //.. impossibly low rating BestNodeRating := Low(BestNodeRating); // for each local node for i := 0 to NodeCount -1 do begin Node := Nodes[i]; // see how well that node matches the SourceNode NodeRating := RateNodeMatch( SourceNode, Node ); if (NodeRating > 0) and (NodeRating > BestNodeRating) then begin BestNode := Node; BestNodeRating := NodeRating; end; end; // return result if BestNodeRating > 0 then begin result := BestNode; end else begin result := nil; end; end; // ** Identify Colored Nets by Finding Nets Equivalent to Colored nets in a // ** source netlist. procedure TneNetList.GetEquivalentColoredNets( SourceNetlist : TneNetlist ); var i : integer; SourceNode : TneNode; begin // find equivalent nodes in Source to match This.ColoredNodes[] array members // This is necessary because schematic editors can change node names // from one export of a netlist to the next. for i := 0 to ColoredNodeCount - 1 do begin SourceNode := SourceNetlist.ColoredNodes[i]; ColoredNodes[i] := EquivalentNode( SourceNode ); end; end; end.
PROGRAM Lotto; PROCEDURE PrintHelp; CONST PROG_NAME = 'Lotto'; BEGIN WriteLn(PROG_NAME); END; FUNCTION Factorial(n: INTEGER): REAL; VAR i: INTEGER; VAR calc_result: REAL; BEGIN calc_result := 1; FOR i := 2 TO n DO BEGIN calc_result := calc_result * i; END; Factorial := calc_result; END; FUNCTION BinomialCoefficient(drawed_numbers, total_numbers: INTEGER): REAL; BEGIN // (m! / (n! * (m-n)!)) // n! = 1 * 2 * 3 * 4 * ... * n // 0! = 1 BinomialCoefficient := (Factorial(total_numbers) / (Factorial(drawed_numbers) * Factorial((total_numbers - drawed_numbers)))); END; BEGIN WriteLn('Lotto 6 aus 45(A): ', BinomialCoefficient(6, 45):7:0); WriteLn('Lotto 6 aus 49(D): ', BinomialCoefficient(6, 49):7:0); WriteLn('Lotto 6 aus 90(I): ', BinomialCoefficient(6, 90):7:0); END.
unit EspecificacaoSangriaReforcoPorCodigoCaixa; interface uses Especificacao, Dialogs; type TEspecificacaoSangriaReforcoPorCodigoCaixa = class(TEspecificacao) private FCodigoCaixa :integer; public constructor Create(codigoCaixa :integer); public function SatisfeitoPor(Objeto :TObject): Boolean; override; end; implementation uses SangriaReforco; { TEspecificacaoSangriaReforcoPorCodigoCaixa } constructor TEspecificacaoSangriaReforcoPorCodigoCaixa.Create(codigoCaixa: integer); begin self.FCodigoCaixa := codigoCaixa; end; function TEspecificacaoSangriaReforcoPorCodigoCaixa.SatisfeitoPor(Objeto: TObject): Boolean; begin result := TSangriaReforco(Objeto).codigo_caixa = self.FCodigoCaixa; end; end.
unit Project87.Asteroid; interface uses QEngine.Camera, QEngine.Texture, QGame.Scene, Strope.Math, Project87.Fluid, Project87.Types.GameObject; const MAX_RESOURCES = 100; FLUID_POSITION_SCALE = 2; type TScannedResources = record Position: array [0..MAX_RESOURCES - 1] of TVectorF; Generated: Boolean; end; TAsteroid = class (TPhysicalObject) class var FResources: TScannedResources; private FMarkerPosition: TVectorF; FFluids: Word; FMaxFluids: Word; FType: TFluidType; FShowFluids: Single; FAsteroidTexture: Byte; procedure GenerateScannedResources; procedure ShowFluidsInAsteroid; public constructor CreateAsteroid(const APosition: TVector2F; AAngle, ARadius: Single; AType: TFluidType; ATexture: Byte = 0); procedure OnDraw; override; procedure OnUpdate(const ADelta: Double); override; procedure Scan; procedure Hit(AAngle: Single; ANumber: Integer); property MaxFluids: Word read FMaxFluids; property Fluids: Word read FFluids write FFluids; property FluidType: TFluidType read FType; end; implementation uses SysUtils, QEngine.Core, QApplication.Application, Project87.Hero, Project87.Resources; {$REGION ' TAsteroid '} constructor TAsteroid.CreateAsteroid(const APosition: TVector2F; AAngle, ARadius: Single; AType: TFluidType; ATexture: Byte = 0); begin inherited Create; if not FResources.Generated then GenerateScannedResources; FPosition := APosition; FAngle := AAngle; FRadius := ARadius; FUseCollistion := True; FType := AType; FMass := 10; FAsteroidTexture := ATexture; FMaxFluids := Trunc(ARadius / FLUID_POSITION_SCALE); end; procedure TAsteroid.GenerateScannedResources; var I: Word; begin FResources.Generated := True; for I := 0 to MAX_RESOURCES - 1 do FResources.Position[I] := GetRotatedVector(Random(360), I * FLUID_POSITION_SCALE); end; procedure TAsteroid.OnDraw; var ScreenSize: TVectorF; NeedDrawMarker: Boolean; begin TheResources.AsteroidTexture[FAsteroidTexture].Draw(FPosition, Vec2F(FRadius, FRadius) * 2, FAngle, $FFFFFFFF); //TODO - map markers { FMarkerPosition := TheEngine.Camera.GetScreenPos(FPosition, false); ScreenSize := TheEngine.Camera.Resolution; FMarkerPosition := (FPosition - TheEngine.Camera.Position); if FMarkerPosition.LengthSqr < RADAR_DISTANCE * RADAR_DISTANCE then begin NeedDrawMarker := False; if Abs(FMarkerPosition.X) - ScreenSize.X * 0.5 > 0 then begin FMarkerPosition := FMarkerPosition * (ScreenSize.X * 0.5 / Abs(FMarkerPosition.X)); NeedDrawMarker := True; end; if Abs(FMarkerPosition.Y) - ScreenSize.Y * 0.5 > 0 then begin FMarkerPosition := FMarkerPosition * (ScreenSize.Y * 0.5 / Abs(FMarkerPosition.Y)); NeedDrawMarker := True; end; if NeedDrawMarker then begin FMarkerPosition := FMarkerPosition + TheEngine.Camera.Position; TheResources.AsteroidTexture.Draw(FMarkerPosition, Vec2F(10, 10), 0, $FFFFFFFF); end; end; } ShowFluidsInAsteroid; end; procedure TAsteroid.OnUpdate(const ADelta: Double); begin if (FShowFluids > 0) then begin FShowFluids := FShowFluids - ADelta; if (FShowFluids < 0) then FShowFluids := 0; end; end; procedure TAsteroid.Scan; begin FShowFluids := FShowFluids + 0.1; if (FShowFluids > 1) then FShowFluids := 1; end; procedure TAsteroid.Hit(AAngle: Single; ANumber: Integer); var I: Integer; begin if FFluids = 0 then Exit; if (FFluids < ANumber) then ANumber := FFluids; FFluids := FFluids - ANumber; for I := 1 to ANumber do TFluid.CreateFluid( FPosition + GetRotatedVector(AAngle, FRadius), GetRotatedVector(AAngle + Random(10) - 5, Random(200) + 50), FType); end; procedure TAsteroid.ShowFluidsInAsteroid; var Alpha, I: Word; Color: Cardinal; begin if (FShowFluids > 0) and (FFluids > 0) then begin Alpha := Trunc(FShowFluids * $120); if Alpha > $FF then Alpha := $FF; case FType of fYellow: Color := $FFFF00; fBlue: Color := $00FF00; fRed: Color := $FF0000; fGreen: Color := $0000FF; else Color := $0000FF; end; for I := 0 to FFluids - 1 do TheResources.FluidTexture.Draw( FPosition + FResources.Position[I], Vec2F(8, 8), 0, Alpha * $1000000 + Color); end; end; {$ENDREGION} end.
unit ImportMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Scanner, Menus, StdCtrls, ExtCtrls,contnrs, ComCtrls, LXScanner; type TDataField = class private FdataType: string; Fcaption: string; FName: string; public property name : string read FName; property caption : string read Fcaption; property dataType : string read FdataType; end; TDataFields = class(TObjectList) private function getItems(index: integer): TDataField; public property items[index:integer] : TDataField read getItems;default; function add: TDataField; end; TDataTable = class private Fcaption: string; Fname: string; FFields: TDataFields; public property fields : TDataFields read FFields; property name : string read Fname; property caption : string read Fcaption; constructor Create; Destructor Destroy;override; end; TDataTables = class(TObjectList) private function getItems(index: integer): TDataTable; public property items[index:integer] : TDataTable read getItems;default; function add: TDataTable; end; //TTableInfo TfmMain = class(TForm) MainMenu1: TMainMenu; Scanner: TLXScanner; File1: TMenuItem; mnOpen: TMenuItem; N1: TMenuItem; mnExit: TMenuItem; OpenDialog: TOpenDialog; Splitter1: TSplitter; mmText: TRichEdit; mmSumary: TRichEdit; StatusBar1: TStatusBar; procedure mnExitClick(Sender: TObject); procedure mnOpenClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ScannerTokenRead(Sender: TObject; Token: TLXToken; var AddToList, Stop: Boolean); private { Private declarations } Tables : TDataTables; procedure GetReferences(Scanner:TLXScanner; aTables : TDataTables); procedure ViewReferences; public { Public declarations } end; var fmMain: TfmMain; const feedBackCount = 50; implementation uses ProgDlg; {$R *.DFM} { help procedures/functions } function inList(const s: string; const list: array of string): integer; var i : integer; begin result := -1; for i:=low(list) to high(list) do if CompareText(list[i],s)=0 then begin result := i; break; end; end; function isKeyword(token:TLXToken; const keyword:string):boolean; begin result := (token<>nil) and (token.Token=ttKeyword) and (compareText(token.text,keyword)=0); end; function getIdentifier(token:TLXToken):string; begin if (token<>nil) and (token.Token=ttIdentifier) then result := token.text else result := ''; end; function isSymbol(token:TLXToken; symbol:char):boolean; begin result := (token<>nil) and (token.Token=ttSpecialChar) and (token.text=symbol); end; function getString(token:TLXToken; var s:string):boolean; begin result := (token<>nil) and (token.Token=ttString); if result then s:=token.text; end; { TfmMain } procedure TfmMain.FormCreate(Sender: TObject); begin Tables := TDataTables.create; OpenDialog.InitialDir:=ExtractFileDir(Application.ExeName); end; procedure TfmMain.mnExitClick(Sender: TObject); begin Close; end; procedure TfmMain.mnOpenClick(Sender: TObject); var fs : TFileStream; begin if OpenDialog.Execute then begin fs := TFileStream.Create(OpenDialog.fileName,fmOpenRead ); try Caption:=Application.Title+' - '+OpenDialog.fileName; dlgProgress.execute; Scanner.Analyze(fs); if not dlgProgress.canceled then begin Tables.Clear; GetReferences(Scanner,Tables); end; if not dlgProgress.canceled then ViewReferences; fs.Position:=0; mmText.Lines.LoadFromStream(fs); finally fs.free; dlgProgress.close; end; end; end; procedure TfmMain.GetReferences(Scanner:TLXScanner; aTables : TDataTables); var i: integer; token : TLXToken; aname,acaption,adatatype,aformat:string; curTable : TDataTable; curTableName : string; curField : TDataField; function nextToken: TLXToken; begin if (i mod feedBackCount)=0 then begin dlgProgress.ProgressBar.Position:=i; Application.ProcessMessages; if dlgProgress.canceled then abort; end; // filter out comments while i<Scanner.count do begin result := Scanner.Token[i]; inc(i); //outputDebugString(pchar(result.text)); if result.Token<>ttComment then exit; end; result := nil; end; procedure goBackAToken; begin if (i>0) and (token<>nil) then begin dec(i); //outputDebugString(':back'); end; end; begin dlgProgress.lbInfo.Caption:='Read Tokens...'; dlgProgress.ProgressBar.Min:=0; dlgProgress.ProgressBar.max:=Scanner.Count; i:=0; token := nextToken; curTable:=nil; curField:=nil; while token<>nil do begin if isKeyword(token,'add') then begin token := nextToken; if isKeyword(token,'file') then begin token := nextToken; if getString(token,aName) then begin curTable:=aTables.add; curTable.fname:=aName; curField:=nil; end; end else if isKeyword(token,'field') and (curTable<>nil) then begin token := nextToken; if getString(token,aName) then begin token := nextToken; if isKeyword(token,'of') then begin token := nextToken; if getString(token,curTableName) and (CompareText(curTableName,curTable.Name)=0) then begin curField := curTable.fields.add; curField.fname := aName; end; end; end; end; end else if (curField<>nil) then begin if isKeyword(token,'as') then begin token := nextToken; adatatype:=getIdentifier(token); if adatatype<>'' then curField.fdataType:=aDatatype; end else if isKeyword(token,'help') then begin token := nextToken; if getString(token,acaption) then curField.fcaption:=acaption; end else if isKeyword(token,'format') then begin token := nextToken; if getString(token,aformat) and (aformat<>'') then begin aformat:=StringReplace(aformat,'x','%s',[rfIgnoreCase]); curField.FdataType:=format(aformat,[curField.fdataType]); end; end end; token := nextToken; end; end; procedure TfmMain.FormDestroy(Sender: TObject); begin Tables.free; end; procedure TfmMain.ViewReferences; var i,j : integer; curTable : TDataTable; curField : TDataField; begin StatusBar1.SimpleText:='Tables:'+IntToStr(tables.Count); dlgProgress.lbInfo.Caption:='Generate Report...'; dlgProgress.ProgressBar.Min:=0; dlgProgress.ProgressBar.max:=tables.Count; mmSumary.Lines.Clear; for i:=0 to tables.Count-1 do begin dlgProgress.ProgressBar.Position:=i; Application.ProcessMessages; if dlgProgress.canceled then abort; curTable:=tables[i]; mmSumary.Lines.add('========'+ curTable.Name +'========'); mmSumary.Lines.add('+ Fields'); for j:=0 to curTable.fields.Count-1 do begin curField:=curTable.fields[j]; mmSumary.Lines.add('|- '+ curField.caption + ' - ' + curField.Name + ' : '+curField.dataType); end; end; end; { TDataFields } function TDataFields.add: TDataField; begin result := TDataField.Create; inherited add(result); end; function TDataFields.getItems(index: integer): TDataField; begin result := TDataField(inherited items[index]); end; { TDataTable } constructor TDataTable.Create; begin FFields:= TDataFields.create; end; destructor TDataTable.Destroy; begin FreeAndNil(FFields); inherited; end; { TDataTables } function TDataTables.add: TDataTable; begin result := TDataTable.Create; inherited add(result); end; function TDataTables.getItems(index: integer): TDataTable; begin result := TDataTable(inherited items[index]); end; procedure TfmMain.ScannerTokenRead(Sender: TObject; Token: TLXToken; var AddToList, Stop: Boolean); begin if dlgProgress.canceled then stop:=true else begin if ((Scanner.Count mod feedBackCount)=0) and (Token<>nil) then begin dlgProgress.lbInfo.caption := 'Read Line:'+IntToStr(Token.row); Application.ProcessMessages; end; end; end; end.
unit Strope.Math; interface type TInterpolationType = ( itLinear = 0, itHermit01 = 1, itHermit10 = 2, itParabolic01 = 3, itParabolic10 = 4, itSquareRoot01 = 5, itSquareRoot10 = 6 ); TVector2I = packed record public constructor Create(X, Y: Integer); class operator Negative(const AVector: TVector2I): TVector2I; class operator Positive(const AVector: TVector2I): TVector2I; class operator Equal(const A, B: TVector2I): Boolean; class operator NotEqual(const A, B: TVector2I): Boolean; class operator Add(const A, B: TVector2I): TVector2I; class operator Subtract(const A, B: TVector2I): TVector2I; class operator Multiply(const A, B: TVector2I): TVector2I; class operator Multiply(A: Integer; const B: TVector2I): TVector2I; class operator Multiply(const A: TVector2I; B: Integer): TVector2I; function Length(): Single; function LengthSqr(): Single; case Byte of 0: (X, Y: Integer); 1: (Arr: array [0..1] of Integer); end; TVector2F = packed record public constructor Create(X, Y: Single); overload; class operator Implicit(const AVector: TVector2I): TVector2F; class operator Explicit(const AVector: TVector2I): TVector2F; class operator Negative(const AVector: TVector2F): TVector2F; class operator Trunc(const AVector: TVector2F): TVector2I; class operator Round(const AVector: TVector2F): TVector2I; class operator Positive(const AVector: TVector2F): TVector2F; class operator Equal(const A, B: TVector2F): Boolean; class operator NotEqual(const A, B: TVector2F): Boolean; class operator Add(const A, B: TVector2F): TVector2F; class operator Subtract(const A, B: TVector2F): TVector2F; class operator Multiply(const A, B: TVector2F): Single; overload; class operator Multiply(const A: TVector2F; B: Single): TVector2F; overload; class operator Multiply(A: Single; const B: TVector2F): TVector2F; overload; function ComponentwiseMultiply(const AVector: TVector2F): TVector2F; function ComponentwiseDivide(const AVector: TVector2F): TVector2F; function Length(): Single; function LengthSqr(): Single; function Normalize(): TVector2F; function Distance(const AVector: TVector2F): Single; function Clip(ALength: Single): TVector2F; function Angle(const AVector: TVector2F): Single; function InterpolateTo(const AVector: TVector2F; AProgress: Single; AInterpolationType: TInterpolationType = itLinear): TVector2F; case Byte of 0: (X, Y: Single); 1: (U, V: Single); 2: (Arr: array [0..1] of Single); end; TVector2IHelper = record helper for TVector2I public function ComponentwiseMultiply(const AVector: TVector2I): TVector2F; function ComponentwiseDivide(const AVector: TVector2I): TVector2F; function Normalized(): TVector2F; function Angle(const AVector: TVector2F): Single; function InterpolateTo(const AVector: TVector2F; AProgress: Single; AInterpolationType: TInterpolationType = itLinear): TVector2F; end; TVectorI = TVector2I; TVectorF = TVector2F; const ZeroVectorI: TVectorI = (X: 0; Y: 0); ZeroVectorF: TVectorF = (X: 0; Y: 0); function Vec2I(X, Y: Integer): TVector2I; inline; function Vec2F(X, Y: Single): TVector2F; inline; {$REGION ' Clamp Functions '} function Clamp(AValue, AMax, AMin: Integer): Integer; overload; function Clamp(AValue, AMax, AMin: Single): Single; overload; function Clamp(AValue, AMax, AMin: Double): Double; overload; function ClampToMax(AValue, AMax: Integer): Integer; overload; function ClampToMax(AValue, AMax: Single): Single; overload; function ClampToMax(AValue, AMax: Double): Double; overload; function ClampToMin(AValue, AMin: Integer): Integer; overload; function ClampToMin(AValue, AMin: Single): Single; overload; function ClampToMin(AValue, AMin: Double): Double; overload; {$ENDREGION} {$REGION ' Interpolate Functions '} function InterpolateValue(AFrom, ATo, AProgress: Single; AInterpolationType: TInterpolationType = itLinear): Single; function LinearInterpolate(AFrom, ATo, AProgress: Single): Single; function Ermit01Interpolate(AFrom, ATo, AProgress: Single): Single; function Ermit10Interpoalte(AFrom, ATo, AProgress: Single): Single; function Parabolic01Interpolate(AFrom, ATo, AProgress: Single): Single; function Parabolic10Interpolate(AFrom, ATo, AProgress: Single): Single; function SquareRoot01Interpolate(AFrom, ATo, AProgress: Single): Single; function SquareRoot10Interpolate(AFrom, ATo, AProgress: Single): Single; {$ENDREGION} {$REGION ' Angle work Functions '} function RoundAngle(Angle: Single): Single; function GetAngle(A, B: TVector2F): Single; overload; function GetAngle(A: TVector2F): Single; overload; function RotateToAngle(SourceAngle, DestionationAngle, Speed: Single): Single; {$ENDREGION} {$REGION ' TVector2F additional Functions '} function Distance(const A, B: TVector2F): Single; function GetRotatedVector(Angle, Length: Single): TVector2F; function Dot(const A, B: TVector2F): Single; {$ENDREGION} {$REGION ' Collision Functions '} function LineVsCircle( const LineA, LineB, CircleCenter: TVector2F; Radius: Single) : Boolean; function PointInBox( const Point, BoxTopLeft, BoxSize: TVector2F) : Boolean; {$ENDREGION} implementation uses Math; {$REGION ' Clamp Functions '} function Clamp(AValue, AMax, AMin: Integer): Integer; begin Exit(Max(Min(AValue, AMax), AMin)); end; function ClampToMax(AValue, AMax: Integer): Integer; begin Exit(Min(AValue, AMax)); end; function ClampToMin(AValue, AMin: Integer): Integer; begin Exit(Max(AValue, AMin)); end; function Clamp(AValue, AMax, AMin: Single): Single; begin Exit(Max(Min(AValue, AMax), AMin)); end; function ClampToMax(AValue, AMax: Single): Single; begin Exit(Min(AValue, AMax)); end; function ClampToMin(AValue, AMin: Single): Single; begin Exit(Max(AValue, AMin)); end; function Clamp(AValue, AMax, AMin: Double): Double; begin Exit(Max(Min(AValue, AMax), AMin)); end; function ClampToMax(AValue, AMax: Double): Double; begin Exit(Min(AValue, AMax)); end; function ClampToMin(AValue, AMin: Double): Double; begin Exit(Max(AValue, AMin)); end; {$ENDREGION} {$REGION ' Interpolate Functions '} function InterpolateValue(AFrom, ATo, AProgress: Single; AInterpolationType: TInterpolationType = itLinear): Single; begin Result := AFrom; case AInterpolationType of itLinear: Result := LinearInterpolate(AFrom, ATo, AProgress); itHermit01: Result := Ermit01Interpolate(AFrom, ATo, AProgress); itHermit10: Result := Ermit10Interpoalte(AFrom, ATo, AProgress); itParabolic01: Result := Parabolic01Interpolate(AFrom, ATo, AProgress); itParabolic10: Result := Parabolic10Interpolate(AFrom, ATo, AProgress); itSquareRoot01: Result := SquareRoot01Interpolate(AFrom, ATo, AProgress); itSquareRoot10: Result := SquareRoot10Interpolate(AFrom, ATo, AProgress); end; end; function LinearInterpolate(AFrom, ATo, AProgress: Single): Single; begin Result := AFrom + (ATo - AFrom) * Clamp(AProgress, 1, 0); end; function Ermit01Interpolate(AFrom, ATo, AProgress: Single): Single; begin AProgress := Clamp(AProgress, 1, 0); Result := AFrom + (ATo - AFrom) * (Sqr(AProgress) * (3 - 2 * AProgress)); end; function Ermit10Interpoalte(AFrom, ATo, AProgress: Single): Single; begin AProgress := Clamp(AProgress, 1, 0); Result := AFrom + (ATo - AFrom) * (Sqr(1 - AProgress) * (1 + 2 * AProgress)); end; function Parabolic01Interpolate(AFrom, ATo, AProgress: Single): Single; begin Result := AFrom + (ATo - AFrom) * Sqr(AProgress); end; function Parabolic10Interpolate(AFrom, ATo, AProgress: Single): Single; begin Result := AFrom + (ATo - AFrom) * (1 - Sqr(AProgress)); end; function SquareRoot01Interpolate(AFrom, ATo, AProgress: Single): Single; begin Result := AFrom + (ATo - AFrom) * Sqrt(AProgress); end; function SquareRoot10Interpolate(AFrom, ATo, AProgress: Single): Single; begin Result := AFrom + (ATo - AFrom) * Sqrt(1 - AProgress); end; {$ENDREGION} {$REGION ' Angle work Functions '} function RoundAngle(Angle: Single): Single; begin repeat if Angle < 0 then Angle := Angle + 360; if Angle >= 360 then Angle := Angle - 360; until (Angle >= 0) and (Angle<360); Result:= Angle; end; function GetAngle(A, B: TVector2F): Single; var S, C: Single; begin C := (B.Y - A.Y) / Distance(A, B); C := Clamp(C, 1, -1); S := arccos(C) * 180 / PI; if (A.X - B.X) > 0 then S := RoundAngle(360 - S); S := RoundAngle(180 - S); Result:= S; end; function GetAngle(A: TVector2F): Single; var S, C: Single; begin C := (-A.Y) / A.Length; C := Clamp(C, 1, -1); S := arccos(C) * 180 / PI; if A.X > 0 then S := RoundAngle(360 - S); S := RoundAngle(180 - S); Result := S; end; function RotateToAngle(SourceAngle, DestionationAngle, Speed: Single): Single; var Angle, Source: Single; begin Source := SourceAngle; if ((SourceAngle < 10) or (DestionationAngle<10)) then begin SourceAngle := RoundAngle(SourceAngle + 90); DestionationAngle := RoundAngle(DestionationAngle + 90); end; if ((SourceAngle > 350) or (DestionationAngle > 350)) then begin SourceAngle := RoundAngle(SourceAngle - 90); DestionationAngle := RoundAngle(DestionationAngle - 90); end; Angle := Speed; if (Abs(DestionationAngle - SourceAngle) < Speed) then Angle := Abs(DestionationAngle - SourceAngle); if (SourceAngle < DestionationAngle) then begin if (DestionationAngle - SourceAngle > 180) then Angle := -1 * Angle; end else begin if (SourceAngle - DestionationAngle < 180) then Angle := -1 * Angle; end; Result := RoundAngle(Angle + Source); end; {$ENDREGION} {$REGION ' Collision Functions '} function LineVsCircle(const LineA, LineB, CircleCenter: TVector2F; Radius: Single) : Boolean; var p1, p2: array[ 0..1 ] of Single; dx, dy: Single; a, b, c: Single; begin p1[0] := LineA.X - CircleCenter.X; p1[1] := LineA.Y - CircleCenter.Y; p2[0] := LineB.X - CircleCenter.X; p2[1] := LineB.Y - CircleCenter.Y; dx := p2[0] - p1[0]; dy := p2[1] - p1[1]; a := sqr(dx) + sqr(dy); b := (p1[0] * dx + p1[1] * dy) * 2; c := Sqr(p1[0]) + Sqr(p1[1]) - Sqr(Radius); if -b < 0 then Result := c < 0 else if -b < a * 2 then Result := a * c * 4 - Sqr(b) < 0 else Result := a + b + c < 0; end; function PointInBox( const Point, BoxTopLeft, BoxSize: TVector2F) : Boolean; begin Result := (Point.X >= BoxTopLeft.X) and (Point.X <= BoxTopLeft.X + BoxSize.X) and (Point.Y >= BoxTopLeft.Y) and (Point.Y <= BoxTopLeft.Y + BoxSize.Y); end; {$ENDREGION} {$REGION ' TVector2I '} function Vec2I(X, Y: Integer): TVector2I; begin Result.Create(X, Y); end; constructor TVector2I.Create(X, Y: Integer); begin Self.X := X; Self.Y := Y; end; class operator TVector2I.Negative(const AVector: TVector2I): TVector2I; begin Result.X := -AVector.X; Result.Y := -AVector.Y; Exit(Result); end; class operator TVector2I.Positive(const AVector: TVector2I): TVector2I; begin Exit(AVector); end; class operator TVector2I.Equal(const A, B: TVector2I): Boolean; begin Exit((A.X = B.X) and (A.Y = B.Y)); end; class operator TVector2I.NotEqual(const A, B: TVector2I): Boolean; begin Exit((A.X <> B.X) or (A.Y <> B.Y)); end; class operator TVector2I.Add(const A, B: TVector2I): TVector2I; begin Result.Create(A.X + B.X, A.Y + B.Y); end; class operator TVector2I.Subtract(const A, B: TVector2I): TVector2I; begin Result.Create(A.X - B.X, A.Y - B.Y); end; class operator TVector2I.Multiply(const A, B: TVector2I): TVector2I; begin Result.Create(A.X * B.X, A.Y * B.Y); end; class operator TVector2I.Multiply(A: Integer; const B: TVector2I): TVector2I; begin Result.Create(A * B.X, A * B.Y); end; class operator TVector2I.Multiply(const A: TVector2I; B: Integer): TVector2I; begin Result.Create(A.X * B, A.Y * B); end; function TVector2I.Length(): Single; begin Result := Sqrt(Sqr(Self.X) + Sqr(Self.Y)); end; function TVector2I.LengthSqr(): Single; begin Result := Sqr(Self.X) + Sqr(Self.Y); end; {$ENDREGION} {$REGION ' TVector2F '} function Vec2F(X, Y: Single): TVector2F; begin Result.Create(X, Y); end; constructor TVector2F.Create(X, Y: Single); begin Self.X := X; Self.Y := Y; end; class operator TVector2F.Implicit(const AVector: TVector2I): TVector2F; begin Result.Create(AVector.X, AVector.Y); end; class operator TVector2F.Explicit(const AVector: TVector2I): TVector2F; begin Result.Create(AVector.X, AVector.Y); end; class operator TVector2F.Negative(const AVector: TVector2F): TVector2F; begin Result.X := -AVector.X; Result.Y := -AVector.Y; Exit(Result); end; class operator TVector2F.Trunc(const AVector: TVector2F): TVector2I; begin Result.Create(Trunc(AVector.X), Trunc(AVector.Y)); end; class operator TVector2F.Round(const AVector: TVector2F): TVector2I; begin Result.Create(Round(AVector.X), Round(AVector.Y)); end; class operator TVector2F.Positive(const AVector: TVector2F): TVector2F; begin Exit(AVector); end; class operator TVector2F.Equal(const A, B: TVector2F): Boolean; begin Exit((A.X = B.X) and (A.Y = B.Y)); end; class operator TVector2F.NotEqual(const A, B: TVector2F): Boolean; begin Exit((A.X <> B.X) or (A.Y <> B.Y)); end; class operator TVector2F.Add(const A, B: TVector2F): TVector2F; begin Result.Create(A.X + B.X, A.Y + B.Y); end; class operator TVector2F.Subtract(const A, B: TVector2F): TVector2F; begin Result.Create(A.X - B.X, A.Y - B.Y); end; class operator TVector2F.Multiply(const A, B: TVector2F): Single; begin Result := A.X * B.X + A.Y * B.Y; end; class operator TVector2F.Multiply(const A: TVector2F; B: Single): TVector2F; begin Result.Create(A.X * B, A.Y * B); end; class operator TVector2F.Multiply(A: Single; const B: TVector2F): TVector2F; begin Result.Create(A * B.X, A * B.Y); end; function TVector2F.ComponentwiseMultiply(const AVector: TVector2F): TVector2F; begin Result.Create(Self.X * AVector.X, Self.Y * AVector.Y); end; function TVector2F.ComponentwiseDivide(const AVector: TVector2F): TVector2F; begin Result.Create(Self.X / AVector.X, Self.Y / AVector.Y); end; function TVector2F.Length(): Single; begin Result := Sqrt(Sqr(X) + Sqr(Y)); end; function TVector2F.LengthSqr(): Single; begin Result := Sqr(X) + Sqr(Y); end; function TVector2F.Normalize(): TVector2F; var ALength: Single; begin ALength := Self.Length; Result.Create(Self.X / ALength, Self.Y / ALength); end; function TVector2F.Distance(const AVector: TVector2F): Single; begin Result := Sqrt(Sqr(Self.X - AVector.X) + Sqr(Self.Y - AVector.Y)); end; function TVector2F.Clip(ALength: Single): TVector2F; var AVectorLength: Single; begin AVectorLength := Self.Length; if AVectorLength > ALength then Result.Create(Self.X / ALength, Self.Y / ALength) else Result := Self; end; function TVector2F.Angle(const AVector: TVector2F): Single; var S, C: Single; begin C := (AVector.Y - Self.Y) / Self.Distance(AVector); C := Clamp(C, 1, -1); S := ArcCos(C) * 180 / Pi; if (Self.X - AVector.X) > 0 then S := RoundAngle(360 - S); S := RoundAngle(180 - S); Result:= S; end; function TVector2F.InterpolateTo(const AVector: TVector2F; AProgress: Single; AInterpolationType: TInterpolationType = itLinear): TVector2F; begin Result.Create( InterpolateValue(Self.X, AVector.X, AProgress, AInterpolationType), InterpolateValue(Self.Y, AVector.Y, AProgress, AInterpolationType)); end; function Distance(const A, B: TVector2F): Single; begin Result:= Sqrt(Sqr(A.X - B.X) + Sqr(A.Y - B.Y)); end; function GetRotatedVector(Angle, Length: Single): TVector2F; begin Result.X:= sin(Angle / 180 * Pi) * Length; Result.Y:= -cos(Angle / 180 * Pi) * Length; end; function Dot(const A, B: TVector2F): Single; begin Result:= A.X * B.X + A.Y * B.Y; end; {$ENDREGION} {$REGION ' TVector2IHelper '} function TVector2IHelper.ComponentwiseMultiply(const AVector: TVector2I): TVector2F; begin Result.Create(Self.X * AVector.X, Self.Y * AVector.Y); end; function TVector2IHelper.ComponentwiseDivide(const AVector: TVector2I): TVector2F; begin Result.Create(Self.X / AVector.X, Self.Y / AVector.Y); end; function TVector2IHelper.Normalized(): TVector2F; var ALength: Single; begin ALength := Self.Length; Result.Create(Self.X / ALength, Self.Y / ALength); end; function TVector2IHelper.Angle(const AVector: TVector2F): Single; begin if (ZeroVectorF = AVector) or (ZeroVectorI = Self) then Exit(0); Result := ArcCos(Self * AVector / (Self.Length * AVector.Length)); end; function TVector2IHelper.InterpolateTo(const AVector: TVector2F; AProgress: Single; AInterpolationType: TInterpolationType = itLinear): TVector2F; begin Result.Create( InterpolateValue(Self.X, AVector.X, AProgress, AInterpolationType), InterpolateValue(Self.Y, AVector.Y, AProgress, AInterpolationType)); end; {$ENDREGION} end.
unit StringUtilitario; interface type TStringUtilitario = class public class function ApenasNumeros (const Texto :String) :String; class function EstaVazia (Texto :String) :Boolean; class function FormataCEP (const CEP :String) :String; overload; class function FormataCEP (const CEP :String; UsaPonto :Boolean) :String; overload; class function FormataDinheiro (const Valor :Real) :String; class function LetraPorSequencia(NumeroSequencia :Integer) :String; class function StringVazia :String; class function RemoveCaracter(const Texto :String; const caracter :String = '') :String; class function CaracterAEsquerda(Caracter :Char; Texto :String; tamanho_maximo :Integer) :String; class function NomeDoComputador :String; class function MascaraFone (const fone :String) :String; class function TamanhoArquivo(Arquivo: string) :Integer; class function MascaraTelefone(const telefone :string) :String; end; implementation uses SysUtils, Registry, windows, Classes; { TStringUtilitario } class function TStringUtilitario.ApenasNumeros( const Texto: String): String; var nX: Integer; begin result := ''; for nX := 1 To Length(Texto) do begin if Texto[nX] in ['0'..'9'] Then result := result + Texto[nX]; end; end; class function TStringUtilitario.TamanhoArquivo(Arquivo: string): Integer; begin with TFileStream.Create(Arquivo, fmOpenRead or fmShareExclusive) do try Result := Size; finally Free; end; end; class function TStringUtilitario.CaracterAEsquerda(Caracter :Char; Texto: String; tamanho_maximo: Integer): String; var vezes :Integer; begin vezes := tamanho_maximo - Length(Texto); Result := StringOfChar(Caracter, vezes ) + Texto; end; class function TStringUtilitario.EstaVazia(Texto: String): Boolean; begin result := (Trim(Texto) = self.StringVazia); end; class function TStringUtilitario.FormataCEP(const CEP: String; UsaPonto :Boolean): String; var nX: Integer; begin result := ''; for nX := 1 to Length(CEP) do begin if CEP[nX] in ['0'..'9'] Then result := result + CEP[nX]; end; if (Length(Result) <> 8) then exit; if UsaPonto then result := copy(Result,1,2) + '.' + copy(Result,3,3) + '-' + copy(Result,6,3) else result := copy(Result,1,2) + copy(Result,3,3) + '-' + copy(Result,6,3); end; class function TStringUtilitario.FormataCEP(const CEP: String): String; begin result := self.FormataCEP(CEP, true); end; class function TStringUtilitario.FormataDinheiro( const Valor: Real): String; begin result := FormatFloat(' ,0.00; -,0.00;', Valor); end; class function TStringUtilitario.NomeDoComputador: String; var iLen: Cardinal; begin iLen := MAX_COMPUTERNAME_LENGTH + 1; // From Windows.pas Result := StringOfChar(#0, iLen); GetComputerName(PChar(Result), iLen); SetLength(Result, iLen); end; class function TStringUtilitario.LetraPorSequencia( NumeroSequencia: Integer): String; const ALFABETO = 'ABCDEFGHIJLMNOPQRSTUVXZ'; begin result := ALFABETO[NumeroSequencia]; end; class function TStringUtilitario.RemoveCaracter(const Texto :String; const caracter: String): String; var I :integer; begin if caracter <> '' then result := StringReplace(Texto, caracter, '', [rfReplaceAll]) else for I := 1 To Length(Texto) do if Texto [I] In ['0'..'9'] Then Result := Result + Texto [I]; end; class function TStringUtilitario.StringVazia: String; begin result := ''; end; class function TStringUtilitario.MascaraFone(const fone: String): String; begin result := '('+copy(fone,1,2)+')'+copy(fone,3,8); end; class function TStringUtilitario.MascaraTelefone(const telefone: string): String; begin result := '('+copy(telefone,1,2)+')'+copy(telefone,3,4)+'-'+copy(telefone,7,4); end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit Client.ServerMethods.FD_DBX_Unit; interface uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethodsClient = class(TDSAdminClient) private FEchoStringCommand: TDBXCommand; FReverseStringCommand: TDBXCommand; FStreamGetCommand: TDBXCommand; FStreamPostCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string): string; function ReverseString(Value: string): string; function StreamGet: TStream; function StreamPost(AStream: TStream): string; end; implementation function TServerMethodsClient.EchoString(Value: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FDBXConnection.CreateCommand; FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FEchoStringCommand.Text := 'TServerMethods.EchoString'; FEchoStringCommand.Prepare; end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.ExecuteUpdate; Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethodsClient.ReverseString(Value: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FDBXConnection.CreateCommand; FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FReverseStringCommand.Text := 'TServerMethods.ReverseString'; FReverseStringCommand.Prepare; end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.ExecuteUpdate; Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethodsClient.StreamGet: TStream; begin if FStreamGetCommand = nil then begin FStreamGetCommand := FDBXConnection.CreateCommand; FStreamGetCommand.CommandType := TDBXCommandTypes.DSServerMethod; FStreamGetCommand.Text := 'TServerMethods.StreamGet'; FStreamGetCommand.Prepare; end; FStreamGetCommand.ExecuteUpdate; Result := FStreamGetCommand.Parameters[0].Value.GetStream(FInstanceOwner); end; function TServerMethodsClient.StreamPost(AStream: TStream): string; begin if FStreamPostCommand = nil then begin FStreamPostCommand := FDBXConnection.CreateCommand; FStreamPostCommand.CommandType := TDBXCommandTypes.DSServerMethod; FStreamPostCommand.Text := 'TServerMethods.StreamPost'; FStreamPostCommand.Prepare; end; FStreamPostCommand.Parameters[0].Value.SetStream(AStream, FInstanceOwner); FStreamPostCommand.ExecuteUpdate; Result := FStreamPostCommand.Parameters[1].Value.GetWideString; end; constructor TServerMethodsClient.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TServerMethodsClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TServerMethodsClient.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FStreamGetCommand.DisposeOf; FStreamPostCommand.DisposeOf; inherited; end; end.
unit UpdaterTest; interface uses dbTest, dbObjectTest; type TUpdaterTest = class (TdbObjectTestNew) private procedure SaveFile(FilePath: string); published procedure ProcedureLoad; override; procedure UpdateMainProgram; procedure UpdateBoutique; end; implementation uses DB, UtilConst, Classes, TestFramework, SysUtils, FormStorage, ZStoredProcedure, UnilWin, ZLibEx, Dialogs, CommonData; { TdbUnitTest } procedure TUpdaterTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'OBJECTS\Program\'; inherited; end; procedure TUpdaterTest.SaveFile(FilePath: string); var Stream: TStream; begin Stream := TStringStream.Create(ConvertConvert(FileReadString(FilePath))); with TZStoredProc.Create(nil), UnilWin.GetFileVersion(FilePath) do begin try Connection := ZConnection; StoredProcName := 'gpInsertUpdate_Object_Program'; Params.Clear; Params.CreateParam(ftString, 'inProgramName', ptInput); Params.CreateParam(ftFloat, 'inMajorVersion', ptInput); Params.CreateParam(ftFloat, 'inMinorVersion', ptInput); Params.CreateParam(ftBlob, 'inProgramData', ptInput); Params.CreateParam(ftString, 'inSession', ptInput); ParamByName('inProgramName').AsString := ExtractFileName(FilePath); ParamByName('inMajorVersion').AsFloat := VerHigh; ParamByName('inMinorVersion').AsFloat := VerLow; ParamByName('inProgramData').LoadFromStream(Stream, ftMemo); ParamByName('inSession').AsString := gc_User.Session; ExecProc; finally Free; Stream.Free; end; end; end; procedure TUpdaterTest.UpdateBoutique; begin SaveFile(ExtractFileDir(ParamStr(0)) + '\Boutique.exe'); end; procedure TUpdaterTest.UpdateMainProgram; begin if FileExists(ExtractFileDir(ParamStr(0)) + '\midas.dll') then SaveFile(ExtractFileDir(ParamStr(0)) + '\midas.dll'); if FileExists(ExtractFileDir(ParamStr(0)) + '\Upgrader4.exe') then SaveFile(ExtractFileDir(ParamStr(0)) + '\Upgrader4.exe'); SaveFile(ExtractFileDir(ParamStr(0)) + '\' + gc_ProgramName); end; initialization TestFramework.RegisterTest('Сохранение программы', TUpdaterTest.Suite); end.
unit Restourant.Consts.Database; interface const Folder = 'data'; PackedFile = 'data.zip'; FileExt = '.json'; Resource = 'DATABASE'; Section = 'DATA'; C = 'c_const'; R_TMC = 'r_tmc'; R_TMC_CTGR = 'r_tmc_ctgr'; R_TMC_GROUP = 'r_tmc_group'; R_TMC_GROUPSHARE = 'r_tmc_groupshare'; R_ENTRS_PLATES = 'r_entrs_plates'; ConstEntName = ''; FieldConstID = 'ID'; FieldConstFINT = 'FINT'; FieldConstFFLOAT = 'FFLOAT'; FieldConstFSTR = 'FSTR'; FieldConstFBLOB = 'FBLOB'; FieldRefID = 'ID'; FieldRefNAME = 'NAME'; FieldRefFLAG_DELETE = 'FLAG_DELETE'; FieldRefCOMENT = 'COMENT'; FieldRefEDIZM_SNAME = 'EDIZM_SNAME'; FieldRefPRICE = 'PRICE'; FieldRefTMC_GROUP_ID = 'TMC_GROUP_ID'; FieldRefGROUPNAME = 'GROUPNAME'; FormatPRICE = '# ### ##0.00'; FormatQUANT = '# ### ##0.00'; FormatDATE = 'dd.mm.yyyy'; implementation end.
{ Invokable interface ITxRxWS } unit TxRxWSIntf; interface uses InvokeRegistry, Types, XSBuiltIns, CommunicationObj; type ITxRxWS = interface(IInvokable) ['{8F256C8D-4844-411C-8018-B8E492EF5677}'] // ISynchro procedure Set_Pulso_Largo; safecall; procedure Set_Pulso_Corto(PRF_Rate: TxDualPulseEnum); safecall; function Get_Frecuencia: Integer; safecall; function Get_Pulse: TxPulseEnum; safecall; function Get_PRF_Rate: TxDualPulseEnum; safecall; // ITxStatus function Get_Tx_Status: RadarStatusEnum; safecall; function Get_Encendido: WordBool; safecall; function Get_HV: WordBool; safecall; function Get_Listo: WordBool; safecall; function Get_Inter_Lock: WordBool; safecall; function Get_Ventilacion: WordBool; safecall; function Get_Averia: WordBool; safecall; function Get_Averia_MPS: WordBool; safecall; function Get_Averia_Ventilador: WordBool; safecall; function Get_Averia_Fuente_Filamento: WordBool; safecall; function Get_Local: WordBool; safecall; // IRxStatus function Get_Fuente_5V_N: WordBool; safecall; function Get_Fuente_5V_P: WordBool; safecall; function Get_Fuente_15V_N: WordBool; safecall; function Get_Fuente_15V_P: WordBool; safecall; function Get_Stalo_Locked: WordBool; safecall; function Get_Rx_Status: RadarStatusEnum; safecall; function Get_DRX_Ready: WordBool; safecall; function Get_Stalo_Temperature: Double; safecall; function Get_Stalo_Power: Double; safecall; function Get_Stalo_Frequency: Int64; safecall; function Get_Stalo_ExtRef: WordBool; safecall; function Get_Stalo_Ref_Unlocked: WordBool; safecall; function Get_Stalo_RF_Unlocked: WordBool; safecall; function Get_Stalo_RF_Output: WordBool; safecall; function Get_Stalo_VoltageError: WordBool; safecall; function Get_Stalo_Ref_Output: WordBool; safecall; function Get_Stalo_Blanking: WordBool; safecall; function Get_Stalo_LockRecovery: WordBool; safecall; function Get_AFC_Status: WordBool; safecall; function Get_Tx_Frequency: Int64; safecall; function Get_Tx_IF: Int64; safecall; function Get_Tx_PulsePower: Double; safecall; function Get_NCO_Frequency: Int64; safecall; procedure StartAcquiring; safecall; function Get_Potencia_Code: Integer; safecall; function Get_Potencia_Unit: Double; safecall; function Get_MPS_Volt_Code: Integer; safecall; function Get_MPS_Volt_Unit: Double; safecall; function Get_MPS_Corr_Code: Integer; safecall; function Get_MPS_Corr_Unit: Double; safecall; function Get_Fuente_24VN_Code: Integer; safecall; function Get_Fuente_24VN_Unit: Double; safecall; function Get_Fuente_24VP_Code: Integer; safecall; function Get_Fuente_24VP_Unit: Double; safecall; function Get_Fuente_50V_Code: Integer; safecall; function Get_Fuente_50V_Unit: Double; safecall; function Get_Fuente_100V_Code: Integer; safecall; function Get_Fuente_100V_Unit: Double; safecall; function Get_Fuente_400V_Code: Integer; safecall; function Get_Fuente_400V_Unit: Double; safecall; function Get_Fuente_Filamento_Code: Integer; safecall; function Get_Fuente_Filamento_Unit: Double; safecall; // ITxRxStatus function Get_Tx_Pulso: TxPulseEnum; safecall; function Get_Numero: Integer; safecall; function Get_Longitud_Onda: TWaveLengthEnum; safecall; // ITxControl procedure Tx_Encender; safecall; procedure Tx_Apagar; safecall; procedure Set_HV(Value: WordBool); safecall; // IRxControl procedure Rx_Encender; safecall; procedure Rx_Apagar; safecall; procedure Set_Stalo_Freq(Value: Int64); safecall; procedure Set_Stalo_Power(Value: Double); safecall; procedure Stalo_Reset; safecall; procedure Set_AFC_Status(Value: WordBool); safecall; procedure Set_Stalo_Output(Value: WordBool); safecall; procedure Stalo_Update; safecall; procedure Set_NCO_Frequency(Value: Int64); safecall; // ITxRxMeasure function Get_Rango_Tx_Potencia: Integer; safecall; function Get_Sector_Tx_Potencia: Integer; safecall; function Get_Rango_Tx_MPS_Volt: Integer; safecall; function Get_Rango_Tx_MPS_Corr: Integer; safecall; function Get_Rango_Tx_Fuente24V_N: Integer; safecall; function Get_Rango_Tx_Fuente24V_P: Integer; safecall; function Get_Rango_Tx_Fuente50V: Integer; safecall; function Get_Rango_Tx_Fuente400V: Integer; safecall; function Get_Rango_Tx_Fuente_Filamento: Integer; safecall; function Get_Rango_Tx_Fuente100V: Integer; safecall; function Get_Sector_Tx_MPS_Volt: Integer; safecall; function Get_Sector_Tx_MPS_Corr: Integer; safecall; function Get_Sector_Tx_Fuente24V_N: Integer; safecall; function Get_Sector_Tx_Fuente24V_P: Integer; safecall; function Get_Sector_Tx_Fuente50V: Integer; safecall; function Get_Sector_Tx_Fuente100V: Integer; safecall; function Get_Sector_Tx_Fuente400V: Integer; safecall; function Get_Sector_Tx_Fuente_Filamento: Integer; safecall; // ITxRxMeasureControl procedure Set_Rango_Tx_Potencia(Value: Integer); safecall; procedure Set_Sector_Tx_Potencia(Value: Integer); safecall; procedure Set_Rango_Tx_MPS_Volt(Value: Integer); safecall; procedure Set_Rango_Tx_MPS_Corr(Value: Integer); safecall; procedure Set_Rango_Tx_Fuente24V_N(Value: Integer); safecall; procedure Set_Rango_Tx_Fuente24V_P(Value: Integer); safecall; procedure Set_Rango_Tx_Fuente50V(Value: Integer); safecall; procedure Set_Rango_Tx_Fuente100V(Value: Integer); safecall; procedure Set_Rango_Tx_Fuente400V(Value: Integer); safecall; procedure Set_Rango_Tx_Fuente_Filamento(Value: Integer); safecall; procedure Set_Sector_Tx_MPS_Volt(Value: Integer); safecall; procedure Set_Sector_Tx_MPS_Corr(Value: Integer); safecall; procedure Set_Sector_Tx_Fuente24V_N(Value: Integer); safecall; procedure Set_Sector_Tx_Fuente24V_P(Value: Integer); safecall; procedure Set_Sector_Tx_Fuente50V(Value: Integer); safecall; procedure Set_Sector_Tx_Fuente100V(Value: Integer); safecall; procedure Set_Sector_Tx_Fuente400V(Value: Integer); safecall; procedure Set_Sector_Tx_Fuente_Filamento(Value: Integer); safecall; property Local: WordBool read Get_Local; property Numero: Integer read Get_Numero; property Tx_Pulso: TxPulseEnum read Get_Tx_Pulso; property Longitud_Onda: TWaveLengthEnum read Get_Longitud_Onda; property Stalo_Power: Double read Get_Stalo_Power write Set_Stalo_Power; property Stalo_Frequency: Int64 read Get_Stalo_Frequency write Set_Stalo_Freq; property NCO_Frequency: Int64 read Get_NCO_Frequency write Set_NCO_Frequency; property Stalo_RF_Output: WordBool read Get_Stalo_RF_Output write Set_Stalo_Output; property AFC_Status: WordBool read Get_AFC_Status write Set_AFC_Status; property Stalo_Temperature: Double read Get_Stalo_Temperature; property Stalo_ExtRef: WordBool read Get_Stalo_ExtRef; property Stalo_Ref_Unlocked: WordBool read Get_Stalo_Ref_Unlocked; property Stalo_RF_Unlocked: WordBool read Get_Stalo_RF_Unlocked; property Stalo_VoltageError: WordBool read Get_Stalo_VoltageError; property Stalo_Ref_Output: WordBool read Get_Stalo_Ref_Output; property Stalo_Blanking: WordBool read Get_Stalo_Blanking; property Stalo_LockRecovery: WordBool read Get_Stalo_LockRecovery; property Tx_Frequency: Int64 read Get_Tx_Frequency; property Tx_IF: Int64 read Get_Tx_IF; property Tx_PulsePower: Double read Get_Tx_PulsePower; property Rx_Status: RadarStatusEnum read Get_Rx_Status; property Fuente_5V_N: WordBool read Get_Fuente_5V_N; property Fuente_5V_P: WordBool read Get_Fuente_5V_P; property Fuente_15V_N: WordBool read Get_Fuente_15V_N; property Fuente_15V_P: WordBool read Get_Fuente_15V_P; property Stalo_Locked: WordBool read Get_Stalo_Locked; property DRX_Ready: WordBool read Get_DRX_Ready; property Encendido: WordBool read Get_Encendido; property HV: WordBool read Get_HV write Set_HV; property Listo: WordBool read Get_Listo; property Averia_MPS: WordBool read Get_Averia_MPS; property Potencia_Code: Integer read Get_Potencia_Code; property Potencia_Unit: Double read Get_Potencia_Unit; property MPS_Volt_Code: Integer read Get_MPS_Volt_Code; property MPS_Volt_Unit: Double read Get_MPS_Volt_Unit; property MPS_Corr_Code: Integer read Get_MPS_Corr_Code; property MPS_Corr_Unit: Double read Get_MPS_Corr_Unit; property Fuente_24VN_Code: Integer read Get_Fuente_24VN_Code; property Fuente_24VN_Unit: Double read Get_Fuente_24VN_Unit; property Fuente_24VP_Code: Integer read Get_Fuente_24VP_Code; property Fuente_24VP_Unit: Double read Get_Fuente_24VP_Unit; property Fuente_50V_Code: Integer read Get_Fuente_50V_Code; property Fuente_50V_Unit: Double read Get_Fuente_50V_Unit; property Fuente_100V_Code: Integer read Get_Fuente_100V_Code; property Fuente_100V_Unit: Double read Get_Fuente_100V_Unit; property Fuente_400V_Code: Integer read Get_Fuente_400V_Code; property Fuente_400V_Unit: Double read Get_Fuente_400V_Unit; property Fuente_Filamento_Code: Integer read Get_Fuente_Filamento_Code; property Fuente_Filamento_Unit: Double read Get_Fuente_Filamento_Unit; property Tx_Status: RadarStatusEnum read Get_Tx_Status; property Inter_Lock: WordBool read Get_Inter_Lock; property Ventilacion: WordBool read Get_Ventilacion; property Averia_Ventilador: WordBool read Get_Averia_Ventilador; property Averia_Fuente_Filamento: WordBool read Get_Averia_Fuente_Filamento; property Rango_Tx_Potencia: Integer read Get_Rango_Tx_Potencia write Set_Rango_Tx_Potencia; property Sector_Tx_Potencia: Integer read Get_Sector_Tx_Potencia write Set_Sector_Tx_Potencia; property Rango_Tx_MPS_Volt: Integer read Get_Rango_Tx_MPS_Volt write Set_Rango_Tx_MPS_Volt; property Sector_Tx_MPS_Volt: Integer read Get_Sector_Tx_MPS_Volt write Set_Sector_Tx_MPS_Volt; property Rango_Tx_MPS_Corr: Integer read Get_Rango_Tx_MPS_Corr write Set_Rango_Tx_MPS_Corr; property Sector_Tx_MPS_Corr: Integer read Get_Sector_Tx_MPS_Corr write Set_Sector_Tx_MPS_Corr; property Rango_Tx_Fuente24V_N: Integer read Get_Rango_Tx_Fuente24V_N write Set_Rango_Tx_Fuente24V_N; property Sector_Tx_Fuente24V_N: Integer read Get_Sector_Tx_Fuente24V_N write Set_Sector_Tx_Fuente24V_N; property Rango_Tx_Fuente24V_P: Integer read Get_Rango_Tx_Fuente24V_P write Set_Rango_Tx_Fuente24V_P; property Sector_Tx_Fuente24V_P: Integer read Get_Sector_Tx_Fuente24V_P write Set_Sector_Tx_Fuente24V_P; property Sector_Tx_Fuente50V: Integer read Get_Sector_Tx_Fuente50V write Set_Sector_Tx_Fuente50V; property Rango_Tx_Fuente50V: Integer read Get_Rango_Tx_Fuente50V write Set_Rango_Tx_Fuente50V; property Sector_Tx_Fuente100V: Integer read Get_Sector_Tx_Fuente100V write Set_Sector_Tx_Fuente100V; property Rango_Tx_Fuente100V: Integer read Get_Rango_Tx_Fuente100V write Set_Rango_Tx_Fuente100V; property Rango_Tx_Fuente400V: Integer read Get_Rango_Tx_Fuente400V write Set_Rango_Tx_Fuente400V; property Sector_Tx_Fuente400V: Integer read Get_Sector_Tx_Fuente400V write Set_Sector_Tx_Fuente400V; property Sector_Tx_Fuente_Filamento: Integer read Get_Sector_Tx_Fuente_Filamento write Set_Sector_Tx_Fuente_Filamento; property Rango_Tx_Fuente_Filamento: Integer read Get_Rango_Tx_Fuente_Filamento write Set_Rango_Tx_Fuente_Filamento; end; implementation end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // {$H+} unit RowEntryFixture; interface Uses {Delphi} SysUtils, {Fit} ColumnFixture, Parse; const ERROR_INDICATOR = 'Unable to enter last row: '; RIGHT_STYLE = 'pass'; WRONG_STYLE = 'fail'; Type TRowEntryFixture = class(TColumnFixture) protected function appendCell(row: TParse; text: String): TParse; public constructor Create; override; procedure enterRow; virtual; abstract; procedure doRow(row: TParse); override; procedure reportError(row: TParse; e: Exception); function makeMessageCell(e: Exception): TParse; procedure insertRowAfter(currentRow: TParse; rowToAdd: TParse); end; implementation { RowEntryFixture } procedure TRowEntryFixture.doRow(row: TParse); var index: integer; begin index := AnsiPos(ERROR_INDICATOR, row.parts.body); if (index > 0) then exit; inherited doRow(row); try enterRow(); right(appendCell(row, 'entered')); except on e: Exception do begin wrong(appendCell(row, 'skipped')); reportError(row, e); end; end; end; function TRowEntryFixture.appendCell(row: TParse; text: String): TParse; var lastCell: TParse; begin lastCell := TParse.Create('td', text, nil, nil); row.parts.last.more := lastCell; result := lastCell; end; procedure TRowEntryFixture.reportError(row: TParse; e: Exception); var errorCell: TParse; begin errorCell := makeMessageCell(e); insertRowAfter(row, TParse.Create('tr', '', errorCell, nil)); end; function TRowEntryFixture.makeMessageCell(e: Exception): TParse; var errorCell: TParse; begin errorCell := TParse.Create('td', '', nil, nil); errorCell.addToTag(' colspan=''' + IntToStr(fColumnBindings.count + 1) + ''''); errorCell.addToBody('<i>' + ERROR_INDICATOR + e.Message + '</i>'); wrong(errorCell); result := errorCell; end; procedure TRowEntryFixture.insertRowAfter(currentRow, rowToAdd: TParse); var nextRow: TParse; begin nextRow := currentRow.more; currentRow.more := rowToAdd; rowToAdd.more := nextRow; end; constructor TRowEntryFixture.create; begin inherited; end; end.
unit MainU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, {System.Variants,} System.Classes, {Vcl.Graphics,} Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, SprayFileHandler, Registry, Winapi.Shellapi, StatusFrmU, GameFolderHintFrmU, AboutFrmU, Vcl.FileCtrl, VTFPrevFrmU; type TSprayErrorTypeCount = record Successes: NativeInt; GameNotInstalled: NativeInt; SprayTooLarge: NativeInt; InvalidVTFFile: NativeInt; IOError: NativeInt; end; type TMain = class(TForm) GameDropPanel: TPanel; GameLabel: TLabel; GameComboBox: TComboBox; GameStatusLbl: TLabel; GamePathSelBtn: TButton; MainPnl: TPanel; ExistingSprayList: TListBox; ImportSpraysList: TListBox; ExistingSprayPnl: TPanel; ExistingSpraysLbl: TLabel; Splitter1: TSplitter; ImportSpraysPnl: TPanel; ImportSpraysLbl: TLabel; DeleteSprayBtn: TButton; ImportSpraysBtnPnl: TPanel; RemoveSpraysBtn: TButton; ImportSelBtn: TButton; ImportAllBtn: TButton; AddSpraysBtn: TButton; SprayImportDlg: TOpenDialog; ClearGamePathBtn: TButton; AboutBtnPnl: TPanel; AboutBtn: TButton; procedure FormCreate(Sender: TObject); procedure GameComboBoxChange(Sender: TObject); procedure ExistingSprayListClick(Sender: TObject); procedure ExistingSprayListKeyPress(Sender: TObject; var Key: Char); procedure DeleteSprayBtnClick(Sender: TObject); procedure AddSpraysBtnClick(Sender: TObject); procedure RemoveSpraysBtnClick(Sender: TObject); procedure ListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ImportSelBtnClick(Sender: TObject); procedure ImportSpraysListClick(Sender: TObject); procedure ImportSpraysListKeyPress(Sender: TObject; var Key: Char); procedure ImportAllBtnClick(Sender: TObject); procedure ClearGamePathBtnClick(Sender: TObject); procedure GamePathSelBtnClick(Sender: TObject); procedure AboutBtnClick(Sender: TObject); procedure ExistingSprayListDblClick(Sender: TObject); procedure ExistingSprayListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private StatusFrm: TStatusFrm; procedure GameBoxChangeStatus; procedure ExistingSpraysListPopulate(const path: string); procedure PreviewSpray(index: NativeInt); procedure DeleteBtnDisablerEnabler; procedure ImportBtnsDisablerEnabler; procedure DeleteSpray; procedure AddSprayToImportList(const FileName: string); procedure RemoveSpraysFromImportList; function ImportSpray(index: NativeInt; var ErrorStruct: TSprayErrorTypeCount): NativeInt; procedure ImportSelectedSprays; procedure ImportAllSprays; procedure SprayStatusUpdate(const ErrorStruct: TSprayErrorTypeCount); function VTFValidate(const FileName: string): Boolean; function SelectGameDirectory(index: NativeInt): Boolean; procedure ClearGameDirectory(index: NativeInt); procedure ShowAboutForm; procedure WMDROPFILES(var msg : TWMDropFiles); message WM_DROPFILES; public InfoHandler: TSprayFileHandler; end; var Main: TMain; const clWindowText: Integer = -16777208; clBtnFace: Integer = -16777201; implementation {$R *.dfm} procedure TMain.FormCreate(Sender: TObject); var regReaderSteam: TRegistry; SteamApps: string; i: NativeInt; begin StatusFrm := nil; regReaderSteam := TRegistry.Create; regReaderSteam.RootKey := HKEY_CURRENT_USER; if regReaderSteam.KeyExists('Software\Valve\Steam') then begin regReaderSteam.OpenKeyReadOnly('Software\Valve\Steam'); SteamApps := IncludeTrailingPathDelimiter(StringReplace(regReaderSteam.ReadString('SteamPath'),'/','\',[rfReplaceAll]))+'steamapps\'; end else begin ShowMessage('Steam is not installed on this computer.'); Close; end; regReaderSteam.CloseKey; regReaderSteam.Free; InfoHandler := TSprayFileHandler.Create(SteamApps); InfoHandler.PopulateStringList(GameComboBox.Items); DragAcceptFiles(Handle,True); for i := 1 to ParamCount do begin ImportSpraysList.Items.Add(ParamStr(i)); end; end; procedure TMain.PreviewSpray(index: NativeInt); begin VTFPrevForm.LoadImage(InfoHandler.GetMainSprayPath(GameComboBox.ItemIndex) + ExistingSprayList.Items.Strings[index]); VTFPrevForm.Show; Show; end; procedure TMain.GameBoxChangeStatus; begin ExistingSprayList.Clear; GamePathSelBtn.Enabled := (GameComboBox.ItemIndex >= 0); ClearGamePathBtn.Enabled := GamePathSelBtn.Enabled; if InfoHandler.GetGamePath(GameComboBox.ItemIndex) = '' then begin GameStatusLbl.Caption := 'Game is not installed, or you need to select its path.'; GameStatusLbl.Font.Color := $00FFFFFF; GameStatusLbl.Color := $000000FF; end else begin GameStatusLbl.Caption := 'Game is installed. Its currently-imported sprays are listed on the right.'; GameStatusLbl.Font.Color := clWindowText; GameStatusLbl.Color := clBtnFace; ExistingSpraysListPopulate(InfoHandler.GetMainSprayPath(GameComboBox.ItemIndex)); ImportAllBtn.Hint := Format('Import all Sprays To Import into %s',[InfoHandler.GetGameShortName(GameComboBox.ItemIndex)]); ImportSelBtn.Hint := Format('Import selected sprays into %s',[InfoHandler.GetGameShortName(GameComboBox.ItemIndex)]); end; DeleteBtnDisablerEnabler; ImportBtnsDisablerEnabler; end; procedure TMain.ExistingSprayListClick(Sender: TObject); begin DeleteBtnDisablerEnabler; end; procedure TMain.ExistingSprayListDblClick(Sender: TObject); begin PreviewSpray(ExistingSprayList.ItemIndex); end; procedure TMain.ExistingSprayListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin ListKeyDown(Sender,Key,Shift); if (Key = $0D {Enter}) and (not ( ssCtrl in Shift)) and (not (ssShift in Shift)) and (not (ssAlt in Shift)) then PreviewSpray(ExistingSprayList.ItemIndex); end; procedure TMain.ExistingSprayListKeyPress(Sender: TObject; var Key: Char); begin DeleteBtnDisablerEnabler end; procedure TMain.ExistingSpraysListPopulate(const path: string); var VTFFiles: TSearchRec; begin if DirectoryExists(path) then begin if FindFirst(Path+'*.vtf', faAnyFile, VTFFiles) = 0 then repeat ExistingSprayList.Items.Add(ExtractFileName(VTFFiles.Name)); until FindNext(VTFFiles) <> 0; FindClose(VTFFiles); end; end; procedure TMain.GameComboBoxChange(Sender: TObject); begin GameBoxChangeStatus; end; procedure TMain.GamePathSelBtnClick(Sender: TObject); begin SelectGameDirectory(GameComboBox.ItemIndex); end; procedure TMain.DeleteBtnDisablerEnabler; begin if ExistingSprayList.ItemIndex >= 0 then DeleteSprayBtn.Enabled := true else DeleteSprayBtn.Enabled := false; end; procedure TMain.ImportBtnsDisablerEnabler; begin ImportAllBtn.Enabled := (ImportSpraysList.Count > 0) and (GameComboBox.ItemIndex >= 0) and (InfoHandler.GetGamePath(GameComboBox.ItemIndex) <> ''); ImportSelBtn.Enabled := (ImportAllBtn.Enabled) and (ImportSpraysList.SelCount > 0); end; procedure TMain.ListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = $41 {A}) and (ssCtrl in Shift) and (not (ssShift in Shift)) and (not (ssAlt in Shift)) then TListBox(Sender).SelectAll; end; procedure TMain.DeleteSpray; var i: NativeInt; begin if MessageBox(Handle,'Do you wish to delete the selected sprays from this game?','Spray Deletion', MB_YESNO or MB_ICONQUESTION) = IDYES then begin for i := 0 to ExistingSprayList.Count - 1 do if ExistingSprayList.Selected[i] then InfoHandler.DeleteFullSpray(ChangeFileExt(ExistingSprayList.Items.Strings[i],''), GameComboBox.ItemIndex); ExistingSprayList.DeleteSelected; end; end; procedure TMain.DeleteSprayBtnClick(Sender: TObject); begin DeleteSpray; end; procedure TMain.AddSpraysBtnClick(Sender: TObject); var i: NativeInt; begin if SprayImportDlg.Execute then for i := 0 to SprayImportDlg.Files.Count - 1 do AddSprayToImportList(SprayImportDlg.Files.Strings[i]); end; procedure TMain.AddSprayToImportList(const FileName: string); begin if FileExists(FileName) and VTFValidate(FileName) and (ImportSpraysList.Items.IndexOf(FileName) = -1) then ImportSpraysList.Items.Add(FileName); ImportBtnsDisablerEnabler; end; procedure TMain.AboutBtnClick(Sender: TObject); begin ShowAboutForm; end; procedure TMain.RemoveSpraysBtnClick(Sender: TObject); begin RemoveSpraysFromImportList; end; procedure TMain.RemoveSpraysFromImportList; begin ImportSpraysList.DeleteSelected; ImportBtnsDisablerEnabler; end; function TMain.VTFValidate(const FileName: string): Boolean; var VTFFile: File; TestVar: Cardinal; begin FileMode := fmOpenRead; AssignFile(VTFFile,FileName); Reset(VTFFile,4); if not eof(VTFFile) then BlockRead(VTFFile,TestVar,1) else TestVar := 0; CloseFile(VTFFile); Result := (TestVar = VTF_MAGIC); end; procedure TMain.WMDROPFILES(var msg: TWMDropFiles) ; const MAXFILENAME = 4095; var cnt, fileCount : integer; fileName : array [0..MAXFILENAME] of char; begin // how many files dropped? fileCount := DragQueryFile(msg.Drop, $FFFFFFFF, fileName, MAXFILENAME) ; // query for file names for cnt := 0 to -1 + fileCount do begin DragQueryFile(msg.Drop, cnt, fileName, MAXFILENAME) ; AddSprayToImportList(fileName); end; //release memory DragFinish(msg.Drop); end; function TMain.ImportSpray(index: NativeInt; var ErrorStruct: TSprayErrorTypeCount): NativeInt; begin if StatusFrm = nil then StatusFrm := TStatusFrm.Create(Self); Result := InfoHandler.ExportFullSpray(ImportSpraysList.Items.Strings[index],GameComboBox.ItemIndex); if Result = SFH_EC_SUCCESS then begin Inc(ErrorStruct.Successes); StatusFrm.StatusMemo.Lines.Append(Format('%s: import successful!',[ImportSpraysList.Items.Strings[index]])); end else if Result = SFH_EC_GAME_NOT_INSTALLED then begin Inc(ErrorStruct.GameNotInstalled); StatusFrm.StatusMemo.Lines.Append(Format('(!) %s: game not installed',[ImportSpraysList.Items.Strings[index]])); end else if Result = SFH_EC_SPRAY_TOO_LARGE then begin Inc(ErrorStruct.SprayTooLarge); StatusFrm.StatusMemo.Lines.Append(Format('(!) %s: spray too large',[ImportSpraysList.Items.Strings[index]])); end else if Result = SFH_EC_INVALID_VTF_FILE then begin Inc(ErrorStruct.InvalidVTFFile); StatusFrm.StatusMemo.Lines.Append(Format('(!) %s: invalid VTF file',[ImportSpraysList.Items.Strings[index]])); end else if Result = SFH_EC_IO_ERROR then begin Inc(ErrorStruct.IOError); StatusFrm.StatusMemo.Lines.Append(Format('(!) %s: I/O error',[ImportSpraysList.Items.Strings[index]])); end; end; procedure TMain.ImportSpraysListClick(Sender: TObject); begin ImportBtnsDisablerEnabler; end; procedure TMain.ImportSpraysListKeyPress(Sender: TObject; var Key: Char); begin ImportBtnsDisablerEnabler; end; procedure TMain.ImportSelBtnClick(Sender: TObject); begin ImportSelectedSprays; end; procedure TMain.ImportSelectedSprays; var Errors: TSprayErrorTypeCount; i: NativeInt; begin // initialize error counts Errors.Successes := 0; Errors.GameNotInstalled := 0; Errors.SprayTooLarge := 0; Errors.InvalidVTFFile := 0; Errors.IOError := 0; // clear status window if it exists if StatusFrm <> nil then StatusFrm.StatusMemo.Clear; // Go! for i := 0 to ImportSpraysList.Count - 1 do begin if ImportSpraysList.Selected[i] then begin ImportSpray(i,Errors); end; end; // Update status label SprayStatusUpdate(Errors); end; procedure TMain.ImportAllBtnClick(Sender: TObject); begin ImportAllSprays; end; procedure TMain.ImportAllSprays; var Errors: TSprayErrorTypeCount; i: NativeInt; begin // initialize error counts Errors.Successes := 0; Errors.GameNotInstalled := 0; Errors.SprayTooLarge := 0; Errors.InvalidVTFFile := 0; Errors.IOError := 0; // clear status window if it exists if StatusFrm <> nil then StatusFrm.StatusMemo.Clear; // Go! for i := 0 to ImportSpraysList.Count - 1 do begin ImportSpray(i,Errors); end; // Update status label SprayStatusUpdate(Errors); end; procedure TMain.SprayStatusUpdate(const ErrorStruct: TSprayErrorTypeCount); begin if ErrorStruct.Successes = 0 then begin GameStatusLbl.Color := $000000FF; GameStatusLbl.Font.Color := $00FFFFFF; GameStatusLbl.Caption := 'No successful spray imports. Details in status window.'; if StatusFrm <> nil then StatusFrm.Show; end else if (ErrorStruct.GameNotInstalled > 0) or (ErrorStruct.SprayTooLarge > 0) or (ErrorStruct.InvalidVTFFile > 0) or (ErrorStruct.IOError > 0) then begin GameStatusLbl.Color := $0000FFFF; GameStatusLbl.Font.Color := $00000000; GameStatusLbl.Caption := 'Some sprays did not import properly. Details in status window.'; ExistingSprayList.Clear; ExistingSpraysListPopulate(InfoHandler.GetMainSprayPath(GameComboBox.ItemIndex)); if StatusFrm <> nil then StatusFrm.Show; end else begin GameStatusLbl.Color := $0000FF00; GameStatusLbl.Font.Color := $00000000; GameStatusLbl.Caption := 'All sprays were imported successfully!'; FreeAndNil(StatusFrm); ExistingSprayList.Clear; ExistingSpraysListPopulate(InfoHandler.GetMainSprayPath(GameComboBox.ItemIndex)); end; end; function TMain.SelectGameDirectory(index: NativeInt): Boolean; var DSCaption,Dir: string; HintFrm: TGameFolderHintFrm; begin HintFrm := TGameFolderHintFrm.Create(Self); HintFrm.Show; DSCaption := Format('Game Directory for %s',[InfoHandler.GetGameShortName(index)]); if SelectDirectory(DSCaption,'',Dir,[],Self) then begin Dir := IncludeTrailingPathDelimiter(Dir); Result := InfoHandler.SetGamePath(index,Dir); if Result then begin GameBoxChangeStatus; GameStatusLbl.Caption := Format('Game install path changed to %s',[Dir]); GameStatusLbl.Color := $00FF0000; GameStatusLbl.Font.Color := $00FFFFFF; end else begin GameStatusLbl.Caption := Format('Invalid directory. Game install path not changed.',[Dir]); GameStatusLbl.Color := $00800000; GameStatusLbl.Font.Color := $00FFFFFF; end; end else begin Result := false; end; HintFrm.Free; end; procedure TMain.ClearGameDirectory(index: NativeInt); begin InfoHandler.ClearGamePath(index); GameBoxChangeStatus; GameStatusLbl.Caption := 'Game install path information cleared from application. Select a different path or restart application to rescan.'; GameStatusLbl.Color := $00808080; GameStatusLbl.Font.Color := $00FFFFFF; end; procedure TMain.ClearGamePathBtnClick(Sender: TObject); begin ClearGameDirectory(GamecomboBox.ItemIndex); end; procedure TMain.ShowAboutForm; var AboutForm: TAboutFrm; begin AboutForm := TAboutFrm.Create(Self); AboutForm.ShowModal; AboutForm.Free; end; end.
{*******************************************************} { } { Delphi FireMonkey Mobile Services } { } { Description of interfaces for operation with } { media storage (Audios, Videos, Images) } { } { Copyright(c) 2012-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.MediaLibrary; interface uses System.Types, FMX.Types, FMX.Controls, FMX.Graphics, FMX.Messages; type IFMXImageManagerService = interface; IFMXTakenImageService = interface; IFMXCameraService = interface; IFMXAudioManagerService = interface; IFMXTakenAudioService = interface; IFMXVideoManagerService = interface; {$REGION 'Image manager services'} TImageOrientation = (ioUp, ioRight, ioDown, ioLeft); { Geographical coordinates of a place of a picture } TLocationInfo = record Latitude: Double; Longitude: Double; end; { Representation of Image with meta information } TImageInfo = class abstract public // Image context function Bitmap: TBitmap; virtual; abstract; // Date of shooting of the photo function DateTaken: TDateTime; virtual; abstract; // Camera orientation at the moment of photo shooting function Orientation: TImageOrientation; virtual; abstract; // Geographical coordinates of a place of a picture function LocationInfo: TLocationInfo; virtual; abstract; end; TImages = array of TImageInfo; { Interface of images manager } IFMXImageManagerService = interface (IInterface) ['{F06A5B8F-D4BC-4A0D-AD91-BF49208861E4}'] // Returns the image on an index function GetImage(const Index: Integer): TImageInfo; // Returns all images from mobile store function GetAllImages: TImages; // Returns count of all images from mobile store function GetCount: Integer; // Insert image into mobile store procedure InsertImage(const Bitmap: TBitmap); end; TOnDidCancelTaking = procedure of object; TOnDidFinishTaking = procedure (Image: TBitmap) of object; TMessageDidCancelTaking = class (TMessage); TMessageDidFinishTakingImageFromCamera = class (TMessage<TBitmap>); TMessageDidFinishTakingImageFromLibrary = class (TMessage<TBitmap>); { Pick image from Photo Library. Call native UI picker } IFMXTakenImageService = interface (IInterface) ['{5DADF207-B6CE-4C3A-9E0F-C45B39128DA5}'] procedure TakeImageFromLibrary(const AControl: TControl; const ARequiredResolution: TSize; const AOnDidDinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking); end; { Get photo from device's camera } IFMXCameraService = interface (IInterface) ['{6779963D-633A-4ED0-80C8-C71AB4E26D91}'] procedure TakePhoto(const AControl: TControl; const ARequiredResolution: TSize; const AOnDidDinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking); end; {$ENDREGION} {$REGION 'Audio manager services'} { Common class represents video or audio information } TMediaInfo = class (TObject); TPlayList = array of TMediaInfo; { Representation of audio information } TAudioInfo = class abstract (TMediaInfo) public function Title: string; virtual; abstract; function Artist: string; virtual; abstract; function AlbumTitle: string; virtual; abstract; function AlbumArtist: string; virtual; abstract; function Genre: string; virtual; abstract; function Composer: string; virtual; abstract; function Duration: TTime; virtual; abstract; function AlbumTrackNumber: Cardinal; virtual; abstract; function DiscNumber: Cardinal; virtual; abstract; function Lyrics: string; virtual; abstract; function DiscCover: TBitmap; virtual; abstract; end; TAudios = array of TAudioInfo; { Representation of album information } TAlbum = class abstract public function Title: string; virtual; abstract; function Artist: string; virtual; abstract; function NumberOfSongs: Cardinal; virtual; abstract; function Cover: TBitmap; virtual; abstract; end; TAlbums = array of TAlbum; { Representation of artist information } TArtist = class abstract public function Artist: string; virtual; abstract; function NumberOfSongs: Integer; virtual; abstract; end; TArtists = array of TArtist; { Representation of genre information } TGenre = class abstract public function Genre: string; virtual; abstract; function CountSongs: Cardinal; virtual; abstract; end; TGenres = array of TGenre; { Interface of audio manager } IFMXAudioManagerService = interface (IInterface) ['{E2D6C4F8-F365-4E24-A461-C48288E4C710}'] function GetAudio(const Index: Integer): TAudioInfo; function GetAudios: TAudios; overload; function GetAudios(const Album: TAlbum): TAudios; overload; function GetAudios(const Artist: TArtist): TAudios; overload; function GetAudios(const Genre: TGenre): TAudios; overload; function GetAlbums: TAlbums; function GetArtists: TArtists; function GetGenres: TGenres; end; { Pick image from iPod Library. Uses native UI picker } IFMXTakenAudioService = interface (IInterface) ['{7114C6A2-2A2A-4CDA-AB63-291C7C8D440E}'] function GetAudioFromLibrary: TAudios; end; {$ENDREGION} {$REGION 'Video manager services'} { Representation of video information } TVideoInfo = class abstract(TMediaInfo) public function Title: string; virtual; abstract; function AlbumTitle: string; virtual; abstract; function Artist: string; virtual; abstract; function Duration: TTime; virtual; abstract; function Resolution: TSize; virtual; abstract; function Thumb: TBitmap; virtual; abstract; end; TVideos = array of TVideoInfo; { Interface of video manager } IFMXVideoManagerService = interface (IInterface) ['{C61ECA12-EF39-4FAF-A301-B8BA43F425BD}'] function GetVideoFromLibrary: TVideos; function GetVideo(const Index: Integer): TVideoInfo; function GetAllVideos: TVideos; end; {$ENDREGION} {$REGION 'Share Text and Image with other native services'} IFMXShareSheetActionsService = interface (IInterface) ['{79FCC7B1-C5BF-4533-B31E-084F1A6E2264}'] procedure Share(const AControl: TControl; const AText: string; const AImage: TBitmap); end; {$ENDREGION} implementation {$IFDEF IOS} uses FMX.MediaLibrary.iOS; {$ENDIF} {$IFDEF ANDROID} uses FMX.MediaLibrary.Android; {$ENDIF} initialization {$IF Defined(IOS) OR Defined(ANDROID)} RegisterMediaLibraryServices; {$ENDIF} end.
unit UtilsDateTime; interface function SeasonOfMonth(AMonth: Word): Word; function IsCurrentSeason(ADate: TDateTime): Boolean; implementation uses SysUtils; function SeasonOfMonth(AMonth: Word): Word; begin Result := ((AMonth - 1) div 3) + 1; end; function IsCurrentSeason(ADate: TDateTime): Boolean; var tmpYear1, tmpMonth1, tmpYear2, tmpMonth2, tmpDay: Word; begin DecodeDate(ADate, tmpYear1, tmpMonth1, tmpDay); DecodeDate(now, tmpYear2, tmpMonth2, tmpDay); Result := (tmpYear1 = tmpYear2) and (SeasonOfMonth(tmpMonth1) = SeasonOfMonth(tmpMonth2)); end; end.
(* ENUNCIADO Fazer um programa em Free Pascal que leia seis números (a11, a12, b1, a21, a22, b2) e imprima uma solução para o sistema de equações lineares abaixo: a11 x + a12 y = b1 a21 x + a22 y = b2 O método de cálculo do sistema é indiferente, desde que o resolva independente dos valores informados. Veja um exemplo de execução incluindo entrada e saída: Exemplo de entrada: 2.0 1.0 11.0 5.0 7.0 13.0 Saída esperada para a entrada acima: x = 7.111 y = -3.222 *) program 5equacoeslineares; var a11, a12, b1, a21, a22, b2: real; x, y: real; begin read(a11); read(a12); read(b1); read(a21); read(a22); read(b2); x := ((b2 * a12) - (a22 * b1)) / ((a21 * a12) - (a11 * a22)); y := (b1 - a11 * x) / a12; writeln('x = ', x:0:3); writeln('y = ', y:0:3); end.
(* FLAC (Free Lossless Audio Codec) components This file is a part of Audio Components Suite. All rights reserved. See the license file for more details. Copyright (c) 2002-2010, Andrei Borovsky, anb@symmetrica.net Copyright (c) 2005-2006 Christian Ulrich, mail@z0m3ie.de Copyright (c) 2014-2015 Sergey Bodrov, serbod@gmail.com *) { Status: TFLACOut - not tested TFLACIn - OK Some problems in record packing/alignment for FLAC__StreamMetadata and it's members tested for Win32 } unit acs_flac; (* Title: ACS_FLAC NewAC interface to libFLAC.dll *) interface uses Classes, SysUtils, {FastMove,} ACS_Types, ACS_Classes, ACS_Tags, flac , ACS_File, acs_strings {$IFDEF LINUX} , baseunix {$ENDIF} {$IFDEF WIN32} , Windows {$ENDIF} ; type (* Class: TFLACOut FLAC encoder component. Descends from <TAcsCustomFileOut>. Requires libFLAC.dll More information about FLAC can be found at http://flac.sourceforge.com. *) TFLACOut = class(TAcsCustomFileOut) private Buffer: PAcsBuffer8; FBufSize: Integer; _encoder: P_FLAC__StreamEncoder; FVerify: Boolean; FBlockSize: Word; FBestModelSearch: Boolean; FEnableMidSideStereo: Boolean; FMaxLPCOrder: Word; EndOfInput: Boolean; FEnableLooseMidSideStereo: Boolean; FQLPCoeffPrecision: Word; FQLPCoeffPrecisionSearch: Boolean; FMaxResidualPartitionOrder: Word; FMinResidualPartitionOrder: Word; FCompressionLevel: Integer; BolckInserted: Boolean; FTags: TVorbisTags; procedure SetEnableLooseMidSideStereo(val: Boolean); procedure SetBestModelSearch(val: Boolean); procedure SetCompressionLevel(val: Integer); procedure SetTags(AValue: TVorbisTags); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init(); override; procedure Done(); override; function DoOutput(Abort: Boolean): Boolean; override; published (* Property: BestModelSearch Similar to America's Next Top Model, except for algorithms. *) property BestModelSearch: Boolean read FBestModelSearch write SetBestModelSearch; (* Property: Blocksize The size you want some blocks to be. Has nothing to do with <BestModelSearch> *) property BlockSize: Word read FBlockSize write FBlockSize; (* Property: CompressionLevel What level you want your compression at. *) property CompressionLevel: Integer read FCompressionLevel write SetCompressionLevel; (* Property: EnableMidSideStereo Set this property to True to get a bit more compression. *) property EnableMidSideStereo: Boolean read FEnableMidSideStereo write FEnableMidSideStereo; property EnableLooseMidSideStereo: Boolean read FEnableLooseMidSideStereo write SetEnableLooseMidSideStereo; property MaxLPCOrder: Word read FMaxLPCOrder write FMaxLPCOrder; property MaxResidualPartitionOrder: Word read FMaxResidualPartitionOrder write FMaxResidualPartitionOrder; property MinResidualPartitionOrder: Word read FMinResidualPartitionOrder write FMinResidualPartitionOrder; property QLPCoeffPrecision: Word read FQLPCoeffPrecision write FQLPCoeffPrecision; property QLPCoeffPrecisionSearch: Boolean read FQLPCoeffPrecisionSearch write FQLPCoeffPrecisionSearch; (* Property: Tags Use this property to add a set of Vorbis-style comments (artist, title, etc.) to the output file. *) property Tags: TVorbisTags read FTags write SetTags; (* Property: Verify Setting Verify to True forces the FLAC encoder to verify its own output. It slows down encoding process and usually unnecessary. *) property Verify: Boolean read FVerify write FVerify; end; (* Class: TFLACIn FLAC decoder component. Descends from <TAuFileIn>. Requires libFLAC.dll More information about FLAC can be found at http://flac.sourceforge.com. *) { TFLACIn } TFLACIn = class(TAcsCustomFileIn) private EndOfMetadata: Boolean; FComments: TVorbisTags; Residue: Integer; //Buff: PAcsBuffer8; //BuffSize: LongWord; _decoder: P_FLAC__StreamDecoder; FBlockSize: LongWord; BytesPerBlock: LongWord; MinFrameSize: LongWord; FCheckMD5Signature: Boolean; FSignatureValid: Boolean; FSampleSize: Integer; function GetComments: TVorbisTags; protected procedure OpenFile(); override; procedure CloseFile(); override; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; function GetData(ABuffer: Pointer; ABufferSize: Integer): Integer; override; function Seek(SampleNum: Integer): Boolean; override; (* Property: IsMD5SignatureValid If MD5 signature checking is turned on, this property returns True if the signature is correct (i.e. file contents is not broken). This property value becomes meaningful only after the file has finished playing. Note that if FLAC codec cannot check the signature for some internal reason, this property still returns True.*) property IsMD5SignatureValid: Boolean read FSignatureValid; (* Property: VorbisComments Read this property to get tags (artist, title, etc.) that may be attached to the file.*) property VorbisComments: TVorbisTags read GetComments; published (* Property: CheckMD5Signature This property specifies whether the input file's MD5 signature should be checked. The MD5 signature checking should be turned on before the file starts playing. If you set this property to True, you can use <IsMD5SignatureValid> value to check the signature after file has finished playing. Note, that seeking in the input file turns the signature checking off (the value of CheckMD5Signature becomes False). In this case <IsMD5SignatureValid> will aalways return True.*) property CheckMD5Signature: Boolean read FCheckMD5Signature write FCheckMD5Signature; property EndSample; property StartSample; end; implementation type FLACBuf = array[0..0] of FLAC__int32; PFLACBuf = ^FLACBuf; FLACUBuf = array[0..0] of FLAC__uint32; PFLACUBuf = ^FLACBuf; type TBlockInfo = record BlockType: Word; BlockLength: LongWord; HasNext: Boolean; end; TVComments = record Vendor: Utf8String; Title: Utf8String; Artist: Utf8String; Album: Utf8String; Date: Utf8String; Genre: Utf8String; Track: Utf8String; Disc: Utf8String; Reference: Utf8String; TrackGain: Utf8String; TrackPeak: Utf8String; AlbumGain: Utf8String; AlbumPeak: Utf8String; end; function BuildCommentsBlock(var Comments: TVComments; var Block: Pointer; HasNext: Boolean): Integer; var BS: Integer; Header: array[0..4] of Byte; t: byte; P: PAnsiChar; i, StrCount: Integer; procedure AddString(const Str: Utf8String); var l: Integer; begin l:=Length(Str); Move(l, P[i], 4); Inc(i, 4); Move(Str[1], P[i], l); Inc(i, l); end; begin BS:=4; StrCount:=0; Comments.Vendor:=Utf8Encode('VENDOR=Hacked'); Inc(BS, Length(Comments.Vendor) + 4); if Comments.Title <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.Title) + 4); end; if Comments.Artist <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.Artist) + 4); end; if Comments.Album <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.Album) + 4); end; if Comments.Date <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.Date) + 4); end; if Comments.Genre <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.Genre) + 4); end; if Comments.Track <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.Track) + 4); end; if Comments.Disc <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.Disc) + 4); end; if Comments.Reference <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.Reference) + 4); end; if Comments.TrackGain <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.TrackGain) + 4); end; if Comments.TrackPeak <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.TrackPeak) + 4); end; if Comments.AlbumGain <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.AlbumGain) + 4); end; if Comments.AlbumPeak <> '' then begin Inc(StrCount); Inc(BS, Length(Comments.AlbumPeak) + 4); end; Header[0]:=Ord(FLAC__METADATA_TYPE_VORBIS_COMMENT); if not HasNext then Inc(Header[0], 128); Move(BS, Header[1], 3); t:=Header[3]; Header[3]:=Header[1]; Header[1]:=t; Result:=BS + 4; GetMem(Block, Result); P:=PAnsiChar(Block); Move(Header[0], P[0], 4); i:=4; AddString(Comments.Vendor); Move(StrCount, P[i], 4); Inc(i, 4); if Comments.Title <> '' then AddString(Comments.Title); if Comments.Artist <> '' then AddString(Comments.Artist); if Comments.Album <> '' then AddString(Comments.Album); if Comments.Date <> '' then AddString(Comments.Date); if Comments.Genre <> '' then AddString(Comments.Genre); if Comments.Track <> '' then AddString(Comments.Track); if Comments.Disc <> '' then AddString(Comments.Disc); if Comments.Reference <> '' then AddString(Comments.Reference); if Comments.TrackGain <> '' then AddString(Comments.TrackGain); if Comments.TrackPeak <> '' then AddString(Comments.TrackPeak); if Comments.AlbumGain <> '' then AddString(Comments.AlbumGain); if Comments.AlbumPeak <> '' then AddString(Comments.AlbumPeak); end; function EncWriteCBFunc(encoder: P_FLAC__StreamEncoder; buffer: PFLAC__byte; bytes, samples, current_frame: LongWord; client_data: Pointer): Integer; cdecl; var FLACOut: TFLACOut; BI: TBlockInfo; Header: array[0..3] of Byte; Comm: TVComments; Block: Pointer; bresult: LongInt; begin FLACOut:=TFLACOut(client_data); Result:=FLAC__STREAM_ENCODER_WRITE_STATUS_OK; try if not FLACOut.BolckInserted then begin Move(buffer^, Header, 4); BI.HasNext:=(Header[0] shr 7) = 0; BI.BlockType:=Header[0] mod 128; if (BI.BlockType = Ord(FLAC__METADATA_TYPE_VORBIS_COMMENT)) then begin FLACOut.BolckInserted:=True; if FlacOut.FTags.Artist <> '' then Comm.Artist:=Utf8Encode(WideString(_vorbis_Artist + '=') + FlacOut.FTags.Artist); if FlacOut.FTags.Album <> '' then Comm.Album:=Utf8Encode(WideString(_vorbis_Album + '=') + FlacOut.FTags.Album); if FlacOut.FTags.Title <> '' then Comm.Title:=Utf8Encode(WideString(_vorbis_Title + '=') + FlacOut.FTags.Title); if FlacOut.FTags.Date <> '' then Comm.Date:=Utf8Encode(WideString(_vorbis_Date + '=') + FlacOut.FTags.Date); if FlacOut.FTags.Genre <> '' then Comm.Genre:=Utf8Encode(WideString(_vorbis_Genre + '=') + FlacOut.FTags.Genre); if FlacOut.FTags.Track <> '' then Comm.Track:=Utf8Encode(WideString(_vorbis_Track + '=') + FlacOut.FTags.Track); if FlacOut.FTags.Disc <> '' then Comm.Disc:=Utf8Encode(WideString(_vorbis_Disc + '=') + FlacOut.FTags.Disc); if FlacOut.FTags.Reference <> '' then Comm.Reference:=Utf8Encode(WideString(_vorbis_Reference + '=') + FlacOut.FTags.Reference); if FlacOut.FTags.TrackGain <> '' then Comm.TrackGain:=Utf8Encode(WideString(_vorbis_TrackGain + '=') + FlacOut.FTags.TrackGain); if FlacOut.FTags.TrackPeak <> '' then Comm.TrackPeak:=Utf8Encode(WideString(_vorbis_TrackPeak + '=') + FlacOut.FTags.TrackPeak); if FlacOut.FTags.AlbumGain <> '' then Comm.AlbumGain:=Utf8Encode(WideString(_vorbis_AlbumGain + '=') + FlacOut.FTags.AlbumGain); if FlacOut.FTags.AlbumPeak <> '' then Comm.AlbumPeak:=Utf8Encode(WideString(_vorbis_AlbumPeak + '=') + FlacOut.FTags.AlbumPeak); bytes:=BuildCommentsBlock(Comm, Block, BI.HasNext); bresult:=FLACOut.FStream.Write(Block^, bytes); FreeMem(Block); end else bresult:=FLACOut.FStream.Write(buffer^, bytes); end else bresult:=FLACOut.FStream.Write(buffer^, bytes); if bresult <> Integer(bytes) then Result:=FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; except Result:=FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; end; end; function EncSeekCBFunc(encoder: P_FLAC__StreamEncoder; absolute_byte_offset: FLAC__uint64; client_data: Pointer): Integer; cdecl; var FLACOut: TFLACOut; begin FLACOut:=TFLACOut(client_data); Result:=FLAC__STREAM_ENCODER_SEEK_STATUS_OK; try FLACOut.FStream.Seek(absolute_byte_offset, soFromBeginning); except Result:=FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR; end; end; function EncTellCBFunc(decoder: P_FLAC__StreamDecoder; var absolute_byte_offset: FLAC__uint64; client_data: Pointer): Integer; cdecl; var FLACOut: TFLACOut; begin FLACOut:=TFLACOut(client_data); absolute_byte_offset:=FLACOut.Stream.Position; Result:=FLAC__STREAM_ENCODER_TELL_STATUS_OK; end; procedure EncMetadataCBFunc(decoder: P_FLAC__StreamDecoder; metadata: Pointer; client_data: Pointer); cdecl; begin // Nothing to do here end; function DecReadCBFunc(decoder: P_FLAC__StreamDecoder; buffer: PFLAC__byte; var bytes: LongWord; client_data: Pointer): Integer; cdecl; var FLACIn: TFLACIn; begin FLACIn:=TFLACIn(client_data); Result:=FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; if FLACIn.FStream.Position >= FLACIn.FStream.Size then begin Result:=FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; Exit; end; try bytes:=FLACIn.FStream.Read(buffer^, bytes); if bytes = 0 then Result:=FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; except Result:=FLAC__STREAM_DECODER_READ_STATUS_ABORT; end; end; function DecSeekCBFunc(decoder: P_FLAC__StreamDecoder; absolute_byte_offset: FLAC__uint64; client_data: Pointer): Integer; cdecl; var FLACIn: TFLACIn; begin FLACIn:=TFLACIn(client_data); if not FLACIn.FSeekable then begin Result:=FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED; Exit; end; Result:=FLAC__STREAM_DECODER_SEEK_STATUS_OK; try FLACIn.FStream.Seek(absolute_byte_offset, soFromBeginning); if absolute_byte_offset > FlacIn.FSize then Result:=FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; except Result:=FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; end; end; function DecTellCBFunc(decoder: P_FLAC__StreamDecoder; var absolute_byte_offset: FLAC__uint64; client_data: Pointer): Integer; cdecl; var FLACIn: TFLACIn; begin FLACIn:=TFLACIn(client_data); if FLACIn.FSize = 0 then begin Result:=FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED; Exit; end; Result:=FLAC__STREAM_DECODER_TELL_STATUS_OK; try absolute_byte_offset:=FLACIn.FStream.Position; except Result:=FLAC__STREAM_DECODER_TELL_STATUS_ERROR; end; end; function DecLengthCBFunc(decoder: P_FLAC__StreamDecoder; var stream_length: FLAC__uint64; client_data: Pointer): Integer; cdecl; var FLACIn: TFLACIn; begin FLACIn:=TFLACIn(client_data); Result:=FLAC__STREAM_DECODER_LENGTH_STATUS_OK; try stream_length:=FLACIn.FStream.Size; except Result:=FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; end; end; function DecEOFCBFunc(decoder: P_FLAC__StreamDecoder; client_data: Pointer): LongBool; cdecl; var FLACIn: TFLACIn; begin FLACIn:=TFLACIn(client_data); Result:=(FLACIn.FStream.Position >= FLACIn.FStream.Size); end; function DecWriteCBFunc(decoder: P_FLAC__StreamDecoder; frame: PFLAC__Frame; buffer: PFLACInt32BufArray; client_data: Pointer): Integer; cdecl; var FLACIn: TFLACIn; Header: PFLAC__FrameHeader; i, ii, j: LongWord; begin FLACIn:=TFLACIn(client_data); Header:=PFLAC__FrameHeader(frame); FLACIn.FBlockSize:=Header.blocksize; FLACIn.BytesPerBlock:=FLACIn.FBlockSize * (FLACIn.FBPS div 8) * FLACIn.FChan; if FLACIn.FAudioBuffer.Size < FLACIn.BytesPerBlock then FLACIn.FAudioBuffer.Size:=FLACIn.BytesPerBlock; if FLACIn.FAudioBuffer.Interleaved then begin {$R-} for i:=0 to FLACIn.FBlockSize-1 do begin for j:=0 to FLACIn.FChan-1 do begin ii:=((i * FLACIn.FChan) + j) * (FLACIn.FBPS div 8); if FLACIn.FBPS = 8 then pUInt8(FLACIn.FAudioBuffer.Memory + ii)^:=UInt8(buffer[j][i]) else if FLACIn.FBPS = 16 then pUInt16(FLACIn.FAudioBuffer.Memory + ii)^:=UInt16(buffer[j][i]) else if FLACIn.FBPS = 24 then begin pUInt8(FLACIn.FAudioBuffer.Memory + ii + 0)^:=UInt8( UInt32(buffer[j][i]) AND $000000FF); pUInt8(FLACIn.FAudioBuffer.Memory + ii + 1)^:=UInt8((UInt32(buffer[j][i]) AND $0000FF00) shr 8); pUInt8(FLACIn.FAudioBuffer.Memory + ii + 2)^:=UInt8((UInt32(buffer[j][i]) AND $00FF0000) shr 16); end; end; end; {$R-} // manually move WritePosition FLACIn.FAudioBuffer.WritePosition:=FLACIn.BytesPerBlock; end else // if not FLACIn.FAudioBuffer.Interleaved then begin end; Result:=FLAC__STREAM_ENCODER_OK; end; function Utf8ToWideStr(s: AnsiString): WideString; begin {$ifdef FPC} Result:=UTF8Decode(s); {$else} {$WARNINGS OFF} {$IF CompilerVersion < 20} Result:=Utf8Decode(s); {$IFEND} {$IF CompilerVersion >= 20} Result:=Utf8ToString(s); {$IFEND} {$WARNINGS ON} {$endif FPC} end; procedure DecMetadataCBProc(decoder: P_FLAC__StreamDecoder; metadata: PFLAC__StreamMetadata; client_data: Pointer); cdecl; var FLACIn: TFLACIn; FI: FLAC__StreamMetadata_StreamInfo; i: Integer; S: AnsiString; Entry: PFLAC__StreamMetadata_VorbisComment_Entry; SL: TStringList; begin FLACIn:=TFLACIn(client_data); if metadata._type = FLAC__METADATA_TYPE_STREAMINFO then begin //LongWord(metadata):=LongWord(metadata) + 4; FI:=metadata.stream_info; FLACIn.FSR:=FI.sample_rate; FLACIn.FChan:=FI.channels; //if FLACIn.FChan > 2 then FLACIn.FValid:=False; FLACIn.FBPS:=FI.bits_per_sample; FLACIn.FTotalSamples:=FI.total_samples; FLACIn.FSize:=FLACIn.FTotalSamples * (FLACIn.FBPS div 8) * FLACIn.FChan; FLACIn.MinFrameSize:=FI.min_framesize; if FLACIn.FSR <> 0 then FLACIn.FTotalTime:=FLACIn.FTotalSamples / FLACIn.FSR; end; if metadata._type = FLAC__METADATA_TYPE_VORBIS_COMMENT then begin SL:=TStringList.Create(); Entry:=metadata.vorbis_comment.comments; for i:=0 to metadata.vorbis_comment.num_comments - 1 do begin SetLength(S, Entry.length); Move(Entry.entry^, S[1], Length(S)); SL.Add(String(S)); Inc(PtrUInt(Entry), SizeOf(FLAC__StreamMetadata_VorbisComment_Entry)); end; FLACIn.FComments.Title:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Title)]); FLACIn.FComments.Artist:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Artist)]); FLACIn.FComments.Album:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Album)]); FLACIn.FComments.Date:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Date)]); FLACIn.FComments.Genre:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Genre)]); FLACIn.FComments.Track:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Track)]); FLACIn.FComments.Disc:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Disc)]); FLACIn.FComments.Reference:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Reference)]); FLACIn.FComments.TrackGain:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_TrackGain)]); FLACIn.FComments.TrackPeak:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_TrackPeak)]); FLACIn.FComments.AlbumGain:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_AlbumGain)]); FLACIn.FComments.AlbumPeak:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_AlbumPeak)]); FLACIn.FComments.Artist:=Utf8ToWideStr(SL.Values[AnsiUpperCase(_vorbis_Title)]); SL.Free; end; FLacIn.EndOfMetadata:=metadata.is_last; end; procedure DecErrorCBProc(decoder: P_FLAC__StreamDecoder; status: Integer; client_data: Pointer); cdecl; var FLACIn: TFLACIn; begin FLACIn:=TFLACIn(client_data); FLACIn.FValid:=False; end; constructor TFLACOut.Create(AOwner: TComponent); begin inherited Create(AOwner); FVerify:=False; FBlockSize:=4608; FBestModelSearch:=False; FEnableMidSideStereo:=True; FCompressionLevel:=-1; FTags:=TVorbisTags.Create; end; destructor TFLACOut.Destroy(); begin FTags.Free; inherited Destroy; end; procedure TFLACOut.Init(); begin if not LibFLACLoaded then raise EAcsException.Create(LibFLACPath + ' library could not be loaded.'); if not Assigned(FStream) then begin if FFileName = '' then raise EAcsException.Create('File name is not assigned.'); if (not FileExists(FFileName)) or (FFileMode = foRewrite) then FStream:=TFileStream.Create(FFileName, fmCreate, FAccessMask) else FStream:=TFileStream.Create(FFileName, fmOpenReadWrite, FAccessMask); end; EndOfInput:=False; BolckInserted:=False; _encoder:=FLAC__stream_encoder_new(); if not Assigned(_encoder) then raise EAcsException.Create('Failed to initialize FLAC encoder.'); FInput.Init(); FLAC__stream_encoder_set_verify(_encoder, FVerify); FLAC__stream_encoder_set_channels(_encoder, FInput.Channels); FLAC__stream_encoder_set_bits_per_sample(_encoder, FInput.BitsPerSample); FLAC__stream_encoder_set_sample_rate(_encoder, FInput.SampleRate); if FInput.Channels = 2 then begin FLAC__stream_encoder_set_do_mid_side_stereo(_encoder, FEnableMidSideStereo); FLAC__stream_encoder_set_loose_mid_side_stereo(_encoder, FEnableLooseMidSideStereo); end; FLAC__stream_encoder_set_blocksize(_encoder, FBlockSize); if FCompressionLevel >= 0 then FLAC__stream_encoder_set_compression_level(_encoder, FCompressionLevel) else begin FLAC__stream_encoder_set_max_lpc_order(_encoder, FMaxLPCOrder); if FQLPCoeffPrecision + FInput.BitsPerSample > 31 then FQLPCoeffPrecision:=31 - FInput.BitsPerSample; FLAC__stream_encoder_set_qlp_coeff_precision(_encoder, FQLPCoeffPrecision); FLAC__stream_encoder_set_do_qlp_coeff_prec_search(_encoder, FQLPCoeffPrecisionSearch); FLAC__stream_encoder_set_min_residual_partition_order(_encoder, FMinResidualPartitionOrder); FLAC__stream_encoder_set_max_residual_partition_order(_encoder, FMaxResidualPartitionOrder); FLAC__stream_encoder_set_do_exhaustive_model_search(_encoder, FBestModelSearch); end; //if FInput.Size > 0 then // FLAC__stream_encoder_set_total_samples_estimate(_encoder, Round(FInput.Size/(FInput.BitsPerSample shr 3)/FInput.Channels)); //FLAC__stream_encoder_set_seek_callback(_encoder, EncSeekCBFunc); //FLAC__stream_encoder_set_write_callback(_encoder, EncWriteCBFunc); //FLAC__seekable_stream_encoder_set_client_data(_encoder, Self); if FLAC__stream_encoder_init_stream(_encoder, EncWriteCBFunc, EncSeekCBFunc, EncTellCBFunc, EncMetadataCBFunc, Self) <> FLAC__STREAM_ENCODER_OK then begin FInput.Done(); raise EAcsException.Create('Failed to initialize FLAC encoder.'); end; FBufSize:=FBlockSize * (FInput.BitsPerSample shr 3) * FInput.Channels; GetMem(Buffer, FBufSize); end; procedure TFLACOut.Done(); begin if Assigned(FStream) then FLAC__stream_encoder_finish(_encoder); FLAC__stream_encoder_delete(_encoder); if Buffer <> nil then FreeMem(Buffer); Buffer:=nil; FreeAndNil(FStream); FInput.Done(); end; function TFLACOut.DoOutput(Abort: Boolean): Boolean; var Len, i, samples: LongWord; FB: PFLACBuf; FBU: PFLACUBuf; B16: PAcsBuffer16; B32: PAcsBuffer32; begin Result:=True; if not CanOutput then Exit; if Abort or EndOfInput then begin Result:=False; Exit; end; //Len:=FInput.FillBuffer(Buffer, FBufSize, EndOfInput); Len:=Self.FillBufferFromInput(EndOfInput); (*while Len < FBufSize do begin l:=Finput.CopyData(@Buffer[Len], FBufSize-Len); Inc(Len, l); if l = 0 then begin EndOfInput:=True; Break; end; end; *) if Len = 0 then begin Result:=False; Exit; end; samples:=(Len shl 3) div Finput.BitsPerSample; GetMem(FB, samples * SizeOF(FLAC__int32)); if FInput.BitsPerSample = 16 then begin B16:=@Buffer[0]; for i:=0 to samples - 1 do FB[i]:=B16[i]; end else if FInput.BitsPerSample = 8 then begin for i:=0 to samples - 1 do FB[i]:=Buffer[i] end else if FInput.BitsPerSample = 24 then begin FBU:=PFLACUBuf(FB); for i:=0 to samples - 1 do FBU[i]:=(ShortInt(Buffer[i*3 + 2]) shl 16) + (Buffer[i*3 + 1] shl 8) + (Buffer[i*3]); end else if FInput.BitsPerSample = 32 then begin B32:=@Buffer[0]; for i:=0 to samples - 1 do FB[i]:=B32[i]; end; if not FLAC__stream_encoder_process_interleaved(_encoder, @FB[0], samples div FInput.Channels) then raise EAcsException.Create('Failed to encode data.'); FreeMem(FB); end; procedure TFLACOut.SetEnableLooseMidSideStereo(val: Boolean); begin if Val then FEnableMidSideStereo:=True; FEnableLooseMidSideStereo:=Val; end; procedure TFLACOut.SetBestModelSearch(val: Boolean); begin if Val then begin FEnableMidSideStereo:=True; FEnableLooseMidSideStereo:=False; end; FBestModelSearch:=Val; end; { TFLACIn } constructor TFLACIn.Create(AOwner: TComponent); begin inherited Create(AOwner); FComments:=TVorbisTags.Create(); FBufferSize:=$8000; BytesPerBlock:=0; end; destructor TFLACIn.Destroy(); begin CloseFile(); FreeAndNil(FComments); inherited Destroy; end; procedure TFLACIn.OpenFile(); begin if FOpened then Exit; if not LibFLACLoaded then raise EAcsException.Create(LibFLACPath + ' library could not be loaded.'); inherited OpenFile(); if FOpened then begin Residue:=0; FValid:=False; _decoder:=FLAC__stream_decoder_new(); if not Assigned(_decoder) then raise EAcsException.Create('Failed to initialize the FLAC decoder.'); if not FLAC__stream_decoder_set_md5_checking(_decoder, LongBool(FCheckMD5Signature)) then raise EAcsException.Create('Internal error 113, please report to NewAC developers'); FLAC__stream_decoder_set_metadata_respond_all(_decoder); if FLAC__stream_decoder_init_stream(_decoder, DecReadCBFunc, DecSeekCBFunc, DecTellCBFunc, DecLengthCBFunc, DecEOFCBFunc, DecWriteCBFunc, DecMetadataCBProc, DecErrorCBProc, Self) <> FLAC__STREAM_DECODER_INIT_STATUS_OK then raise EAcsException.Create('Failed to set up the FLAC decoder.'); FValid:=True; //BuffSize:=0; //Buff:=nil; // read metadata FComments.Clear(); EndOfMetadata:=False; while (not EndOfMetadata) and (FValid) do begin if not FLAC__stream_decoder_process_single(_decoder) then begin FValid:=False; Break; end; end; if FValid then begin //_CommonTags.Clear(); //_CommonTags.Artist:=FComments.Artist; //_CommonTags.Album:=FComments.Album; //_CommonTags.Title:=FComments.Title; ////{$WARNINGS OFF} //_CommonTags.Year:=FComments.Date; //_CommonTags.Track:=FComments.Track; ////{$WARNINGS ON} //_CommonTags.Genre:=FComments.Genre; end; end; end; procedure TFLACIn.CloseFile(); begin if FOpened then begin if Assigned(_decoder) then begin FSignatureValid:=FLAC__stream_decoder_finish(_decoder); FLAC__stream_decoder_delete(_decoder); _decoder:=nil; end; //if Buff <> nil then FreeMem(Buff); //Buff:=nil; end; inherited CloseFile(); end; function TFLACIn.GetData(ABuffer: Pointer; ABufferSize: Integer): Integer; var dec_state: Integer; begin Result:=0; if not Active then raise EAcsException.Create(strStreamnotopen); if FAudioBuffer.UnreadSize = 0 then begin BufStart:=0; //BufEnd:=0; FAudioBuffer.Reset(); //while FAudioBuffer.WritePosition < (FAudioBuffer.Size-Self.BytesPerBlock) do begin if not FLAC__stream_decoder_process_single(_decoder) then begin dec_state:=FLAC__stream_decoder_get_state(_decoder); if (dec_state = FLAC__STREAM_DECODER_END_OF_STREAM) or (not FValid) then else raise EAcsException.Create('Error reading FLAC file'); end; end; end; FSampleSize:=FChan * (FBPS div 8); if Residue <> 0 then begin BufStart:=(Residue - 1) * FSampleSize; if BufStart >= Self.BytesPerBlock then raise EAcsException.Create('Seek failed'); Residue:=0; Inc(FPosition, BufStart - FSampleSize); end; Result:=ABufferSize - (ABufferSize mod FSampleSize); if Result > FAudioBuffer.UnreadSize then Result:=FAudioBuffer.UnreadSize; FAudioBuffer.Read(ABuffer^, Result); Inc(BufStart, Result); Inc(FPosition, Result); end; function TFLACIn.Seek(SampleNum: Integer): Boolean; var Aligned: Int64; begin FCheckMD5Signature:=False; if FBlockSize <> 0 then begin Residue:=SampleNum mod FBlockSize; Aligned:=SampleNum - Residue; end else Aligned:=SampleNum; Result:=FLAC__stream_decoder_seek_absolute(_decoder, Aligned); if not Result then FLAC__stream_decoder_reset(_decoder); SampleNum:=Aligned; BufStart:=0; BufEnd:=0; end; procedure TFlacOut.SetCompressionLevel(val: Integer); begin if Val > 8 then FCompressionLevel:=8 else FCompressionLevel:=Val; end; procedure TFLACOut.SetTags(AValue: TVorbisTags); begin FTags.Assign(AValue); end; procedure GetBlockInfo(FS: TStream; var BI: TBlockInfo); var Header : array [0..3] of Byte; t: Byte; begin FS.Read(Header, 4); BI.HasNext:=(Header[0] shr 7) = 0; BI.BlockType:=Header[0] mod 128; BI.BlockLength:=0; t:=Header[1]; Header[1]:=Header[3]; Header[3]:=t; Move(Header[1], BI.BlockLength, 3); end; function TFLACIn.GetComments(): TVorbisTags; begin OpenFile(); Result:=FComments; end; initialization if LoadFlacLibrary() then begin FileFormats.Add('flac', 'Free Lossless Audio Codec', TFLACIn); FileFormats.Add('flac', 'Free Lossless Audio Codec', TFLACOut); end; finalization UnloadFlacLibrary(); end.
unit TemplateWSImpl; interface uses InvokeRegistry, Types, XSBuiltIns, TemplateWSIntf, CommunicationObj, Classes; type TTemplateWS = class(TCommObj, ITemplateWS) public function LoadTemplate( TemplateName : string ) : TTemplateInfo; safecall; function GetTemplateList : TStringDynArray; safecall; function TemplateExists( TemplateName : string ) : boolean; safecall; //Control procedure ModifyTemplate( Template : TTemplateInfo ); safecall; procedure Eliminar( TemplateName : string ); safecall; procedure Automatica(TemplateName : string; Value: boolean); safecall; function CheckCredentials : boolean; override; end; implementation uses LayoutManager; { TTemplate } procedure TTemplateWS.Automatica(TemplateName: string; Value: boolean); var LayoutManager : TLayoutManager; TemplateInfo : TTemplateInfo; begin if InControl then begin LayoutManager := TLayoutManager.Create; try TemplateInfo := LayoutManager.LoadTemplate(TemplateName); TemplateInfo.Automatic := Value; LayoutManager.SaveTemplate(TemplateInfo); finally LayoutManager.Free; end; end; end; function TTemplateWS.CheckCredentials: boolean; begin result := CheckAuthHeader >= ul_Designer; end; procedure TTemplateWS.Eliminar(TemplateName: string); var LayoutManager : TLayoutManager; begin LayoutManager := TLayoutManager.Create; try LayoutManager.KillTemplate(TemplateName); finally LayoutManager.Free; end; end; function TTemplateWS.GetTemplateList: TStringDynArray; var i : integer; Templates : TStrings; begin Templates := EnumTemplates; try SetLength( result, Templates.Count ); for i := 0 to Templates.Count-1 do result[i] := Templates[i]; finally Templates.Free; end; end; function TTemplateWS.LoadTemplate(TemplateName: string): TTemplateInfo; var LayoutManager : TLayoutManager; begin LayoutManager := TLayoutManager.Create; try result := LayoutManager.LoadTemplate(TemplateName); finally LayoutManager.Free; end; end; procedure TTemplateWS.ModifyTemplate(Template: TTemplateInfo); var LayoutManager : TLayoutManager; begin LayoutManager := TLayoutManager.Create; try LayoutManager.KillTemplate(Template.Name); LayoutManager.SaveTemplate(Template); finally LayoutManager.Free; end; end; function TTemplateWS.TemplateExists(TemplateName: string): boolean; begin result := TemplateExists(TemplateName); end; initialization InvRegistry.RegisterInvokableClass(TTemplateWS); end.
unit BasicCode; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, AdvPanel, AdvGlowButton, Grids, BaseGrid, AdvGrid, AdvOfficeButtons, MoneyEdit, AdvEdit, AdvMoneyEdit, inifiles, AdvObj, AdvUtil; type TBasicCode_f = class(TForm) pnlSub: TAdvPanel; lblSub: TLabel; lblKind: TLabel; Panel1: TAdvPanel; Label1: TLabel; Label2: TLabel; Label4: TLabel; edtCode: TEdit; edtName: TEdit; rgUse: TRadioGroup; edtRegDate: TEdit; cbLarge: TComboBox; lblLarge: TLabel; cbMiddle: TComboBox; lblMiddle: TLabel; Label3: TLabel; Label5: TLabel; grdbasic: TAdvStringGrid; cbView: TAdvOfficeCheckBox; lblYoyul: TLabel; edtYoyul: TAdvMoneyEdit; AdvPanel1: TAdvPanel; btnAdd: TAdvGlowButton; btnDel: TAdvGlowButton; btnPrint: TAdvGlowButton; btnCls: TAdvGlowButton; btnSave: TAdvGlowButton; btnCancel: TAdvGlowButton; procedure FormShow(Sender: TObject); procedure btnClsClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnDelClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure cbLargeChange(Sender: TObject); procedure cbMiddleChange(Sender: TObject); procedure btnPrintClick(Sender: TObject); procedure edtNameKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure grdBasicRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); procedure btnCancelClick(Sender: TObject); procedure grdbasicGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); procedure grdbasicClickCell(Sender: TObject; ARow, ACol: Integer); private { Private declarations } procedure BasicCodeSave; procedure BasicCodeDELETE; procedure FieldClear; procedure GrdShow; procedure mainGridSet; public { Public declarations } end; var BasicCode_f: TBasicCode_f; implementation uses DM, prtBasicCode, uFunctions, main; {$R *.dfm} const { 'IpgoType', 'BaljuType', 'UpcheType', 'LocType', 'BankType', 'CardType', 'Bunlarge', 'BunMiddle 'BunSmall' } SelectMAX_IpgoType = 'SELECT MAX(ItCode) As MaxCode FROM tblIbgoType'; SelectMAX_BaljuType = 'SELECT MAX(BtCode) As MaxCode FROM tblBaljuType'; SelectMAX_UpcheType = 'SELECT MAX(UtCode) As MaxCode FROM tblUpcheType'; SelectMAX_LocType = 'SELECT MAX(LcCode) As MaxCode FROM tblLocate'; SelectMAX_BankType = 'SELECT MAX(BkCode) As MaxCode FROM tblBank'; SelectMAX_CardType = 'SELECT MAX(CdCode) As MaxCode FROM tblCard'; SelectMAX_Bunlarge = 'SELECT MAX(BlCode) As MaxCode FROM tblBunlarge'; SelectMAX_BunMiddle = 'SELECT MAX(BmCode) As MaxCode FROM tblBunMiddle'; SelectMAX_BunSmall = 'SELECT MAX(BsCode) As MaxCode FROM tblBunSmall'; SelectMAX_Busu = 'SELECT MAX(BusuCode) As MaxCode FROM tblBusu'; SelectMAX_SangGakFinish = 'SELECT MAX(SfCode) As MaxCode FROM tblSangGakFinish'; SelectMAX_SangGakMethod = 'SELECT MAX(SmCode) As MaxCode FROM tblSangGakMethod'; SelectMAX_Chubun = 'SELECT MAX(cbCode) As MaxCode FROM tblChubun'; SelectMAX_Gyejung = 'SELECT MAX(GjCode) As MaxCode FROM tblGyejung'; SelectMAX_Brand = 'SELECT MAX(BrCode) As MaxCode FROM tblBrand'; SelectMAX_Gh = 'SELECT MAX(GhCode) As MaxCode FROM tblGwonhan'; SelectMAX_Jw = 'SELECT MAX(JwCode) As MaxCode FROM tblJikWi'; Select_IpgoType2 = 'SELECT * FROM tblIbgoType' + #10#13 + 'Where ItUse <> ''1'''; Select_BaljuType2 = 'SELECT * FROM tblBaljuType' + #10#13 + 'Where BtUse <> ''1'''; Select_UpcheType2 = 'SELECT * FROM tblUpcheType' + #10#13 + 'Where UtUse <> ''1'''; Select_LocType2 = 'SELECT * FROM tblLocate' + #10#13 + 'Where LcUse <> ''1'''; Select_BankType2 = 'SELECT * FROM tblBank' + #10#13 + 'Where BkUse <> ''1'''; Select_CardType2 = 'SELECT * FROM tblCard' + #10#13 + 'Where CdUse <> ''1'''; Select_Bunlarge2 = 'SELECT * FROM tblBunlarge' + #10#13 + 'Where BlUse <> ''1'''; Select_BunMiddle2 = 'SELECT * FROM tblBunMiddle' + #10#13 + 'Where BmUse <> ''1'''; Select_BunSmall2 = 'SELECT * FROM tblBunSmall' + #10#13 + 'Where BsUse <> ''1'''; Select_Busu2 = 'SELECT * FROM tblBusu' + #10#13 + 'Where busuUse <> ''1'''; Select_SangGakFinish2 = 'SELECT * FROM tblSangGakFinish' + #10#13 + 'Where SfUse <> ''1'''; Select_SangGakMethod2 = 'SELECT * FROM tblSangGakMethod' + #10#13 + 'Where smUse <> ''1'''; Select_Chubun2 = 'SELECT * FROM tblChubun' + #10#13 + 'Where cbUse <> ''1'''; Select_Gyejung2 = 'SELECT * FROM tblGyejung' + #10#13 + 'Where gjUse <> ''1'''; Select_Brand2 = 'SELECT * FROM tblBrand' + #10#13 + 'Where brUse <> ''1'''; Select_Upche2 = 'SELECT * FROM tblUpche' + #10#13 + 'Where ucUse <> ''1'''; Select_Gh2 = 'SELECT * FROM tblGwonHan' + #10#13 + 'Where ghUse <> ''1'''; Select_Jw2 = 'SELECT * FROM tblJikWi' + #10#13 + 'Where jwUse <> ''1'''; Select_IpgoType = 'SELECT * FROM tblIbgoType'; Select_BaljuType = 'SELECT * FROM tblBaljuType'; Select_UpcheType = 'SELECT * FROM tblUpcheType'; Select_LocType = 'SELECT * FROM tblLocate'; Select_BankType = 'SELECT * FROM tblBank'; Select_CardType = 'SELECT * FROM tblCard'; Select_Bunlarge = 'SELECT * FROM tblBunlarge'; Select_BunMiddle = 'SELECT * FROM tblBunMiddle'; Select_BunSmall = 'SELECT * FROM tblBunSmall'; Select_Busu = 'SELECT * FROM tblBusu'; Select_SangGakFinish = 'SELECT * FROM tblSangGakFinish'; Select_SangGakMethod = 'SELECT * FROM tblSangGakMethod'; Select_Chubun = 'SELECT * FROM tblChubun'; Select_Gyejung = 'SELECT * FROM tblGyejung'; Select_Brand = 'SELECT * FROM tblBrand'; Select_Upche = 'SELECT * FROM tblUpche'; Select_Gh = 'SELECT * FROM tblGwonhan'; Select_Jw = 'SELECT * FROM tblJikWi'; SelectExist_IpgoType = 'Select * FROM tblIbgoType' + #10#13 + 'Where ItCode =:ItCode'; SelectExist_BaljuType = 'Select * FROM tblBaljuType' + #10#13 + 'Where BtCode =:BtCode'; SelectExist_UpcheType = 'Select * FROM tblUpcheType' + #10#13 + 'Where UtCode =:UtCode'; SelectExist_LocType = 'Select * FROM tblLocate' + #10#13 + 'Where LcCode =:LcCode'; SelectExist_BankType = 'Select * FROM tblBank' + #10#13 + 'Where BkCode =:BkCode'; SelectExist_CardType = 'Select * FROM tblCard' + #10#13 + 'Where CdCode =:CdCode'; SelectExist_Bunlarge = 'Select * FROM tblBunlarge' + #10#13 + 'Where BlCode =:BlCode'; SelectExist_BunMiddle = 'Select * FROM tblBunMiddle' + #10#13 + 'Where BmCode =:BmCode'; SelectExist_BunSmall = 'Select * FROM tblBunSmall' + #10#13 + 'Where BsCode =:BsCode'; SelectExist_Busu = 'SELECT * FROM tblBusu' + #10#13 + 'Where BusuCode =:BusuCode'; SelectExist_SangGakFinish = 'SELECT * FROM tblSangGakFinish' + #10#13 + 'Where SfCode =:SfCode'; SelectExist_SangGakMethod = 'SELECT * FROM tblSangGakMethod' + #10#13 + 'Where SmCode =:SmCode'; SelectExist_Chubun = 'SELECT * FROM tblChubun' + #10#13 + 'Where CbCode =:CbCode'; SelectExist_Gyejung = 'SELECT * FROM tblGyejung' + #10#13 + 'Where GjCode =:GjCode'; SelectExist_Brand = 'SELECT * FROM tblBrand' + #10#13 + 'Where BrCode =:BrCode'; SelectExist_Gh= 'SELECT * FROM tblGwonHan' + #10#13 + 'Where GhCode =:GhCode'; SelectExist_Jw = 'SELECT * FROM tblJikWi' + #10#13 + 'Where JwCode =:JwCode'; Delete_IpgoType = 'Delete FROM tblIbgoType' + #10#13 + 'Where ItCode =:ItCode'; Delete_BaljuType = 'Delete FROM tblBaljuType' + #10#13 + 'Where BtCode =:BtCode'; Delete_UpcheType = 'Delete FROM tblUpcheType' + #10#13 + 'Where UtCode =:UtCode'; Delete_LocType = 'Delete FROM tblLocate' + #10#13 + 'Where LcCode =:LcCode'; Delete_BankType = 'Delete FROM tblBank' + #10#13 + 'Where BkCode =:BkCode'; Delete_CardType = 'Delete FROM tblCard' + #10#13 + 'Where CdCode =:CdCode'; Delete_Bunlarge = 'Delete FROM tblBunlarge' + #10#13 + 'Where BlCode =:BlCode'; Delete_BunMiddle = 'Delete FROM tblBunMiddle' + #10#13 + 'Where BmCode =:BmCode'; Delete_BunSmall = 'Delete FROM tblBunSmall' + #10#13 + 'Where BsCode =:BsCode'; Delete_Busu = 'Delete FROM tblBusu' + #10#13 + 'Where BusuCode =:BusuCode'; Delete_SangGakFinish = 'Delete FROM tblSangGakFinish' + #10#13 + 'Where SfCode =:SfCode'; Delete_SangGakMethod = 'Delete FROM tblSangGakMethod' + #10#13 + 'Where SmCode =:SmCode'; Delete_Chubun = 'Delete FROM tblChubun' + #10#13 + 'Where CbCode =:CbCode'; Delete_Gyejung = 'Delete FROM tblGyejung' + #10#13 + 'Where GjCode =:GjCode'; Delete_Brand = 'Delete FROM tblBrand' + #10#13 + 'Where BrCode =:BrCode'; Delete_Gh = 'Delete FROM tblGwonHan' + #10#13 + 'Where GhCode =:GhCode'; Delete_Jw = 'Delete FROM tblJikWi' + #10#13 + 'Where JwCode =:JwCode'; Insert_IpgoType = 'Insert Into tblIbgoType' + #10#13 + '(ItCode, ItName, ItRegday, Ituse) Values ' + #10#13 + '(:ItCode, :ItName, :ItRegday, :ItUse) '; Insert_BaljuType = 'Insert Into tblBaljuType' + #10#13 + '(BtCode, BtName, BtRegday, BtUse) Values ' + #10#13 + '(:BtCode, :BtName, :BtRegday, :BtUse) '; Insert_UpcheType = 'Insert Into tblUpcheType' + #10#13 + '(UtCode, UtName, UtRegday, UtUse) Values ' + #10#13 + '(:UtCode, :UtName, :UtRegday, :UtUse) '; Insert_LocType = 'Insert Into tblLocate' + #10#13 + '(LcCode, LcName, LcRegday, LcUse) Values ' + #10#13 + '(:LcCode, :LcName, :LcRegday, :LcUse) '; Insert_BankType = 'Insert Into tblBank' + #10#13 + '(BkCode, BkName, BkRegday, BkUse) Values ' + #10#13 + '(:BkCode, :BkName, :BkRegday, :BkUse) '; Insert_CardType = 'Insert Into tblCard' + #10#13 + '(CdCode, CdName,CdRate, CdPrefix1, CdPrefix2, CdRegday, Cduse) Values ' + #10#13 + '(:CdCode, :CdName, :CdRate, :CdPrefix1, :CdPrefix2, :CdRegday, :CdUse) '; Insert_Bunlarge = 'Insert Into tblBunlarge' + #10#13 + '(BlCode, BlName, BlRegday, BlUse) Values ' + #10#13 + '(:BlCode, :BlName, :BlRegday, :BlUse) '; Insert_BunMiddle = 'Insert Into tblBunMiddle' + #10#13 + '(BlCode, BmCode, BmName, BmRegday, BmUse) Values ' + #10#13 + '(:BlCode, :BmCode, :BmName, :BmRegday, :BmUse) '; Insert_BunSmall = 'Insert Into tblBunSmall' + #10#13 + '(BlCode, BmCode, BsCode, BsName, BsRegday, BsUse) Values ' + #10#13 + '(:BlCode, :BmCode, :BsCode, :BsName, :BsRegday, :BsUse) '; Insert_Busu = 'Insert into tblBusu' + #10#13 + '(BusuCode, BusuName, BusuRegday, BusuUse) Values ' + #10#13 + '(:BusuCode, :BusuName, :BusuRegday, :BusuUse) '; Insert_SangGakFinish = 'Insert into tblSangGakFinish' + #10#13 + '(sfCode, sfName, sfRegday, sfUse) Values ' + #10#13 + '(:sfCode, :sfName, :sfRegday, :sfUse) '; Insert_SangGakMethod = 'Insert into tblSangGakMethod' + #10#13 + '(smCode, smName, smRegday, smUse) Values ' + #10#13 + '(:smCode, :smName, :smRegday, :smUse) '; Insert_Chubun = 'Insert into tblChubun' + #10#13 + '(cbCode, cbName, cbRegday, cbUse) Values ' + #10#13 + '(:cbCode, :cbName, :cbRegday, :cbUse) '; Insert_Gyejung = 'Insert into tblGyejung' + #10#13 + '(gjCode, gjName, gjRegday, gjUse) Values ' + #10#13 + '(:gjCode, :gjName, :gjRegday, :gjuse) '; Insert_Brand = 'Insert Into tblBrand' + #10#13 + '(UcCode, BrCode, BrName, BrRegday, BrUse) Values ' + #10#13 + '(:UcCode, :BrCode, :BrName, :BrRegday, :BrUse) '; Insert_Gh = 'Insert Into tblGwonHan' + #10#13 + '(GhCode, GhName, GhRegday, GhUse) Values ' + #10#13 + '( :GhCode, :GhName, :GhRegday, :GhUse) '; Insert_Jw = 'Insert Into tblJikWi' + #10#13 + '( JwCode, JwName, JwRegday, JwUse) Values ' + #10#13 + '( :JwCode, :JwName, :JwRegday, :JwUse) '; Update_IpgoType = 'Update tblIbgoType set ' + #10#13 + 'ItName=:ItName, ItRegday=:ItRegday, Ituse=:ItUse ' + #10#13 + 'Where ItCode =:ItCode'; Update_BaljuType = 'Update tblBaljuType set ' + #10#13 + 'BtName=:BtName, BtRegday=:BtRegday, BtUse=:BtUse' + #10#13 + 'Where BtCode =:BtCode'; Update_UpcheType = 'Update tblUpcheType set ' + #10#13 + ' UtName=:UtName, UtRegday =:UtRegday, UtUse=:UtUse' + #10#13 + 'Where UtCode =:UtCode'; Update_LocType = 'Update tblLocate set ' + #10#13 + 'LcName=:LcName, LcRegday=:LcRegday, LcUse=:LcUse' + #10#13 + 'Where LcCode =:LcCode'; Update_BankType = 'Update tblBank set ' + #10#13 + 'BkName=:BkName, BkRegday=:BkRegday, BkUse=:BkUse' + #10#13 + 'Where BkCode =:BkCode'; Update_CardType = 'Update tblCard set ' + #10#13 + ' CdName =:CdName,CdRate=:CdRate,CdPrefix1=:CdPrefix1,' + #10#13 + ' CdPrefix2 =:CdPrefix2, CdRegday=:CdRegday, Cduse=:CdUse ' + #10#13 + 'Where CdCode =:CdCode'; Update_Bunlarge = 'Update tblBunlarge set ' + #10#13 + 'BlName=:BlName, BlRegday=:BlRegday, BlUse=:BlUse' + #10#13 + 'Where BlCode =:BlCode'; Update_BunMiddle = 'Update tblBunMiddle set ' + #10#13 + ' BlCode=:BlCode, BmName=:BmName, BmRegday=:BmRegday, BmUse=:BmUse' + #10#13 + 'Where BmCode =:BmCode'; Update_BunSmall = 'Update tblBunSmall set ' + #10#13 + 'BlCode=:BlCode,BmCode =:BmCode, BsName =:BsName, BsRegday=:BsRegday, BsUse=:BsUse' + #10#13 + 'Where BsCode =:BsCode'; Update_Busu = 'Update tblBusu set' + #10#13 + 'BusuName=:BusuName, BusuRegday=:BsusRegday, busuUse=:BusuUse' + #10#13 + 'Where BusuCode =:BusuCode'; Update_SangGakFinish = 'Update tblSangGakFinish set' + #10#13 + 'SfName=:SfName, SfRegday=:SfRegday, SfUse=:SfUse' + #10#13 + 'Where SfCode =:SfCode'; Update_SangGakMethod = 'Update tblSangGakMethod set' + #10#13 + 'SmName=:SmName, SmRegday=:SmRegday, SmUse=:SmUse' + #10#13 + 'Where SmCode =:SmCode'; Update_Chubun = 'Update tblChubun set' + #10#13 + 'CbName=:CbName, CbRegday=:CbRegday, CbUse=:CbUse' + #10#13 + 'Where CbCode =:CbCode'; Update_Gyejung = 'Update tblGyejung set' + #10#13 + 'GjName=:GjName, GjRegday=:GjRegday, GjUse=:GjUse' + #10#13 + 'Where GjCode =:GjCode'; Update_Brand = 'Update tblBrand set ' + #10#13 + ' UcCode=:UcCode, BrName=:BrName, BrRegday=:BrRegday, BrUse=:BrUse' + #10#13 + 'Where BrCode =:BrCode'; Update_Gh = 'Update tblGwonHan set' + #10#13 + 'GhName=:GhName, GhRegday=:GhRegday, GhUse=:GhUse' + #10#13 + 'Where GhCode =:GhCode'; Update_Jw = 'Update tblJikWi set' + #10#13 + 'JwName=:JwName, JwRegday=:JwRegday, JwUse=:JwUse' + #10#13 + 'Where JwCode =:JwCode'; UpdateDelete_IpgoType = 'Update tblIbgoType set ' + #10#13 + 'ItRegday=:ItRegday, Ituse=:ItUse ' + #10#13 + 'Where ItCode =:ItCode'; UpdateDelete_BaljuType = 'Update tblBaljuType set ' + #10#13 + 'BtRegday=:BtRegday, BtUse=:BtUse' + #10#13 + 'Where BtCode =:BtCode'; UpdateDelete_UpcheType = 'Update tblUpcheType set ' + #10#13 + 'UtRegday =:UtRegday, UtUse=:UtUse' + #10#13 + 'Where UtCode =:UtCode'; UpdateDelete_LocType = 'Update tblLocate set ' + #10#13 + 'LcRegday=:LcRegday, LcUse=:LcUse' + #10#13 + 'Where LcCode =:LcCode'; UpdateDelete_BankType = 'Update tblBank set ' + #10#13 + 'BkRegday=:BkRegday, BkUse=:BkUse' + #10#13 + 'Where BkCode =:BkCode'; UpdateDelete_CardType = 'Update tblCard set ' + #10#13 + 'CdRegday=:CdRegday, Cduse=:CdUse ' + #10#13 + 'Where CdCode =:CdCode'; UpdateDelete_Bunlarge = 'Update tblBunlarge set ' + #10#13 + 'BlRegday=:BlRegday, BlUse=:BlUse' + #10#13 + 'Where BlCode =:BlCode'; UpdateDelete_BunMiddle = 'Update tblBunMiddle set ' + #10#13 + 'BmRegday=:BmRegday, BmUse=:BmUse' + #10#13 + 'Where BmCode =:BmCode'; UpdateDelete_BunSmall = 'Update tblBunSmall set ' + #10#13 + 'BsRegday=:BsRegday, BsUse=:BsUse' + #10#13 + 'Where BsCode =:BsCode'; UpdateDelete_Busu = 'Update tblBusu set' + #10#13 + 'BusuRegday= :BusuRegday, busuUse= :BusuUse' + #10#13 + 'Where BusuCode = :BusuCode'; UpdateDelete_SangGakFinish = 'Update tblSangGakFinish set' + #10#13 + 'SfRegday=:SfRegday, SfUse=:SfUse' + #10#13 + 'Where SfCode =:SfCode'; UpdateDelete_SangGakMethod = 'Update tblSangGakMethod set' + #10#13 + 'SmRegday=:SmRegday, SmUse=:SmUse' + #10#13 + 'Where SmCode =:SmCode'; UpdateDelete_Chubun = 'Update tblChubun set' + #10#13 + 'CbRegday=:CbRegday, CbUse=:CbUse' + #10#13 + 'Where CbCode =:CbCode'; UpdateDelete_Gyejung = 'Update tblGyejung set' + #10#13 + 'GjRegday=:GjRegday, GjUse=:GjUse' + #10#13 + 'Where GjCode =:GjCode'; UpdateDelete_Brand = 'Update tblBrand set ' + #10#13 + 'BrRegday=:BrRegday, BrUse=:BrUse' + #10#13 + 'Where BrCode =:BrCode'; UpdateDelete_Gh = 'Update tblGwonHan set' + #10#13 + 'GhRegday=:GhRegday, GhUse=:GhUse' + #10#13 + 'Where GhCode =:GhCode'; UpdateDelete_Jw = 'Update tblJikWi set' + #10#13 + 'JwRegday=:JwRegday, JwUse=:JwUse' + #10#13 + 'Where JwCode =:JwCode'; procedure TBasicCode_f.FormShow(Sender: TObject); begin Caption := '기초코드입력'; fieldClear; GrdShow; end; procedure TBasicCode_f.FieldClear; const Select_BunLarge2 = 'Select * from tblBunLarge' + #13#10 + 'order by Blcode Asc'; Select_BunMiddle2 = 'Select * from tblBunMiddle' + #13#10 + 'where blCode=:blCode' + #13#10 + 'order by Bmcode Asc'; begin edtName.Text := ''; edtCode.Text := ''; edtYoyul.Text := '0'; edtRegDate.Text := ''; rgUse.ItemIndex := 0; case StrCase(lblKind.Caption, ['IpgoType', 'BaljuType', 'UpcheType', 'LocType', 'BankType', 'CardType', 'Bunlarge', 'BunMiddle', 'BunSmall', 'Busu', 'Chubun', 'SangGakFinish', 'SangGakMethod', 'GyeJung', 'Brand', 'GwonHan', 'JikWi' ]) of 0: pnlsub.Height := 36; 1: pnlsub.Height := 36; 2: pnlsub.Height := 36; 3: pnlsub.Height := 36; 4: pnlsub.Height := 36; 5: pnlsub.Height := 36; 6: pnlsub.Height := 36; 7: pnlsub.Height := 36; // begin // pnlsub.Height := 65; // // cbLarge.items.clear; // with dm_f.sqlwork do // begin // SQL.Text := Select_Bunlarge2; // Open; // // while not eof do // begin // cbLarge.items.add(FieldByName('BlCode').AsString); // next; // end; // end; // end; 8: pnlsub.Height := 36; // begin // pnlsub.Height := 96; // cbLarge.items.clear; // with dm_f.sqlwork do // begin // SQL.Text := Select_Bunlarge2; // Open; // // while not eof do // begin // cbLarge.items.add(FieldByName('BlCode').AsString); // next; // end; // end; // cbMiddle.items.clear; // with dm_f.sqlwork do // begin // SQL.Text := Select_BunMiddle2; // paramByName('BlCode').AsString := cbLarge.text; // Open; // // while not eof do // begin // cbMiddle.items.add(FieldByName('BmCode').AsString); // next; // end; // end; // // end; 9: pnlsub.Height := 36; 10: pnlsub.Height := 36; 11: pnlsub.Height := 36; 12: pnlsub.Height := 36; 13: pnlsub.Height := 36; 14: begin pnlsub.Height := 65; // cbLarge.items.clear; with dm_f.sqlwork do begin SQL.Text := Select_Upche; Open; while not eof do begin cbLarge.items.add(FieldByName('ucCode').AsString); next; end; end; end; 15: pnlsub.Height := 36; 16: pnlsub.Height := 36; end; cbLarge.text := ''; cbmiddle.text := ''; lblLarge.Caption := ''; lblMiddle.Caption := ''; cbLarge.itemIndex := -1; cbmiddle.itemIndex := -1; end; procedure TBasicCode_f.BasicCodeSave; begin { 'IpgoType', 'BaljuType', 'UpcheType', 'LocType', 'BankType', 'CardType', 'Bunlarge', 'BunMiddle 'BunSmall' } with dm_f.SqlWork do begin case StrCase(lblKind.Caption, ['IpgoType', 'BaljuType', 'UpcheType', 'LocType', 'BankType', 'CardType', 'Bunlarge', 'BunMiddle', 'BunSmall', 'Busu', 'Chubun', 'SangGakFinish', 'SangGakMethod', 'GyeJung', 'Brand', 'GwonHan', 'JikWi' ]) of 0: begin SQL.Text := SELECTEXIST_IpgoType; ParamByName('itCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_IpgoType else SQL.Text := INSERT_IpgoType; ParamByName('ItCode').AsString := edtCode.text; ParamByName('ItName').AsString := edtname.text; ParamByName('ItRegday').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('ItUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 1: begin SQL.Text := SELECTEXIST_BaljuType; ParamByName('BtCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_BaljuType else SQL.Text := INSERT_BaljuType; ParamByName('BtCode').AsString := edtCode.text; ParamByName('BtName').AsString := edtname.text; ParamByName('BtRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BtUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 2: begin SQL.Text := SELECTEXIST_UpcheType; ParamByName('UtCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_UpcheType else SQL.Text := INSERT_UpcheType; ParamByName('UtCode').AsString := edtCode.text; ParamByName('UtName').AsString := edtname.text; ParamByName('UtRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('UtUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 3: begin SQL.Text := SELECTEXIST_LocType; ParamByName('LcCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_LocType else SQL.Text := INSERT_LocType; ParamByName('LcCode').AsString := edtCode.text; ParamByName('LcName').AsString := edtname.text; ParamByName('LcRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('LcUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 4: begin SQL.Text := SELECTEXIST_BankType; ParamByName('BkCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_BankType else SQL.Text := INSERT_BankType; ParamByName('BkCode').AsString := edtCode.text; ParamByName('BkName').AsString := edtname.text; ParamByName('BkRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BkUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 5: begin SQL.Text := SELECTEXIST_CardType; ParamByName('cdCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_CardType else SQL.Text := INSERT_CardType; ParamByName('CdCode').AsString := edtCode.text; ParamByName('CdName').AsString := edtname.text; ParamByName('CdRate').AsString := edtYoyul.text; ParamByName('CdPrefix1').AsString := ''; ParamByName('Cdprefix2').AsString := ''; ParamByName('CdRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('CdUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 6: begin SQL.Text := SELECTEXIST_Bunlarge; ParamByName('BlCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_Bunlarge else SQL.Text := INSERT_Bunlarge; ParamByName('BlCode').AsString := edtCode.text; ParamByName('BlName').AsString := edtname.text; ParamByName('BlRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BlUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 7: begin if cbLarge.text = '' then begin showmessage('대분류코드를 선택하세요.'); cbLarge.SetFocus; exit; end else begin SQL.Text := SELECTEXIST_BunMiddle; ParamByName('BmCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_BunMiddle else SQL.Text := INSERT_BunMiddle; ParamByName('BlCode').AsString := cbLarge.Text; ParamByName('BmCode').AsString := edtCode.text; ParamByName('BmName').AsString := edtname.text; ParamByName('BmRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BmUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; end; 8: begin if cbLarge.text = '' then begin showmessage('대분류코드를 선택하세요.'); cbLarge.SetFocus; exit; end else if cbmiddle.text = '' then begin showmessage('중분류코드를 선택하세요.'); cbMiddle.SetFocus; exit; end else begin SQL.Text := SELECTEXIST_BunSmall; ParamByName('BsCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_BunSmall else SQL.Text := INSERT_BunSmall; ParamByName('BlCode').AsString := cbLarge.text; ParamByName('BmCode').AsString := cbMiddle.text; ParamByName('BsCode').AsString := edtCode.text; ParamByName('BsName').AsString := edtname.text; ParamByName('BsRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BsUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; end; 9: begin SQL.Text := SELECTEXIST_Busu; ParamByName('BusuCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_Busu else SQL.Text := INSERT_Busu; ParamByName('BuSuCode').AsString := edtCode.text; ParamByName('BusuName').AsString := edtname.text; ParamByName('BusuRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BusuUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 10: begin SQL.Text := SELECTEXIST_Chubun; ParamByName('CbCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_Chubun else SQL.Text := INSERT_Chubun; ParamByName('CbCode').AsString := edtCode.text; ParamByName('CbName').AsString := edtname.text; ParamByName('CbRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('CbUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 11: begin SQL.Text := SELECTEXIST_SangGakFinish; ParamByName('SfCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_SanggakFinish else SQL.Text := INSERT_SanggakFinish; ParamByName('SfCode').AsString := edtCode.text; ParamByName('SfName').AsString := edtname.text; ParamByName('SfRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('SfUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 12: begin SQL.Text := SELECTEXIST_SangGakMethod; ParamByName('SmCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_SangGakMethod else SQL.Text := INSERT_SangGakMethod; ParamByName('SmCode').AsString := edtCode.text; ParamByName('SmName').AsString := edtname.text; ParamByName('SmRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('SmUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 13: begin SQL.Text := SELECTEXIST_Gyejung; ParamByName('GjCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_Gyejung else SQL.Text := INSERT_Gyejung; ParamByName('GjCode').AsString := edtCode.text; ParamByName('GjName').AsString := edtname.text; ParamByName('GjRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('GjUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 14: begin if cbLarge.text = '' then begin showmessage('거래처코드를 선택하세요.'); cbLarge.SetFocus; exit; end else begin SQL.Text := SELECTEXIST_Brand; ParamByName('BrCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_Brand else SQL.Text := INSERT_Brand; ParamByName('UcCode').AsString := cbLarge.Text; ParamByName('BrCode').AsString := edtCode.text; ParamByName('BrName').AsString := edtname.text; ParamByName('BrRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BrUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; end; 15: begin SQL.Text := SELECTEXIST_Gh; ParamByName('GhCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_Gh else SQL.Text := INSERT_Gh; ParamByName('GhCode').AsString := edtCode.text; ParamByName('GhName').AsString := edtname.text; ParamByName('GhRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('GhUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 16: begin SQL.Text := SELECTEXIST_Jw; ParamByName('JwCode').AsString := edtCode.text; open; if not isEmpty then SQL.Text := UPDATE_Jw else SQL.Text := INSERT_Jw; ParamByName('JwCode').AsString := edtCode.text; ParamByName('JwName').AsString := edtname.text; ParamByName('JwRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('JwUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; end; end; end; procedure TBasicCode_f.BasicCodeDelete; //지우면 절대 안되겠다. //후에 데이터의 불일시가 일어날게 뻔하다. begin with dm_f.SqlWork do begin case StrCase(lblKind.Caption, ['IpgoType', 'BaljuType', 'UpcheType', 'LocType', 'BankType', 'CardType', 'Bunlarge', 'BunMiddle', 'BunSmall', 'Busu', 'Chubun', 'SangGakFinish', 'SangGakMethod', 'GyeJung', 'Brand' , 'GwonHan' , 'JikWi' ]) of 0: begin SQL.Text := UPDATEDelete_IpgoType; ParamByName('ItCode').AsString := edtCode.text; ParamByName('ItRegday').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('ItUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 1: begin SQL.Text := UpdateDelete_BaljuType; ParamByName('BtCode').AsString := edtCode.text; ParamByName('BtRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BtUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 2: begin SQL.Text := UpdateDelete_UpcheType; ParamByName('UtCode').AsString := edtCode.text; ParamByName('UtRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('UtUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 3: begin SQL.Text := UpdateDelete_LocType; ParamByName('LcCode').AsString := edtCode.text; ParamByName('LcRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('LcUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 4: begin SQL.Text := UpdateDelete_BankType; ParamByName('BkCode').AsString := edtCode.text; ParamByName('BkRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BkUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 5: begin SQL.Text := UpdateDelete_CardType; ParamByName('CdCode').AsString := edtCode.text; ParamByName('CdRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('CdUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 6: begin SQL.Text := UpdateDelete_Bunlarge; ParamByName('BlCode').AsString := edtCode.text; ParamByName('BlRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BlUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 7: begin SQL.Text := UpdateDelete_BunMiddle; ParamByName('BmCode').AsString := edtCode.text; ParamByName('BmRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BmUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 8: begin SQL.Text := UpdateDelete_BunSmall; ParamByName('BsCode').AsString := edtCode.text; ParamByName('BsRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BsUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 9: begin SQL.Text := UpdateDelete_Busu; ParamByName('BusuCode').AsString := edtCode.text; ParamByName('BusuRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BusuUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 10: begin SQL.Text := UpdateDelete_Chubun; ParamByName('CbCode').AsString := edtCode.text; ParamByName('CbRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('CbUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 11: begin SQL.Text := UpdateDelete_SangGakFinish; ParamByName('SfCode').AsString := edtCode.text; ParamByName('SfRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('SfUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 12: begin SQL.Text := UpdateDelete_SangGakMethod; ParamByName('SmCode').AsString := edtCode.text; ParamByName('SmRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('SmUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 13: begin SQL.Text := UpdateDelete_Gyejung; ParamByName('GjCode').AsString := edtCode.text; ParamByName('GjRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('GjUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 14: begin SQL.Text := UpdateDelete_Brand; ParamByName('BrCode').AsString := edtCode.text; ParamByName('BrRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('BrUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 15: begin SQL.Text := UpdateDelete_Gh; ParamByName('GhCode').AsString := edtCode.text; ParamByName('GhRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('GhUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; 16: begin SQL.Text := UpdateDelete_Jw; ParamByName('JwCode').AsString := edtCode.text; ParamByName('JwRegDay').AsString := FormatDateTime('YYYY-MM-DD', now); ParamByName('JwUse').AsString := intToStr(rgUse.ItemIndex); ExecSql; end; end; end; end; procedure TBasicCode_f.mainGridSet; var FormInit: Tinifile; path: string; iniFile: string; begin path := ExtractFilePath(ParamStr(0)); iniFile := path + 'pess.ini'; FormInit := Tinifile.Create(inifile); with grdBasic do begin ColCount := 6; // Rowcount := 2; // FixedRows := 1; // FixedCols := 1; rowcount := 2; FixedRows := 1; columnHeaders.LoadFromFile(path + 'gridheader\basic.txt'); ColWidths[0] := 38; //연번 ColWidths[1] := 38; //코드 ColWidths[2] := 200; //명칭 ColWidths[3] := 84; //등록일자 // ColWidths[4] := 38; //사용 ColWidths[4] := 0; //사용 ColWidths[5] := 0; //요율 RemoveRows(1, RowCount - 1); end; end; procedure TBasicCode_f.FormCreate(Sender: TObject); begin mainGridSet; end; procedure TBasicCode_f.GrdShow; begin grdBasic.RemoveRows(1, grdBasic.RowCount - 1); with Dm_f.SqlWork do begin case StrCase(lblKind.Caption, ['IpgoType', 'BaljuType', 'UpcheType', 'LocType', 'BankType', 'CardType', 'Bunlarge', 'BunMiddle', 'BunSmall', 'Busu', 'Chubun', 'SangGakFinish', 'SangGakMethod', 'GyeJung', 'Brand', 'GwonHan', 'JikWi' ]) of 0: begin if cbView.Checked = true then SQL.Text := SELECT_IpgoType else SQL.Text := SELECT_IpgoType2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.RowCount - 1] := FieldByName('ItCode').AsString; grdBasic.Cells[2, grdBasic.RowCount - 1] := FieldByName('ItName').AsString; grdBasic.Cells[3, grdBasic.RowCount - 1] := FieldByName('ItRegDay').AsString; grdBasic.Cells[4, grdBasic.RowCount - 1] := FieldByName('ItUse').AsString; Next; end; end; 1: begin if cbView.Checked = true then SQL.Text := SELECT_BaljuType else SQL.Text := SELECT_BaljuType2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.RowCount - 1] := FieldByName('BtCode').AsString; grdBasic.Cells[2, grdBasic.RowCount - 1] := FieldByName('BtName').AsString; grdBasic.Cells[3, grdBasic.RowCount - 1] := FieldByName('BtRegDay').AsString; grdBasic.Cells[4, grdBasic.RowCount - 1] := FieldByName('BtUse').AsString; Next; end; end; 2: begin if cbView.Checked = true then SQL.Text := SELECT_UpcheType else SQL.Text := SELECT_UpcheType2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.RowCount - 1] := FieldByName('UtCode').AsString; grdBasic.Cells[2, grdBasic.RowCount - 1] := FieldByName('UtName').AsString; grdBasic.Cells[3, grdBasic.RowCount - 1] := FieldByName('UtRegDay').AsString; grdBasic.Cells[4, grdBasic.RowCount - 1] := FieldByName('UtUse').AsString; Next; end; end; 3: begin if cbView.Checked = true then SQL.Text := SELECT_LocType else SQL.Text := SELECT_LocType2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.RowCount - 1] := FieldByName('LcCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('LcName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('LcRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('LcUse').AsString; Next; end; end; 4: begin if cbView.Checked = true then SQL.Text := SELECT_BankType else SQL.Text := SELECT_BankType2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('BkCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('BkName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('BkRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('BkUse').AsString; Next; end; end; 5: begin grdBasic.ColWidths[5] := 38; //요율 grdBasic.RemoveRows(1, grdBasic.rowCount - 1); if cbView.Checked = true then SQL.Text := SELECT_CardType else SQL.Text := SELECT_CardType2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('CdCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('CdName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('CdRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('CdUse').AsString; grdBasic.Cells[5, grdBasic.rowCount - 1] := FieldByName('CdRate').AsString; Next; end; end; 6: begin if cbView.Checked = true then SQL.Text := SELECT_Bunlarge else SQL.Text := SELECT_Bunlarge2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('BlCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('BlName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('BlRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('BlUse').AsString; Next; end; end; 7: begin if cbView.Checked = true then SQL.Text := SELECT_BunMiddle else SQL.Text := SELECT_BunMiddle2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('BmCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('BmName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('BmRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('BmUse').AsString; grdBasic.Cells[5, grdBasic.rowCount - 1] := FieldByName('BlCode').AsString; Next; end; end; 8: begin if cbView.Checked = true then SQL.Text := SELECT_BunSmall else SQL.Text := SELECT_BunSmall2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('BsCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('BsName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('BsRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('BsUse').AsString; grdBasic.Cells[5, grdBasic.rowCount - 1] := FieldByName('BlCode').AsString; grdBasic.Cells[6, grdBasic.rowCount - 1] := FieldByName('BmCode').AsString; Next; end; end; 9: begin if cbView.Checked = true then SQL.Text := SELECT_Busu else SQL.Text := SELECT_Busu2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('BusuCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('BusuName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('BusuRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('BusuUse').AsString; Next; end; end; 10: begin if cbView.Checked = true then SQL.Text := SELECT_Chubun else SQL.Text := SELECT_Chubun2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('CbCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('CbName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('CbRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('CbUse').AsString; Next; end; end; 11: begin if cbView.Checked = true then SQL.Text := SELECT_SanggakFinish else SQL.Text := SELECT_SanggakFinish2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('SfCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('SfName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('SfRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('SfUse').AsString; Next; end; end; 12: begin if cbView.Checked = true then SQL.Text := SELECT_SangGakMethod else SQL.Text := SELECT_SangGakMethod2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('SmCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('SmName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('SmRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('SmUse').AsString; Next; end; end; 13: begin if cbView.Checked = true then SQL.Text := SELECT_Gyejung else SQL.Text := SELECT_Gyejung2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('GjCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('GjName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('GjRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('GjUse').AsString; Next; end; end; 14: begin if cbView.Checked = true then SQL.Text := SELECT_Brand else SQL.Text := SELECT_Brand2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('BrCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('BrName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('BrRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('BrUse').AsString; grdBasic.Cells[5, grdBasic.rowCount - 1] := FieldByName('UcCode').AsString; Next; end; end; 15: begin if cbView.Checked = true then SQL.Text := SELECT_Gh else SQL.Text := SELECT_Gh2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('GhCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('GhName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('GhRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('GhUse').AsString; Next; end; end; 16: begin if cbView.Checked = true then SQL.Text := SELECT_Jw else SQL.Text := SELECT_Jw2; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[1, grdBasic.rowCount - 1] := FieldByName('JwCode').AsString; grdBasic.Cells[2, grdBasic.rowCount - 1] := FieldByName('JwName').AsString; grdBasic.Cells[3, grdBasic.rowCount - 1] := FieldByName('JwRegDay').AsString; grdBasic.Cells[4, grdBasic.rowCount - 1] := FieldByName('JwUse').AsString; Next; end; end; end; if grdBasic.rowcount < 2 then begin grdBasic.rowcount := 2; end; grdBasic.FixedRows := 1; grdBasic.autonumbercol(0); end; end; procedure TBasicCode_f.btnClsClick(Sender: TObject); begin Close; end; procedure TBasicCode_f.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := CaFree; end; procedure TBasicCode_f.FormDestroy(Sender: TObject); begin BasicCode_f := nil; end; procedure TBasicCode_f.btnSaveClick(Sender: TObject); begin if edtCode.text = '' then begin Showmessage('코드를 입력하세요'); edtCode.setFocus; exit; end; if edtName.text = '' then begin Showmessage('명칭을 입력하세요'); edtName.setFocus; exit; end; BasicCodeSave; FieldClear; GrdShow; btnAdd.SetFocus; end; procedure TBasicCode_f.btnDelClick(Sender: TObject); var ARow: integer; begin ARow := GrdBasic.Row; BasicCodeDELETE; FieldClear; GrdShow; end; procedure TBasicCode_f.btnAddClick(Sender: TObject); begin with dm_f.SqlWork do begin case StrCase(lblKind.Caption, ['IpgoType', 'BaljuType', 'UpcheType', 'LocType', 'BankType', 'CardType', 'Bunlarge', 'BunMiddle', 'BunSmall', 'Busu', 'Chubun', 'SangGakFinish', 'SangGakMethod', 'GyeJung', 'Brand', 'GwonHan', 'JikWi' ]) of 0: begin SQL.Text := SELECTMAX_IpgoType; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 1: begin SQL.Text := SELECTMAX_BaljuType; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 2: begin SQL.Text := SELECTMAX_UpcheType; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 3: begin SQL.Text := SELECTMAX_LocType; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 4: begin SQL.Text := SELECTMAX_BankType; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 5: begin SQL.Text := SELECTMAX_CardType; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 6: begin SQL.Text := SELECTMAX_Bunlarge; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('000', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '001'; end; 7: begin SQL.Text := SELECTMAX_BunMiddle; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('000', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '001'; end; 8: begin SQL.Text := SELECTMAX_BunSmall; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('000', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '001'; end; 9: begin SQL.Text := SELECTMAX_Busu; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 10: begin SQL.Text := SELECTMAX_Chubun; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 11: begin SQL.Text := SELECTMAX_SangGakFinish; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 12: begin SQL.Text := SELECTMAX_SangGakMethod; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 13: begin SQL.Text := SELECTMAX_GyeJung; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 14: begin SQL.Text := SELECTMAX_Brand; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 15: begin SQL.Text := SELECTMAX_Gh; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; 16: begin SQL.Text := SELECTMAX_Jw; Open; if fieldByName('MaxCode').AsString <> '' then edtCode.Text := formatFloat('00', StrToInt(fieldByName('MaxCode').AsString) + 1) else edtCode.Text := '01'; end; end; end; edtName.Text := ''; edtName.SetFocus; end; procedure TBasicCode_f.cbLargeChange(Sender: TObject); const Select_BunMiddle2 = 'Select * from tblBunMiddle' + #13#10 + 'where BlCode=:BlCode'; Select_BunLarge2 = 'Select * from tblBunLarge' + #13#10 + 'where Blcode =:BlCode'; Select_Upche2 = 'Select * from tblUpche' + #13#10 + 'where Uccode =:UcCode'; Select_Brand2 = 'Select * from tblBrand' + #13#10 + 'where Uccode =:UcCode'; begin case StrCase(lblKind.Caption, ['IpgoType', 'BaljuType', 'UpcheType', 'LocType', 'BankType', 'CardType', 'Bunlarge', 'BunMiddle', 'BunSmall', 'Busu', 'Chubun', 'SangGakFinish', 'SangGakMethod', 'GyeJung', 'Brand', 'Gwonhan', 'JikWi' ]) of 7: begin with dm_f.sqlwork do begin SQL.Text := Select_BunLarge2; paramByName('BlCode').AsString := CbLarge.text; Open; lblLarge.Caption := FieldByname('BlName').AsString; end; cbMiddle.items.clear; with dm_f.sqlwork do begin SQL.Text := Select_BunMiddle2; paramByName('BlCode').AsString := cbLarge.text; Open; while not eof do begin cbMiddle.items.add(FieldByName('BmCode').AsString); next; end; end; end; 8: begin with dm_f.sqlwork do begin SQL.Text := Select_BunLarge2; paramByName('BlCode').AsString := CbLarge.text; Open; lblLarge.Caption := FieldByname('BlName').AsString; end; cbMiddle.items.clear; with dm_f.sqlwork do begin SQL.Text := Select_BunMiddle2; paramByName('BlCode').AsString := cbLarge.text; Open; while not eof do begin cbMiddle.items.add(FieldByName('BmCode').AsString); next; end; end; end; 14: begin with dm_f.sqlwork do begin SQL.Text := Select_Upche2; paramByName('ucCode').AsString := CbLarge.text; Open; lblLarge.Caption := FieldByname('UcSangho').AsString; end; with dm_f.sqlwork do begin close; sql.clear; SQL.Text := SELECT_Brand2; paramByName('ucCode').AsString := cbLarge.text; Open; if not IsEmpty then while not EOF do begin grdBasic.AddRow; grdBasic.Cells[0, grdBasic.RowCount - 1] := FieldByName('BrCode').AsString; grdBasic.Cells[1, grdBasic.RowCount - 1] := FieldByName('BrName').AsString; grdBasic.Cells[2, grdBasic.RowCount - 1] := FieldByName('BrRegDay').AsString; grdBasic.Cells[3, grdBasic.RowCount - 1] := FieldByName('BrUse').AsString; grdBasic.Cells[4, grdBasic.RowCount - 1] := FieldByName('UcCode').AsString; Next; end; end; end; end; end; procedure TBasicCode_f.cbMiddleChange(Sender: TObject); const Select_BunMiddle = 'Select * from tblBunMiddle' + #13#10 + 'where Bmcode =:BmCode and Blcode =:BlCode'; Select_BunLarge = 'Select * from tblBunLarge' + #13#10 + 'where Blcode =:BlCode'; begin with dm_f.sqlwork do begin SQL.Text := Select_BunMiddle; paramByName('BmCode').AsString := CbMiddle.text; paramByName('BlCode').AsString := CbLarge.text; Open; lblMiddle.Caption := FieldByname('BmName').AsString; end; end; procedure TBasicCode_f.btnPrintClick(Sender: TObject); var prtBasicCode_f: TprtBasicCode_f; begin prtBasicCode_f := TprtBasicCode_f.CreateFrm(Self, grdBasic); try with prtBasicCode_f, QuickRep1 do begin PreviewModal; end; finally prtBasicCode_f.Free; end; end; procedure TBasicCode_f.edtNameKeyPress(Sender: TObject; var Key: Char); begin if KEY = #13 then begin btnSave.setfocus; end; end; procedure TBasicCode_f.grdBasicRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); const Select_BunMiddle2 = 'Select * from tblBunMiddle' + #13#10 + 'where Bmcode =:BmCode and Blcode =:BlCode'; Select_BunLarge2 = 'Select * from tblBunLarge' + #13#10 + 'where Blcode =:BlCode'; begin if (grdBasic.cells[1, NewRow] <> '') and (newRow <> 0) then begin edtCode.text := GrdBasic.Cells[1, newRow]; edtName.text := GrdBasic.Cells[2, newRow]; edtRegDate.Text := GrdBasic.Cells[3, newRow]; rgUse.ItemIndex := StrToInt(GrdBasic.Cells[4, newRow]); cblarge.text := GrdBasic.Cells[5, newRow]; cbMiddle.text := GrdBasic.Cells[6, newRow]; edtYoyul.text := GrdBasic.Cells[5, newRow]; with dm_f.sqlwork do begin SQL.Text := Select_BunLarge2; paramByName('BlCode').AsString := CbLarge.text; Open; lblLarge.Caption := FieldByname('BlName').AsString; end; with dm_f.sqlwork do begin SQL.Text := Select_BunMiddle2; paramByName('BmCode').AsString := CbMiddle.text; Open; lblMiddle.Caption := FieldByname('BmName').AsString; end; end; end; procedure TBasicCode_f.btnCancelClick(Sender: TObject); begin fieldClear; GrdShow; end; procedure TBasicCode_f.grdbasicGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); begin if (ARow >= 0) then HAlign := taCenter; end; procedure TBasicCode_f.grdbasicClickCell(Sender: TObject; ARow, ACol: Integer); const Select_BunMiddle2 = 'Select * from tblBunMiddle' + #13#10 + 'where Bmcode =:BmCode and Blcode =:BlCode'; Select_BunLarge2 = 'Select * from tblBunLarge' + #13#10 + 'where Blcode =:BlCode'; begin if (grdBasic.cells[1, aRow] <> '') and (aRow <> 0) then begin edtCode.text := GrdBasic.Cells[1, aRow]; edtName.text := GrdBasic.Cells[2, aRow]; edtRegDate.Text := GrdBasic.Cells[3, aRow]; rgUse.ItemIndex := StrToInt(GrdBasic.Cells[4, aRow]); cblarge.text := GrdBasic.Cells[5, aRow]; cbMiddle.text := GrdBasic.Cells[6, aRow]; edtYoyul.text := GrdBasic.Cells[5, aRow]; with dm_f.sqlwork do begin SQL.Text := Select_BunLarge2; paramByName('BlCode').AsString := CbLarge.text; Open; lblLarge.Caption := FieldByname('BlName').AsString; end; with dm_f.sqlwork do begin SQL.Text := Select_BunMiddle2; paramByName('BmCode').AsString := CbMiddle.text; Open; lblMiddle.Caption := FieldByname('BmName').AsString; end; end; end; end.
unit roDocHost; interface uses Windows, ActiveX, SHDocVw, Classes; type TDocHostUIInfo = packed record cbSize: ULONG; dwFlags: DWORD; dwDoubleClick: DWORD; end; const DOCHOSTUIFLAG_DIALOG = 1; DOCHOSTUIFLAG_DISABLE_HELP_MENU = 2; DOCHOSTUIFLAG_NO3DBORDER = 4; DOCHOSTUIFLAG_SCROLL_NO = 8; DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE = 16; DOCHOSTUIFLAG_OPENNEWWIN = 32; DOCHOSTUIFLAG_DISABLE_OFFSCREEN = 64; DOCHOSTUIFLAG_FLAT_SCROLLBAR = 128; DOCHOSTUIFLAG_DIV_BLOCKDEFAULT = 256; DOCHOSTUIFLAG_ACTIVATE_CLIENTHIT_ONLY = 512; const DOCHOSTUIDBLCLK_DEFAULT = 0; DOCHOSTUIDBLCLK_SHOWPROPERTIES = 1; DOCHOSTUIDBLCLK_SHOWCODE = 2; type { IDocHostUIHandler } IDocHostUIHandler = interface(IUnknown) ['{bd3f23c0-d43e-11cf-893b-00aa00bdce1a}'] function ShowContextMenu(const dwID: DWORD; const ppt: PPOINT; const pcmdtReserved: IUnknown; const pdispReserved: IDispatch): HRESULT; stdcall; function GetHostInfo(var pInfo: TDOCHOSTUIINFO): HRESULT; stdcall; function ShowUI(const dwID: DWORD; const pActiveObject: IOleInPlaceActiveObject; const pCommandTarget: IOleCommandTarget; const pFrame: IOleInPlaceFrame; const pDoc: IOleInPlaceUIWindow): HRESULT; stdcall; function HideUI: HRESULT; stdcall; function UpdateUI: HRESULT; stdcall; function EnableModeless(const fEnable: BOOL): HRESULT; stdcall; function OnDocWindowActivate(const fActivate: BOOL): HRESULT; stdcall; function OnFrameWindowActivate(const fActivate: BOOL): HRESULT; stdcall; function ResizeBorder(const prcBorder: PRECT; const pUIWindow: IOleInPlaceUIWindow; const fRameWindow: BOOL): HRESULT; stdcall; function TranslateAccelerator(const lpMsg: PMSG; const pguidCmdGroup: PGUID; const nCmdID: DWORD): HRESULT; stdcall; function GetOptionKeyPath(var pchKey: POLESTR; const dw: DWORD): HRESULT; stdcall; function GetDropTarget(const pDropTarget: IDropTarget; out ppDropTarget: IDropTarget): HRESULT; stdcall; function GetExternal(out ppDispatch: IDispatch): HRESULT; stdcall; function TranslateUrl(const dwTranslate: DWORD; const pchURLIn: POLESTR; var ppchURLOut: POLESTR): HRESULT; stdcall; function FilterDataObject(const pDO: IDataObject; out ppDORet: IDataObject): HRESULT; stdcall; end; { TRestrictedWebBrowser } TRestrictedWebBrowser = class(TWebBrowser, IDocHostUIHandler) function ShowContextMenu(const dwID: DWORD; const ppt: PPOINT; const pcmdtReserved: IUnknown; const pdispReserved: IDispatch): HRESULT; stdcall; function GetHostInfo(var pInfo: TDOCHOSTUIINFO): HRESULT; stdcall; function ShowUI(const dwID: DWORD; const pActiveObject: IOleInPlaceActiveObject; const pCommandTarget: IOleCommandTarget; const pFrame: IOleInPlaceFrame; const pDoc: IOleInPlaceUIWindow): HRESULT; stdcall; function HideUI: HRESULT; stdcall; function UpdateUI: HRESULT; stdcall; function EnableModeless(const fEnable: BOOL): HRESULT; stdcall; function OnDocWindowActivate(const fActivate: BOOL): HRESULT; stdcall; function OnFrameWindowActivate(const fActivate: BOOL): HRESULT; stdcall; function ResizeBorder(const prcBorder: PRECT; const pUIWindow: IOleInPlaceUIWindow; const fRameWindow: BOOL): HRESULT; stdcall; function TranslateAccelerator(const lpMsg: PMSG; const pguidCmdGroup: PGUID; const nCmdID: DWORD): HRESULT; stdcall; function GetOptionKeyPath(var pchKey: POLESTR; const dw: DWORD): HRESULT; stdcall; function GetDropTarget(const pDropTarget: IDropTarget; out ppDropTarget: IDropTarget): HRESULT; stdcall; function GetExternal(out ppDispatch: IDispatch): HRESULT; stdcall; function TranslateUrl(const dwTranslate: DWORD; const pchURLIn: POLESTR; var ppchURLOut: POLESTR): HRESULT; stdcall; function FilterDataObject(const pDO: IDataObject; out ppDORet: IDataObject): HRESULT; stdcall; public OnTranslateAccelerator:function(Sender:TObject;const lpMsg: PMSG):boolean of object; PoppedUp:record ScreenCoordinates:TPoint; MenuID:DWORD; CommandTarget:IInterface; HTMLObject:IDispatch; end; constructor Create(AOwner: TComponent); override; end; procedure Register; implementation uses Messages; procedure Register; begin RegisterComponents('Internet', [TRestrictedWebBrowser]); end; { TRestrictedWebBrowser } constructor TRestrictedWebBrowser.Create(AOwner: TComponent); begin inherited; OnTranslateAccelerator:=nil; end; function TRestrictedWebBrowser.EnableModeless( const fEnable: BOOL): HRESULT; begin Result := S_OK; end; function TRestrictedWebBrowser.FilterDataObject(const pDO: IDataObject; out ppDORet: IDataObject): HRESULT; begin ppDORet := nil; Result := S_FALSE; end; function TRestrictedWebBrowser.GetDropTarget( const pDropTarget: IDropTarget; out ppDropTarget: IDropTarget): HRESULT; begin Result := E_NOTIMPL; end; function TRestrictedWebBrowser.GetExternal( out ppDispatch: IDispatch): HRESULT; begin ppDispatch := nil; Result := S_FALSE; end; function TRestrictedWebBrowser.GetHostInfo( var pInfo: TDOCHOSTUIINFO): HRESULT; begin pInfo.cbSize := sizeof(TDOCHOSTUIINFO); pInfo.dwFlags := //DOCHOSTUIFLAG_DIALOG or DOCHOSTUIFLAG_DISABLE_HELP_MENU;// or //DOCHOSTUIFLAG_NO3DBORDER or //DOCHOSTUIFLAG_SCROLL_NO or //DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE; pInfo.dwDoubleClick := DOCHOSTUIDBLCLK_DEFAULT; Result := S_OK; end; function TRestrictedWebBrowser.GetOptionKeyPath(var pchKey: POLESTR; const dw: DWORD): HRESULT; begin pchKey := nil; Result := S_FALSE; end; function TRestrictedWebBrowser.HideUI: HRESULT; begin Result := S_OK; end; function TRestrictedWebBrowser.OnDocWindowActivate( const fActivate: BOOL): HRESULT; begin Result := S_OK; end; function TRestrictedWebBrowser.OnFrameWindowActivate( const fActivate: BOOL): HRESULT; begin Result := S_OK; end; function TRestrictedWebBrowser.ResizeBorder(const prcBorder: PRECT; const pUIWindow: IOleInPlaceUIWindow; const fRameWindow: BOOL): HRESULT; begin Result := S_OK; end; function TRestrictedWebBrowser.ShowContextMenu(const dwID: DWORD; const ppt: PPOINT; const pcmdtReserved: IInterface; const pdispReserved: IDispatch): HRESULT; begin //context menu tonen? with PoppedUp do begin ScreenCoordinates:=ppt^; MenuID:=dwID; CommandTarget:=pcmdtReserved; HTMLObject:=pdispReserved; end; if not(PopupMenu=nil) then PopupMenu.Popup(PoppedUp.ScreenCoordinates.X,PoppedUp.ScreenCoordinates.Y); Result := S_OK; end; function TRestrictedWebBrowser.ShowUI(const dwID: DWORD; const pActiveObject: IOleInPlaceActiveObject; const pCommandTarget: IOleCommandTarget; const pFrame: IOleInPlaceFrame; const pDoc: IOleInPlaceUIWindow): HRESULT; begin Result := S_OK; end; function TRestrictedWebBrowser.TranslateAccelerator(const lpMsg: PMSG; const pguidCmdGroup: PGUID; const nCmdID: DWORD): HRESULT; begin //if (lpMsg.message = WM_KEYDOWN) and (lpMsg.wParam = VK_F5) then Result := S_OK; if @OnTranslateAccelerator=nil then begin if lpMsg.wParam in [VK_F1..VK_F12] then Result:=S_OK else Result:=S_FALSE; end else begin if OnTranslateAccelerator(Self,lpMsg) then Result:=S_OK else Result:=S_FALSE; end; end; function TRestrictedWebBrowser.TranslateUrl(const dwTranslate: DWORD; const pchURLIn: POLESTR; var ppchURLOut: POLESTR): HRESULT; begin ppchURLOut := nil; Result := S_FALSE; end; function TRestrictedWebBrowser.UpdateUI: HRESULT; begin Result := S_OK; end; end.
//TP Carre Magique //Enonce: faire un programme qui affiche un carré magique, ce carré aura une dimension impaire, définit en constante. //On pourra ainsi changer de carre en changeant la constante. //Un carre magique est une table d'entier à 2 dimensons, dans tous les colonnes, les lignes et diagonales ont la même somme, //Vous devez utiliser obligatoirement un tableau à 2 dimensions. //Principe: //-1er le premier entier 1, se trouve au nord du milieu de la table //-2ème On place les chiffres de façon croissante en allant au Nord-Est de la position courante une seule fois. //-3ème Si la la place est dejà prise, on se deplace au Nord-Oueste, jusqu'a trouver cette place libre. //-4ème On s'arrête au carre de dimension (5x5),(7x7) //-5ème Le tableau est considere comme spherique. Si on arrie au delà de la dernière colonne, on revient à la première colonne. Idem pour les lignes. //3 Versions, un programme sans fonction et procedure. //Ensuite, codage sur pascal. //Ensuite, la V2 AVEC DES FONCTIONS ET PROC2DURES; //Pour finir, la V3 pareil avec des types enregistrement program CarreMag; uses crt; //BUT: Faire un carre magique, cf principe. //ENTREE: //SORTIE: CONST MINTAB = 1; TAILLETAB = 5; VAR nbMemoire,gen,x,y : INTEGER; board : array[MINTAB..TAILLETAB,MINTAB..TAILLETAB] of INTEGER; toggle : BOOLEAN; //INITIALISATION procedure initBoard(); var i,j : INTEGER; begin //INITIALISATION DU TABLEAU A 0 for i := MINTAB to TAILLETAB do begin for j := MINTAB to TAILLETAB do begin board[i,j] := 0; end; end; end; //Procedure d'actualisation procedure updateBoard(); var k,g,i,j : INTEGER; begin while(toggle <> true)do begin clrscr; toggle := true; //Si la cellule du tableau est égal à 0, alors on fait +1 par rapport a la valeur d'avant grâce a nbMemoire. if (board[x,y] = 0) then begin board[x,y] := nbMemoire; nbMemoire := nbMemoire+1; x := x + 1; end else begin x := x - 1; end; //Verification quand X sort du tableau (éviter l'erreur 201!) IF (x < MINTAB) then begin x:=TAILLETAB; end; if (x > TAILLETAB) then begin x := MINTAB; end; //Vers le haut, dans tous les cas. y := y - 1; //Eviter l'erreur 201 sur y ! if (y <= 0) then begin y := TAILLETAB; end; if (y > TAILLETAB) then begin y := MINTAB; end; //Ecriture du tableau for i := MINTAB to TAILLETAB do begin for j := MINTAB to TAILLETAB do begin if board[i,j] = 0 then begin toggle := false ; end; write(board[j,i]:5); end; writeln(); end; end; end; begin clrscr; //Clear screen nbMemoire := 1; //Initialiser le nombre en mémoire à 1. x := TAILLETAB DIV 2 + 1; //Positionner le X au nord du milieu. y := TAILLETAB DIV 2; //Positionner le y au nord du milieu. //(Position x,y = nord du milieu) //Initialisation (0,0,0,0,0,[...],0,0) initBoard(); //Countdown Writeln('Jeu du carre magique : Commencement dans 2 secondes.'); TextColor(red); Writeln('CARRE MAGIQUE ', TAILLETAB ,'x', TAILLETAB,'.'); TextColor(white); Delay(2000); clrscr; //Affichage du tableau et actualisation, carré magique terminé. updateBoard(); Readln(); end. //PASCAL SANS PROCEDURE { =================================================================================================== =================================================================================================== VERSION SANS PROCECDURE : PASCAL =================================================================================================== =================================================================================================== program CarreMag; uses crt; //BUT: Faire un carre magique, cf principe. //ENTREE: //SORTIE: CONST MINTAB = 1; TAILLETAB = 5; VAR nbMemoire,x,y,i,j : INTEGER; board : array[MINTAB..TAILLETAB,MINTAB..TAILLETAB] of INTEGER; toggle : BOOLEAN; BEGIN clrscr; //Clear screen nbMemoire := 1; //Initialiser le nombre en mémoire à 1. x := TAILLETAB DIV 2 + 1; //Positionner le X au nord du milieu. y := TAILLETAB DIV 2; //Positionner le y au nord du milieu. //(Position x,y = nord du milieu) //Countdown Writeln('Jeu du carre magique : Commencement dans 2 secondes.'); TextColor(red); Writeln('CARRE MAGIQUE ', TAILLETAB ,'x', TAILLETAB,'.'); TextColor(white); Delay(2000); clrscr; //INITIALISATION for i := MINTAB to TAILLETAB do begin for j := MINTAB to TAILLETAB do begin board[i,j] := 0; end; end; //actualisation while(toggle <> true)do begin clrscr; toggle := true; //Si la cellule du tableau est égal à 0, alors on fait +1 par rapport a la valeur d'avant grâce a nbMemoire. if (board[x,y] = 0) then begin board[x,y] := nbMemoire; nbMemoire := nbMemoire+1; x := x + 1; end else begin x := x - 1; end; //Verification quand X sort du tableau (éviter l'erreur 201!) if (x < MINTAB) then begin x:=TAILLETAB; end; if (x > TAILLETAB) then begin x := MINTAB; end; //Vers le haut, dans tous les cas. y := y - 1; //Eviter l'erreur 201 sur y ! if (y <= 0) then begin y := TAILLETAB; end; if (y > TAILLETAB) then begin y := MINTAB; end; //Ecriture du tableau for i := MINTAB to TAILLETAB do begin for j := MINTAB to TAILLETAB do begin if board[i,j] = 0 then begin toggle := false ; end; write(board[j,i]:5); end; writeln(); end; end; Readln(); end. } //ALGO { =================================================================================================== =================================================================================================== VERSION AVEC PROCEDURE : ALGO =================================================================================================== =================================================================================================== ALGORITHME CarMagiq //BUT: Faire un carre magique, cf principe. //ENTREE: tableau et entier ? //SORTIE: Le tableau du carré CONST MINTAB <- 1 : ENTIER TAILLETAB <- 15 : ENTIER VAR nbMemoire,x,y : ENTIER board : tableau[MINTAB..TAILLETAB,MINTAB..TAILLETAB] : ENTIER toggle : BOOLEEN //INITIALISATION PROCEDURE initBoard() var i,j : ENTIER DEBUT //INITIALISATION DU TABLEAU A 0 POUR i <- MINTAB A TAILLETAB FAIRE DEBUT POUR j <- MINTAB A TAILLETAB FAIRE DEBUT board[i,j] <- 0 FINPOUR FINPOUR FIN //PROCEDURE d'actualisation PROCEDURE updateBoard() var k,g,i,j : ENTIER DEBUT TANTQUE(toggle <> vrai)FAIRE DEBUT //EFFACER L'ÉCRAN (clrscr en pascal) toggle <- vrai //Si la cellule du tableau est égal à 0, alors on fait +1 par rapport a la valeur d'avant grâce a nbMemoire. SI (board[x,y] = 0) ALORS DEBUT board[x,y] <- nbMemoire nbMemoire <- nbMemoire+1 x <- x + 1 SINON DEBUT x <- x - 1 FINSI //Verification quand X sort du tableau (éviter l'erreur 201!) SI (x < MINTAB) ALORS DEBUT x<-TAILLETAB FINSI SI (x > TAILLETAB) ALORS DEBUT x <- MINTAB FINSI //Vers le haut, dans Aus les cas. y <- y - 1 //Eviter l'erreur 201 sur y ! SI (y <= 0) ALORS DEBUT y <- TAILLETAB FINSI SI (y > TAILLETAB) ALORS DEBUT y <- MINTAB FINSI //Ecriture du tableau POUR i <- MINTAB A TAILLETAB FAIRE DEBUT POUR j <- MINTAB A TAILLETAB FAIRE DEBUT SI board[i,j] = 0 ALORS DEBUT toggle <- faux FINSI ECRIRE(board[j,i]) //en pascal j'utiliserai ECRIRE(board[j,i]:5); :5 pour l'espacement. FINPOUR ECRIRE('') //saut de ligne FINPOUR FINTANTQUE FIN DEBUT //Efface l'écran (clrscr en pascal) nbMemoire <- 1 //Initialiser le nombre en mémoire à 1. x <- TAILLETAB DIV 2 + 1 //Positionner le X au nord du milieu. y <- TAILLETAB DIV 2 //Positionner le y au nord du milieu. //(Position x,y = nord du milieu) //Initialisation (0,0,0,0,0,[...],0,0) initBoard //Countdown ECRIRE('Jeu du carre magique : Commencement dans 2 secondes.') //Couleur rouge (TextColor(red)) en pascal ECRIRE('CARRE MAGIQUE ', TAILLETAB ,'x', TAILLETAB,'.') //Couleur blanche (TextColor(white)) en pascal //Attendre 2s Delay(2000) en pascal //Efface l'écran (clrscr en pascal) //Affichage du tableau et actualisation, carré magique terminé. updateBoard LIRE //Readln() en pascal FIN. } //ALGO { =================================================================================================== =================================================================================================== VERSION SANS PROCEDURE : ALGO =================================================================================================== =================================================================================================== ALGORITHME CarMagiq //BUT: Faire un carre magique, cf principe. //ENTREE: tableau et entier ? //SORTIE: Le tableau du carré CONST MINTAB = 1 TAILLETAB = 5 VAR nbMemoire,x,y,i,j : ENTIER board : array[MINTAB..TAILLETAB,MINTAB..TAILLETAB] : ENTIER toggle : BOOLEEN DEBUT //EFFACER L'ECRAN (clrscr en pascal) nbMemoire <- 1 //Initialiser le nombre en mémoire à 1. x <- TAILLETAB DIV 2 + 1 //Positionner le X au nord du milieu. y <- TAILLETAB DIV 2 //Positionner le y au nord du milieu. //(Position x,y = nord du milieu) //Countdown ECRIRE('Jeu du carre magique : Commencement dans 2 secondes.') //TEXTE COULEUR ROUGE ECRIRE('CARRE MAGIQUE ', TAILLETAB ,'x', TAILLETAB,'.') //TEXTE COULEUR BLANCHE //Delay(2000) attendre 2 secondes en pascal //EFFACER L'ECRAN (clrscr en pascal) //INITIALISATION POUR i <- MINTAB to TAILLETAB FAIRE DEBUT POUR j <- MINTAB to TAILLETAB FAIRE DEBUT board[i,j] <- 0 FINPOUR FINPOUR //actualisation TANTQUE(toggle <> vrai)FAIRE DEBUT //EFFACER L'ECRAN en pascal) toggle <- vrai //Si la cellule du tableau est égal à 0, alors on fait +1 par rapport a la valeur d'avant grâce a nbMemoire. SI (board[x,y] = 0) ALORS DEBUT board[x,y] <- nbMemoire nbMemoire <- nbMemoire+1 x <- x + 1 SINON DEBUT x <- x - 1 FINSI //Verification quand X sort du tableau (éviter l'erreur 201!) SI (x < MINTAB) ALORS DEBUT x<-TAILLETAB FINSI SI (x > TAILLETAB) ALORS DEBUT x <- MINTAB FINSI //Vers le haut, dans tous les cas. y <- y - 1 //Eviter l'erreur 201 sur y ! SI (y <= 0) ALORS DEBUT y <- TAILLETAB FINSI SI (y > TAILLETAB) ALORS DEBUT y <- MINTAB FINSI //Ecriture du tableau POUR i <- MINTAB to TAILLETAB FAIRE DEBUT POUR j <- MINTAB to TAILLETAB FAIRE DEBUT SI board[i,j] = 0 ALORS DEBUT toggle <- faux FINSI ECRIRE(board[j,i]:5) FINPOUR ECRIRE() FINPOUR FINTANTQUE LIRE() FIN. }
unit uModuleData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, VirtualTrees, Windows, Forms, uPropertyEditorNew, uVtBaseEditor, uLibrary; type { TModuleData } TModuleData = class(TPropertyData) protected fModule: IModule; end; { TUidData } TUidData = class(TModuleData) protected function GetValue: String; override; procedure SetValue(const aValue: String); override; function GetEditLink: IVtEditLink; override; public constructor Create(const aModule: IModule); reintroduce; end; { TNameData } TNameData = class(TModuleData) protected function GetValue: String; override; procedure SetValue(const aValue: String); override; public constructor Create(const aModule: IModule); reintroduce; end; { TTypeSignatureData } TTypeSignatureData = class(TModuleData) private fStrings: TStrings; protected function GetValue: String; override; procedure SetValue(const aValue: String); override; function GetEditLink: IVtEditLink; override; public constructor Create(const aModule: IModule); reintroduce; destructor Destroy; override; end; { TTypeBootloaderData } TTypeBootloaderData = class(TModuleData) private fStrings: TStrings; protected function GetValue: String; override; procedure SetValue(const aValue: String); override; function GetEditLink: IVtEditLink; override; public constructor Create(const aModule: IModule); reintroduce; destructor Destroy; override; end; { TModuleEditor } TModuleEditor = class(TPropertyEditor) private fModule: IModule; procedure SetModule(const aModule: IModule); public property Module: IModule read fModule write SetModule; end; implementation { TModuleEditor } procedure TModuleEditor.SetModule(const aModule: IModule); begin if fModule <> aModule then fModule := aModule; Clear; AddChild(nil, TUidData.Create(fModule)); AddChild(nil, TNameData.Create(fModule)); AddChild(nil, TTypeSignatureData.Create(fModule)); AddChild(nil, TTypeBootloaderData.Create(fModule)); end; { TUidData } constructor TUidData.Create(const aModule: IModule); begin inherited Create; Key := 'UID'; fModule := aModule; end; function TUidData.GetValue: String; begin Result := IntToStr(fModule.Uid); end; procedure TUidData.SetValue(const aValue: String); begin try fModule.Uid :=StrToIntDef(aValue, 0); if fModule.GetLastError <> 0 then raise Exception.Create('Модуль с данным Uid уже существует'); except on E: Exception do MessageBox(Application.MainFormHandle, PChar(Utf8ToAnsi(E.Message)), PChar(Utf8ToAnsi('Ошибка')), MB_ICONERROR + MB_OK); end; end; function TUidData.GetEditLink: IVtEditLink; begin Result := TVtIntegerEditLink.Create(1, 65535, 1); end; { TNameData } constructor TNameData.Create(const aModule: IModule); begin inherited Create; Key := 'Название'; fModule := aModule; end; function TNameData.GetValue: String; begin Result := fModule.Name; end; procedure TNameData.SetValue(const aValue: String); begin fModule.Name := aValue; end; { TTypeSignatureData } constructor TTypeSignatureData.Create(const aModule: IModule); begin inherited Create; Key := 'Тип сигнатуры'; fModule := aModule; fStrings := TStringList.Create; fStrings.CommaText := 'Нет,Автоопределение,RCCU3.0'; end; destructor TTypeSignatureData.Destroy; begin FreeAndNil(fStrings); inherited Destroy; end; function TTypeSignatureData.GetValue: String; begin Result := fStrings[Ord(fModule.TypeSignature)]; end; procedure TTypeSignatureData.SetValue(const aValue: String); begin fModule.TypeSignature := TTypeSignature(fStrings.IndexOf(aValue)); end; function TTypeSignatureData.GetEditLink: IVtEditLink; begin Result := TVtComboEditLink.Create(fStrings); end; { TTypeBootloaderData } function TTypeBootloaderData.GetValue: String; begin Result := fStrings[Ord(fModule.TypeBootloader)]; end; procedure TTypeBootloaderData.SetValue(const aValue: String); begin fModule.TypeBootloader := TTypeBootloader(fStrings.IndexOf(aValue)); end; function TTypeBootloaderData.GetEditLink: IVtEditLink; begin Result := TVtComboEditLink.Create(fStrings); end; constructor TTypeBootloaderData.Create(const aModule: IModule); begin inherited Create; Key := 'Тип bootloader''a'''; fModule := aModule; fStrings := TStringList.Create; fStrings.CommaText := '1,2,3'; end; destructor TTypeBootloaderData.Destroy; begin FreeAndNil(fStrings); inherited Destroy; end; end.
unit gmTool_Stitch_StrightLine; interface uses {$IFDEF FPC} LCLIntf, LCLType, LMessages, Types, {$ELSE} Windows, Messages, {$ENDIF} Graphics, Controls, Forms, Classes, SysUtils, GR32, GR32_Image, GR32_Layers, GR32_Types, gmTools, Thred_Types; type TgmEditMode = (emNew, emAppendChild, emEditNode); TgmtoolStitchStrightLine = class(TgmTool) private FXorPointss : TArrayOfArrayOfPoint; FShapePoints : TArrayOfFloatPoint; FStartPoint, FEndPoint : TFloatPoint; FLeftButtonDown : Boolean; FAngled : Boolean; FShift : TShiftState; //for redraw by shift-keyboard-down //FDragging : Boolean; FTempLayer : TRubberbandLayer; FEditMode: TgmEditMode; FVertexCount: Integer; FSelections: TArrayOfPFRMHED; FXorDrawn : Boolean; function CorrectLocation(P1,P2:TPoint):TRect ; procedure ClearPoints; procedure DrawStarOnCanvas; procedure DrawSelectionXOR; procedure DrawStarOnBackground; procedure SetAngled(const Value: Boolean); procedure Reset; //Esc pressed procedure RebuildXorPoint; procedure SetEditMode(const Value: TgmEditMode); //avoid too many convertion protected procedure MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); override; procedure MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); override; procedure MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); override; procedure KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); override; procedure KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); override; //RELATED MODE procedure ShapeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure ShapeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure ShapeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure NodeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure NodeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure NodeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); { procedure MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); } property Angled : Boolean read FAngled write SetAngled; public function IsCanFinish:Boolean; override; constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure ClearSelection; procedure AddSelection(Afrm : PFRMHED); property EditMode : TgmEditMode read FEditMode write SetEditMode; property VertexCount : Integer read FVertexCount write FVertexCount; property ShapePoints : TArrayOfFloatPoint read FShapePoints; property Selections : TArrayOfPFRMHED read FSelections write FSelections; published end; implementation uses Math, GR32_Polygons, gmIntegrator, gmShape_StraightStar; type TCustomImgViewAccess = class(TCustomImage32);//hack! TLayerCollectionAccess = class(TLayerCollection); function TgmtoolStitchStrightLine.CorrectLocation(P1, P2: TPoint): TRect; begin //topleft Result.Left := min(P1.X ,P2.X); Result.Top := min(P1.Y, P2.Y); //bottomright Result.Right := Max(P1.X ,P2.X); Result.Bottom := Max(P1.Y ,P2.Y); end; constructor TgmtoolStitchStrightLine.Create(AOwner: TComponent); begin inherited; //Cursor := crGrWandPlus;//crGrZoomIn; FVertexCount := 5; end; destructor TgmtoolStitchStrightLine.Destroy; begin isCanFinish();//free temp layer inherited; end; function TgmtoolStitchStrightLine.isCanFinish: Boolean; begin result := True; if Assigned(FTempLayer) then begin FTempLayer.Free; FTempLayer := nil; end; ClearPoints; ClearSelection; FModified := False; {$IFDEF DEBUGLOG} DebugLog('isCanFinish' ); {$ENDIF} end; procedure TgmtoolStitchStrightLine.ClearPoints; begin if Length(FShapePoints) > 0 then begin SetLength(FShapePoints, 0); end; FShapePoints := nil; end; procedure TgmtoolStitchStrightLine.DrawStarOnCanvas; var i, LPointCount : Integer; LPoints : TArrayOfPoint; LCanvas : TCanvas; begin LPoints := nil; LPointCount := Length(FShapePoints); if LPointCount > 1 then begin LCanvas := Image32.Bitmap.Canvas; SetLength(LPoints, LPointCount); try for i := 0 to (LPointCount - 1) do begin //LPoints[i] := Self.Image32.BitmapToControl( Point(FPolygon[i]) ); LPoints[i] := Point(FShapePoints[i]); end; if LCanvas.Pen.Mode <> pmNotXor then begin LCanvas.Pen.Mode := pmNotXor; end; LCanvas.Polyline(LPoints); finally SetLength(LPoints, 0); LPoints := nil; end; end; end; procedure TgmtoolStitchStrightLine.RebuildXorPoint; var i,j : Integer; dx, dy : TFloat; begin dx := FEndPoint.X - FStartPoint.X; dy := FEndPoint.Y - FStartPoint.Y; SetLength(FXorPointss, Length(FSelections)); for i := 0 to Length(FSelections) -1 do begin SetLength(FXorPointss[i], Length(FSelections[i].flt)); for j := 0 to Length(FSelections[i].flt)-1 do begin //LPoints[i] := Point(FShapePoints[i]); with FSelections[i].flt[j] do FXorPointss[i][j] := Point(FloatPoint(X + dx, Y + dy)); end; end; end; procedure TgmtoolStitchStrightLine.DrawSelectionXOR; var i,j : Integer; LCanvas : TCanvas; begin LCanvas := Image32.Bitmap.Canvas; if LCanvas.Pen.Mode <> pmNotXor then begin LCanvas.Pen.Mode := pmNotXor; end; FXorDrawn := not FXorDrawn; for i := 0 to Length(FXorPointss) -1 do begin LCanvas.Polyline(FXorPointss[i]); end; end; procedure TgmtoolStitchStrightLine.DrawStarOnBackground; var i, LPointCount : Integer; LPolygon : TPolygon32; LFillColor : TColor32; begin LPointCount := Length(FShapePoints); if LPointCount > 2 then begin LPolygon := TPolygon32.Create; try for i := 0 to (LPointCount - 1) do begin LPolygon.Add( FixedPoint(FShapePoints[i]) ); end; LFillColor := clTrGreen32; //Color32(shpFillColor.Brush.Color); LPolygon.Draw(Self.Image32.Bitmap, LFillColor, LFillColor); finally LPolygon.Free; end; end; end; procedure TgmtoolStitchStrightLine.MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin case EditMode of emNew, emAppendChild : ShapeMouseDown(Sender, Button, Shift, x,y, Layer); emEditNode : NodeMouseDown(Sender, Button, Shift, x,y, Layer); end; end; //draw marque box indicating area to be zoomed procedure TgmtoolStitchStrightLine.MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin case EditMode of emNew, emAppendChild : ShapeMouseMove(Sender, Shift, x,y, Layer); emEditNode : NodeMouseMove(Sender, Shift, x,y, Layer); end; end; procedure TgmtoolStitchStrightLine.MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin case EditMode of emNew, emAppendChild : ShapeMouseUp(Sender, Button, Shift, x,y, Layer); emEditNode : NodeMouseUp(Sender, Button, Shift, x,y, Layer); end; end; procedure TgmtoolStitchStrightLine.KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var LAngled : Boolean; begin case Key of VK_CONTROL : begin Angled := False; end; VK_ESCAPE : begin Reset; end; end; //DebugLog('KeyDown:'+ IntToStr(key)); end; procedure TgmtoolStitchStrightLine.KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_CONTROL : begin Angled := True; end; end; //DebugLog('KeyUp:'+ IntToStr(key)); end; procedure TgmtoolStitchStrightLine.SetAngled(const Value: Boolean); begin if FAngled <> Value then begin FAngled := Value; if FLeftButtonDown then begin with Image32.BitmapToControl(Point(FEndPoint)) do self.MouseMove(Image32, FShift, X, Y, nil ); {$IFDEF DEBUGLOG} DebugLog('Angled set to '+booltostr(FAngled) ); {$ENDIF} end; end; end; procedure TgmtoolStitchStrightLine.Reset; begin if FLeftButtonDown then begin FLeftButtonDown := False; case EditMode of emNew, emAppendChild : begin DrawStarOnCanvas; ClearPoints; end; emEditNode : begin DrawSelectionXOR; FEndPoint := FStartPoint; RebuildXorPoint; DrawSelectionXOR; end; end; FModified := False; end; end; procedure TgmtoolStitchStrightLine.AddSelection(Afrm: PFRMHED); var L : Integer; begin L := Length(FSelections); SetLength(FSelections, L+1 ); FSelections[L] := Afrm; end; procedure TgmtoolStitchStrightLine.ClearSelection; begin SetLength(FSelections, 0); SetLength(FXorPointss, 0); end; procedure TgmtoolStitchStrightLine.ShapeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); var LPoint : TFloatPoint; begin if Button = mbLeft then begin FAngled := not (ssCtrl in Shift); //initial LPoint := self.Image32.ControlToBitmap( FloatPoint(X, Y) ); ClearPoints; FStartPoint := LPoint; FEndPoint := LPoint; FShapePoints := GetStraightStarPoints(FStartPoint, FEndPoint, FVertexCount, FAngled); // DebugLog(Format('%d points. first: %d,%d',[Length(FPolygon), FPolygon[i])); DrawStarOnCanvas; FLeftButtonDown := True; // StatusBar1.Panels[0].Text := Format('Last Down at ( X = %d, Y = %d )', [LPoint.X, LPoint.Y]); end; end; procedure TgmtoolStitchStrightLine.ShapeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); var LPoint : TFloatPoint; begin if FLeftButtonDown then begin FModified := True; // erase the old figure Image32.Bitmap.BeginUpdate; DrawStarOnCanvas; // get new points of the figure FEndPoint := self.Image32.ControlToBitmap( FloatPoint(X, Y) ); FShapePoints := GetStraightStarPoints(FStartPoint, FEndPoint, self.FVertexCount, FAngled); DrawStarOnCanvas; Image32.Bitmap.EndUpdate; Image32.Invalidate; end; end; procedure TgmtoolStitchStrightLine.ShapeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin if FLeftButtonDown then begin FLeftButtonDown := False; DrawStarOnCanvas; //DrawStarOnBackground; end; end; procedure TgmtoolStitchStrightLine.NodeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin if Button = mbLeft then begin if FXorDrawn then DrawSelectionXOR; FStartPoint := self.Image32.ControlToBitmap( FloatPoint(X, Y) ); FEndPoint := FStartPoint; FLeftButtonDown := True; if Length(FSelections) > 0 then begin RebuildXorPoint; DrawSelectionXOR; end; end; end; procedure TgmtoolStitchStrightLine.NodeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin if FLeftButtonDown and (Length(FSelections) > 0) then begin FModified := True; // erase the old figure Image32.Bitmap.BeginUpdate; DrawSelectionXOR; // get new points of selection FEndPoint := self.Image32.ControlToBitmap( FloatPoint(X, Y) ); RebuildXorPoint; DrawSelectionXOR; Image32.Bitmap.EndUpdate; Image32.Invalidate; end; end; procedure TgmtoolStitchStrightLine.NodeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); var i,j : Integer; dx, dy : TFloat; begin {$IFDEF DEBUGLOG} DebugLog('NodeMouseUp'); {$ENDIF} if FLeftButtonDown then //only interest on Left Mouse begin FLeftButtonDown := False; { TODO -ox2nie : in future, better to using Transformation class rather than inplace transform. } dx := FEndPoint.X - FStartPoint.X; dy := FEndPoint.Y - FStartPoint.Y; //if FStartPoint <> FEndPoint then //incompatible error FModified := (dx <> 0) and (dy <> 0); if FModified then begin for i := 0 to Length(FSelections) -1 do begin for j := 0 to Length(FSelections[i].flt)-1 do begin //LPoints[i] := Point(FShapePoints[i]); with FSelections[i].flt[j] do begin //FXorPointss[i][j] := Point(FloatPoint(X + dx, Y + dy)); x := X + dx; y := Y + dy; end; end; end; //Image32.Invalidate; end; end; end; procedure TgmtoolStitchStrightLine.SetEditMode(const Value: TgmEditMode); begin if FEditMode <> Value then begin //Reset; isCanFinish; FEditMode := Value; end; end; end.
{$V-} unit Mouse; interface var MouseExists : boolean; MouseVisible : boolean; MouseButtons : byte; {01} procedure MouseReset; {02} procedure MouseCursor(on:boolean); {03} procedure MouseStatus(var status, col, lin : integer); {04} procedure MouseMoveTo(new_col, new_lin : integer); {05} function MousePressed (button:integer; var count,col,lin:integer):boolean; {06} function MouseReleased(button:integer; var count,col,lin:integer):boolean; {07} procedure MouseRange(col1,lin1,col2,lin2 : integer); {08} procedure MouseTextCursor(cursor_type : integer; arg1, arg2 : word); {09} procedure MouseReadMotion(var horizontal_count, vertical_count : integer); {10} procedure LightPenOn; {11} procedure LightPenOff; {12} procedure MouseRatio(horizontal, vertical : integer); {13} procedure MouseConditionalOff(col1, lin1, col2, lin2 : integer); {14} function MouseGetSize : word; {15} procedure MouseSaveDriver(var p:pointer; s:word); {16} procedure MouseRestoreDriver(var p:pointer; s:word); {17} procedure MouseGetSensitivity(var h,v:word); {18} procedure MouseSetCRTPage(page:byte); {19} function MouseGetCRTPage : byte; {20} procedure MouseEnableDriver; {21} function MouseDisableDriver : boolean; {22} procedure MouseSetLanguage(lan:byte); {23} function MouseGetLanguage : byte; {24} procedure MouseGetInformation(var Version,MouseType:string; var IRQp:byte); {25} procedure CurHand; {26} procedure CurHourGlass; {27} procedure CurUpArrow; {28} procedure CurLeftArrow; {29} procedure CurStandard; {30} procedure CurBigStandard; {31} procedure CurSight; implementation uses Dos; type tCursMask = record Matr : array[1..2,1..16] of word; Horz, Vert : integer; end; var masc : tCursMask; r : Registers; {<<< XX >>>---------------------------------------------------------------- | CallMouse ---------------------------------------------------------------------------} procedure CallMouse(MouseFunction : integer); begin r.AX := MouseFunction; intr ($33, r); end; { CallMouse } {<<< XX >>>---------------------------------------------------------------- | MouseGraphCursor ---------------------------------------------------------------------------} procedure MouseGraphCursor; begin r.BX := word(masc.Horz); r.CX := word(masc.vert); r.DX := ofs(masc); r.ES := seg(masc); CallMouse($09); end; {<<< XX >>>---------------------------------------------------------------- | BTW (BinToWord) ---------------------------------------------------------------------------} function BTW(str:string) : word; var w, aux, cont : word; begin w := 0; aux := 1; for cont := length(str) DownTo 1 do begin w := w + (ord(str[cont])-48)*aux; aux := aux * 2; end; BTW := w; end; {<<< 01 >>>---------------------------------------------------------------- | MouseReset ---------------------------------------------------------------------------} procedure MouseReset; begin CallMouse($00); MouseExists := r.AX <> 0; MouseButtons := r.BX; MouseVisible := false; end; { Reset } {<<< 02 >>>---------------------------------------------------------------- | MouseCursor ---------------------------------------------------------------------------} procedure MouseCursor(on:boolean); begin if (on) then begin if (MouseVisible) then exit; CallMouse($01); MouseVisible := true; end else begin if (not MouseVisible) then exit; CallMouse($02); MouseVisible := false; end; end; {<<< 03 >>>---------------------------------------------------------------- | MouseStatus ---------------------------------------------------------------------------} procedure MouseStatus(var status, col, lin : integer); begin CallMouse ($03); col := r.CX; lin := r.DX; status := r.BX; end; {<<< 04 >>>---------------------------------------------------------------- | MouseMoveTo ---------------------------------------------------------------------------} procedure MouseMoveTo(new_col, new_lin : integer); begin r.CX := new_col; r.DX := new_lin; CallMouse($04); end; {<<< 05 >>>---------------------------------------------------------------- | MousePressed ---------------------------------------------------------------------------} function MousePressed(button:integer; var count,col,lin:integer):boolean; var result : boolean; begin with r do begin BX := pred(button); CallMouse($05); case button of 1 : result := AX and $01 <> 0; 2 : result := AX and $02 <> 0; 3 : result := AX and $04 <> 0; end; { case } count := BX; col := CX; lin := DX; end; { with } MousePressed := result; end; {<<< 06 >>>---------------------------------------------------------------- | MouseReleased ---------------------------------------------------------------------------} function MouseReleased(button:integer; var count,col,lin:integer):boolean; var result : boolean; begin with r do begin BX := pred(button); CallMouse($06); case button of 1 : result := AX and $01 <> 0; 2 : result := AX and $02 <> 0; 3 : result := AX and $04 <> 0; end; { case } count := BX; col := CX; lin := DX; end; { with } MouseReleased := result; end; {<<< 07 >>>---------------------------------------------------------------- | MouseRange ---------------------------------------------------------------------------} procedure MouseRange(col1,lin1,col2,lin2 : integer); begin r.CX := col1; r.DX := col2; CallMouse($07); r.CX := lin1; r.DX := lin2; CallMouse($08); end; {<<< 08 >>>---------------------------------------------------------------- | MouseTextCursor ---------------------------------------------------------------------------} procedure MouseTextCursor(cursor_type : integer; arg1, arg2 : word); begin r.BX := cursor_type; r.CX := arg1; r.DX := arg2; CallMouse($0A); end; {<<< 09 >>>---------------------------------------------------------------- | MouseReadMotion ---------------------------------------------------------------------------} procedure MouseReadMotion(var horizontal_count, vertical_count : integer); begin CallMouse($0B); horizontal_count := r.CX; vertical_count := r.DX; end; {<<< 10 >>>---------------------------------------------------------------- | LightPenOn ---------------------------------------------------------------------------} procedure LightPenOn; begin CallMouse($0D); end; {<<< 11 >>>---------------------------------------------------------------- | LightPenOff ---------------------------------------------------------------------------} procedure LightPenOff; begin CallMouse($0E); end; {<<< 12 >>>---------------------------------------------------------------- | MouseRatio ---------------------------------------------------------------------------} procedure MouseRatio(horizontal, vertical : integer); begin if (vertical < 1) then vertical := 1; if (horizontal < 1) then horizontal := 1; r.CX := horizontal; r.DX := vertical; CallMouse($0F); end; {<<< 13 >>>---------------------------------------------------------------- | MouseConditionalOff ---------------------------------------------------------------------------} procedure MouseConditionalOff(col1, lin1, col2, lin2 : integer); begin if (not MouseVisible) then exit; r.CX := col1; r.DX := lin1; r.SI := col2; r.DI := lin2; CallMouse($10); MouseVisible := false; end; {<<< 14 >>>---------------------------------------------------------------- | MouseGetSize ---------------------------------------------------------------------------} function MouseGetSize : word; begin CallMouse($15); MouseGetSize := r.BX; end; {<<< 15 >>>---------------------------------------------------------------- | MouseSaveDriver ---------------------------------------------------------------------------} procedure MouseSaveDriver(var p:pointer; s:word); begin GetMem(p,s); r.ES := seg(p); r.DX := ofs(p); CallMouse($16); end; {<<< 16 >>>---------------------------------------------------------------- | MouseRestoreDriver ---------------------------------------------------------------------------} procedure MouseRestoreDriver(var p:pointer; s:word); begin r.ES := seg(p); r.DX := ofs(p); CallMouse($17); FreeMem(p,s); end; {<<< 17 >>>---------------------------------------------------------------- | MouseGetSensitivity ---------------------------------------------------------------------------} procedure MouseGetSensitivity(var h,v:word); begin CallMouse($1B); h := r.BX; { Raz„o (mickeys/pixel) na horizontal } v := r.CX; { Raz„o (mickeys/pixel) na vertical } end; {<<< 18 >>>---------------------------------------------------------------- | MouseSetCRTPage ---------------------------------------------------------------------------} procedure MouseSetCRTPage(page:byte); begin r.BX := page; CallMouse($1D); end; {<<< 19 >>>---------------------------------------------------------------- | MouseGetCRTPage ---------------------------------------------------------------------------} function MouseGetCRTPage : byte; begin CallMouse($1E); MouseGetCRTPage := r.BX end; {<<< 20 >>>---------------------------------------------------------------- | MouseDisableDriver ---------------------------------------------------------------------------} function MouseDisableDriver : boolean; begin CallMouse($1F); MouseDisableDriver := r.AX = $1F; end; {<<< 21 >>>---------------------------------------------------------------- | MouseEnableDriver ---------------------------------------------------------------------------} procedure MouseEnableDriver; begin CallMouse($20); end; {<<< 22 >>>---------------------------------------------------------------- | MouseSetLanguage ---------------------------------------------------------------------------} procedure MouseSetLanguage(lan:byte); begin r.BX := lan; CallMouse($22); end; {<<< 23 >>>---------------------------------------------------------------- | MouseGetLanguage ---------------------------------------------------------------------------} function MouseGetLanguage : byte; begin CallMouse($23); MouseGetLanguage := r.BX end; {<<< 24 >>>---------------------------------------------------------------- | MouseGetInformation ---------------------------------------------------------------------------} procedure MouseGetInformation(var Version,MouseType:string; var IRQp:byte); Const mType : array[1..5] of string[12] = ('Bus Mouse', 'Serial Mouse','InPort Mouse', 'PS/2 Mouse', 'HP Mouse'); var VerAux : string[10]; begin CallMouse($24); str(r.BH, Version); str(r.BL, VerAux); Version := Version + '.' + VerAux; MouseType := mType[r.CH]; IRQp := r.CL; end; {<<< 25 >>>---------------------------------------------------------------- | CurHand ---------------------------------------------------------------------------} procedure CurHand; begin with masc do begin matr[1,01] := BTW('1111001111111111'); matr[2,01] := BTW('0000110000000000'); matr[1,02] := BTW('1110110111111111'); matr[2,02] := BTW('0001001000000000'); matr[1,03] := BTW('1110110111111111'); matr[2,03] := BTW('0001001000000000'); matr[1,04] := BTW('1110110111111111'); matr[2,04] := BTW('0001001000000000'); matr[1,05] := BTW('1110110111111111'); matr[2,05] := BTW('0001001000000000'); matr[1,06] := BTW('1110110001001111'); matr[2,06] := BTW('0001001110110000'); matr[1,07] := BTW('1110110110110001'); matr[2,07] := BTW('0001001001001110'); matr[1,08] := BTW('1110110110110110'); matr[2,08] := BTW('0001001001001001'); matr[1,09] := BTW('1000110110110110'); matr[2,09] := BTW('0111001001001001'); matr[1,10] := BTW('0110111111111110'); matr[2,10] := BTW('1001000000000001'); matr[1,11] := BTW('0110111111111110'); matr[2,11] := BTW('1001000000000001'); matr[1,12] := BTW('0110111111111110'); matr[2,12] := BTW('1001000000000001'); matr[1,13] := BTW('0111111111111110'); matr[2,13] := BTW('1000000000000001'); matr[1,14] := BTW('1011111111111110'); matr[2,14] := BTW('0100000000000001'); matr[1,15] := BTW('1101111111111101'); matr[2,15] := BTW('0010000000000010'); matr[1,16] := BTW('1110000000000011'); matr[2,16] := BTW('0001111111111100'); Horz := 5; Vert := 0; end; MouseGraphCursor; end; {<<< 26 >>>---------------------------------------------------------------- | CurHourGlass ---------------------------------------------------------------------------} procedure CurHourGlass; begin with masc do begin matr[1,01] := BTW('1000000000000011'); matr[2,01] := BTW('0111111111111100'); matr[1,02] := BTW('1011111111111011'); matr[2,02] := BTW('0100000000000100'); matr[1,03] := BTW('1011111111111011'); matr[2,03] := BTW('0100000000000100'); matr[1,04] := BTW('1011100000111011'); matr[2,04] := BTW('0100011111000100'); matr[1,05] := BTW('1101000000010111'); matr[2,05] := BTW('0010111111101000'); matr[1,06] := BTW('1110100000101111'); matr[2,06] := BTW('0001011111010000'); matr[1,07] := BTW('1111010001011111'); matr[2,07] := BTW('0000101110100000'); matr[1,08] := BTW('1111001010011111'); matr[2,08] := BTW('0000110101100000'); matr[1,09] := BTW('1111011011011111'); matr[2,09] := BTW('0000100100100000'); matr[1,10] := BTW('1110111011101111'); matr[2,10] := BTW('0001000100010000'); matr[1,11] := BTW('1101111011110111'); matr[2,11] := BTW('0010000100001000'); matr[1,12] := BTW('1011111011111011'); matr[2,12] := BTW('0100000100000100'); matr[1,13] := BTW('1011110101111011'); matr[2,13] := BTW('0100001010000100'); matr[1,14] := BTW('1011101010111011'); matr[2,14] := BTW('0100010101000100'); matr[1,15] := BTW('1000000000000011'); matr[2,15] := BTW('0111111111111100'); matr[1,16] := BTW('1111111111111111'); matr[2,16] := BTW('0000000000000000'); Horz := 7; Vert := 7; end; MouseGraphCursor; end; {<<< 27 >>>---------------------------------------------------------------- | CurUpArrow ---------------------------------------------------------------------------} procedure CurUpArrow; begin with masc do begin matr[1,01] := BTW('1111111111111111'); matr[2,01] := BTW('0000000100000000'); matr[1,02] := BTW('1111111111111111'); matr[2,02] := BTW('0000001110000000'); matr[1,03] := BTW('1111111111111111'); matr[2,03] := BTW('0000001110000000'); matr[1,04] := BTW('1111111111111111'); matr[2,04] := BTW('0000011111000000'); matr[1,05] := BTW('1111111111111111'); matr[2,05] := BTW('0000011111000000'); matr[1,06] := BTW('1111111111111111'); matr[2,06] := BTW('0000111111100000'); matr[1,07] := BTW('1111111111111111'); matr[2,07] := BTW('0000111111100000'); matr[1,08] := BTW('1111111111111111'); matr[2,08] := BTW('0001111111110000'); matr[1,09] := BTW('1111111111111111'); matr[2,09] := BTW('0001111111110000'); matr[1,10] := BTW('1111111111111111'); matr[2,10] := BTW('0011111111111000'); matr[1,11] := BTW('1111111111111111'); matr[2,11] := BTW('0000001110000000'); matr[1,12] := BTW('1111111111111111'); matr[2,12] := BTW('0000001110000000'); matr[1,13] := BTW('1111111111111111'); matr[2,13] := BTW('0000001110000000'); matr[1,14] := BTW('1111111111111111'); matr[2,14] := BTW('0000001110000000'); matr[1,15] := BTW('1111111111111111'); matr[2,15] := BTW('0000001110000000'); matr[1,16] := BTW('1111111111111111'); matr[2,16] := BTW('0000001110000000'); Horz := 7; Vert := 0; end; MouseGraphCursor; end; {<<< 28 >>>---------------------------------------------------------------- | CurLeftArrow ---------------------------------------------------------------------------} procedure CurLeftArrow; begin with masc do begin matr[1,01] := BTW('1111111111111111'); matr[2,01] := BTW('0000000000000000'); matr[1,02] := BTW('1111111111111111'); matr[2,02] := BTW('0000000000000000'); matr[1,03] := BTW('1111111111111111'); matr[2,03] := BTW('0000000000000000'); matr[1,04] := BTW('1111111111111111'); matr[2,04] := BTW('0000000000000000'); matr[1,05] := BTW('1111111111111111'); matr[2,05] := BTW('0000000110000000'); matr[1,06] := BTW('1111111111111111'); matr[2,06] := BTW('0000011110000000'); matr[1,07] := BTW('1111111111111111'); matr[2,07] := BTW('0011111111111111'); matr[1,08] := BTW('1111111111111111'); matr[2,08] := BTW('1111111111111111'); matr[1,09] := BTW('1111111111111111'); matr[2,09] := BTW('0011111111111111'); matr[1,10] := BTW('1111111111111111'); matr[2,10] := BTW('0000011110000000'); matr[1,11] := BTW('1111111111111111'); matr[2,11] := BTW('0000000110000000'); matr[1,12] := BTW('1111111111111111'); matr[2,12] := BTW('0000000000000000'); matr[1,13] := BTW('1111111111111111'); matr[2,13] := BTW('0000000000000000'); matr[1,14] := BTW('1111111111111111'); matr[2,14] := BTW('0000000000000000'); matr[1,15] := BTW('1111111111111111'); matr[2,15] := BTW('0000000000000000'); matr[1,16] := BTW('1111111111111111'); matr[2,16] := BTW('0000000000000000'); Horz := 0; Vert := 7; end; MouseGraphCursor; end; {<<< 29 >>>---------------------------------------------------------------- | CurStandard (Default) ---------------------------------------------------------------------------} procedure CurStandard; begin with masc do begin matr[1,01] := BTW('0011111111111111'); matr[2,01] := BTW('0000000000000000'); matr[1,02] := BTW('0001111111111111'); matr[2,02] := BTW('0100000000000000'); matr[1,03] := BTW('0000111111111111'); matr[2,03] := BTW('0110000000000000'); matr[1,04] := BTW('0000011111111111'); matr[2,04] := BTW('0111000000000000'); matr[1,05] := BTW('0000001111111111'); matr[2,05] := BTW('0111100000000000'); matr[1,06] := BTW('0000000111111111'); matr[2,06] := BTW('0111110000000000'); matr[1,07] := BTW('0000000011111111'); matr[2,07] := BTW('0111111000000000'); matr[1,08] := BTW('0000000001111111'); matr[2,08] := BTW('0111111100000000'); matr[1,09] := BTW('0000000000111111'); matr[2,09] := BTW('0111111110000000'); matr[1,10] := BTW('0000000000011111'); matr[2,10] := BTW('0111110000000000'); matr[1,11] := BTW('0000000111111111'); matr[2,11] := BTW('0110110000000000'); matr[1,12] := BTW('0001000011111111'); matr[2,12] := BTW('0100011000000000'); matr[1,13] := BTW('0011000011111111'); matr[2,13] := BTW('0000011000000000'); matr[1,14] := BTW('1111100001111111'); matr[2,14] := BTW('0000001100000000'); matr[1,15] := BTW('1111100001111111'); matr[2,15] := BTW('0000001100000000'); matr[1,16] := BTW('1111110000111111'); matr[2,16] := BTW('0000000000000000'); Horz := 0; Vert := 0; end; MouseGraphCursor; end; {<<< 30 >>>---------------------------------------------------------------- | CurBigStandard ---------------------------------------------------------------------------} procedure CurBigStandard; begin with masc do begin matr[1,01] := BTW('0000000000000000'); matr[2,01] := BTW('0000000000000000'); matr[1,02] := BTW('0000000000000001'); matr[2,02] := BTW('0111111111111100'); matr[1,03] := BTW('0000000000000011'); matr[2,03] := BTW('0111111111111000'); matr[1,04] := BTW('0000000000000111'); matr[2,04] := BTW('0111111111110000'); matr[1,05] := BTW('0000000000001111'); matr[2,05] := BTW('0111111111100000'); matr[1,06] := BTW('0000000000011111'); matr[2,06] := BTW('0111111111000000'); matr[1,07] := BTW('0000000000111111'); matr[2,07] := BTW('0111111110000000'); matr[1,08] := BTW('0000000000011111'); matr[2,08] := BTW('0111111111000000'); matr[1,09] := BTW('0000000000001111'); matr[2,09] := BTW('0111111111100000'); matr[1,10] := BTW('0000000000000111'); matr[2,10] := BTW('0111110111110000'); matr[1,11] := BTW('0000001000000011'); matr[2,11] := BTW('0111100011111000'); matr[1,12] := BTW('0000011100000001'); matr[2,12] := BTW('0111000001111100'); matr[1,13] := BTW('0000111110000000'); matr[2,13] := BTW('0110000000111110'); matr[1,14] := BTW('0001111111000001'); matr[2,14] := BTW('0100000000011100'); matr[1,15] := BTW('0011111111100011'); matr[2,15] := BTW('0000000000001000'); matr[1,16] := BTW('0111111111110111'); matr[2,16] := BTW('0000000000000000'); Horz := 0; Vert := 0; end; MouseGraphCursor; end; {<<< 31 >>>---------------------------------------------------------------- | CurSight ---------------------------------------------------------------------------} procedure CurSight; begin with masc do begin matr[1,01] := BTW('1111111111111111'); matr[2,01] := BTW('0000000100000000'); matr[1,02] := BTW('1111111111111111'); matr[2,02] := BTW('0000000100000000'); matr[1,03] := BTW('1111111111111111'); matr[2,03] := BTW('0000011111000000'); matr[1,04] := BTW('1111111111111111'); matr[2,04] := BTW('0000100100100000'); matr[1,05] := BTW('1111111111111111'); matr[2,05] := BTW('0001000100010000'); matr[1,06] := BTW('1111111111111111'); matr[2,06] := BTW('0011001110001000'); matr[1,07] := BTW('1111111111111111'); matr[2,07] := BTW('0010010001001000'); matr[1,08] := BTW('1111111111111111'); matr[2,08] := BTW('1111110101111110'); matr[1,09] := BTW('1111111111111111'); matr[2,09] := BTW('0010010001001000'); matr[1,10] := BTW('1111111111111111'); matr[2,10] := BTW('0010001110001000'); matr[1,11] := BTW('1111111111111111'); matr[2,11] := BTW('0001000100010000'); matr[1,12] := BTW('1111111111111111'); matr[2,12] := BTW('0000100100100000'); matr[1,13] := BTW('1111111111111111'); matr[2,13] := BTW('0000011111000000'); matr[1,14] := BTW('1111111111111111'); matr[2,14] := BTW('0000000100000000'); matr[1,15] := BTW('1111111111111111'); matr[2,15] := BTW('0000000100000000'); matr[1,16] := BTW('1111111111111111'); matr[2,16] := BTW('0000000000000000'); Horz := 7; Vert := 7; end; MouseGraphCursor; end; {==========================================================================} begin CallMouse(0); MouseExists := r.AX <> 0; MouseButtons := r.BX; MouseVisible := false; end.
unit uAcompMedico; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uDMPrincipal, uFormCadBase, ImgList, DB, ComCtrls, ToolWin, Grids, DBGrids, StdCtrls, JvExStdCtrls, JvCombobox, JvExControls, JvXPCore, JvXPButtons, JvEdit, ConstTipos, Mask, JvExMask, JvToolEdit, uFuncoesGeral; const NumLinhas = 3; MargemEsq = 75; EspacoLinhas = 13; TamLinha = 70; type TfrmAcompMedico = class(TfrmCadBase) edtDataInicial: TJvDateEdit; edtDataFinal: TJvDateEdit; dbgOcorrencias: TDBGrid; edtMat: TEdit; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tbtn_ImprimirClick(Sender: TObject); procedure tbtn_VisualizarClick(Sender: TObject); procedure tbtn_ExcelClick(Sender: TObject); procedure tbtn_ExcluirClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ds1DataChange(Sender: TObject; Field: TField); procedure tbtn_AlterarClick(Sender: TObject); procedure tbtn_IncluirClick(Sender: TObject); procedure dbgOcorrenciasDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btn_PesquisarClick(Sender: TObject); private slLinhas : TStringList; { Private declarations } public fMat : String; function Registro: Boolean; procedure OpenAcompMedico; class procedure Carregar(Mat: String); { Public declarations } end; var frmAcompMedico: TfrmAcompMedico; implementation uses ZDataset, uAcompMedicoCad, uAlunos, uAcompMedicoRel, uDMAction; {$R *.dfm} { TfrmAcompMedico } procedure TfrmAcompMedico.btn_PesquisarClick(Sender: TObject); var sSQL : String; begin sSQL := 'SELECT * FROM AcompMedico WHERE Mat = '+QuotedStr(fMat); if edtDataInicial.Date > 0 then sSQL := sSQL + ' AND Data >= ' +QuotedStr(FormatDateTime('yyyy-mm-dd', edtDataInicial.Date)); if edtDataFinal.Date > 0 then sSQL := sSQL + ' AND Data <= ' +QuotedStr(FormatDateTime('yyyy-mm-dd', edtDataFinal.Date)); sSQL := sSQL + ' ORDER BY Data'; //desc DMPrincipal.OpenSQL(DMPrincipal.qry_AcompMedico, sSQL); end; class procedure TfrmAcompMedico.Carregar(Mat: String); begin Application.CreateForm(TfrmAcompMedico, frmAcompMedico); try frmAcompMedico.fMat := Mat; frmAcompMedico.edt_Pesquisa.Text := DMPrincipal.OpenSQL_Sel_str('SELECT Nome FROM Alunos WHERE Mat = ' + QuotedStr(Mat)); frmAcompMedico.btn_Pesquisar.Click; frmAcompMedico.ShowModal; finally FreeAndNil(frmAcompMedico); end; end; procedure TfrmAcompMedico.dbgOcorrenciasDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var Ultimalinha : Integer; ilinha : Integer; begin with dbgOcorrencias.Canvas do begin FillRect(Rect); if DMPrincipal.qry_AcompMedico.Active and (DMPrincipal.qry_AcompMedico.RecordCount > 0) then begin // Data de ocorrência Font.Name := 'Arial'; Font.Size := 10; Font.Style := [fsBold]; TextOut(Rect.Left + 2, Rect.Top + 2, FormatDateTime('dd/mm/yyyy', DMPrincipal.qry_AcompMedico.FieldByName('Data').Value)); // Texto da ocorrência Font.Name := 'Courier New'; Font.Size := 8; Font.Style := []; slLinhas.Text := WrapText(DMPrincipal.qry_AcompMedico.FieldByName('Observacoes').AsString, TamLinha); if slLinhas.Count > Numlinhas then Ultimalinha := NumLinhas else Ultimalinha := slLinhas.Count; for iLinha := 0 to Ultimalinha - 1 do TextOut(Rect.Left + MargemEsq , Rect.Top + 1 + iLinha * EspacoLinhas, slLinhas[iLinha]); end; end; end; procedure TfrmAcompMedico.ds1DataChange(Sender: TObject; Field: TField); begin inherited; statusBar_1.Panels[0].Text := 'Ocorrências ('+IntToStr(DMPrincipal.qry_AcompMedico.RecordCount)+' registro(s) encontrado(s) )'; end; procedure TfrmAcompMedico.FormCreate(Sender: TObject); begin inherited; ds1.DataSet := DMPrincipal.qry_AcompMedico; slLinhas := TStringList.Create; end; procedure TfrmAcompMedico.FormDestroy(Sender: TObject); begin inherited; slLinhas.Free; end; procedure TfrmAcompMedico.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then btn_PesquisarClick(Sender); end; procedure TfrmAcompMedico.FormShow(Sender: TObject); begin inherited; edtMat.Text := fMat; edt_Pesquisa.Text := frmAlunos.ds1.DataSet.FieldByName('Nome').AsString; end; procedure TfrmAcompMedico.OpenAcompMedico; begin with DMPrincipal.qry_AcompMedico do begin Close; SQL.Clear; SQL.Add('SELECT * FROM AcompMedico WHERE Mat = ' + QuotedStr(fMat)); Open; end; end; function TfrmAcompMedico.Registro: Boolean; begin with DMPrincipal.qry_executaSQL do begin Active := False; SQL.Clear; SQL.Add('CALL sp_AcompMedico_IU ( :vNumOcorrencia, :vMat, :vData, :vObservacoes)' ); case frmAcompMedicoCad.Operacao of opIncluir : begin ParamByName('vNumOcorrencia').Value := 0; ParamByName('vMat').Value := fMat; end; opAlterar : begin ParamByName('vNumOcorrencia').Value := ds1.DataSet.FieldValues['NumOcorrencia']; ParamByName('vMat').Value := ds1.DataSet.FieldValues['Mat']; end; end; ParamByName('vData').AsDate := frmAcompMedicoCad.edtData.Date; ParamByName('vObservacoes').AsString := frmAcompMedicoCad.mmoOcorrencias.Lines.Text; try DMPrincipal.Zconn.StartTransaction; ExecSQL; except on E: Exception do begin Result := False; DMPrincipal.Zconn.Rollback; Application.MessageBox(PAnsiChar(e.Message + #13 + 'Erro ao Tentar excecutar esta Ação!' + #13 + 'Entre em contato com o Suporte do Sistema!'), 'Atenção!',MB_ICONWARNING); Exit; end; end; DMPrincipal.Zconn.Commit; Result := True; end; end; procedure TfrmAcompMedico.tbtn_AlterarClick(Sender: TObject); var ponto : TBookmark; begin inherited; ds1.DataSet.DisableControls; ponto := ds1.DataSet.GetBookmark; Application.CreateForm(TfrmAcompMedicoCad, frmAcompMedicoCad); try frmAcompMedicoCad.Operacao := opAlterar; frmAcompMedicoCad.ShowModal; if frmAcompMedicoCad.ModalResult = mrOk then begin DMPrincipal.Espiao.Esp_AlteracaoGuarda(Self.Caption, ds1.DataSet); Registro; OpenAcompMedico; ds1.DataSet.GotoBookmark(ponto); DMPrincipal.Espiao.Esp_AlteracaoVerifica( Self.Caption,'NumOcorrencia', ds1.DataSet,[ds1.DataSet.FieldByName('NumOcorrencia').AsString]); end; finally ds1.DataSet.EnableControls; ds1.DataSet.FreeBookMark(ponto); FreeAndNil(frmAcompMedicoCad); end; end; procedure TfrmAcompMedico.tbtn_ExcelClick(Sender: TObject); begin inherited; // end; procedure TfrmAcompMedico.tbtn_ExcluirClick(Sender: TObject); begin if Application.MessageBox('Deseja realmente Excluir o Registro?', 'Exclusão!', MB_YESNO + MB_ICONQUESTION) = ID_YES then begin ExcluirRegistro(DMPrincipal.Zconn, DMPrincipal.qry_sp_Delete, DMPrincipal.qry_AcompMedico,'AcompMedico','NumOcorrencia','NumOcorrencia'); DMPrincipal.Espiao.Esp_IncExc(Self.Caption, tbtn_Excluir.Caption,DMPrincipal.qry_AcompMedico,['NumOcorrencia', 'Mat']); OpenAcompMedico; ds1.DataSet.Last; end; end; procedure TfrmAcompMedico.tbtn_ImprimirClick(Sender: TObject); begin inherited; Try Application.CreateForm(TqRelAcompMedico,qRelAcompMedico); qRelAcompMedico.ShowModal; DMPrincipal.Espiao.RegistraLog(Self.Caption, tbtn_Imprimir.Caption, 'Imprimir'); finally freeAndNil(qRelAcompMedico); end; end; procedure TfrmAcompMedico.tbtn_IncluirClick(Sender: TObject); begin inherited; Application.CreateForm(TfrmAcompMedicoCad, frmAcompMedicoCad); try frmAcompMedicoCad.Operacao := opIncluir; frmAcompMedicoCad.edtData.Date := Date; frmAcompMedicoCad.ShowModal; if frmAcompMedicoCad.ModalResult = mrOk then begin Registro; OpenAcompMedico; ds1.DataSet.Last; DMPrincipal.Espiao.Esp_IncExc(Self.Caption, tbtn_Incluir.Caption,ds1.DataSet,['NumOcorrencia', 'Mat', 'Data', 'Observacoes']); end; finally FreeAndNil(frmAcompMedicoCad); end; end; procedure TfrmAcompMedico.tbtn_VisualizarClick(Sender: TObject); begin inherited; ds1.DataSet.DisableControls; Application.CreateForm(TfrmAcompMedicoCad, frmAcompMedicoCad); try frmAcompMedicoCad.Operacao := opVisualizar; frmAcompMedicoCad.ShowModal; DMPrincipal.Espiao.RegistraLog(Self.Caption, tbtn_Visualizar.Caption, 'Acompanhamento Médico'); finally ds1.DataSet.EnableControls; FreeAndNil(frmAcompMedicoCad); end; end; end.
unit BoardPattern; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, PatternDisplayer, Board, Project; type TBoardPatternForm = class(TForm) FileNamesTListBox: TListBox; Panel1: TPanel; CancelTButton: TButton; OKTButton: TButton; ScrollBox1: TScrollBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FileNamesTListBoxClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormResize(Sender: TObject); private { Private declarations } PatternDisplayer : TvePatternDisplayer; PatternFolder : string; Board : TbrBoard; public { Public declarations } Project : TveProject; end; var BoardPatternForm: TBoardPatternForm; implementation {$R *.dfm} uses BoardSize; procedure TBoardPatternForm.FormCreate(Sender: TObject); begin PatternDisplayer := TvePatternDisplayer.Create( Self ); PatternDisplayer.Parent := ScrollBox1; PatternDisplayer.Left := 0; PatternDisplayer.Top := 0; PatternDisplayer.Project.BoardWidth := 50; PatternDisplayer.Project.BoardHeight := 50; PatternDisplayer.PixelsPerCell := (ScrollBox1.Height) div 38; end; procedure TBoardPatternForm.FormShow(Sender: TObject); var PatternFileSpec : string; SearchRec : TSearchRec; FileName : string; begin Board := Project.Board; // folder used by multiple functions on this form PatternFolder := ExtractFilePath(ParamStr(0)) + 'Patterns\'; //PatternFolder := 'C:\Pattern\'; // first strip type in list is standard stripboard FileNamesTListBox.AddItem( 'Stripboard', nil ); FileNamesTListBox.AddItem( 'Donut', nil ); FileNamesTListBox.AddItem( 'Tripad', nil ); // fill list with file names PatternFileSpec := PatternFolder + '*.per'; if SysUtils.FindFirst( PatternFileSpec, 0, SearchRec ) = 0 then begin repeat FileName := ChangeFileExt(( SearchRec.Name ), '' ); FileNamesTListBox.AddItem( FileName, nil ); until FindNext( SearchRec ) <> 0; FindClose( SearchRec ); end; end; procedure TBoardPatternForm.FileNamesTListBoxClick(Sender: TObject); procedure SetupInBuiltPattern( Pattern : TbrPattern ); begin PatternDisplayer.Project.Clear; PatternDisplayer.Project.Board.Width := ScrollBox1.Width div PatternDisplayer.PixelsPerCell; PatternDisplayer.Project.Board.Height := ScrollBox1.Height div PatternDisplayer.PixelsPerCell; PatternDisplayer.Project.Board.Pattern := Pattern; PatternDisplayer.Project.Board.Prepare; end; var SelectionIndex : integer; FileName : string; begin SelectionIndex := FileNamesTListBox.ItemIndex; // invalid selection if (SelectionIndex < 0) or (SelectionIndex > FileNamesTListBox.Count) then begin exit; end; // first value is standard stripboard if SelectionIndex = 0 then begin SetupInBuiltPattern( ptStrip ); end else if SelectionIndex = 1 then begin SetupInBuiltPattern( ptDonut ); end else if SelectionIndex = 2 then begin SetupInBuiltPattern( ptTripad ); end // following values are names of files else begin FileName := PatternFolder + FileNamesTListBox.Items[SelectionIndex] + '.per'; PatternDisplayer.LoadFromFile( FileName ); end; // draw new pattern ScrollBox1.HorzScrollBar.Position := 0; ScrollBox1.VertScrollBar.Position := 0; PatternDisplayer.Paint; end; procedure TBoardPatternForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult <> mrOK then begin exit; end; // if OK button clicked, then use new board Board.LoadFromBoard( PatternDisplayer.Project.Board ); RescueOffBoardItems( Project ); end; procedure TBoardPatternForm.FormResize(Sender: TObject); var ButtonWidth : integer; Centre : integer; begin // centre import and close buttons ButtonWidth := CancelTButton.Width; Centre := Panel1.Width div 2; OKTButton.Left := Centre - ((ButtonWidth * 3) div 2); CancelTButton.Left := Centre + (ButtonWidth div 2); end; end.
{ Mystix Copyright (C) 2005 Piotr Jura This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You can contact with me by e-mail: pjura@o2.pl } unit uMyIniFiles; interface uses Graphics, SysUtils, IniFiles; type TMyIniFile = class(TIniFile) public function ReadColor(const Section, Ident: String; Default: TColor): TColor; procedure WriteColor(const Section, Ident: String; Value: TColor); end; implementation { TMyIniFile } function TMyIniFile.ReadColor(const Section, Ident: String; Default: TColor): TColor; var Color: String; begin Color := ReadString(Section, Ident, ''); if Color <> '' then Result := TColor( StrToInt(Color) ) else Result := Default; end; procedure TMyIniFile.WriteColor(const Section, Ident: String; Value: TColor); begin WriteString(Section, Ident, '$' + IntToHex(Integer(Value), 8)); end; end.
unit BreakContinueForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { Private declarations } public procedure Show(const Msg: string); end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.Button1Click(Sender: TObject); var S: string; I: Integer; Found: Boolean; begin { Break - Exits loop Continue - Jumps to condition or counter increment, continuing with next loop iteration } S := 'Hello World'; Found := False; for I := Low(S) to High(S) do // '=' is used for testing equality (not '==') if S[I] = 'o' then begin Found := True; Break; end; end; procedure TForm1.Show(const Msg: string); begin Memo1.Lines.Add(Msg); end; end.
unit GpVCL.OwnerDrawBitBtn; interface uses Winapi.Messages, Winapi.Windows, System.Classes, Vcl.Themes, Vcl.Graphics, Vcl.Controls, Vcl.Buttons; type TOwnerDrawBitBtn = class(Vcl.Buttons.TBitBtn) public type TOwnerDrawEvent = reference to procedure (button: TOwnerDrawBitBtn; canvas: TCanvas; drawRect: TRect; buttonState: TThemedButton); strict private FCanvas : TCanvas; FDetails : TThemedElementDetails; FIsFocused : boolean; FMouseInControl: boolean; FOnOwnerDraw : TOwnerDrawEvent; FState : TButtonState; strict protected procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; procedure DoDrawText(DC: HDC; const text: string; var textRect: TRect; textFlags: Cardinal); procedure DrawItem(const DrawItemStruct: TDrawItemStruct); protected procedure SetButtonStyle(ADefault: Boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DrawText(const value: string; textBounds: TRect; textFlags: longint); property OnOwnerDraw: TOwnerDrawEvent read FOnOwnerDraw write FOnOwnerDraw; end; TBitBtn = class(TOwnerDrawBitBtn) end; implementation uses System.Types, System.SysUtils; { TOwnerDrawBitBtn } procedure TOwnerDrawBitBtn.CMMouseEnter(var Message: TMessage); begin FMouseInControl := true; inherited; end; procedure TOwnerDrawBitBtn.CMMouseLeave(var Message: TMessage); begin FMouseInControl := false; inherited; end; procedure TOwnerDrawBitBtn.CNDrawItem(var Message: TWMDrawItem); begin if assigned(OnOwnerDraw) then DrawItem(Message.DrawItemStruct^) else inherited; end; constructor TOwnerDrawBitBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); FCanvas := TCanvas.Create; end; destructor TOwnerDrawBitBtn.Destroy; begin FreeAndNil(FCanvas); inherited; end; procedure TOwnerDrawBitBtn.DrawItem(const DrawItemStruct: TDrawItemStruct); var buttonState: TThemedButton; flags : longint; isDown : boolean; isDefault : boolean; rect : TRect; styleSvc : TCustomStyleServices; begin FCanvas.Handle := DrawItemStruct.hDC; rect := ClientRect; with DrawItemStruct do begin FCanvas.Handle := hDC; FCanvas.Font := Self.Font; isDown := itemState and ODS_SELECTED <> 0; isDefault := itemState and ODS_FOCUS <> 0; if not Enabled then FState := bsDisabled else if isDown then FState := bsDown else FState := bsUp; end; if not Enabled then buttonState := tbPushButtonDisabled else if IsDown then buttonState := tbPushButtonPressed else if FMouseInControl then buttonState := tbPushButtonHot else if FIsFocused or isDefault then buttonState := tbPushButtonDefaulted else buttonState := tbPushButtonNormal; if ThemeControl(Self) then begin styleSvc := StyleServices; FDetails := styleSvc.GetElementDetails(buttonState); // Parent background. if not (csGlassPaint in ControlState) then styleSvc.DrawParentBackground(Handle, DrawItemStruct.hDC, FDetails, True) else FillRect(DrawItemStruct.hDC, rect, GetStockObject(BLACK_BRUSH)); // buttonState shape. styleSvc.DrawElement(DrawItemStruct.hDC, FDetails, DrawItemStruct.rcItem); styleSvc.GetElementContentRect(FCanvas.Handle, FDetails, DrawItemStruct.rcItem, rect); if assigned(OnOwnerDraw) then OnOwnerDraw(Self, FCanvas, ClientRect, buttonState); if FIsFocused and isDefault and styleSvc.IsSystemStyle then begin FCanvas.Pen.Color := clWindowFrame; FCanvas.Brush.Color := clBtnFace; DrawFocusRect(FCanvas.Handle, rect); end; end else begin rect := ClientRect; flags := DFCS_BUTTONPUSH or DFCS_ADJUSTRECT; if IsDown then flags := flags or DFCS_PUSHED; if DrawItemStruct.itemState and ODS_DISABLED <> 0 then flags := flags or DFCS_INACTIVE; { DrawFrameControl doesn't allow for drawing a button as the default buttonState, so it must be done here. } if FIsFocused or isDefault then begin FCanvas.Pen.Color := clWindowFrame; FCanvas.Pen.Width := 1; FCanvas.Brush.Style := bsClear; FCanvas.Rectangle(rect.Left, rect.Top, rect.Right, rect.Bottom); { DrawFrameControl must draw within this border } InflateRect(rect, -1, -1); end; { DrawFrameControl does not draw a pressed buttonState correctly } if isDown then begin FCanvas.Pen.Color := clBtnShadow; FCanvas.Pen.Width := 1; FCanvas.Brush.Color := clBtnFace; FCanvas.Rectangle(rect.Left, rect.Top, rect.Right, rect.Bottom); InflateRect(rect, -1, -1); end else DrawFrameControl(DrawItemStruct.hDC, rect, DFC_BUTTON, flags); if FIsFocused then begin rect := ClientRect; InflateRect(rect, -1, -1); end; FCanvas.Font := Self.Font; if isDown then OffsetRect(rect, 1, 1); if assigned(FOnOwnerDraw) then OnOwnerDraw(Self, FCanvas, rect, buttonState); if FIsFocused and isDefault then begin rect := ClientRect; InflateRect(rect, -4, -4); FCanvas.Pen.Color := clWindowFrame; FCanvas.Brush.Color := clBtnFace; DrawFocusRect(FCanvas.Handle, rect); end; end; FCanvas.Handle := 0; end; procedure TOwnerDrawBitBtn.DoDrawText(DC: HDC; const Text: string; var textRect: TRect; textFlags: Cardinal); var textColor : TColor; textFormats: TTextFormat; begin if ThemeControl(Self) then begin if (FState = bsDisabled) or (not StyleServices.IsSystemStyle and (seFont in StyleElements)) then begin if not StyleServices.GetElementColor(FDetails, ecTextColor, textColor) or (textColor = clNone) then textColor := FCanvas.Font.Color; end else textColor := FCanvas.Font.Color; textFormats := TTextFormatFlags(textFlags); if csGlassPaint in ControlState then Include(textFormats, tfComposited); StyleServices.DrawText(DC, FDetails, text, textRect, textFormats, textColor); end else Winapi.Windows.DrawText(DC, text, Length(text), textRect, textFlags); end; procedure TOwnerDrawBitBtn.DrawText(const value: string; textBounds: TRect; textFlags: longint); const wordBreakFlag: array[Boolean] of longint = (0, DT_WORDBREAK); var flags: Longint; begin if ThemeControl(Self) then begin Brush.Style := bsClear; DoDrawText(FCanvas.Handle, Caption, textBounds, textFlags OR DrawTextBiDiModeFlags(0) OR wordBreakFlag[WordWrap]); end else begin flags := DrawTextBiDiModeFlags(0) or wordBreakFlag[WordWrap]; Brush.Style := bsClear; if (FState = bsDisabled) then begin OffsetRect(textBounds, 1, 1); Font.Color := clBtnHighlight; DoDrawText(FCanvas.Handle, Caption, textBounds, textFlags OR flags); OffsetRect(textBounds, -1, -1); Font.Color := clBtnShadow; DoDrawText(FCanvas.Handle, Caption, textBounds, textFlags OR flags); end else DoDrawText(FCanvas.Handle, Caption, textBounds, textFlags OR flags); end; end; procedure TOwnerDrawBitBtn.SetButtonStyle(ADefault: Boolean); begin inherited SetButtonStyle(ADefault); FIsFocused := ADefault; end; end.
unit DataHV; // THVTableData - trida starajici se o vyplnovani tabulky hnacich vozidel interface uses THnaciVozidlo, ComCtrls, SysUtils; type THVTableData=class private LV:TListView; public reload:boolean; procedure LoadToTable(); procedure UpdateLine(HV:THV); procedure UpdateTable(); procedure AddHV(line:Integer; HV:THV); procedure RemoveHV(line:Integer); constructor Create(LV:TListView); end; var HVTableData:THVTableData; implementation uses THvDatabase, Prevody, fMain, Trakce, SprDb; //////////////////////////////////////////////////////////////////////////////// constructor THVTableData.Create(LV:TListView); begin inherited Create; Self.LV := LV; end;//ctor //////////////////////////////////////////////////////////////////////////////// procedure THVTableData.LoadToTable(); var i, j:Integer; LI:TListItem; addr:Pointer; begin Self.LV.Clear(); for i := 0 to _MAX_ADDR-1 do begin if (HVDb.HVozidla[i] = nil) then continue; GetMem(addr, 3); Integer(addr^) := HVDb.HVozidla[i].adresa; LI := Self.LV.Items.Add; LI.Caption := IntToStr(i); LI.Data := addr; for j := 0 to Self.LV.Columns.Count-2 do LI.SubItems.Add(''); Self.UpdateLine(HVDb.HVozidla[i]); end; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure THVTableData.UpdateTable(); var i:Integer; begin for i := 0 to _MAX_ADDR-1 do begin if (not Assigned(HVDb.HVozidla[i])) then continue; if ((HVDb.HVozidla[i].changed) or (Self.reload)) then begin Self.UpdateLine(HVDb.HVozidla[i]); Self.LV.UpdateItems(HVDb.HVozidla[i].index, HVDb.HVozidla[i].index); end; end;//for i Self.reload := false; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure THVTableData.UpdateLine(HV:THV); var line:Integer; data:THVData; stav:THVStav; slot:TSlot; i:Integer; str:string; begin if (HV = nil) then Exit; HV.changed := false; line := HV.index; data := HV.data; stav := HV.stav; slot := HV.Slot; Self.LV.Items.Item[line].Caption := IntToStr(HV.adresa); Self.LV.Items.Item[line].SubItems.Strings[0] := data.Nazev; Self.LV.Items.Item[line].SubItems.Strings[1] := data.Oznaceni; Self.LV.Items.Item[line].SubItems.Strings[2] := data.Majitel; Self.LV.Items.Item[line].SubItems.Strings[3] := data.Poznamka; case (data.Trida) of THVClass.parni : Self.LV.Items.Item[line].SubItems.Strings[4] := 'parní'; THVClass.diesel : Self.LV.Items.Item[line].SubItems.Strings[4] := 'diesel'; THVClass.motor : Self.LV.Items.Item[line].SubItems.Strings[4] := 'motor'; THVClass.elektro : Self.LV.Items.Item[line].SubItems.Strings[4] := 'elektro'; end;//case case (stav.StanovisteA) of lichy : Self.LV.Items.Item[line].SubItems.Strings[5] := 'lichý'; sudy : Self.LV.Items.Item[line].SubItems.Strings[5] := 'sudý'; end;//case Self.LV.Items.Item[line].SubItems.Strings[18] := Format('%5.2f',[stav.najeto_vpred.Metru]); Self.LV.Items.Item[line].SubItems.Strings[19] := IntToStr(stav.najeto_vpred.Bloku); Self.LV.Items.Item[line].SubItems.Strings[20] := Format('%5.2f',[stav.najeto_vzad.Metru]); Self.LV.Items.Item[line].SubItems.Strings[21] := IntToStr(stav.najeto_vzad.Bloku); if (stav.stanice <> nil) then Self.LV.Items.Item[line].SubItems.Strings[6] := stav.stanice.Name else Self.LV.Items.Item[line].SubItems.Strings[6] := ''; if (stav.souprava > -1) then Self.LV.Items.Item[line].SubItems.Strings[17] := Soupravy.GetSprNameByIndex(stav.souprava) else Self.LV.Items.Item[line].SubItems.Strings[17] := '-'; case (slot.pom) of TPomStatus.progr : Self.LV.Items.Item[line].SubItems.Strings[16] := 'progr'; TPomStatus.error : Self.LV.Items.Item[line].SubItems.Strings[16] := 'error'; TPomStatus.pc : Self.LV.Items.Item[line].SubItems.Strings[16] := 'automat'; TPomStatus.released : Self.LV.Items.Item[line].SubItems.Strings[16] := 'ruční'; end;//case if (not HV.Slot.Prevzato) then begin // neprevzato Self.LV.Items.Item[line].SubItems.Strings[7] := '---'; Self.LV.Items.Item[line].SubItems.Strings[8] := '---'; Self.LV.Items.Item[line].SubItems.Strings[9] := '?'; Self.LV.Items.Item[line].SubItems.Strings[10] := '????'; Self.LV.Items.Item[line].SubItems.Strings[11] := '????'; Self.LV.Items.Item[line].SubItems.Strings[12] := '????'; Self.LV.Items.Item[line].SubItems.Strings[13] := '???? ????'; Self.LV.Items.Item[line].SubItems.Strings[14] := '???? ????'; if (slot.stolen) then Self.LV.Items.Item[line].SubItems.Strings[15] := 'ukradeno' else Self.LV.Items.Item[line].SubItems.Strings[15] := '---'; end else begin // prevzato Self.LV.Items.Item[line].SubItems.Strings[7] := IntToStr(TrkSystem.GetStepSpeed(Slot.speed)) + 'km/h / '+IntToStr(Slot.speed)+' st'; Self.LV.Items.Item[line].SubItems.Strings[8] := IntToStr(Slot.smer); Self.LV.Items.Item[line].SubItems.Strings[9] := IntToStr(PrevodySoustav.BoolToInt(Slot.funkce[0])); str := ''; for i := 1 to 4 do str := str + IntToStr(PrevodySoustav.BoolToInt(Slot.funkce[i])); Self.LV.Items.Item[line].SubItems.Strings[10] := str; str := ''; for i := 5 to 8 do str := str + IntToStr(PrevodySoustav.BoolToInt(Slot.funkce[i])); Self.LV.Items.Item[line].SubItems.Strings[11] := str; str := ''; for i := 9 to 12 do str := str + IntToStr(PrevodySoustav.BoolToInt(Slot.funkce[i])); Self.LV.Items.Item[line].SubItems.Strings[12] := str; str := ''; for i := 13 to 20 do begin str := str + IntToStr(PrevodySoustav.BoolToInt(Slot.funkce[i])); if (i = 16) then str := str + ' '; end; Self.LV.Items.Item[line].SubItems.Strings[13] := str; str := ''; for i := 21 to 28 do begin str := str + IntToStr(PrevodySoustav.BoolToInt(Slot.funkce[i])); if (i = 24) then str := str + ' '; end; Self.LV.Items.Item[line].SubItems.Strings[14] := str; if (slot.com_err) then Self.LV.Items.Item[line].SubItems.Strings[15] := 'COM ERROR!' else Self.LV.Items.Item[line].SubItems.Strings[15] := 'PC'; end;//else not prevzato end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure THVTableData.AddHV(line:Integer; HV:THV); var i:Integer; LI:TListItem; addr:Pointer; begin LI := Self.LV.Items.Insert(line); GetMem(addr, 3); Integer(addr^) := HV.adresa; LI.Data := addr; LI.Caption := IntToStr(HV.adresa); // = adresa for i := 0 to Self.LV.Columns.Count-1 do LI.Subitems.Add(''); Self.UpdateLine(HV); end;//procedure procedure THVTableData.RemoveHV(line:Integer); begin Self.LV.Items.Delete(line); end;//procedure //////////////////////////////////////////////////////////////////////////////// initialization finalization HVTableData.Free(); end.//unit
unit Apple.Utils; interface uses Macapi.ObjcRuntime, {$IFDEF IOS} iOSapi.Foundation, iOSapi.CocoaTypes, iOSapi.UIKit; {$ELSE} {$IFDEF MACOS} Macapi.Foundation, Macapi.CocoaTypes, Macapi.AppKit; {$ENDIF MACOS} {$ENDIF IOS} function NSStringToString(APtr: Pointer): string; overload; function NSStringToString(AStr: NSString): string; overload; function NSDateToDateTime(APtr: Pointer): TDateTime; overload; function NSDateToDateTime(ADate: NSDate): TDateTime; overload; function NSNumberToInt(ANumber: NSNumber): Integer; overload; function NSNumberToInt(APtr: Pointer): Integer; overload; function NSNumberToLongInt(ANumber: NSNumber): LongInt; overload; function NSNumberToLongInt(APtr: Pointer): LongInt; overload; function NSNumberToDouble(ANumber: NSNumber): Double; overload; function NSNumberToDouble(APtr: Pointer): Double; overload; function NSNumberToBool(ANumber: NSNumber): Boolean; overload; function NSNumberToBool(APtr: Pointer): Boolean; overload; function NSObjectToString(AObject: NSObject): string; overload; function NSObjectToString(APtr: Pointer): string; overload; function DateTimeToNSDate(ADateTime: TDateTime): NSDate; function NSStrPtr(AString: string): Pointer; function IntToNSNumber(ANumber: Integer): NSNumber; function NSNumberPtr(ANumber: Integer): Pointer; overload; function NSNumberPtr(ANumber: Double): Pointer; overload; function NSNumberPtr(ANumber: Single): Pointer; overload; function NSNumberPtr(ANumber: Int64): Pointer; overload; function NSNumberPtr(ANumber: SmallInt): Pointer; overload; function NSNumberPtr(ANumber: Cardinal): Pointer; overload; function NSNumberPtr(ANumber: Word): Pointer; overload; function NSNumberPtr(ANumber: UInt64): Pointer; overload; function NSNumberPtr(ANumber: Boolean): Pointer; overload; function PtrForObject(AObject: NSObject): Pointer; function ObjcClassName(APtr: Pointer): string; function StringToNSUrl(AString: string): NSUrl; procedure OpenURL(AUrl: string); {$IFDEF IOS} function ActiveView: UIView; function SharedApplication: UIApplication; {$ELSE} function ActiveView: NSView; function SharedApplication: NSApplication; {$ENDIF} implementation uses Macapi.ObjectiveC, System.SysUtils, System.StrUtils, FMX.Platform, FMX.Forms, {$IFDEF IOS} FMX.Platform.iOS {$ELSE} FMX.Platform.Mac {$ENDIF} ; function NSStringToString(APtr: Pointer): string; begin //TODO: Rewrite using routines from //http://delphihaven.wordpress.com/2011/09/26/converting-from-a-cocoa-string-to-a-delphi-string/ Result := NSStringToString(TNSString.Wrap(APtr)); end; function NSStringToString(AStr: NSString): string; begin //TODO: Rewrite using routines from //http://delphihaven.wordpress.com/2011/09/26/converting-from-a-cocoa-string-to-a-delphi-string/ Result := string(AStr.UTF8String); end; function NSStrPtr(AString: string): Pointer; begin {$IFDEF IOS} Result := TNSString.OCClass.stringWithUTF8String(MarshaledAString(UTF8Encode(AString))); {$ELSE} Result := TNSString.OCClass.stringWithUTF8String(PAnsiChar(UTF8Encode(AString))); {$ENDIF} end; function PtrForObject(AObject: NSObject): Pointer; begin Result := (AObject as ILocalObject).GetObjectID; end; function DateTimeToNSDate(ADateTime: TDateTime): NSDate; const cnDateTemplate = 'YYYY-MM-dd HH:mm:ss'; cnDateFmt = '%.4d-%.2d-%.2d %.2d:%.2d:%.2d'; var Day, Month, Year, Hour, Min, Sec, MSec: Word; DateStr: string; Tmp: NSDate; Formatter: NSDateFormatter; begin DecodeDate(ADateTime, Year, Month, Day); DecodeTime(ADateTime, Hour, Min, Sec, MSec); DateStr := Format(cnDateFmt, [Year, Month, Day, Hour, Min, Sec, 0]); Formatter := TNSDateFormatter.Create; try Formatter.setDateFormat(NSStr(cnDateTemplate)); Tmp := formatter.dateFromString(NSStr(DateStr)); Result := TNSDate.Wrap(Tmp.addTimeInterval(MSec / 1000)); Result.retain; finally Formatter.release; end; end; function NSDateToDateTime(APtr: Pointer): TDateTime; begin Result := NSDateToDateTime(TNSDate.Wrap(APtr)); end; function NSDateToDateTime(ADate: NSDate): TDateTime; var lCalendar: NSCalendar; lComps: NSDateComponents; lUnits: Cardinal; begin lCalendar := TNSCalendar.Wrap(TNSCalendar.OCClass.currentCalendar); lUnits := NSYearCalendarUnit or NSMonthCalendarUnit or NSDayCalendarUnit or NSHourCalendarUnit or NSMinuteCalendarUnit or NSSecondCalendarUnit; lComps := lCalendar.components(lUnits, ADate); Result := EncodeDate(lComps.year, lComps.month, lComps.day) + EncodeTime(lComps.hour, lComps.minute, lComps.second, 0); end; function NSObjectToString(AObject: NSObject): string; begin Result := NSObjectToString(PtrForObject(AObject)); end; function NSObjectToString(APtr: Pointer): string; var lClass: string; begin //This is NOT the ideal way to do this, but it will have to do until I can //figure out how to determine the actual Objective-C type behind a specified //pointer. lClass := ObjcClassName(APtr); if EndsStr('Date', lClass) then //This will format it a bit nicer than using NSDate.description, which //would use yyyy-mm-dd hh:mm:ss +0000 Result := DateTimeToStr(NSDateToDateTime(APtr)) else //The reason this works is because the NSObject class has a description //selector. While this isn't exposed in the Delphi wrapping of NSObject, we //can hijack the one in NSString, and the Objective-C runtime will happily //send the message to the object instance, which will respond accordingly. Result := NSStringToString(TNSString.Wrap(APtr).description); end; function NSNumberToInt(ANumber: NSNumber): Integer; begin Result := ANumber.integerValue; end; function NSNumberToInt(APtr: Pointer): Integer; begin Result := NSNumberToInt(TNSNumber.Wrap(APtr)); end; function NSNumberToLongInt(ANumber: NSNumber): LongInt; begin Result := ANumber.longLongValue; end; function NSNumberToLongInt(APtr: Pointer): LongInt; begin Result := NSNumberToLongInt(TNSNumber.Wrap(APtr)); end; function NSNumberToDouble(ANumber: NSNumber): Double; begin Result := ANumber.doubleValue; end; function NSNumberToDouble(APtr: Pointer): Double; begin Result := NSNumberToDouble(TNSNumber.Wrap(APtr)); end; function NSNumberToBool(ANumber: NSNumber): Boolean; overload; begin Result := ANumber.boolValue; end; function NSNumberToBool(APtr: Pointer): Boolean; overload; begin Result := NSNumberToBool(TNSNumber.Wrap(APtr)); end; function NSNumberPtr(ANumber: Integer): Pointer; begin Result := TNSNumber.OCClass.numberWithInt(ANumber); end; function NSNumberPtr(ANumber: Double): Pointer; begin Result := TNSNumber.OCClass.numberWithDouble(ANumber); end; function NSNumberPtr(ANumber: Single): Pointer; begin Result := TNSNumber.OCClass.numberWithFloat(ANumber); end; function NSNumberPtr(ANumber: Int64): Pointer; begin Result := TNSNumber.OCClass.numberWithLongLong(ANumber); end; function NSNumberPtr(ANumber: SmallInt): Pointer; begin Result := TNSNumber.OCClass.numberWithShort(ANumber); end; function NSNumberPtr(ANumber: Cardinal): Pointer; begin Result := TNSNumber.OCClass.numberWithUnsignedInt(ANumber); end; function NSNumberPtr(ANumber: Word): Pointer; begin Result := TNSNumber.OCClass.numberWithUnsignedShort(ANumber); end; function NSNumberPtr(ANumber: UInt64): Pointer; begin Result := TNSNumber.OCClass.numberWithUnsignedLongLong(ANumber); end; function NSNumberPtr(ANumber: Boolean): Pointer; overload; begin Result := TNSNumber.OCClass.numberWithBool(ANumber); end; function IntToNSNumber(ANumber: Integer): NSNumber; begin Result := TNSNumber.Wrap(NSNumberPtr(ANumber)); end; function ObjcClassName(APtr: Pointer): string; begin Result := string(class_getname(object_getclass(APtr))); end; function StringToNSUrl(AString: string): NSUrl; begin Result := TNSUrl.Wrap(TNSUrl.OCClass.URLWithString(NSStr(AString))) end; procedure OpenURL(AUrl: string); begin SharedApplication.openURL(StringToNSUrl(AUrl)); end; {$IFDEF IOS} function ActiveView: UIView; {$ELSE} function ActiveView: NSView; {$ENDIF} begin Result := WindowHandleToPlatform(Screen.ActiveForm.Handle).View; end; {$IFDEF IOS} function SharedApplication: UIApplication; begin Result := TUIApplication.wrap(TUIApplication.OCClass.SharedApplication); end; {$ELSE} function SharedApplication: NSApplication; begin Result := TNSApplication.wrap(TNSApplication.OCClass.SharedApplication); end; {$ENDIF} end.
unit dataunit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sqlite3conn, sqldb, FileUtil, sqlite3dyn; type { TData1 } TData1 = class(TDataModule) DBConnection: TSQLite3Connection; SQLQuery1: TSQLQuery; SQLQuery2: TSQLQuery; Counter: TSQLQuery; SQLTransaction1: TSQLTransaction; Zones: TSQLQuery; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private public procedure OpenDatabase; procedure CloseDatabase; function countbadges(const badgetype: string): integer; end; var Data1: TData1; implementation {$R *.lfm} { TData1 } procedure TData1.DataModuleCreate(Sender: TObject); begin {$IFDEF LINUX} sqlite3dyn.sqlitedefaultlibrary := './libsqlite3.so'; {$ENDIF} end; procedure TData1.DataModuleDestroy(Sender: TObject); begin Zones.Close; SQLQuery1.Close; DBConnection.Close; end; procedure TData1.OpenDatabase; begin DBConnection.Open; end; procedure TData1.CloseDatabase; begin SQLQuery1.Active := False; Zones.Active := False; DBConnection.Close; end; function TData1.countbadges(const badgetype: string): integer; begin // get the number of unique badges for the given badge type Counter.active := false; Counter.SQL.Text:= 'select count(distinct DisplayName) as badgecount from badges where Type = ' + quotedstr(badgetype); Counter.Open; try Counter.first; result := Counter.FieldByName('badgecount').AsInteger; finally Counter.close; end; end; end.
unit BancoDespacho; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CustomModule, Menus, StdActns, ActnList, JvComponentBase, JvFormPlacement, ExtCtrls, JvExControls, JvComponent, JvEnterTab, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, dxLayoutControl, cxGrid, ADODB, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLookAndFeelPainters, StdCtrls, cxButtons, cxPC, cxDBEdit, cxCheckBox, cxLabel, cxMemo, cxSpinEdit, cxTimeEdit, cxGroupBox, cxBlobEdit, ppComm, ppRelatv, ppDB, ppDBPipe, DBCtrls, DBActns; type TfrmBancoDespacho = class(TfrmCustomModule) dxLayoutControl1: TdxLayoutControl; dxLayoutGroup3: TdxLayoutGroup; dsDatos: TDataSource; dxLayoutControl1Group2: TdxLayoutGroup; dsPaciente: TDataSource; dsDonacion: TDataSource; dsDonante: TDataSource; qrPaciente: TADOQuery; qrDonacion: TADOQuery; qrDonante: TADOQuery; qrDonantePacienteID: TStringField; qrDonanteTipoDonante: TWideStringField; qrDonanteEstado: TWideStringField; qrDonanteRechaso: TWideStringField; qrDonanteRechasoNota: TWideStringField; qrEntradaPaciente: TADOQuery; qrEntradaPacienteEntredaID: TStringField; qrEntradaPacienteFecha: TDateTimeField; qrEntradaPacientePacienteID: TStringField; qrEntradaPacienteClienteID: TStringField; qrEntradaPacienteDoctorID: TStringField; qrEntradaPacientePolizaID: TStringField; qrEntradaPacienteEnClinica: TBooleanField; qrEntradaPacienteRecordClinica: TStringField; qrEntradaPacienteResultadoPaciente: TIntegerField; qrEntradaPacienteResultadoDoctor: TIntegerField; qrEntradaPacienteFechaPrometida: TDateTimeField; qrEntradaPacienteHoraPrometida: TStringField; qrEntradaPacienteFlebotomistaID: TStringField; qrEntradaPacienteNota: TMemoField; qrEntradaPacienteCoberturaConfirmada: TBooleanField; qrEntradaPacienteProyectoID: TStringField; qrEntradaPacienteRecid: TLargeintField; qrEntradaPacienteBruto: TBCDField; qrEntradaPacienteDescuento: TBCDField; qrEntradaPacienteSubTotal: TBCDField; qrEntradaPacienteCoberturaSeguro: TBCDField; qrEntradaPacienteNeto: TBCDField; qrEntradaPacienteNombrePaciente: TStringField; qrEntradaPacienteDireccion: TMemoField; qrEntradaPacienteTelefonos: TStringField; qrEntradaPacienteEmail: TStringField; qrEntradaPacienteClienteNombre: TStringField; qrEntradaPacienteSucursalId: TStringField; qrEntradaPacienteUserID: TStringField; qrEntradaPacienteTotalPendiente: TFloatField; qrEntradaPacienteCobroID: TStringField; qrEntradaPacienteTotalPagado: TBCDField; qrEntradaPacienteHoraEntrada: TStringField; qrEntradaPacientePrioridad: TIntegerField; qrEntradaPacienteFax: TStringField; qrEntradaPacienteTipoDocumento: TIntegerField; qrEntradaPacienteCoberturaPorc: TBCDField; qrEntradaPacienteCoberturaValor: TBCDField; qrEntradaPacienteDescuentoPorc: TBCDField; qrEntradaPacienteDescuentoValor: TBCDField; qrEntradaPacienteAprobadoPor: TStringField; qrEntradaPacienteMuestraNo: TStringField; qrEntradaPacienteAprobacionNo: TStringField; qrEntradaPacienteMonedaID: TStringField; qrEntradaPacienteFechaEntrada: TDateTimeField; qrEntradaPacienteCoberturaExpPorc: TBooleanField; qrEntradaPacienteEdadPaciente: TBCDField; qrEntradaPacienteNombreDoctor: TStringField; qrEntradaPacientePublicarInternet: TBooleanField; qrEntradaPacienteOrigen: TStringField; qrEntradaPacienteCarnet: TStringField; qrEntradaPacientePublicarInternetDoctor: TBooleanField; qrEntradaPacienteCuadreGlobal: TStringField; qrEntradaPacienteCuadreUsuario: TStringField; qrEntradaPacienteDescAutorizadoPor: TStringField; qrEntradaPacienteGastosVarios: TBCDField; qrEntradaPacienteNoAS400: TBooleanField; qrEntradaPacienteNoAxapta: TBooleanField; qrEntradaPacienteNoFactura: TBooleanField; qrEntradaPacienteFactExterior: TBooleanField; qrEntradaPacienteHold: TBooleanField; qrEntradaPacienteRepMuestra: TBooleanField; qrEntradaPacienteEntradaIdAnt: TStringField; qrEntradaPacienteDetalle: TADOQuery; qrEntradaPacienteDetallePruebaID: TStringField; qrEntradaPacienteDetalleComboPruebaID: TStringField; qrEntradaPacienteDetallePrecio: TBCDField; qrEntradaPacienteDetalleDescuento: TBCDField; qrEntradaPacienteDetalleDescuentoExtra: TBCDField; qrEntradaPacienteDetalleCodigoAutorizacion: TStringField; qrEntradaPacienteDetalleTotalLinea: TBCDField; qrEntradaPacienteDetalleRefRecid: TLargeintField; qrEntradaPacienteDetalleSecuencia: TLargeintField; qrEntradaPacienteDetalleDescripcion: TStringField; qrEntradaPacienteDetalleDescPct: TBCDField; qrEntradaPacienteDetalleCoberturaAplica: TBooleanField; qrEntradaPacienteDetalleCoberturaEspecial: TBCDField; qrEntradaPacienteDetalleCoberturaEspecialPorc: TBCDField; qrEntradaPacienteDetalleCoberturaAplicada: TBCDField; qrEntradaPacienteDetalleDescuentoLineaAplicado: TBCDField; qrEntradaPacienteDetalleMuestraNo: TStringField; qrEntradaPacienteDetalleComentario: TMemoField; qrEntradaPacienteDetalleCoberturaExpPorc: TBooleanField; qrEntradaPacienteDetalleRepMuestra: TBooleanField; qrEntradaPacienteDetalleMuestraAnt: TStringField; dsEntradaPacienteDetalle: TDataSource; dsEntradaPaciente: TDataSource; ppEntradaPaciente: TppDBPipeline; ppEntradaPacienteDetalle: TppDBPipeline; qrPacienteClienteID: TStringField; qrPacienteNombre: TStringField; qrPacienteContacto: TStringField; qrPacienteTelefono: TStringField; qrPacienteFax: TStringField; qrPacienteGrupoCliente: TStringField; qrPacienteIncluirPrecioTicket: TBooleanField; qrPacienteAutoConfirmar: TBooleanField; qrPacienteEmpleadoID: TStringField; qrPacienteCodigoAxapta: TStringField; qrPacienteemail: TStringField; qrPacientedireccionweb: TStringField; qrPacienteTelefono2: TStringField; qrPacienteMonedaID: TStringField; qrPacienteIdentificacion: TStringField; qrPacienteOrigen: TIntegerField; qrPacienteDireccion: TMemoField; qrPacienteCiudadID: TStringField; qrPacientePruebasPorDia: TSmallintField; qrPacienteCoberturaPorc: TBCDField; qrPacientePrincipal: TStringField; qrPacienteEnvioResultado: TIntegerField; qrPacientePublicarInternet: TBooleanField; qrPacienteSexo: TIntegerField; qrPacienteFechaNacimiento: TDateTimeField; qrPacienteSeguro: TStringField; qrPacientePoliza: TStringField; qrPacienteCobrarDiferencia: TBooleanField; qrPacienteEnviarFax: TBooleanField; qrPacienteActivarDescuentos: TBooleanField; qrPacienteUsarAliasNombre: TBooleanField; qrPacienteUsarAliasPrueba: TBooleanField; qrPacienteSiempreInternet: TBooleanField; qrPacienteImprimirAliasNombre: TBooleanField; qrPacienteImprimirAliasPrueba: TBooleanField; qrPacienteImprimirSoloTotales: TBooleanField; qrPacienteImprimirAliasResultados: TBooleanField; qrPacienteAlias: TStringField; qrPacienteQuienPaga: TStringField; qrPacienteTipoCliente: TStringField; qrPacienteEntregarResultados: TStringField; qrPacienteTextoReferencia: TStringField; qrPacienteSiempreImprimir: TBooleanField; qrPacienteTipoSangre: TStringField; qrPacientePacienteCiaId: TStringField; qrTipoDonacion: TADOQuery; dsTipoDonacion: TDataSource; qrTipoDonacionTipoFundaID: TWideStringField; qrTipoDonacionTipoFundaDes: TWideStringField; qrTipoDonacionDias: TIntegerField; qrDonanteDonanteActivo: TSmallintField; qrProductos: TADOQuery; dsProductos: TDataSource; qrProcesos: TADOQuery; dsProcesos: TDataSource; DataSetInsert1: TDataSetInsert; DataSetPost1: TDataSetPost; DataSetCancel1: TDataSetCancel; DataSetDelete1: TDataSetDelete; DataSetEdit1: TDataSetEdit; DataSetDelete2: TDataSetDelete; qrDetalles: TADOQuery; dsDetalles: TDataSource; qrDetallesProductoID: TWideStringField; qrDetallesCantidad: TBCDField; qrDetallesFecha: TDateTimeField; qrDetallesHora: TDateTimeField; qrDetallesDonacionId: TStringField; ActDetalles: TAction; qrDonacionDonacionID: TStringField; qrDonacionFecha: TDateTimeField; qrDonacionPacienteID: TStringField; qrDonacionNotaEntrevista: TMemoField; qrDonacionDonacionStatus: TWideStringField; qrDonacionDonacionEstado: TStringField; qrDonacionDonacionTipo: TStringField; qrDonacionComentario: TMemoField; qrDonacionCantidadRecogida: TBCDField; qrDonacionTemperatura: TBCDField; qrDonacionPeso: TBCDField; qrDonacionPulsoMinimo: TBCDField; qrDonacionPulsoEstado: TStringField; qrDonacionTensionArteriar: TStringField; qrDonacionHoraInicio: TDateTimeField; qrDonacionHoraFin: TDateTimeField; qrDonacionDirigidoNombre: TStringField; qrDonacionHospital: TStringField; qrDonacionFechaTranfusion: TDateTimeField; qrDonacionMedico: TStringField; qrDonacionTelefono: TStringField; qrDonacionTelefono2: TStringField; qrDonacionDireccionMedico: TMemoField; qrDonacionPagina: TSmallintField; qrDonacionTipoFundaID: TWideStringField; qrDonacionHemoglobina: TStringField; qrDonacionHematocito: TStringField; qrDonacionGlobulosBlancos: TStringField; qrDonacionPlaquetas: TStringField; qrDonacionNotasCuestionario: TMemoField; qrDonacionProductoID: TWideStringField; qrProductosProductoID: TWideStringField; qrProductosProductoDes: TWideStringField; qrProductosPrecio: TBCDField; qrProductosPrecioDolares: TBCDField; qrProcesosProcesoId: TWideStringField; qrProcesosProcesoDes: TStringField; dxLayoutControl1Item1: TdxLayoutItem; cxDBTextEdit4: TcxDBTextEdit; dxLayoutGroup1: TdxLayoutGroup; dxLayoutGroup2: TdxLayoutGroup; dxLayoutItem1: TdxLayoutItem; dxLayoutGroup4: TdxLayoutGroup; qrDetallesReservado: TBooleanField; cxButton1: TcxButton; Item1: TdxLayoutItem; Item4: TdxLayoutItem; cxGrid3: TcxGrid; cxGridDBTableView3: TcxGridDBTableView; cxGridDBColumn1: TcxGridDBColumn; cxGridLevel3: TcxGridLevel; Item3: TdxLayoutItem; cgDatos: TcxGrid; dbDatos: TcxGridDBTableView; dbDatosCodigoId: TcxGridDBColumn; dbDatosCantidad: TcxGridDBColumn; dbDatosFecha: TcxGridDBColumn; dbDatosHora: TcxGridDBColumn; dbDatosDonacionId: TcxGridDBColumn; dbDatosReservado: TcxGridDBColumn; lvDatos: TcxGridLevel; qrDetallesCodigoId: TStringField; Group1: TdxLayoutGroup; Item2: TdxLayoutItem; cxDBTextEdit1: TcxDBTextEdit; Item5: TdxLayoutItem; cxDBTextEdit2: TcxDBTextEdit; qrDetallesNombrePaciente: TStringField; procedure ActDetallesExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmBancoDespacho: TfrmBancoDespacho; implementation uses DataModule, DialogoTipoDonacion, DialogoEntrevista, DataBanco; {$R *.dfm} procedure TfrmBancoDespacho.ActDetallesExecute(Sender: TObject); begin inherited; qrDetalles.Close; qrDetalles.Parameters.ParamByName('ProductoId').Value:= DMB.qrBancoInventarioProductoID.Value; qrDetalles.Open; end; procedure TfrmBancoDespacho.FormCreate(Sender: TObject); begin inherited; DMB.qrBancoInventario.Close; DMB.qrBancoInventario.Open; ActDetallesExecute(Sender); { qrProductos.Close; qrProductos.Open; qrProcesos.Close; qrProcesos.Open; DM.qrDonacionesAprobadas.Close; DM.qrDonacionesAprobadas.Open; qrDonacion.Close; qrDonacion.Parameters.ParamByName('DonacionID').Value:= DM.qrDonacionesAprobadasDonacionID.Value; qrDonacion.Open; qrInventario.Close; qrInventario.Parameters.ParamByName('DonacionID').Value:= DM.qrDonacionesAprobadasDonacionID.Value; qrInventario.Open; } end; end.
unit uMenuHelper; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Menus; type { TPopupMenuHelper } TPopupMenuHelper = class helper for TPopupMenu public procedure AddMenuItem(const aCaption: string; const aClick: TNotifyEvent = nil); procedure AddMenuItem(const aParent: TMenuItem; const aCaption: string; const aImageIndex: Integer; const aClick: TNotifyEvent = nil); function AddSubMenu(const aCaption: string): TMenuItem; end; implementation { TPopupMenuHelper } procedure TPopupMenuHelper.AddMenuItem(const aCaption: string; const aClick: TNotifyEvent); var MenuItem: TMenuItem; begin MenuItem := TMenuItem.Create(Self); MenuItem.Caption := aCaption; MenuItem.OnClick := aClick; Items.Add(MenuItem); end; procedure TPopupMenuHelper.AddMenuItem(const aParent: TMenuItem; const aCaption: string; const aImageIndex: Integer; const aClick: TNotifyEvent); var MenuItem: TMenuItem; begin MenuItem := TMenuItem.Create(Self); MenuItem.Caption := aCaption; MenuItem.ImageIndex := aImageIndex; MenuItem.OnClick := aClick; aParent.Add(MenuItem); end; function TPopupMenuHelper.AddSubMenu(const aCaption: string): TMenuItem; begin Result := TMenuItem.Create(Self); Result.Caption := aCaption; Items.Add(Result); end; end.
unit MainFormU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.WinXPanels, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, FireDAC.Stan.Intf, FireDAC.Comp.BatchMove, Vcl.ComCtrls, FireDAC.Comp.BatchMove.Text, FireDAC.Comp.BatchMove.DataSet, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.Phys.IB, FireDAC.Phys.IBDef; type TMainForm = class(TForm) FDBatchMove: TFDBatchMove; CustomersTable: TFDQuery; dsCustomers: TDataSource; CustomerTable: TFDQuery; dsCustomer: TDataSource; EmployeeConnection: TFDConnection; PageControl1: TPageControl; TabSheet3: TTabSheet; Button1: TButton; DBGrid2: TDBGrid; DBGrid3: TDBGrid; Panel1: TPanel; Panel2: TPanel; ComboBox1: TComboBox; TabSheet2: TTabSheet; btnResetData: TButton; btnOpenDatasets: TButton; DelphicookbookConnection: TFDConnection; procedure btnResetDataClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnOpenDatasetsClick(Sender: TObject); private { Private declarations } procedure CloseDataSets; procedure OpenDataSets; procedure SetUpReader; procedure SetUpWriter; procedure ResetData; public { Public declarations } end; var MainForm: TMainForm; implementation uses IOUtils; {$R *.dfm} procedure TMainForm.btnOpenDatasetsClick(Sender: TObject); begin OpenDataSets; end; procedure TMainForm.btnResetDataClick(Sender: TObject); begin ResetData; end; procedure TMainForm.Button1Click(Sender: TObject); begin // ensure user make a choice if ComboBox1.ItemIndex = -1 then begin ShowMessage('You have to make a choice'); exit; end; CloseDataSets; // Create reader SetUpReader; // Create writer SetUpWriter; // Analyze source text file structure FDBatchMove.GuessFormat; FDBatchMove.Execute; // show data OpenDataSets; end; procedure TMainForm.CloseDataSets; begin CustomersTable.Close; end; procedure TMainForm.OpenDataSets; begin CustomersTable.Close; CustomersTable.Open; CustomerTable.Close; CustomerTable.Open; end; procedure TMainForm.SetUpReader; var LTextReader: TFDBatchMoveTextReader; LDataSetReader: TFDBatchMoveDataSetReader; begin case ComboBox1.ItemIndex of 0: begin // Create text reader // FDBatchMove will automatically manage the reader instance. LTextReader := TFDBatchMoveTextReader.Create(FDBatchMove); // Set source text data file name // data.txt provided with demo LTextReader.FileName := ExtractFilePath(Application.ExeName) + '..\..\data\data.txt'; // Setup file format LTextReader.DataDef.Separator := ';'; // to estabilish if first row is definition row (it is this case) LTextReader.DataDef.WithFieldNames := True; end; 1: begin // Create text reader // FDBatchMove will automatically manage the reader instance. LDataSetReader := TFDBatchMoveDataSetReader.Create(FDBatchMove); // Set source dataset LDataSetReader.DataSet := CustomerTable; LDataSetReader.Optimise := False; end; 2: begin LDataSetReader := TFDBatchMoveDataSetReader.Create(FDBatchMove); // set dataset source LDataSetReader.DataSet := CustomersTable; // because dataset will be show on ui LDataSetReader.Optimise := False; end; end; end; procedure TMainForm.SetUpWriter; var LDataSetWriter: TFDBatchMoveDataSetWriter; LTextWriter: TFDBatchMoveTextWriter; begin case ComboBox1.ItemIndex of 0: begin // Create dataset writer and set FDBatchMode as owner. Then // FDBatchMove will automatically manage the writer instance. LDataSetWriter := TFDBatchMoveDataSetWriter.Create(FDBatchMove); // Set destination dataset LDataSetWriter.DataSet := CustomersTable; // because dataset will be show on ui LDataSetWriter.Optimise := False; end; 1: begin // Create dataset writer and set FDBatchMode as owner. Then // FDBatchMove will automatically manage the writer instance. LDataSetWriter := TFDBatchMoveDataSetWriter.Create(FDBatchMove); // Set destination dataset LDataSetWriter.DataSet := CustomersTable; // because dataset will be show on ui LDataSetWriter.Optimise := False; end; 2: begin LTextWriter := TFDBatchMoveTextWriter.Create(FDBatchMove); // set destination file LTextWriter.FileName := ExtractFilePath(Application.ExeName) + 'DataOut.txt'; // ensure to write on empty file if TFile.Exists(LTextWriter.FileName) then TFile.Delete(LTextWriter.FileName); end; end; end; procedure TMainForm.ResetData; begin DelphicookbookConnection.ExecSQL('delete from {id CUSTOMERS}'); end; end.
unit Launchpad; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseModel, JSON_Helper, Rocket, Launch; type IBaseLaunchpad = interface(IBaseModel) ['{5F822B68-8F65-426B-87BB-DAB668569845}'] function GetDetails: string; function GetFullName: string; function GetId: string; function GetLatitude: Double; function GetLaunchAttempts: LongWord; function GetLaunches: ILaunchList; function GetLaunchesId: TStringList; function GetLaunchSuccesses: LongWord; function GetLocality: string; function GetLongitude: Double; function GetName: string; function GetRegion: string; function GetRockets: IRocketList; function GetRocketsId: TStringList; function GetStatus: string; function GetTimeZone: string; procedure SetDetails(AValue: string); procedure SetFullName(AValue: string); procedure SetId(AValue: string); procedure SetLatitude(AValue: Double); procedure SetLaunchAttempts(AValue: LongWord); procedure SetLaunches(Avalue: ILaunchList); procedure SetLaunchesId(AValue: TStringList); procedure SetLaunchSuccesses(AValue: LongWord); procedure SetLocality(AValue: string); procedure SetLongitude(AValue: Double); procedure SetName(AValue: string); procedure SetRegion(AValue: string); procedure SetRockets(AValue: IRocketList); procedure SetRocketsId(AValue: TStringList); procedure SetStatus(AValue: string); procedure SetTimeZone(AValue: string); end; ILaunchpad = interface(IBaseLaunchpad) ['{9C45D5E5-619D-4F6D-AF4A-E2B9EDA8E9B4}'] property Details: string read GetDetails write SetDetails; property FullName: string read GetFullName write SetFullName; property Id: string read GetId write SetId; property Latitude: Double read GetLatitude write SetLatitude; property LaunchAttempts: LongWord read GetLaunchAttempts write SetLaunchAttempts; property Launches: ILaunchList read GetLaunches write SetLaunches; property LaunchesId: TStringList read GetLaunchesId write SetLaunchesId; property LaunchSuccesses: LongWord read GetLaunchSuccesses write SetLaunchSuccesses; property Locality: string read GetLocality write SetLocality; property Longitude: Double read GetLongitude write SetLongitude; property Name: string read GetName write SetName; property Region: string read GetRegion write SetRegion; property Rockets: IRocketList read GetRockets write SetRockets; property RocketsId: TStringList read GetRocketsId write SetRocketsId; property Status: string read GetStatus write SetStatus; property TimeZone: string read GetTimeZone write SetTimeZone; end; ILaunchpadList = interface(IBaseModelList) ['{8EB54717-9CC1-4B35-B23C-805979B2ED91}'] end; { TLaunchpadEnumerator } TLaunchpadEnumerator = class(TBaseModelEnumerator) function GetCurrent: ILaunchpad; property Current : ILaunchpad read GetCurrent; end; function NewLaunchpad: ILaunchpad; function NewLaunchpadList: ILaunchpadList; operator enumerator(AList: ILaunchpadList): TLaunchpadEnumerator; implementation uses Variants, RocketEndpoint, LaunchEndpoint; type { TLaunchpad } TLaunchpad = class(TBaseModel, ILaunchpad) private FDetails: string; FFullName: string; FId: string; FLatitude: double; FLaunchAttempts: LongWord; FLaunches: ILaunchList; FLaunchesId: TStringList; FLaunchSuccesses: LongWord; FLocality: string; FLongitude: double; FName: string; FRegion: string; FRockets: IRocketList; FRocketsId: TStringList; FStatus: string; FTimeZone: string; function GetDetails: string; function GetFullName: string; function GetId: string; function GetLatitude: Double; function GetLaunchAttempts: LongWord; function GetLaunches: ILaunchList; function GetLaunchesId: TStringList; function GetLaunchSuccesses: LongWord; function GetLocality: string; function GetLongitude: Double; function GetName: string; function GetRegion: string; function GetRockets: IRocketList; function GetRocketsId: TStringList; function GetStatus: string; function GetTimeZone: string; procedure SetDetails(AValue: string); procedure SetDetails(AValue: Variant); procedure SetFullName(AValue: string); procedure SetFullName(AValue: Variant); procedure SetId(AValue: string); procedure SetId(AValue: Variant); procedure SetLatitude(AValue: Double); procedure SetLatitude(AValue: Variant); procedure SetLaunchAttempts(AValue: LongWord); procedure SetLaunchAttempts(AValue: Variant); procedure SetLaunches(AValue: ILaunchList); procedure SetLaunchesId(AValue: TStringList); procedure SetLaunchSuccesses(AValue: LongWord); procedure SetLaunchSuccesses(AValue: Variant); procedure SetLocality(AValue: string); procedure SetLocality(AValue: Variant); procedure SetLongitude(AValue: Double); procedure SetLongitude(AValue: Variant); procedure SetName(AValue: string); procedure SetName(AValue: Variant); procedure SetRegion(AValue: string); procedure SetRegion(AValue: Variant); procedure SetRockets(AValue: IRocketList); procedure SetRocketsId(AValue: TStringList); procedure SetStatus(AValue: string); procedure SetStatus(AValue: Variant); procedure SetTimeZone(AValue: string); procedure SetTimeZone(AValue: Variant); public constructor Create; destructor destroy; override; function ToString(): string; override; published property details: Variant write SetDetails; property full_name: Variant write SetFullName; property id: Variant write SetId; property latitude: Variant write SetLatitude; property launch_attempts: Variant write SetLaunchAttempts; property launches: TStringList read GetLaunchesId write SetLaunchesId; property launch_successes: Variant write SetLaunchSuccesses; property locality: Variant write SetLocality; property longitude: Variant write SetLongitude; property name: Variant write SetName; property region: Variant write SetRegion; property rockets: TStringList read GetRocketsId write SetRocketsId; property status: Variant write SetStatus; property time_zone: Variant write SetTimeZone; end; { TLaunchpadList } TLaunchpadList = class(TBaseModelList, ILaunchpadList) function NewItem: IBaseModel; override; end; function NewLaunchpad: ILaunchpad; begin Result := TLaunchpad.Create; end; function NewLaunchpadList: ILaunchpadList; begin Result := TLaunchpadList.Create; end; operator enumerator(AList: ILaunchpadList): TLaunchpadEnumerator; begin Result := TLaunchpadEnumerator.Create; Result.FList := AList; end; { TLaunchpadEnumerator } function TLaunchpadEnumerator.GetCurrent: ILaunchpad; begin Result := FCurrent as ILaunchpad; end; { TLaunchpadList } function TLaunchpadList.NewItem: IBaseModel; begin Result := NewLaunchpad; end; { TLaunchpad } function TLaunchpad.GetDetails: string; begin Result := FDetails; end; function TLaunchpad.GetFullName: string; begin Result := FFullName; end; function TLaunchpad.GetId: string; begin Result := FId; end; function TLaunchpad.GetLatitude: Double; begin Result := FLatitude; end; function TLaunchpad.GetLaunchAttempts: LongWord; begin Result := FLaunchAttempts; end; function TLaunchpad.GetLaunches: ILaunchList; var LaunchEndpoint: ILaunchEndpoint; LaunchID: string; Launch: ILaunch; begin if (FLaunches = nil) then begin LaunchEndpoint := NewLaunchEndpoint; FLaunches := NewLaunchList; for LaunchID in FLaunchesId do begin; Launch := LaunchEndpoint.One(LaunchID); FLaunches.Add(Launch); end; end; Result := FLaunches; end; function TLaunchpad.GetLaunchesId: TStringList; begin Result := FLaunchesId; end; function TLaunchpad.GetLaunchSuccesses: LongWord; begin Result := FLaunchSuccesses; end; function TLaunchpad.GetLocality: string; begin Result := FLocality; end; function TLaunchpad.GetLongitude: Double; begin Result := FLongitude; end; function TLaunchpad.GetName: string; begin Result := FName; end; function TLaunchpad.GetRegion: string; begin Result := FRegion; end; function TLaunchpad.GetRockets: IRocketList; var RocketEndpoint: IRocketEndpoint; RocketID: string; Rocket: IRocket; begin if (FRockets = nil) then begin RocketEndpoint := NewRocketEndpoint; FRockets := NewRocketList; for RocketID in FRocketsId do begin; Rocket := RocketEndpoint.One(RocketID); FRockets.Add(Rocket); end; end; Result := FRockets; end; function TLaunchpad.GetRocketsId: TStringList; begin Result := FRocketsId; end; function TLaunchpad.GetStatus: string; begin Result := FStatus; end; function TLaunchpad.GetTimeZone: string; begin Result := FTimeZone; end; procedure TLaunchpad.SetDetails(AValue: string); begin FDetails := AValue; end; procedure TLaunchpad.SetDetails(AValue: Variant); begin if VarIsNull(AValue) then begin FDetails := ''; end else if VarIsStr(AValue) then FDetails := AValue; end; procedure TLaunchpad.SetFullName(AValue: string); begin FFullName := AValue; end; procedure TLaunchpad.SetFullName(AValue: Variant); begin if VarIsNull(AValue) then begin FFullName := ''; end else if VarIsStr(AValue) then FFullName := AValue; end; procedure TLaunchpad.SetId(AValue: string); begin FId := AValue; end; procedure TLaunchpad.SetId(AValue: Variant); begin if VarIsNull(AValue) then begin FId := ''; end else if VarIsStr(AValue) then FId := AValue; end; procedure TLaunchpad.SetLatitude(AValue: Double); begin FLatitude := AValue; end; procedure TLaunchpad.SetLatitude(AValue: Variant); begin if VarIsNull(AValue) then begin FLatitude := -0; end else if VarIsNumeric(AValue) then FLatitude := AValue; end; procedure TLaunchpad.SetLaunchAttempts(AValue: LongWord); begin FLaunchAttempts := AValue; end; procedure TLaunchpad.SetLaunchAttempts(AValue: Variant); begin if VarIsNull(AValue) then begin FLaunchAttempts := -0; end else if VarIsNumeric(AValue) then FLaunchAttempts := AValue; end; procedure TLaunchpad.SetLaunches(AValue: ILaunchList); begin FLaunches := AValue; end; procedure TLaunchpad.SetLaunchesId(AValue: TStringList); begin FLaunchesId := AValue; end; procedure TLaunchpad.SetLaunchSuccesses(AValue: LongWord); begin FLaunchSuccesses := AValue; end; procedure TLaunchpad.SetLaunchSuccesses(AValue: Variant); begin if VarIsNull(AValue) then begin FLaunchSuccesses := -0; end else if VarIsNumeric(AValue) then FLaunchSuccesses := AValue; end; procedure TLaunchpad.SetLocality(AValue: string); begin FLocality := AValue; end; procedure TLaunchpad.SetLocality(AValue: Variant); begin if VarIsNull(AValue) then begin FLocality := ''; end else if VarIsStr(AValue) then FLocality := AValue; end; procedure TLaunchpad.SetLongitude(AValue: Double); begin FLongitude := AValue; end; procedure TLaunchpad.SetLongitude(AValue: Variant); begin if VarIsNull(AValue) then begin FLongitude := -0; end else if VarIsNumeric(AValue) then FLongitude := AValue; end; procedure TLaunchpad.SetName(AValue: string); begin FName := AValue; end; procedure TLaunchpad.SetName(AValue: Variant); begin if VarIsNull(AValue) then begin FName := ''; end else if VarIsStr(AValue) then FName := AValue; end; procedure TLaunchpad.SetRegion(AValue: string); begin FRegion := AValue; end; procedure TLaunchpad.SetRegion(AValue: Variant); begin if VarIsNull(AValue) then begin FRegion := ''; end else if VarIsStr(AValue) then FRegion := AValue; end; procedure TLaunchpad.SetRockets(AValue: IRocketList); begin FRockets := AValue; end; procedure TLaunchpad.SetRocketsId(AValue: TStringList); begin FRocketsId := AValue; end; procedure TLaunchpad.SetStatus(AValue: string); begin FStatus := AValue; end; procedure TLaunchpad.SetStatus(AValue: Variant); begin if VarIsNull(AValue) then begin FStatus := ''; end else if VarIsStr(AValue) then FStatus := AValue; end; procedure TLaunchpad.SetTimeZone(AValue: string); begin FTimeZone := AValue; end; procedure TLaunchpad.SetTimeZone(AValue: Variant); begin if VarIsNull(AValue) then begin FTimeZone := ''; end else if VarIsStr(AValue) then FTimeZone := AValue; end; constructor TLaunchpad.Create; begin inherited Create; FLaunchesId := TStringList.Create; FRocketsId := TStringList.Create; FLaunchesId.SkipLastLineBreak := True; FRocketsId.SkipLastLineBreak := True; end; destructor TLaunchpad.destroy; begin FreeAndNil(FLaunchesId); FreeAndNil(FRocketsId); inherited destroy; end; function TLaunchpad.ToString(): string; begin Result := Format('' + 'Details: %s' + LineEnding + 'Full Name: %s' + LineEnding + 'ID: %s' + LineEnding + 'Latitude: %f' + LineEnding + 'Launch Attempts: %u' + LineEnding + 'Launches: %s' + LineEnding + 'Launch Successes: %u' + LineEnding + 'Locality: %s' + LineEnding + 'Longitude: %f' + LineEnding + 'Name: %s' + LineEnding + 'Region: %s' + LineEnding + 'Rockets: %s' + LineEnding + 'Status: %s' + LineEnding + 'Time Zone: %s' , [ GetDetails, GetFullName, GetId, GetLatitude, GetLaunchAttempts, GetLaunchesId.Text, GetLaunchSuccesses, GetLocality, GetLongitude, GetName, GetRegion, GetRocketsId.Text, GetStatus, GetTimeZone ]); end; end.
unit uCommon; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Controls, Forms, Dialogs, ComCtrls, Buttons, Menus, LCLType, LCLIntf; type TOnScreenShot = procedure(Sender: TObject; AMs: TMemoryStream) of Object; type { TScreenShot } TScreenShot = class(TThread) private FMS: TMemoryStream; FMSComp: TMemoryStream; FPixelFormat: TPixelFormat; FCompressionQuality: TJPEGQualityRange; FOnScreenShot: TOnScreenShot; procedure TakeScreenShot; procedure DoScreenShot; protected procedure Execute; override; public constructor Create(APixelFormat: TPixelFormat; ACompressionQuality: TJPEGQualityRange); destructor Destroy; override; public property OnScreenShot: TOnScreenShot read FOnScreenShot write FOnScreenShot; end; function MessageDlgEx(const AMsg: String; ADlgType: TMsgDlgType; ABtns: TMsgDlgButtons; ABtnCaptions: array of string; AShowBtnGlyph: Boolean; AParent: TForm): TModalResult; implementation uses uTCPCryptoCompression; constructor TScreenShot.Create(APixelFormat: TPixelFormat; ACompressionQuality: TJPEGQualityRange); begin inherited Create(True); FPixelFormat := APixelFormat; FCompressionQuality := ACompressionQuality; FMS := TMemoryStream.Create; FMSComp := TMemoryStream.Create; end; destructor TScreenShot.Destroy; begin FMS.Free; FMSComp.Free; inherited Destroy; end; procedure TScreenShot.TakeScreenShot; var Bmp: TBitmap; Jpg: TJPEGImage; ScreenDC: HDC; CompRate: Single; begin Bmp := TBitmap.Create; try ScreenDC := GetDC(0); Bmp.PixelFormat := FPixelFormat; Bmp.LoadFromDevice(ScreenDC); ReleaseDC(0, ScreenDC); Jpg := TJpegImage.Create; try Jpg.CompressionQuality := FCompressionQuality; Jpg.Assign(Bmp); FMS.Clear; Jpg.SaveToStream(FMS); CompressStream(FMS, FMSComp, clBestCompression, CompRate); FMSComp.Position := 0; {$IFDEF UNIX} if Assigned(FOnScreenShot) then FOnScreenShot(Self, FMSComp); {$ENDIF} finally Jpg.Free; end; finally Bmp.Free; end; end; procedure TScreenShot.DoScreenShot; begin if Assigned(FOnScreenShot) then FOnScreenShot(Self, FMSComp); end; procedure TScreenShot.Execute; begin while not Terminated do begin {$IFDEF UNIX} //linux does not like threaded screenshots Synchronize(@TakeScreenShot); {$ELSE} TakeScreenShot; Synchronize(@DoScreenShot); {$ENDIF} end; end; function MessageDlgEx(const AMsg: String; ADlgType: TMsgDlgType; ABtns: TMsgDlgButtons; ABtnCaptions: array of string; AShowBtnGlyph: Boolean; AParent: TForm): TModalResult; var MsgFrm: TForm; BitBtn: TBitBtn; I: Integer; CapCnt: Integer; begin MsgFrm := CreateMessageDialog(AMsg, ADlgType, ABtns); try MsgFrm.FormStyle := fsSystemStayOnTop; if AParent <> nil then begin MsgFrm.Position := poDefaultSizeOnly; MsgFrm.Left := AParent.Left + (AParent.Width - MsgFrm.Width) div 2; MsgFrm.Top := AParent.Top + (AParent.Height - MsgFrm.Height) div 2; end else MsgFrm.Position := poWorkAreaCenter; CapCnt := 0; for I := 0 to MsgFrm.ComponentCount - 1 do begin if (MsgFrm.Components[I] is TBitBtn) then begin BitBtn := TBitBtn(MsgFrm.Components[I]); if not AShowBtnGlyph then BitBtn.GlyphShowMode := gsmNever; if Length(ABtnCaptions) > 0 then begin if CapCnt > High(ABtnCaptions) then Break; BitBtn.Caption := ABtnCaptions[CapCnt]; Inc(CapCnt); end; end; end; Result := MsgFrm.ShowModal; finally MsgFrm.Free end; end; end.
unit mnWindowsTestCase; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework; type TmnWindowsTestCase = class(TTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure testAddRemoveWindowMessageFilter; procedure testHWNDArrayListConvertors; procedure testLoadResAsStr; end; implementation uses mnWindows, UTestConsts, Classes, mnSystem, Messages; {$R ..\..\..\files\Strings\TestUnit\TestUnit.res} { TmnWindowsTestCase } procedure TmnWindowsTestCase.SetUp; begin end; procedure TmnWindowsTestCase.TearDown; begin end; procedure TmnWindowsTestCase.testAddRemoveWindowMessageFilter; begin CheckTrue(mnAddWindowMessageFilter(WM_MOUSEMOVE)); CheckTrue(mnRemoveWindowMessageFilter(WM_MOUSEMOVE)); end; procedure TmnWindowsTestCase.testHWNDArrayListConvertors; var Arr, Arr2: mnTHWNDArray; List: TList; begin SetLength(Arr, 3); Arr[0] := Int_0; Arr[1] := Int_2; Arr[2] := Int_3; // mnHWNDArrayToList List := mnHWNDArrayToList(Arr); CheckEquals(List.Count, 3); CheckEquals(mnPHWND(List[0])^, Int_0); CheckEquals(mnPHWND(List[1])^, Int_2); CheckEquals(mnPHWND(List[2])^, Int_3); // mnHWNDListToArray Arr2 := mnHWNDListToArray(List); CheckEquals(Length(Arr2), 3); CheckEquals(Arr2[0], Int_0); CheckEquals(Arr2[1], Int_2); CheckEquals(Arr2[2], Int_3); mnClearList(List); List.Free; end; procedure TmnWindowsTestCase.testLoadResAsStr; begin CheckEquals(mnLoadResAsStr('Res_RCDATA'), 'I am a Res_RCDATA'); CheckEquals(mnLoadResAsStr(HInstance, 'Res_RCDATA'), 'I am a Res_RCDATA'); CheckEquals(mnLoadResAsStr('NoExists'), ''); end; initialization // Register any test cases with the test runner RegisterTest(TmnWindowsTestCase.Suite); end.
unit Android.BroadcastReceiver; interface uses System.Classes , System.Generics.Collections , FMX.Platform , Androidapi.JNIBridge , Androidapi.JNI.App , Androidapi.JNI.Embarcadero , Androidapi.JNI.GraphicsContentViewText , Androidapi.JNI.JavaTypes , Androidapi.Helpers ; type // 直接 class(TJavaLocal, JFMXBroadcastReceiverListener) を定義するとダメ! // グローバル変数にインスタンスをつっこんでも削除されて、Broadcast 受信で // アプリが落ちる! // なので、TInterfacedObject を継承していないクラスから派生したクラスの // インナークラスとして JFMXBroadcastReceiverListener を定義する // このクラスは自動的に削除されないため、上手く動作する! TBroadcastReceiver = class public type // Broadcast Receiver を通知するイベント // JString にしているので、Intent.ACTION_XXX と equals で比較可能 TBroadcastReceiverEvent = procedure(const iAction: JString) of object; // JFMXBroadcastReceiver を実装した JavaClass として Listener を定義 TBroadcastReceiverListener = class(TJavaLocal, JFMXBroadcastReceiverListener) private var FBroadcastReceiver: TBroadcastReceiver; public constructor Create(const iBroadcastReceiver: TBroadcastReceiver); // Broadcast Receiver から呼び出されるコールバック procedure onReceive(context: JContext; intent: JIntent); cdecl; end; private var // つぎの2つは保存しないと消えて無くなる! FBroadcastReceiverListener: JFMXBroadcastReceiverListener; FReceiver: JFMXBroadcastReceiver; // 通知対象の ACTION を保持している変数 FActions: TList<String>; // イベントハンドラ FOnReceived: TBroadcastReceiverEvent; protected constructor Create; // Broadcast Receiver の設定と解除 procedure SetReceiver; procedure UnsetReceiver; public destructor Destroy; override; // 通知して欲しい ACTION の登録と削除 procedure AddAction(const iActions: array of JString); procedure RemoveAction(const iAction: JString); procedure ClearAction; // Boradcast Receiver を受け取った時のイベント property OnReceived: TBroadcastReceiverEvent read FOnReceived write FOnReceived; end; // Boradcast Receiver のインスタンスを返す function BroadcastReceiver: TBroadcastReceiver; implementation uses System.UITypes, System.SysUtils , Androidapi.NativeActivity , FMX.Forms , FMX.Types ; // Braodcast Receiver の唯一のインスタンス var GBroadcastReceiver: TBroadcastReceiver = nil; function BroadcastReceiver: TBroadcastReceiver; begin if (GBroadcastReceiver = nil) then GBroadcastReceiver := TBroadcastReceiver.Create; Result := GBroadcastReceiver; end; { TBroadcastReceiver.TBroadcastReceiverListener } constructor TBroadcastReceiver.TBroadcastReceiverListener.Create( const iBroadcastReceiver: TBroadcastReceiver); begin inherited Create; FBroadcastReceiver := iBroadcastReceiver; end; procedure TBroadcastReceiver.TBroadcastReceiverListener.onReceive( context: JContext; intent: JIntent); var JStr: String; Str: String; procedure CallEvent; var Action: String; begin // Broadcast は Delphi のメインスレッドで届くわけでは無いので // Synchronize で呼び出す Action := JStr; TThread.CreateAnonymousThread( procedure begin TThread.Synchronize( TThread.CurrentThread, procedure begin if (Assigned(FBroadcastReceiver.FOnReceived)) then FBroadcastReceiver.FOnReceived(StringToJString(Action)); end ); end ).Start; end; begin // Broadcast を受け取ったら、このメソッドが呼ばれる! JStr := JStringToString(intent.getAction); for Str in FBroadcastReceiver.FActions do if (Str = JStr) then CallEvent; end; { TReceiverListener } procedure TBroadcastReceiver.AddAction(const iActions: array of JString); var Str: String; JStr: String; Action: JString; OK: Boolean; Changed: Boolean; begin Changed := False; for Action in iActions do begin OK := True; JStr := JStringToString(Action); for Str in FActions do if (Str = JStr) then begin OK := False; Break; end; if (OK) then begin FActions.Add(JStr); Changed := True; end; end; if (Changed) then SetReceiver; Log.d('Exiting AddAction'); end; procedure TBroadcastReceiver.ClearAction; begin FActions.Clear; UnsetReceiver; end; constructor TBroadcastReceiver.Create; begin inherited; FActions := TList<String>.Create; // Boardcast Receiver を設定 SetReceiver; end; destructor TBroadcastReceiver.Destroy; begin // Broadcast Receiver を解除 UnsetReceiver; FActions.DisposeOf; inherited; end; procedure TBroadcastReceiver.RemoveAction(const iAction: JString); var i: Integer; JStr: String; begin JStr := JStringToString(iAction); for i := 0 to FActions.Count - 1 do if (FActions[i] = JStr) then begin FActions.Delete(i); SetReceiver; Break; end; end; procedure TBroadcastReceiver.SetReceiver; var Filter: JIntentFilter; Str: String; begin if (FReceiver <> nil) then UnsetReceiver; // Intent Filter を作成 Filter := TJIntentFilter.JavaClass.init; for Str in FActions do Filter.addAction(StringToJString(Str)); // TBroadcastReceiverListener を実体とした BroadcastReceiver を作成 Log.d('TBroadcastReceiverListener.Create'); FBroadcastReceiverListener := TBroadcastReceiverListener.Create(Self); Log.d('TJFMXBroadcastReceiver.init'); FReceiver := TJFMXBroadcastReceiver.JavaClass.init(FBroadcastReceiverListener); try // レシーバーとして登録 Log.d('register receiver'); SharedActivityContext.getApplicationContext.registerReceiver( FReceiver, Filter); except on E: Exception do Log.d('Exception: %s', [E.Message]); end; Log.d('Exiting SetReceiver'); end; procedure TBroadcastReceiver.UnsetReceiver; begin // アプリケーションが終了中でなければ、BroadcastReceiver を解除 if (FReceiver <> nil) and (not (SharedActivityContext as JActivity).isFinishing) then try SharedActivityContext.getApplicationContext.unregisterReceiver(FReceiver); except end; FReceiver := nil; end; initialization finalization if (GBroadcastReceiver <> nil) then GBroadcastReceiver.DisposeOf; end.
unit UCL.TUCaptionBar; interface uses UCL.Classes, UCL.Utils, UCL.TUThemeManager, Winapi.Windows, Winapi.Messages, System.Classes, VCL.Controls, VCL.ExtCtrls, VCL.Forms, VCL.Graphics; type TUCustomCaptionBar = class(TCustomPanel, IUThemeControl) private FThemeManager: TUThemeManager; FDragMovement: Boolean; FSystemMenuEnabled: Boolean; FDoubleClickMaximize: Boolean; FUseNormalStyle: Boolean; procedure SetThemeManager(const Value: TUThemeManager); // Setters procedure SetUseNormalStyle(const Value: Boolean); procedure WM_LButtonDblClk(var Msg: TMessage); message WM_LBUTTONDBLCLK; procedure WM_LButtonDown(var Msg: TMessage); message WM_LBUTTONDOWN; procedure WM_RButtonUp(var Msg: TMessage); message WM_RBUTTONUP; public constructor Create(aOwner: TComponent); override; procedure UpdateTheme; published property ThemeManager: TUThemeManager read FThemeManager write SetThemeManager; // Field property property DragMovement: Boolean read FDragMovement write FDragMovement default true; property SystemMenuEnabled: Boolean read FSystemMenuEnabled write FSystemMenuEnabled default true; property DoubleClickMaximize: Boolean read FDoubleClickMaximize write FDoubleClickMaximize default true; // Setter property property UseNormalStyle: Boolean read FUseNormalStyle write SetUseNormalStyle default false; end; TUCaptionBar = class(TUCustomCaptionBar) published // Common property property Align; property Alignment; property Anchors; property BiDiMode; property Caption; property DoubleBuffered; property Enabled; property Font; property Padding; property ParentBiDiMode; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property ShowCaption; property ShowHint; property Touch; property VerticalAlignment; property Visible; // Common events property OnClick; property OnDblClick; property OnGesture; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnResize; end; implementation { THEME } procedure TUCustomCaptionBar.SetThemeManager(const Value: TUThemeManager); begin if Value <> FThemeManager then begin // Disconnect current ThemeManager if FThemeManager <> nil then FThemeManager.DisconnectControl(Self); // Connect to new ThemeManager if Value <> nil then Value.ConnectControl(Self); FThemeManager := Value; UpdateTheme; end; end; procedure TUCustomCaptionBar.UpdateTheme; begin // Not set ThemeManager if ThemeManager = nil then Color := $FFFFFF // Normal style (like VCL) else if UseNormalStyle = true then begin if ThemeManager.ColorOnBorder = true then Color := ThemeManager.ActiveColor // Active color else Color := $FFFFFF; // White end // New style (like UWP), depend AppTheme light or dark else begin if ThemeManager.Theme = utLight then Color := $F2F2F2 // Light color else Color := $2B2B2B; // Dark color end; Font.Color := GetTextColorFromBackground(Color); end; { SETTERS } procedure TUCustomCaptionBar.SetUseNormalStyle(const Value: Boolean); begin if Value <> FUseNormalStyle then begin FUseNormalStyle := Value; UpdateTheme; end; end; { MAIN CLASS } constructor TUCustomCaptionBar.Create(aOwner: TComponent); begin inherited Create(aOwner); // New properties FDragMovement := true; FSystemMenuEnabled := true; FDoubleClickMaximize := true; FUseNormalStyle := false; // Common properties Align := alTop; BevelOuter := bvNone; BorderStyle := bsNone; Height := 32; Ctl3D := false; Enabled := true; FullRepaint := false; StyleElements := []; // Neccesary TabStop := false; Font.Name := 'Segoe UI'; Font.Size := 9; UpdateTheme; end; { MESSAGES } procedure TUCustomCaptionBar.WM_LButtonDblClk(var Msg: TMessage); begin inherited; if DoubleClickMaximize = true then if Parent is TForm then begin if (Parent as TForm).WindowState <> wsMaximized then (Parent as TForm).WindowState := wsMaximized else (Parent as TForm).WindowState := wsNormal; end; end; procedure TUCustomCaptionBar.WM_LButtonDown(var Msg: TMessage); begin inherited; if DragMovement = true then begin ReleaseCapture; Parent.Perform(WM_SYSCOMMAND, $F012, 0); end; end; procedure TUCustomCaptionBar.WM_RButtonUp(var Msg: TMessage); const WM_SYSMENU = 787; var P: TPoint; begin inherited; if SystemMenuEnabled = true then begin P.X := Msg.LParamLo; P.Y := Msg.LParamHi; P := ClientToScreen(P); Msg.LParamLo := P.X; Msg.LParamHi := P.Y; SendMessage(Parent.Handle, WM_SYSMENU, 0, Msg.LParam); end; end; end.
unit Report_PriceIntervention2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorReport, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, dsdAddOn, ChoicePeriod, Vcl.Menus, dxBarExtItems, dxBar, cxClasses, dsdDB, Datasnap.DBClient, dsdAction, Vcl.ActnList, cxPropertiesStore, cxLabel, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, Vcl.ExtCtrls, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC, dsdGuides, cxButtonEdit, cxCurrencyEdit, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, cxPCdxBarPopupMenu, dxSkinsdxBarPainter, cxCheckBox, cxGridBandedTableView, cxGridDBBandedTableView, cxSplitter; type TReport_PriceIntervention2Form = class(TAncestorReportForm) bbExecuteDialog: TdxBarButton; cxLabel8: TcxLabel; cxLabel9: TcxLabel; cePrice1: TcxCurrencyEdit; cePrice2: TcxCurrencyEdit; cxLabel7: TcxLabel; cxLabel12: TcxLabel; cePrice5: TcxCurrencyEdit; cePrice6: TcxCurrencyEdit; cxLabel13: TcxLabel; cePrice3: TcxCurrencyEdit; cxLabel14: TcxLabel; cePrice4: TcxCurrencyEdit; cxLabel15: TcxLabel; ceMarginReport: TcxButtonEdit; MarginReportGuides: TdsdGuides; MarginReportItemOpenForm: TdsdOpenForm; ExecuteDialog: TExecuteDialog; spInsertUpdate: TdsdStoredProc; bb: TdxBarButton; cxGrid1: TcxGrid; cxGridDBTableView1: TcxGridDBTableView; cxGridDBColumn1: TcxGridDBColumn; cxGridDBColumn2: TcxGridDBColumn; cxGridDBColumn3: TcxGridDBColumn; cxGridDBColumn4: TcxGridDBColumn; cxGridDBColumn5: TcxGridDBColumn; cxGridDBColumn6: TcxGridDBColumn; cxGridDBColumn7: TcxGridDBColumn; cxGridDBColumn8: TcxGridDBColumn; cxGridDBColumn9: TcxGridDBColumn; cxGridDBColumn10: TcxGridDBColumn; cxGridDBColumn11: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; DBViewAddOn1: TdsdDBViewAddOn; MasterCDS1: TClientDataSet; MasterDS1: TDataSource; spSelectMaster: TdsdStoredProc; cxSplitter: TcxSplitter; actInsertUpdate: TdsdUpdateDataSet; private { Private declarations } public { Public declarations } end; var Report_PriceIntervention2Form: TReport_PriceIntervention2Form; implementation {$R *.dfm} initialization RegisterClass(TReport_PriceIntervention2Form) end.
unit Model.Invoice; interface uses Model.Interfaces; function CreateInvoiceModelClass: IInvoiceModelInterface; implementation uses Model.Declarations, System.Generics.Collections, Model.Database, System.SysUtils; type TInvoiceModel = class (TInterfacedObject, IInvoiceModelInterface) private fInvoiceFormLabelsText: TInvoiceFormLabelsText; fDatabase: IDatabaseInterface; fInvoice: TInvoice; fCurrentInvoiceItems: TObjectList<TInvoiceItem>; fRunningBalance, fDiscount: Currency; function GetInvoiceRunningBalance:Currency; procedure CalculateInvoiceAmounts; function GetNumberOfInvoiceItems:integer; procedure GetCustomerFromID (const customerID: integer; var customer: TCustomer); function GetInvoiceDiscount: Currency; public function GetInvoiceFormLabelsText: TInvoiceFormLabelsText; constructor Create; destructor Destroy; override; procedure SetInvoice(const newInvoice: TInvoice); procedure GetInvoice(var invoice: TInvoice); procedure GetCustomerList(var customers: TObjectList<TCustomer>); procedure GetItems(var items: TObjectList<TItem>); procedure GetCustomer (const customerName: string; var customer: TCustomer); procedure AddInvoiceItem(const itemDescription: string; const quantity: integer); procedure GetInvoiceItems (var itemsList: TObjectList<TInvoiceItem>); procedure GetInvoiceItemFromID (const itemID: Integer; var item: TItem); procedure DeleteAllInvoiceItems; procedure DeleteInvoiceItem (const delItemID: integer); procedure PrintInvoice; property InvoiceRunningBalance: Currency read GetInvoiceRunningBalance; property NumberOfInvoiceItems: integer read GetNumberOfInvoiceItems; property InvoiceDiscount: Currency read GetInvoiceDiscount; end; function CreateInvoiceModelClass: IInvoiceModelInterface; begin result:=TInvoiceModel.Create; end; { TInvoiceModel } procedure TInvoiceModel.AddInvoiceItem(const itemDescription: string; const quantity: integer); var tmpInvoiceItem: TInvoiceItem; tmpItem: TItem; begin if trim(itemDescription)='' then Exit; tmpItem:=fDatabase.GetItemFromDescription(trim(itemDescription)); if not Assigned(tmpItem) then Exit; tmpInvoiceItem:=TInvoiceItem.Create; tmpInvoiceItem.ID:=tmpItem.ID; tmpInvoiceItem.InvoiceID:=fInvoice.ID; tmpInvoiceItem.UnitPrice:=tmpItem.Price; tmpInvoiceItem.Quantity:=quantity; fCurrentInvoiceItems.Add(tmpInvoiceItem); end; procedure TInvoiceModel.CalculateInvoiceAmounts; var tmpItem: TInvoiceItem; begin fRunningBalance:=0.00; for tmpItem in fCurrentInvoiceItems do fRunningBalance:=fRunningBalance+(tmpItem.Quantity*tmpItem.UnitPrice); end; constructor TInvoiceModel.Create; begin fDatabase:=CreateDatabaseClass; fInvoice:=TInvoice.Create; fInvoice.ID:=1; fInvoice.Number:=Random(3000); fCurrentInvoiceItems:=TObjectList<TInvoiceItem>.Create; end; procedure TInvoiceModel.DeleteAllInvoiceItems; begin fCurrentInvoiceItems.Clear; end; procedure TInvoiceModel.DeleteInvoiceItem(const delItemID: integer); var i: integer; begin if delItemID<=0 then Exit; for i := 0 to fCurrentInvoiceItems.Count-1 do begin if fCurrentInvoiceItems.Items[i].ID=delItemID then begin fCurrentInvoiceItems.Delete(i); break; end; end; end; destructor TInvoiceModel.Destroy; begin fCurrentInvoiceItems.Free; fInvoice.Free; inherited; end; procedure TInvoiceModel.GetCustomer(const customerName: string; var customer: TCustomer); begin if not Assigned(customer) then Exit; if trim(customerName)<>'' then begin customer.ID:=fDatabase.GetCustomerFromName(trim(customerName)).ID; customer.Name:=fDatabase.GetCustomerFromName(trim(customerName)).Name; customer.DiscountRate:=fDatabase.GetCustomerFromName(trim(customerName)).DiscountRate; customer.Balance:=fDatabase.GetCustomerFromName(trim(customerName)).Balance; fInvoice.CustomerID:=customer.ID; end; end; procedure TInvoiceModel.GetCustomerFromID(const customerID: integer; var customer: TCustomer); var tmpCustomerList: TObjectList<TCustomer>; tmpCustomer: TCustomer; begin if not Assigned(customer) then Exit; GetCustomerList(tmpCustomerList); for tmpCustomer in tmpCustomerList do if tmpCustomer.ID=customerID then begin customer.ID:=tmpCustomer.ID; customer.Name:=tmpCustomer.Name; customer.DiscountRate:=tmpCustomer.DiscountRate; customer.Balance:=tmpCustomer.Balance; break; end; end; procedure TInvoiceModel.GetCustomerList(var customers: TObjectList<TCustomer>); begin customers:=fDatabase.GetCustomerList end; procedure TInvoiceModel.GetInvoice(var invoice: TInvoice); begin invoice:=fInvoice; end; function TInvoiceModel.GetInvoiceDiscount: Currency; var tmpCustomer: TCustomer; tmpDiscount: Double; begin fDiscount:=0.00; tmpDiscount:=0.00; tmpCustomer:=TCustomer.Create; GetCustomerFromID(fInvoice.CustomerID, tmpCustomer); tmpDiscount:=tmpCustomer.DiscountRate; tmpCustomer.Free; CalculateInvoiceAmounts; fDiscount:=fRunningBalance*tmpDiscount/100; Result:=fDiscount; end; procedure TInvoiceModel.SetInvoice(const newInvoice: TInvoice); begin fInvoice:=newInvoice; end; function TInvoiceModel.GetInvoiceFormLabelsText: TInvoiceFormLabelsText; begin fInvoiceFormLabelsText.Title:='Sales Invoice'; fInvoiceFormLabelsText.CustomerDetailsGroupText:='Customer Details'; fInvoiceFormLabelsText.CustomerText:='Customer:'; fInvoiceFormLabelsText.CustomerDiscountRateText:='Discount Rate:'; fInvoiceFormLabelsText.CustomerOutstandingBalanceText:='Outstanding Balance:'; fInvoiceFormLabelsText.InvoiceItemsGroupText:='Invoice Items'; fInvoiceFormLabelsText.InvoiceItemsText:='Item:'; fInvoiceFormLabelsText.InvoiceItemsQuantityText:='Quantity:'; fInvoiceFormLabelsText.InvoiceItemsAddItemButtonText:='Add Item'; fInvoiceFormLabelsText.InvoiceItemsGridItemText:='Item'; fInvoiceFormLabelsText.InvoiceItemsGridQuantityText:='Quantity'; fInvoiceFormLabelsText.InvoiceItemsGridUnitPriceText:='Unit Price'; fInvoiceFormLabelsText.InvoiceItemsGridAmountText:='Amount'; fInvoiceFormLabelsText.BalanceGroupText:='Balance'; fInvoiceFormLabelsText.BalanceInvoiceBalanceText:='Invoice Balance:'; fInvoiceFormLabelsText.BalanceDiscountText:='Discount'; fInvoiceFormLabelsText.BalanceTotalText:='Total:'; fInvoiceFormLabelsText.PrintInvoiceButtonText:='Print Invoice'; fInvoiceFormLabelsText.PrintingText:='Printing Invoice...'; fInvoiceFormLabelsText.CancelButtonText:='Cancel'; result:=fInvoiceFormLabelsText; end; procedure TInvoiceModel.GetInvoiceItemFromID(const itemID: Integer; var item: TItem); var tmpItem: TItem; begin if (not Assigned(item)) then Exit; tmpItem:=fDatabase.GetItemFromID(itemID); if Assigned(tmpItem) then begin item.ID:=tmpItem.ID; item.Description:=tmpItem.Description; item.Price:=tmpItem.Price end; end; procedure TInvoiceModel.GetInvoiceItems( var itemsList: TObjectList<TInvoiceItem>); var tmpInvoiceItem: TInvoiceItem; i: integer; begin if not Assigned(itemsList) then Exit; itemsList.Clear; for i:=0 to fCurrentInvoiceItems.Count-1 do begin tmpInvoiceItem:=TInvoiceItem.Create; tmpInvoiceItem.ID:=fCurrentInvoiceItems.Items[i].ID; tmpInvoiceItem.InvoiceID:=fCurrentInvoiceItems.Items[i].InvoiceID; tmpInvoiceItem.ItemID:=fCurrentInvoiceItems.Items[i].ItemID; tmpInvoiceItem.UnitPrice:=fCurrentInvoiceItems.Items[i].UnitPrice; tmpInvoiceItem.Quantity:=fCurrentInvoiceItems.Items[i].Quantity; itemsList.Add(tmpInvoiceItem); end; end; function TInvoiceModel.GetInvoiceRunningBalance: Currency; begin CalculateInvoiceAmounts; Result:=fRunningBalance; end; procedure TInvoiceModel.GetItems(var items: TObjectList<TItem>); begin items:=fDatabase.GetItems end; function TInvoiceModel.GetNumberOfInvoiceItems: integer; begin result:=fCurrentInvoiceItems.Count; end; procedure TInvoiceModel.PrintInvoice; begin fDatabase.SaveCurrentSales(fRunningBalance-fDiscount); end; end.
unit ComponentContainer; interface uses SysUtils, Classes, Graphics, Controls, Dialogs,Types ; type TComponentContainer = class(TCustomControl) private mcontrols: array of TControl; mhorizontal:boolean; protected procedure Paint; override; public constructor Create(AOwner:TComponent); override; procedure addControl(ctrl:TControl; X:integer=-1;Y:integer=-1); function hasControl(ctrl:TControl):boolean; function getPosition(X, Y: Integer):integer; function getCtrlPos(ctrl:TControl):integer; procedure deleteControl(id:integer); overload; procedure moveControl(frompos,topos:integer); procedure deleteControl(ctrl:TControl);overload; procedure refreshControls(); procedure DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure DragDrop(Sender, Source: TObject; X, Y: Integer); procedure ResizeEvt(Sender: TObject); procedure clearlasts(del: boolean=false); function controlsCount():integer; published property Align; property Caption; property Color; property Cursor; property DragCursor; property DragMode; property Enabled; property Font; property Hint; property ParentFont; property ParentShowHint; property PopupMenu; property Visible; property Anchors; property Horizontal : boolean read mhorizontal write mhorizontal; end; procedure Register; var CurrentDraggingControl: TControl; LastParent: TControl; implementation constructor TComponentContainer.Create(AOwner:TComponent); begin inherited Create(AOwner); Width:=50; Height:=50; Color:=clWhite; setlength(mcontrols,0); horizontal:=false; onDragOver:=DragOver; onDragDrop:=DragDrop; onResize:=ResizeEvt; end; function TComponentContainer.controlsCount():integer; begin result:=length(mcontrols); end; procedure TComponentContainer.clearlasts(del: boolean=false); begin if(assigned(CurrentDraggingControl) and assigned(LastParent)) then begin if(LastParent is TComponentContainer) then begin if(del) then begin (LastParent as TComponentContainer).deleteControl(CurrentDraggingControl); end; end else showmessage('invalid class type'); end else begin showmessage('Drag control not assigned'); end; CurrentDraggingControl:=nil; LastParent:=nil end; procedure TComponentContainer.moveControl(frompos,topos:integer); var tctrl: TControl; i:integer; begin tctrl:=mcontrols[frompos]; if((frompos>controlsCount) or (frompos<0) or (topos>controlsCount) or (topos<0)) then begin showmessage('bad position'); exit; end; if(frompos>topos) then begin for i := frompos downto topos +1 do mcontrols[i]:=mcontrols[i-1]; end else begin for i := frompos to topos -1 do mcontrols[i]:=mcontrols[i+1]; end; mcontrols[topos]:=tctrl; end; function TComponentContainer.hasControl(ctrl:TControl):boolean; var i:integer; begin result:=false; for i := 0 to controlsCount-1 do begin if(mcontrols[i]=ctrl) then begin result:=true; break; end; end; end; function TComponentContainer.getPosition(X, Y: Integer):integer; var i,ttop:integer; begin result:=-1; for i := 0 to controlsCount -1 do begin ttop:=mcontrols[i].Top-5; if((Y>ttop) AND (Y<ttop+mcontrols[i].height)) then begin result:=i; break; end; end; end; procedure TComponentContainer.DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := Source is TPersistent; end; procedure TComponentContainer.DragDrop(Sender, Source: TObject; X, Y: Integer); begin addControl((Source as TControl),X,Y); end; procedure TComponentContainer.addControl(ctrl:TControl; X:integer=-1;Y:integer=-1); var i,i2:integer; begin if(hascontrol(ctrl)) then begin if((X>=0) and (Y>=0)) then begin i:=getCtrlPos(ctrl); i2:=getPosition(X, Y); if((i2>=0) and (i>=0)) then begin moveControl(i,i2); end else begin if(i>=0) then begin moveControl(i,controlsCount-1); //if no position, add it at the end end else //control not found, should not happen begin showmessage('Can''t get position'); end; end; end; clearlasts(); end else //control does not exists begin i:=controlsCount; setlength(mcontrols,i+1); ctrl.parent:=self; mcontrols[i]:=ctrl; if((X>=0) and (Y>=0)) then begin i2:=getPosition(X, Y); if(i2>=0) then begin moveControl(i,i2); end else begin //showmessage('Can''t get position'); end; end; clearlasts(true); end; refreshControls(); refresh(); end; procedure TComponentContainer.deleteControl(id:integer); var i:integer; begin if((id<0) or (id>=controlsCount)) then begin showmessage('Bad control ID'); exit; end; for i := id to controlsCount - 2 do begin mcontrols[i]:=mcontrols[i+1]; end; setlength(mcontrols,controlsCount-1); refreshControls(); end; procedure TComponentContainer.deleteControl(ctrl:TControl); var i:integer; begin i:=getCtrlPos(ctrl); if(i>=0) then deleteControl(i); end; function TComponentContainer.getCtrlPos(ctrl:TControl):integer; var i:integer; begin result:=-1; for i := 0 to controlsCount -1 do begin if(mcontrols[i]=ctrl) then begin result:=i; break; end; end; end; procedure TComponentContainer.ResizeEvt(Sender: TObject); begin refreshControls(); end; procedure TComponentContainer.refreshControls(); var ctop,cleft:integer; i:integer; begin ctop:=5; cleft:=5; for i := 0 to controlsCount - 1 do begin if(horizontal) then begin mcontrols[i].Top:= 5; mcontrols[i].Left:=cleft; mcontrols[i].width:=round((width-5)/controlsCount)-5; //-10 pour laisser une marge pour les triangles if(mcontrols[i].width> (round(width/2)-5)) then mcontrols[i].width:=round(width/2)-5; mcontrols[i].visible:=true; mcontrols[i].refresh(); cleft := cleft + mcontrols[i].width + 5; end else begin mcontrols[i].Top:= ctop; mcontrols[i].Left:=5; mcontrols[i].width:=width-10; mcontrols[i].visible:=true; mcontrols[i].refresh(); ctop := ctop + mcontrols[i].Height + 5; end; end; refresh(); end; procedure Register; begin RegisterComponents('Samples', [TComponentContainer]); end; procedure TComponentContainer.Paint; var i,x,y:integer; tcoords:array [0..2] of TPoint; begin inherited Paint; with Canvas do begin Brush.Style:=bsSolid; Brush.Color:=Color; Pen.Color:=clBlack; Rectangle(0,0,Width,Height); x:=round((width-TextWidth(Caption))/2); y:=round((height-TextHeight(Caption))/2); textout(x,y,caption); end; canvas.brush.color:=clBlack; for i := 0 to controlsCount - 1 do begin mcontrols[i].refresh(); if(i<(controlsCount - 1)) then begin if(horizontal) then begin tcoords[0].X:=mcontrols[i].left + mcontrols[i].width; tcoords[1].X:=mcontrols[i].left + mcontrols[i].width;//round(width/2)+2; tcoords[0].Y:=round(height/2)+2; tcoords[1].Y:=round(height/2)-2; tcoords[2].X:=mcontrols[i].left + mcontrols[i].width +5; tcoords[2].Y:=round(height/2); canvas.Polygon(tcoords); end else begin tcoords[0].X:=round(width/2)-2; tcoords[1].X:=round(width/2)+2; tcoords[0].Y:=mcontrols[i].top + mcontrols[i].Height; tcoords[1].Y:=mcontrols[i].top + mcontrols[i].Height; tcoords[2].X:=round(width/2); tcoords[2].Y:=mcontrols[i].top + mcontrols[i].Height +5; canvas.Polygon(tcoords); end; end; end; end; end.
unit SimThyrBaseServices; { SimThyr Project } { A numerical simulator of thyrotropic feedback control } { Version 5.0.0 (Mirage) } { (c) J. W. Dietrich, 1994 - 2023 } { (c) Ludwig Maximilian University of Munich 1995 - 2002 } { (c) Ruhr University of Bochum 2005 - 2023 } { This unit provides some global functions for use by other units } { Source code released under the BSD License } { See http://simthyr.sourceforge.net for details } {$mode objfpc}{$R+} {$IFDEF LCLCocoa} {$modeswitch objectivec1} {$ENDIF} interface uses Classes, SysUtils, StrUtils, SimThyrTypes, SimThyrResources, UnitConverter, DOM, DateUtils; const iuSystemScript = -1; iuCurrentScript = -2; iuWordSelectTable = 0; iuWordWrapTable = 1; iuNumberPartsTable = 2; iuUnTokenTable = 3; iuWhiteSpaceList = 4; function EncodeGreek(theString: string): string; function DecodeGreek(theString: string): string; function XMLDateTime2DateTime(const XMLDateTime: string): TDateTime; function TryXMLDateTime2DateTime(const S: ShortString; out Value: TDateTime): boolean; function NodeContent(theRoot: TDOMNode; Name: string): string; procedure VarFromNode(theRoot: TDOMNode; Name: string; var theVar: real); function SimpleNode(Doc: TXMLDocument; Name, Value: string): TDOMNode; function AsTime(x: real): TDateTime; function FormattedTime(x: real): Str255; procedure SetStandardFactors; implementation function EncodeGreek(theString: string): string; {encodes greek mu letter as ASCII substitution sequence} var theFlags: TReplaceFlags; begin theFlags := [rfReplaceAll, rfIgnoreCase]; Result := StringReplace(theString, #194#181, 'mc', theFlags); end; function DecodeGreek(theString: string): string; {decodes ASCII substitution sequence for greek mu letter} begin Result := UTF8Decode(StringReplace(theString, 'mc', PrefixLabel[4], [rfReplaceAll, rfIgnoreCase])); end; function XMLDateTime2DateTime(const XMLDateTime: string): TDateTime; { adapted and expanded from a suggestion by Luiz Americo Pereira Camara } var DateOnly, TimeOnly: string; theDate, theTime: TDateTime; TPos: integer; begin TPos := Pos('T', XMLDateTime); if TPos <> 0 then begin DateOnly := Copy(XMLDateTime, 1, TPos - 1); TimeOnly := Copy(XMLDateTime, TPos + 1, Length(XMLDateTime)); theDate := ScanDateTime(LeftStr(ISO_8601_DATE_FORMAT, 10), DateOnly); theTime := ScanDateTime(RightStr(ISO_8601_DATE_FORMAT, 8), TimeOnly); Result := theDate + theTime; end else begin DateOnly := XMLDateTime; Result := ScanDateTime(LeftStr(ISO_8601_DATE_FORMAT, 10), DateOnly); end; end; function TryXMLDateTime2DateTime(const S: ShortString; out Value: TDateTime): boolean; begin Result := True; try Value := XMLDateTime2DateTime(s); except on EConvertError do Result := False end; end; function NodeContent(theRoot: TDOMNode; Name: string): string; {supports XML routines, gets the contents of a node in a file} var theNode: TDOMNode; theText: string; begin if assigned(theRoot) then begin Result := 'NA'; theNode := theRoot.FindNode(Name); if assigned(theNode) then begin try theText := UTF8Encode(theNode.TextContent); if theText <> '' then Result := theText; except Result := 'NA'; end; theNode.Destroy; end else Result := 'NA'; end; end; procedure VarFromNode(theRoot: TDOMNode; Name: string; var theVar: real); {supports XML routines} var oldSep: char; theString: string; begin oldSep := DefaultFormatSettings.DecimalSeparator; DefaultFormatSettings.DecimalSeparator := kPERIOD; theString := NodeContent(theRoot, Name); if theString <> 'NA' then theVar := StrToFloat(theString); DefaultFormatSettings.DecimalSeparator := oldSep; end; function SimpleNode(Doc: TXMLDocument; Name, Value: string): TDOMNode; {supports XML routines, creates an XML node from the contents of a string} var ItemNode, TextNode: TDOMNode; begin ItemNode := Doc.CreateElement(Name); TextNode := Doc.CreateTextNode(UTF8Decode(Value)); ItemNode.AppendChild(TextNode); Result := ItemNode; end; function AsTime(x: real): TDateTime; {Converts second values to TDateTime representation} var r: longint; y, d: word; theTime, theDate: TDateTime; begin y := 1900; d := 1; theDate := EncodeDateDay(y, d); r := trunc(x); theTime := IncSecond(theDate, r); AsTime := theTime; end; function FormattedTime(x: real): Str255; {Converts second values to a formatted time} begin FormattedTime := FormatDateTime(gDateTimeFormat, AsTime(x)); end; procedure SetStandardFactors; var j: integer; begin for j := i_pos to cT3_pos do gParameterFactor[j] := 1; // default values, to be changed later in program run end; end.
unit NoiseGeneratorOctaves_u; interface uses RandomMCT, NoiseGenerator_u, NoiseGeneratorPerlin_u, generation; type NoiseGeneratorOctaves=class(NoiseGenerator) private generatorCollection:ar_NoiseGeneratorPerlin; octaves:integer; public constructor Create(rand:rnd; i:integer); destructor Destroy; override; function generateNoiseOctaves(ad:ar_double; i,j,k,l,i1,j1:integer; d,d1,d2:double):ar_double; function func_4109_a(ad:ar_double; i,j,k,l:integer; d,d1,d2:double):ar_double; end; implementation uses MathHelper_u; constructor NoiseGeneratorOctaves.Create(rand:rnd; i:integer); var j:integer; begin octaves:=i; setlength(generatorCollection,i); for j:=0 to i-1 do generatorCollection[j]:=NoiseGeneratorPerlin.Create(rand); end; destructor NoiseGeneratorOctaves.Destroy; var i:integer; begin for i:=0 to length(generatorCollection)-1 do generatorCollection[i].Free; setlength(generatorCollection,0); inherited; end; function NoiseGeneratorOctaves.generateNoiseOctaves(ad:ar_double; i,j,k,l,i1,j1:integer; d,d1,d2:double):ar_double; var k1,l1:integer; d3,d4,d5,d6:double; l2,l3:int64; begin if length(ad)=0 then setlength(ad,l*i1*j1) else for k1:=0 to length(ad)-1 do ad[k1]:=0; d3:=1; for l1:=0 to octaves-1 do begin d4:=i * d3 * d; d5:=j * d3 * d1; d6:=k * d3 * d2; l2:=MathHelper_u.floor_double_long(d4); l3:=MathHelper_u.floor_double_long(d6); d4:=d4-l2; d6:=d6-l3; l2:=l2 mod $1000000; l3:=l3 mod $1000000; d4:=d4+l2; d6:=d6+l3; generatorCollection[l1].func_805_a(ad, d4, d5, d6, l, i1, j1, d * d3, d1 * d3, d2 * d3, d3); d3:=d3/2; end; result:=ad; end; function NoiseGeneratorOctaves.func_4109_a(ad:ar_double; i,j,k,l:integer; d,d1,d2:double):ar_double; begin result:=generateNoiseOctaves(ad, i, 10, j, k, 1, l, d, 1, d1); end; end.
unit Builder.Interfaces.ITripComputer; interface type ITripComputer = Interface ['{64CF3043-6628-451B-A821-1A4CFA2E0508}'] function GetModel: string; End; implementation end.
unit IntfUtils; {********************************************** Kingstar Delphi Library Copyright (C) Kingstar Corporation <Unit> IntfUtils <What> 实现接口的基础类 <Written By> Huang YanLai <History> **********************************************} interface uses windows,ActiveX,Sysutils,ComObj; type TVCLInterfacedObject0 = class(TObject,IUnknown) private FCounting : Boolean; FRefCount: Integer; FIsDestroying: Boolean; protected property IsDestroying : Boolean read FIsDestroying; public { IUnknown } function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; constructor Create(Counting : Boolean=False); procedure BeforeDestruction; override; Destructor Destroy;override; property RefCount: Integer read FRefCount; end; TVCLInterfacedObject = class(TVCLInterfacedObject0) private public constructor Create(Counting : Boolean=False); destructor Destroy;override; end; TVCLDelegateObject = class(TVCLInterfacedObject0,IUnknown) private FOwner : TObject; protected public constructor Create(AOwner : TObject); property Owner : TObject read FOwner ; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; end; TAutoIntfObjectEx = class(TObject,IUnknown, IDispatch, ISupportErrorInfo) private FController: Pointer; FRefCount: Integer; FDispTypeInfo: ITypeInfo; FDispIntfEntry: PInterfaceEntry; FDispIID: TGUID; FServerExceptionHandler: IServerExceptionHandler; function GetController: IUnknown; protected { IUnknown } //function IUnknown.QueryInterface = ObjQueryInterface; //function IUnknown._AddRef = ObjAddRef; //function IUnknown._Release = ObjRelease; { IUnknown methods for other interfaces } function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { ISupportErrorInfo } function InterfaceSupportsErrorInfo(const iid: TIID): HResult; stdcall; { IDispatch } function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; function GetTypeInfoCount(out Count: Integer): HResult; stdcall; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; public constructor Create(const TypeLib: ITypeLib; const DispIntf: TGUID); constructor CreateAggregated(const TypeLib: ITypeLib; const DispIntf: TGUID;const Controller: IUnknown); destructor Destroy; override; procedure Initialize; virtual; function ObjAddRef: Integer; virtual; stdcall; function ObjQueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function ObjRelease: Integer; virtual; stdcall; property Controller: IUnknown read GetController; property RefCount: Integer read FRefCount; function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; override; property DispIntfEntry: PInterfaceEntry read FDispIntfEntry; property DispTypeInfo: ITypeInfo read FDispTypeInfo; property DispIID: TGUID read FDispIID; property ServerExceptionHandler: IServerExceptionHandler read FServerExceptionHandler write FServerExceptionHandler; end; implementation uses DebugMemory,logFile; { TVCLInterfacedObject0 } constructor TVCLInterfacedObject0.Create(Counting: Boolean=False); begin FCounting := Counting; FRefCount := 0; FIsDestroying:=False; end; function TVCLInterfacedObject0._AddRef: Integer; begin //writeLog(className+'.addRef',lcConstruct_Destroy); if FCounting then begin Result := InterlockedIncrement(FRefCount); end else result := -1; end; function TVCLInterfacedObject0._Release: Integer; begin //writeLog(className+'.release',lcConstruct_Destroy); if FCounting then begin Result := InterlockedDecrement(FRefCount); if (Result = 0) and not FIsDestroying then Destroy; end else result := -1; end; function TVCLInterfacedObject0.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; destructor TVCLInterfacedObject0.Destroy; begin WriteLog('count='+IntToStr(FRefCount),lcConstruct_Destroy); //if (FRefCount > 0) and FCounting then CoDisconnectObject(Self, 0); inherited; end; procedure TVCLInterfacedObject0.BeforeDestruction; begin inherited; FIsDestroying:=true; end; { TVCLDelegateObject } constructor TVCLDelegateObject.Create(AOwner: TObject); begin inherited Create(False); FOwner := AOwner; end; function TVCLDelegateObject.QueryInterface(const IID: TGUID; out Obj): HResult; begin if FOwner.GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; { TAutoIntfObjectEx } constructor TAutoIntfObjectEx.Create(const TypeLib: ITypeLib; const DispIntf: TGUID); begin CreateAggregated(TypeLib,DispIntf,nil); end; constructor TAutoIntfObjectEx.CreateAggregated(const TypeLib: ITypeLib; const DispIntf: TGUID;const Controller: IUnknown); begin LogCreate(self); OleCheck(TypeLib.GetTypeInfoOfGuid(DispIntf, FDispTypeInfo)); FDispIntfEntry := GetInterfaceEntry(DispIntf); FRefCount := 1; FController := Pointer(Controller); Initialize; Dec(FRefCount); end; destructor TAutoIntfObjectEx.Destroy; begin if FRefCount > 0 then CoDisconnectObject(Self, 0); inherited; LogDestroy(self); end; function TAutoIntfObjectEx.GetController: IUnknown; begin Result := IUnknown(FController); end; procedure TAutoIntfObjectEx.Initialize; begin end; { TAutoIntfObjectEx.IUnknown } function TAutoIntfObjectEx.ObjQueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TAutoIntfObjectEx.ObjAddRef: Integer; begin Result := InterlockedIncrement(FRefCount); end; function TAutoIntfObjectEx.ObjRelease: Integer; begin // InterlockedDecrement returns only 0 or 1 on Win95 and NT 3.51 // returns actual result on NT 4.0 Result := InterlockedDecrement(FRefCount); if Result = 0 then Destroy; end; { TAutoIntfObjectEx.IUnknown for other interfaces } function TAutoIntfObjectEx.QueryInterface(const IID: TGUID; out Obj): HResult; begin {if FController <> nil then Result := IUnknown(FController).QueryInterface(IID, Obj) else Result := ObjQueryInterface(IID, Obj);} Result := ObjQueryInterface(IID, Obj); end; function TAutoIntfObjectEx._AddRef: Integer; begin if FController <> nil then Result := IUnknown(FController)._AddRef else Result := ObjAddRef; end; function TAutoIntfObjectEx._Release: Integer; begin if FController <> nil then Result := IUnknown(FController)._Release else Result := ObjRelease; end; { TAutoIntfObjectEx.ISupportErrorInfo } function TAutoIntfObjectEx.InterfaceSupportsErrorInfo(const iid: TIID): HResult; begin if GetInterfaceEntry(iid) <> nil then Result := S_OK else Result := S_FALSE; end; function TAutoIntfObjectEx.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; begin Result := DispGetIDsOfNames(FDispTypeInfo, Names, NameCount, DispIDs); end; function TAutoIntfObjectEx.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; begin Pointer(TypeInfo) := nil; if Index <> 0 then begin Result := DISP_E_BADINDEX; Exit; end; ITypeInfo(TypeInfo) := FDispTypeInfo; Result := S_OK; end; function TAutoIntfObjectEx.GetTypeInfoCount(out Count: Integer): HResult; begin Count := 1; Result := S_OK; end; function TAutoIntfObjectEx.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; const INVOKE_PROPERTYSET = INVOKE_PROPERTYPUT or INVOKE_PROPERTYPUTREF; begin if Flags and INVOKE_PROPERTYSET <> 0 then Flags := INVOKE_PROPERTYSET; Result := FDispTypeInfo.Invoke(Pointer(Integer(Self) + FDispIntfEntry.IOffset), DispID, Flags, TDispParams(Params), VarResult, ExcepInfo, ArgErr); end; function TAutoIntfObjectEx.SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; { begin Result := HandleSafeCallException(ExceptObject, ExceptAddr, DispIID, '', ''); end; } var Msg: string; Handled: Integer; begin //WriteException; Handled := 0; if ServerExceptionHandler <> nil then begin if ExceptObject is Exception then Msg := Exception(ExceptObject).Message; Result := 0; ServerExceptionHandler.OnException(ClassName, ExceptObject.ClassName, Msg, Integer(ExceptAddr), '', '', Handled, Result); end; if Handled = 0 then Result := HandleSafeCallException(ExceptObject, ExceptAddr, DispIID, '', ''); //WriteException; end; { TVCLInterfacedObject } constructor TVCLInterfacedObject.Create(Counting: Boolean); begin LogCreate(self); inherited; end; destructor TVCLInterfacedObject.Destroy; begin inherited; LogDestroy(self); end; end.
unit edidTypes; // MIT License // // Copyright (c) 2020 Dmitry Boyarintsev // // 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. {$mode objfpc}{$H+} interface type // Manufacturer ID is in big-endian byte order. This is important for Letter2 // as it rolls over the between the first and the second byte TEDIDMan = bitpacked record case byte of 1: ( let3 : 0..31; // bits 0..4 let2 : 0..31; // bits 5..9 let1 : 0..31; // bits 10..14 res : 0..1; // bit 15 ); 2: (w: word;) end; TEDIDVideoInput = bitpacked record case byte of // analog 0:( AnVSyncPulse : 0..1; AnSyncOnGreen : 0..1; AnIsCompSync : 0..1; AnSepSync : 0..1; AnBlankToBlack: 0..1; AnSyncLevel : 0..3; IsNotAnalog : 0..1; // isDigital ); // digital 1: ( DigVideoIntf : 0..15; DigBitDepth : 0..7; isDigital : 0..1; ); end; TEDIDFeatures = bitpacked record isContTiming : 0..1; // Continuous timings with GTF or CVT isPrefTimingSpecified : 0..1; // Preferred timing mode specified in descriptor block 1 isStdsRGB : 0..1; // Standard sRGB colour space. Bytes 25–34 must contain sRGB standard values. DisplayType : 0..3; // DPMSActiveOff : 0..1; // DPMS active-off supported DPMSSuspend : 0..1; // DPMS suspend supported DPMSStandBy : 0..1; // DPMS standby supported end; TEDIDSupportedTiming = bitpacked record case byte of 0: (flag : 0..1 shl 24 - 1); end; TEDIDAspect = bitpacked record VertFreq : 0..63; AspectRatio : 0..3; end; TEDIDActiveBlank8Bit = packed record Active : byte; Blank : byte; end; TEDIDActiveBlank4Bit = bitpacked record Blank : 0..15; Active : 0..15; end; TEDIDOffsetSync8Bit = packed record Active : byte; Blank : byte; end; TEDIDOffsetSync4Bit = bitpacked record Blank : 0..15; Active : 0..15; end; TEDIDOffsetSync2Bit = bitpacked record VertSync : 0..3; VertOffset : 0..3; HorzSync : 0..3; HorzOffset : 0..3; end; TEDIDImageSize4Bit = bitpacked record vert : 0..15; horz : 0..15; end; TEDIDDetailedTimeDescr = packed record pixelClock : Word; // little endian horzAB8 : TEDIDActiveBlank8Bit; horzAB4 : TEDIDActiveBlank4Bit; vertAB8 : TEDIDActiveBlank8Bit; vertAB4 : TEDIDActiveBlank4Bit; horzPS8 : TEDIDOffsetSync8Bit; vertPS4 : TEDIDOffsetSync4Bit; PorchSync2 : TEDIDOffsetSync2Bit; horzMm : Byte; vertMm : Byte; imageSize : TEDIDImageSize4Bit; horzBorder : Byte; vertBorder : Byte; Features : Byte; end; TEDIDDisplayDescr = packed record zero : Word; // must be zero res : Byte; descrType : Byte; version : Byte; // used by case byte of // value of descrType Display Range Limits Descriptor. 00: (buf : array [0..12] of byte); $FE: (text : array [0..12] of char); $FC: (displayText : array [0..12] of char); $FF: (serialNum : array [0..12] of char); end; TEDIDDescr = packed record case byte of 0: (time: TEDIDDetailedTimeDescr); 1: (disp: TEDIDDisplayDescr); end; TEDIDStdTiming = packed record res : Byte; aspect : TEDIDAspect; end; TEDIDRec = packed record // Structure, version 1.4 // Header information Hdr : array [0..7] of byte; ManId : TEDIDMan; ProdCode : Word; SerNum : LongWord; ManWeek : Byte; ManYear : Byte; EdidVer : Byte; EdidRev : Byte; // Basic display parameters VideoInp : TEDIDVideoInput; SzH : Byte; SzV : Byte; Gamma : Byte; Features : TEDIDFeatures; // Chromaticity coordinates. redGreenXY : Byte; blueWhite : Byte; redX : Byte; redY : Byte; greenX : Byte; greenY : Byte; blueX : Byte; blueY : Byte; whiteX : Byte; whiteY : Byte; // Supported Timings supTime1 : Byte; supTime2 : Byte; supTime3 : Byte; // Standard timing information. Up to 8 2-byte fields describing standard display modes suppRes : array [0..7] of TEDIDStdTiming; descr : array [0..3] of TEDIDDescr; extNum : Byte; checkSum : Byte; end; PEDIDRec = ^TEDIDRec; const VIDEOINTF_UNDEF = 0; // = undefined VIDEOINTF_HDMIA = 2; VIDEOINTF_HDMIB = 3; VIDEOINTF_MDDI = 8; // MDDI VIDEOINTF_DISPORT = 9; // DisplayPort DISPTYPE_ANALOG_MONO = 0; DISPTYPE_ANALOG_RGB = 1; DISPTYPE_ANALOG_NRGB = 2; DISPTYPE_ANALOG_UND = 3; DISPTYPE_DIGIT_444 = 0; DISPTYPE_DIGIT_444_444 = 1; DISPTYPE_DIGIT_444_422 = 2; DISPTYPE_DIGIT_444_444_422 = 3; SUPTIME1_720_400_70 = 1 shl 7; // VGA SUPTIME1_720_400_88 = 1 shl 6; // XGA SUPTIME1_640_480_60 = 1 shl 5; // VGA SUPTIME1_640_480_67 = 1 shl 4; // Apple Macintosh II SUPTIME1_640_480_72 = 1 shl 3; SUPTIME1_640_480_75 = 1 shl 2; SUPTIME1_800_600_56 = 1 shl 1; SUPTIME1_800_600_60 = 1 shl 0; SUPTIME2_800_600_72 = 1 shl 7; SUPTIME2_800_600_75 = 1 shl 6; SUPTIME2_832_624_75 = 1 shl 5; // Apple Macintosh II SUPTIME2_1024_768_87 = 1 shl 4; // interlaced (1024×768i) SUPTIME2_1024_768_60 = 1 shl 3; SUPTIME2_1024_768_70 = 1 shl 2; SUPTIME2_1024_768_75 = 1 shl 1; SUPTIME2_1280_1024_75 = 1 shl 0; SUPTIME3_1152_870_75 = 1 shl 7; // Apple Macintosh II ASPECT_16_10 = 0; ASPECT_4_3 = 1; ASPECT_5_4 = 2; ASPECT_16_9 = 3; DISPDESCR_DUMMY = $10; DISPDESCR_ADDSTDTIME = $F8; DISPDESCR_CVT = $F9; DISPDESCR_DCM = $F9; DISPDESCR_ADDSTDTIMEID = $FA; DISPDESCR_ADDWHITE = $FB; DISPDESCR_DISPNAME = $FC; DISPDESCR_DISPRANGE = $FD; DISPDESCR_TEXT = $FE; DISPDESCR_SERIALNUM = $FF; function EdidManToStr(const m: TEDIDMan): string; function EdidGetDisplayName(const m: TEDIDRec): string; function EdidGetPhysSizeMm(const ed: TEDIDRec; out horzMm, vertMM: Integer): Boolean; implementation function EdidManToStr(const m: TEDIDMan): string; const base = Ord('A')-1; var le : TEDIDMan; begin Result:=''; le.w := BEtoN(m.w); SetLength(Result, 3); Result[1]:=Chr(le.let1+base); Result[2]:=Chr(le.let2+base); Result[3]:=Chr(le.let3+base); end; function Trim(const ch: array of char): string; var i : integer; begin i := length(ch)-1; while (i>=0) do begin if not (ch[i] in [#0, #32, #9, #13, #10]) then Break; dec(i); end; if (i < 0) then Result := ''; inc(i); SetLength(Result, i); Move(ch[0], Result[1], i); end; function EdidGetDisplayName(const m: TEDIDRec): string; var i : integer; begin for i := low(m.descr) to high(m.descr) do begin if m.descr[i].disp.zero <> 0 then Continue; if m.descr[i].disp.descrType = DISPDESCR_DISPNAME then begin Result := Trim(m.descr[i].disp.displayText); Exit; end; end; Result := ''; end; function EdidGetPhysSizeMm(const ed: TEDIDRec; out horzMm, vertMM: Integer): Boolean; var i : integer; begin horzMm := 0; vertMm := 0; for i:=low(ed.descr) to high(ed.descr) do if (ed.descr[i].time.pixelClock>0) then begin horzMm := (ed.descr[i].time.imageSize.horz shl 8) or (ed.descr[i].time.horzMm); vertMm := (ed.descr[i].time.imageSize.vert shl 8) or (ed.descr[i].time.vertMm); break; end; if (horzMm = 0) and (vertMm = 0) then begin horzMm := ed.SzH * 10; vertMm := ed.SzV * 10; end; Result := (horzMm > 0) and (vertMm > 0) end; end.
{; ; Lab 2 Part A Parallel Port programming ;************************************************************************* ; Before you start filling in the code, you are going to need the following ; documents for technical information: ; 4601-Lab2 Appendix C ; http://retired.beyondlogic.org/spp/parallel.htm -How do parallel ports work ; http://umcs.maine.edu/~cmeadow/courses/cos335/80x86InstructionReference.pdf ; ; ;************************************************************************* ; Start with standard 80x86 assembler boilerplate i.e. a skeleton of a program ; which is common to most assembler code. This programme is more comments and ; discussion than anything else. ; ; The actual assembler code that needs to be written is only about 20 lines. ; ; All the heavy lifting is done for you. In the areas marked as: ;__________________________________________> ; Your code goes here ;<__________________________________________ ; the student will put a few lines of code to become familiar with writing code. ; The important things to note are the steps and the how they relate to handling ; interrupts in this particular microprocessor i.e. the 80x86 in real mode ; ; some acronyms that we'll use ; PIC priority interrupt controller. There are 2 in a classic PC ; OS operating system ; ISR interrupt service routine ; ; NOTE ; **** ; For this particular exercise, you are actually using a Pascal compiler ; to 'assemble' your program. The advantage is that you still get to see ; how the actual code does stuff, but you don't have to worry about every little ; detail. It is the main advantage of any compiler. We could have used a C compiler ; as well but this one works just fine. The little constructs that make your life ; easier will be noted. ; ;******************************************************************************* ;* Note that hex values are designated by a '$' symbol so * ;* the usual 0x0FF or 0FFh notation becomes $FF. Comments are also noted as * ;* anything enclosed in curly brackets. * ;******************************************************************************* ; define some constants that we will use. It is always best to define all constants ; and use the name rather than to use the raw number in the code ;} const EOI = $20 ; PIC = $20 ; { the 8259 interrupt controller } IRQ7 = $F ; LPT1 = $378 ; BUSY : string[4] = '-\|/' ; {; ; variables to be used (a Pascal construct) ;} var counter : word ; { 16-bit number } saveint : pointer ; { 32-bit pointer } {; ; This is the Interrupt Service Routine (ISR). This is where the interrupt handler ; code lives. ; If you only ever call your own routines and they are all in this ; file AND if everything fits in a single 64K segment, then you probably ; wouldn't have to worry about making sure that the segment registers ; are valid and point to your variables. ; ; An interrupt can occur at any time and a jump to this routine will just happen. ; It is up to you to set things up the way that you want them, handle the ; interrupt and then put everything back the way it was. Interrupt handlers ; must put everything back EXACTLY as it was before the handler was called. ; For this processor, the FLAGS register and the Program Counter (CS:IP) are pushed onto the ; stack when the interrupt handler is called (automatically) and popped off the stack ; with the IRET instruction ;********************************************************************* ; important steps ; 1 - sve any registers that you are going to change ; 2 - set the DS register to point to the data segment of your variables so ; you can reference variables properly (two hints: (1) look above at variables that were ; instantiated. Like an array in C, the first variable is the start of your segment ; (2)To get the 'address of' a variable you need to use SEG,(2) Remember your assembly class, ; you can't populate your DS register directly) ; 3 - Increment the interrupt counter ; 4 - send the EOI command to the PIC otherwise you'll never see another interrupt ; (hint: the PIC is a port) ; 5 - restore the registers that you changed (put your toys away) ; 6 - make interrupt return as opposed to a regular procedure return ; and done ;} Procedure LptIsr ; far ; assembler ; { this is a Pascal construct for assembly procedures, pretty much like C } asm {_____________________________________________>} push ds push ax push dx // marker mov dx, $379 in al, dx mov ax, seg counter mov ds, ax inc counter mov al, EOI out PIC, al pop dx pop ax pop ds iret {<_____________________________________________} end ; { ; ; The main program that just waits for an interrupt and puts up some ; sort of a status display ;} begin asm { ; ; Below is where we write code to replace the stock hardware interrupt ; vector with our custom vector. Fill in the blanks below with code to ; step though how to do this. ;--------------------------------------------------------- ; ; ; Put zero in the 'count' variable ; there are lots of ways of doing this ; about 1 to 3 lines of assembler code should do} {_____________________________________________>} MOV counter, 0 {<_____________________________________________} {; ; now the painful steps of setting the system up to allow ; recognising and handling the interrupt } { ; !! Step 1 ; send the EOI command to the PIC to ready it for interrupts ; hint: look for information on how to write to x86 ports. ;} {_____________________________________________>} mov al, EOI out PIC, al {<_____________________________________________} {; ; !! Step 2 ; Disable IRQ7 using the interrupt mask register IMR bit in the PIC #1 for now ; so that we don't get an interrupt before we are ready to actually ; process one. Refer to Appendix C in the lab document ; ; A quick word about setting bits, ; We can individually set bits in a register easily by using a bit mask and ; then depending on the activity (set a bit high or low) apply a logical ; operation to the register with the mask. For example: ; ; We want to set bit 5 low of an 8 bit word; we use a mask: 11101111. ; We then read in the value from an external port register(e.g. 11010110) ; To set the bit LOW, we then AND the mask and the received word: ; 11101111 AND 11010110 = 11000110 ; We would then write that word back to the external port register. ; ; To set bit 5 HIGH, we have another mask: 00010000. As above, we read in ; in the word from the port, then OR it to set the bit high: ; 11000110 OR 00010000 = 11010110 ; Again, we would write this to the external port register. ; {_____________________________________________>} in al, PIC+1 or al, $80 out PIC+1, al {<_____________________________________________} {; ; !! Step 3 ; - Save the current IRQ7 vector for restoring later. For this processor, ; this is just always done. ; - This is a system function call in any OS; We are running this in DOS ; we will use the DOS INT 21 call to retrieve the interrupt vector. ; reference http://en.wikipedia.org/wiki/MS-DOS_API ; To set up the call: ; AH = 0x35 this is the function number that fetches a vector ; AL = the software interrupt vector that we want to read 0..255 ; INT 0x21 is the standard way of getting at DOS services. Any OS running ; on this processor will use some variation of this idea. ; When the function call returns, you will find the interrupt vector ; in the es:bx registers; the es holds the segment, the bx holds the offset. ;} {_____________________________________________>} mov ah, $35 mov al, IRQ7 int $21 {<_____________________________________________} {; ; Put the values of ES and BX into the 32-bit 'saveint' variable ; so that we can restore the interrupt pointer at the end of the programme. ; We'll use the saveint variable like an array; we'll need to cast the saveint ; to a word. ;} {_____________________________________________>} mov word ptr saveint, BX mov word ptr saveint+2, ES {<_____________________________________________} { ; !! Step 4 ; Move the address of our ISR into the IRQ7 slot in the table ; Unless you do this step, nothing is going to happen when an interrupt ; occurs, at least nothing that you have any control over ; Just like above, there is a DOS system call to do this. You could do it ; yourself, but it is always good policy to use a system call if there is ; one. ; Again, the call is made through INT 0x21 with some registers ; defined as follows in order to set up the call: ; AH = 0x25 this is the function number that sets a vector ; AL = the software interrupt vector that we want to set 0..255 ; DS:DX = the 32-bit address of our ISR ; ; If you change the value of the DS register to satisfy the function call, ; be sure to save it, then restore it after the call. ; ; You can find the segment part and offset part of the address ; of the procedure LptIsr using the 'seg' and 'offset' assembler operations } {_____________________________________________>} push ds move ah, $25 mov al, IRQ7 mov bx, seg LptIsr mov ds, bx mov dx, offset LptIsr int $21 pop ds {<_____________________________________________} {; ; !! Step 5 ; Enable interrupts at the LPT1 device itself so that signals coming ; in on pin 10 on the LPT1 connector will cause an interrupt. ; Set the bit in the control register (byte) of LPT1 which should be ; at address LPT1+2. Look at Appendix C, you need to toggle specific ; bits and leave the other bits alone. {_____________________________________________>} mov dx, LPT1+2 in al, dx or al, $10 out dx, al {<_____________________________________________} {; ; !! Step 6 ; Lastly set up the PIC to allow interrupts on IRQ7. Same here, you need ; to toggle specific bits while leaving other bits alone. {_____________________________________________>} mov dx, PIC+1 in al, DX and al, $7F out dx, al {<_____________________________________________} { ; At this point, interrupts should be enabled and if they occur, our ; interrupt service routine is set up to handle the interrupt by just ; counting the interrupts as they occur. This is happening in the ; 'background' so we can do whatever we want in the 'foreground'. ; In this case, we will simply give some sort of indication of the ; value of the interrupt counter; using the LEDs on the printer port ; is an easy way of accomplishing this. ; ; We now go into a continuous loop (this is common programming practise in ; embedded systems.) ;} @loop: {; ; Check for a keypress to exit out, if no keypress: send the low 8-bits of the ; counter variable to the LED display on LPT1 so that you can see the ; results of counting the interrupts; ;} mov ah,1 int $16 jnz @alldone {; ; write the value of the counter variable to the LPT1 port to light the LEDs ;} {_____________________________________________>} mov ax, counter mov dx, LPT1 out dx, ax {<_____________________________________________} jmp @loop {; jump back to loop and check for key to quit} @alldone: {; ; ; so we have done what we set out to do. An interrupt was generated ; the code handled it and displayed something. Now undo all the steps ; that we went through to try and restore the machine to it's original ; state ; ; ! Undo Step 6 by disabling the IRQ7 interrupt on the PIC ;} {_____________________________________________>} mov dx, PIC+1 in al, dx or al, $80 out dx, al {<_____________________________________________} {; ; ! Undo Step 5 by disabling the LPT1's ability to interrupt ;} {_____________________________________________>} mov dx, LPT1+2 in al, dx and al, $EF out dx, AL {<_____________________________________________} {; ; ! Undo Step 4 by replacing the interrupt service routine address with the original ; one that we saved in 'saveint' when we started up. This is the same system call ; that you made before which sets a vector in the interrupt table except this time ; the value for the pointer is in 'saveint' ;} {_____________________________________________>} push ds mov ah, $25 mov al, IRQ7 mov dx, word ptr saveint mov bx, word ptr saveint+2 mov ds, bx int $21 pop ds {<_____________________________________________} {; ; and that should do it. Everything that was done to the system has been undone and it should be safe to quit ;} end ; end .
unit FMX.ScrollView; interface uses FMX.Types, System.Types, System.Classes, FMX.forms, FMX.Layouts, FMX.Controls; type TScrollView = class(TVertScrollBox) private FOldkeyboardHidden, FoldKeyboardShow: TVirtualKeyboardEvent; FOldFocusChange: TNotifyEvent; FForm: TCustomForm; FKBBounds: TRectF; FNeedOffset: Boolean; procedure DoInject; procedure DoResetInject; protected { Events } procedure FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); procedure FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); procedure FormFocusChanged(Sender: TObject); { tools } procedure CalcContentBoundsProc(Sender: TObject; var ContentBounds: TRectF); procedure RestorePosition; public procedure UpdateKBBounds; destructor Destroy; override; constructor Create(AOwner: TComponent); override; end; procedure Register; implementation uses System.Math; { TScrollView } procedure TScrollView.CalcContentBoundsProc(Sender: TObject; var ContentBounds: TRectF); begin if FNeedOffset and (FKBBounds.Top > 0) then begin ContentBounds.Bottom := Max(ContentBounds.Bottom, 2 * FForm.ClientHeight - FKBBounds.Top); end; end; constructor TScrollView.Create(AOwner: TComponent); begin inherited; if AOwner is TCustomForm then FForm := (AOwner as TCustomForm) else if Application.MainForm <> nil then FForm := (Application.MainForm as TCustomForm); {$IFNDEF MSWINDOWS} VKAutoShowMode := TVKAutoShowMode.Always; {$ENDIF} if Assigned(FForm) then DoInject; end; destructor TScrollView.Destroy; begin if Assigned(FForm) then DoResetInject; inherited; end; procedure TScrollView.DoInject; begin FOldkeyboardHidden := FForm.OnVirtualKeyboardHidden; FoldKeyboardShow := FForm.OnVirtualKeyboardShown; FOldFocusChange := FForm.OnFocusChanged; FForm.OnVirtualKeyboardHidden := FormVirtualKeyboardHidden; FForm.OnVirtualKeyboardShown := FormVirtualKeyboardShown; FForm.OnFocusChanged := FormFocusChanged; OnCalcContentBounds := CalcContentBoundsProc; end; procedure TScrollView.DoResetInject; begin FForm.OnVirtualKeyboardHidden := FOldkeyboardHidden; FForm.OnVirtualKeyboardShown := FoldKeyboardShow; FForm.OnFocusChanged := FOldFocusChange; end; procedure TScrollView.FormFocusChanged(Sender: TObject); begin if Assigned(FOldFocusChange) then FOldFocusChange(Sender); UpdateKBBounds; end; procedure TScrollView.FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin if Assigned(FOldkeyboardHidden) then FOldkeyboardHidden(Sender, KeyboardVisible, Bounds); FKBBounds.Create(0, 0, 0, 0); FNeedOffset := False; RestorePosition; end; procedure TScrollView.FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin if Assigned(FoldKeyboardShow) then FOldkeyboardHidden(Sender, KeyboardVisible, Bounds); FKBBounds := TRectF.Create(Bounds); FKBBounds.TopLeft := FForm.ScreenToClient(FKBBounds.TopLeft); FKBBounds.BottomRight := FForm.ScreenToClient(FKBBounds.BottomRight); UpdateKBBounds; end; procedure TScrollView.RestorePosition; begin ViewportPosition := PointF(ViewportPosition.X, 0); RealignContent; end; procedure TScrollView.UpdateKBBounds; var LFocused: TControl; LFocusRect: TRectF; begin FNeedOffset := False; if Assigned(FForm.Focused) then begin LFocused := TControl(FForm.Focused.GetObject); LFocusRect := LFocused.AbsoluteRect; LFocusRect.Offset(ViewportPosition); if (LFocusRect.IntersectsWith(TRectF.Create(FKBBounds))) and (LFocusRect.Bottom > FKBBounds.Top) then begin FNeedOffset := True; RealignContent; Application.ProcessMessages; ViewportPosition := PointF(ViewportPosition.X, LFocusRect.Bottom - FKBBounds.Top); end; end; if not FNeedOffset then RestorePosition; end; procedure Register; begin RegisterComponents('HashLoad', [TScrollView]); end; end.
unit ControladorGrilla; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Buttons, LResources, Graphics, DBGrids, StdCtrls, DB, sqldb, Forms, Controls, LCLType, frmedicionbase, ControladorEdicion; const CAD_FILTRO = '__FILTRO__'; type TTipoBuscador = ( tbParametro, //Busca registro utilizando el parámetro __FILTRO__ del query tbFiltro, //Usa la propiedad "Filter" del Query (en subforms, donde no se puede cerrar y abrir el query) tbBusqueda //Usa el método "Locate" del Query. No filtra, sólo ubica el registro (en subforms, donde no se puede cerrar y abrir el query) ); { TControladorGrilla } TControladorGrilla = class(TComponent) private FAntesBuscar: TNotifyEvent; FAntesEliminar: TNotifyEvent; FAntesEditar: TNotifyEvent; FAntesAgregar: TNotifyEvent; FAvisarBorrado: boolean; FBotonBuscar: TBitBtn; FBotonAgregar: TBitBtn; FBotonEditar: TBitBtn; FBotonEliminar: TBitBtn; FBotonSeleccionar: TBitBtn; FBotonCancelar: TBitBtn; FBotonCerrar: TBitBtn; FAltoBotones: integer; FAnchoBotones: integer; FBuscador: TCustomEdit; FCampoIdPadre: TNumericField; FControlEdicion: TControladorEdicion; FDespuesBuscar: TNotifyEvent; FDespuesEliminar: TNotifyEvent; FDespuesEditar: TNotifyEvent; FDespuesAgregar: TNotifyEvent; FExpresionFiltro: string; FGrilla: TDBGrid; FSQLQuery: TSQLQuery; FTipoBuscador: TTipoBuscador; procedure SetAltoBotones(const AValue: integer); procedure SetAnchoBotones(const AValue: integer); procedure SetAntesBuscar(AValue: TNotifyEvent); procedure SetAntesEliminar(AValue: TNotifyEvent); procedure SetAntesEditar(AValue: TNotifyEvent); procedure SetAntesAgregar(AValue: TNotifyEvent); procedure SetAvisarBorrado(AValue: boolean); procedure SetBotonBuscar(const AValue: TBitBtn); procedure SetBotonAgregar(const AValue: TBitBtn); procedure SetBotonEditar(const AValue: TBitBtn); procedure SetBotonEliminar(const AValue: TBitBtn); procedure SetBotonSeleccionar(const AValue: TBitBtn); procedure SetBotonCancelar(const AValue: TBitBtn); procedure SetBotonCerrar(const AValue: TBitBtn); procedure SetBuscador(const AValue: TCustomEdit); procedure SetCampoIdPadre(AValue: TNumericField); procedure SetControlEdicion(AValue: TControladorEdicion); procedure SetDespuesBuscar(AValue: TNotifyEvent); procedure SetDespuesEliminar(AValue: TNotifyEvent); procedure SetDespuesEditar(AValue: TNotifyEvent); procedure SetDespuesAgregar(AValue: TNotifyEvent); procedure SetExpresionFiltro(AValue: string); //Tipo: Utilizar "__FILTRO__" dentro de la cadena para armar la expresión a buscar //Por ejemplo: "Nombre=__FILTRO__ OR Descripcion=__FILTRO__" procedure SetGrilla(const AValue: TDBGrid); procedure SetSQLQuery(const AValue: TSQLQuery); procedure AgregarExecute(Sender: TObject); procedure BuscarExecute(Sender: TObject); procedure CancelarExecute(Sender: TObject); procedure EliminarExecute(Sender: TObject); procedure EditarExecute(Sender: TObject); procedure SeleccionarExecute(Sender: TObject); procedure GrillaDblClick(Sender: TObject); procedure QueryBeforeOpen(DataSet: TDataSet); procedure edBuscarKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure GrillaKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure SetTipoBuscador(AValue: TTipoBuscador); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure refrescarQuery(enfocarBuscador: boolean = False); published property AltoBotones: integer read FAltoBotones write SetAltoBotones default 26; property AnchoBotones: integer read FAnchoBotones write SetAnchoBotones default 86; property AntesAgregar: TNotifyEvent read FAntesAgregar write SetAntesAgregar; property AntesBuscar: TNotifyEvent read FAntesBuscar write SetAntesBuscar; property AntesEditar:TNotifyEvent read FAntesEditar write SetAntesEditar; property AntesEliminar: TNotifyEvent read FAntesEliminar write SetAntesEliminar; property AvisarBorrado: boolean read FAvisarBorrado write SetAvisarBorrado default True; property BotonAgregar: TBitBtn read FBotonAgregar write SetBotonAgregar; property BotonEditar: TBitBtn read FBotonEditar write SetBotonEditar; property BotonEliminar: TBitBtn read FBotonEliminar write SetBotonEliminar; property BotonSeleccionar: TBitBtn read FBotonSeleccionar write SetBotonSeleccionar; property BotonCancelar: TBitBtn read FBotonCancelar write SetBotonCancelar; property BotonCerrar: TBitBtn read FBotonCerrar write SetBotonCerrar; property BotonBuscar: TBitBtn read FBotonBuscar write SetBotonBuscar; property Buscador: TCustomEdit read FBuscador write SetBuscador; property CampoIdPadre: TNumericField read FCampoIdPadre write SetCampoIdPadre; property ControlEdicion: TControladorEdicion read FControlEdicion write SetControlEdicion; property DespuesAgregar: TNotifyEvent read FDespuesAgregar write SetDespuesAgregar; property DespuesBuscar: TNotifyEvent read FDespuesBuscar write SetDespuesBuscar; property DespuesEditar:TNotifyEvent read FDespuesEditar write SetDespuesEditar; property DespuesEliminar: TNotifyEvent read FDespuesEliminar write SetDespuesEliminar; property ExpresionFiltro: string read FExpresionFiltro write SetExpresionFiltro; property Grilla: TDBGrid read FGrilla write SetGrilla; property SQLQuery: TSQLQuery read FSQLQuery write SetSQLQuery; property TipoBuscador: TTipoBuscador read FTipoBuscador write SetTipoBuscador default tbParametro; end; procedure Register; implementation procedure Register; begin RegisterComponents('Mis Componentes', [TControladorGrilla]); end; { TControladorGrilla } procedure TControladorGrilla.SetBotonAgregar(const AValue: TBitBtn); begin if FBotonAgregar = AValue then exit; FBotonAgregar := AValue; if FBotonAgregar <> nil then begin FBotonAgregar.Visible := True; FBotonAgregar.Glyph.Assign(CreateBitmapFromLazarusResource('btgr_add')); FBotonAgregar.Caption := '&Agregar'; FBotonAgregar.Width := FAnchoBotones; FBotonAgregar.Height := FAltoBotones; FBotonAgregar.OnClick := @AgregarExecute; end; end; procedure TControladorGrilla.SetAnchoBotones(const AValue: integer); begin if FAnchoBotones = AValue then exit; FAnchoBotones := AValue; if FBotonAgregar <> nil then FBotonAgregar.Width := FAnchoBotones; if FBotonEditar <> nil then FBotonEditar.Width := FAnchoBotones; if FBotonEliminar <> nil then FBotonEliminar.Width := FAnchoBotones; if FBotonSeleccionar <> nil then FBotonSeleccionar.Width := FAnchoBotones; if FBotonCancelar <> nil then FBotonCancelar.Width := FAnchoBotones; if FBotonCerrar <> nil then FBotonCerrar.Width := FAnchoBotones; //Paso los valores al control de edicion if Assigned(ControlEdicion) then begin ControlEdicion.AnchoBotones := FAnchoBotones; end; end; procedure TControladorGrilla.SetAntesBuscar(AValue: TNotifyEvent); begin if FAntesBuscar=AValue then Exit; FAntesBuscar:=AValue; end; procedure TControladorGrilla.SetAntesEliminar(AValue: TNotifyEvent); begin if FAntesEliminar=AValue then Exit; FAntesEliminar:=AValue; end; procedure TControladorGrilla.SetAntesEditar(AValue: TNotifyEvent); begin if FAntesEditar=AValue then Exit; FAntesEditar:=AValue; end; procedure TControladorGrilla.SetAntesAgregar(AValue: TNotifyEvent); begin if FAntesAgregar=AValue then Exit; FAntesAgregar:=AValue; end; procedure TControladorGrilla.SetAvisarBorrado(AValue: boolean); begin if FAvisarBorrado = AValue then Exit; FAvisarBorrado := AValue; end; procedure TControladorGrilla.SetBotonBuscar(const AValue: TBitBtn); begin if FBotonBuscar = AValue then exit; FBotonBuscar := AValue; if FBotonBuscar <> nil then begin FBotonBuscar.Glyph.Assign(CreateBitmapFromLazarusResource('btgr_search')); FBotonBuscar.Caption := ''; //Botón cuadrado, se asigna el ancho igual que el alto FBotonBuscar.Width := 25; FBotonBuscar.Height := 25; FBotonBuscar.OnClick := @BuscarExecute; end; end; procedure TControladorGrilla.SetAltoBotones(const AValue: integer); begin if FAltoBotones = AValue then exit; FAltoBotones := AValue; if FBotonAgregar <> nil then FBotonAgregar.Height := FAltoBotones; if FBotonEditar <> nil then FBotonEditar.Height := FAltoBotones; if FBotonEliminar <> nil then FBotonEliminar.Height := FAltoBotones; if FBotonSeleccionar <> nil then FBotonSeleccionar.Height := FAltoBotones; if FBotonCancelar <> nil then FBotonCancelar.Height := FAltoBotones; if FBotonCerrar <> nil then FBotonCerrar.Height := FAltoBotones; //Paso los valores al control de edicion if Assigned(ControlEdicion) then begin ControlEdicion.AltoBotones := FAltoBotones; end; end; procedure TControladorGrilla.SetBotonEditar(const AValue: TBitBtn); begin if FBotonEditar = AValue then exit; FBotonEditar := AValue; if FBotonEditar <> nil then begin FBotonEditar.Visible := True; FBotonEditar.Glyph.Assign(CreateBitmapFromLazarusResource('btgr_edit')); FBotonEditar.Caption := '&Editar'; FBotonEditar.Width := FAnchoBotones; FBotonEditar.Height := FAltoBotones; FBotonEditar.OnClick := @EditarExecute; end; end; procedure TControladorGrilla.SetBotonEliminar(const AValue: TBitBtn); begin if FBotonEliminar = AValue then exit; FBotonEliminar := AValue; if FBotonEliminar <> nil then begin FBotonEliminar.Visible := True; FBotonEliminar.Glyph.Assign(CreateBitmapFromLazarusResource('btgr_delete')); FBotonEliminar.Caption := '&Eliminar'; FBotonEliminar.Width := FAnchoBotones; FBotonEliminar.Height := FAltoBotones; FBotonEliminar.OnClick := @EliminarExecute; end; end; procedure TControladorGrilla.SetBotonSeleccionar(const AValue: TBitBtn); begin if FBotonSeleccionar = AValue then exit; FBotonSeleccionar := AValue; if FBotonSeleccionar <> nil then begin FBotonSeleccionar.Visible := True; FBotonSeleccionar.Glyph.Assign(CreateBitmapFromLazarusResource('btgr_back')); FBotonSeleccionar.Caption := '&Seleccionar'; FBotonSeleccionar.Width := FAnchoBotones; FBotonSeleccionar.Height := FAltoBotones; FBotonSeleccionar.OnClick := @SeleccionarExecute; end; end; procedure TControladorGrilla.SetBotonCancelar(const AValue: TBitBtn); begin if FBotonCancelar = AValue then exit; FBotonCancelar := AValue; if FBotonCancelar <> nil then begin FBotonCancelar.Visible := True; FBotonCancelar.Glyph.Assign(CreateBitmapFromLazarusResource('btgr_cancel')); FBotonCancelar.Caption := '&Cancelar'; FBotonCancelar.Width := FAnchoBotones; FBotonCancelar.Height := FAltoBotones; FBotonCancelar.OnClick := @CancelarExecute; end; end; procedure TControladorGrilla.SetBotonCerrar(const AValue: TBitBtn); begin if FBotonCerrar = AValue then exit; FBotonCerrar := AValue; if FBotonCerrar <> nil then begin FBotonCerrar.Visible := True; FBotonCerrar.Glyph.Assign(CreateBitmapFromLazarusResource('btgr_quit')); FBotonCerrar.Caption := '&Cerrar'; FBotonCerrar.Width := FAnchoBotones; FBotonCerrar.Height := FAltoBotones; FBotonCerrar.OnClick := @CancelarExecute; end; end; procedure TControladorGrilla.SetBuscador(const AValue: TCustomEdit); begin if FBuscador = AValue then exit; FBuscador := AValue; if FBuscador <> nil then begin FBuscador.OnKeyDown := @edBuscarKeyDown; end; end; procedure TControladorGrilla.SetCampoIdPadre(AValue: TNumericField); begin if FCampoIdPadre = AValue then Exit; FCampoIdPadre := AValue; end; procedure TControladorGrilla.SetControlEdicion(AValue: TControladorEdicion); begin if FControlEdicion=AValue then Exit; FControlEdicion:=AValue; if Assigned(FControlEdicion) then begin FControlEdicion.AltoBotones:=FAltoBotones; FControlEdicion.AnchoBotones:=FAnchoBotones; end; end; procedure TControladorGrilla.SetDespuesBuscar(AValue: TNotifyEvent); begin if FDespuesBuscar=AValue then Exit; FDespuesBuscar:=AValue; end; procedure TControladorGrilla.SetDespuesEliminar(AValue: TNotifyEvent); begin if FDespuesEliminar=AValue then Exit; FDespuesEliminar:=AValue; end; procedure TControladorGrilla.SetDespuesEditar(AValue: TNotifyEvent); begin if FDespuesEditar=AValue then Exit; FDespuesEditar:=AValue; end; procedure TControladorGrilla.SetDespuesAgregar(AValue: TNotifyEvent); begin if FDespuesAgregar=AValue then Exit; FDespuesAgregar:=AValue; end; procedure TControladorGrilla.SetExpresionFiltro(AValue: string); begin if FExpresionFiltro=AValue then Exit; FExpresionFiltro:=AValue; end; procedure TControladorGrilla.SetGrilla(const AValue: TDBGrid); begin if FGrilla = AValue then exit; FGrilla := AValue; if FGrilla <> nil then begin FGrilla.OnKeyDown := @GrillaKeyDown; FGrilla.OnDblClick := @GrillaDblClick; end; end; procedure TControladorGrilla.SetSQLQuery(const AValue: TSQLQuery); begin if FSQLQuery = AValue then exit; FSQLQuery := AValue; //Si el SQL está vacío, cargo la plantilla con el formato de búsqueda if (FSQLQuery <> nil) and (FSQLQuery.SQL.Count=0) then begin FSQLQuery.SQL.Add('-- Siempre el primer campo debe ser el ID (clave primaria)'); FSQLQuery.SQL.Add('SELECT <campo_id>, <campo_1>, ...'); FSQLQuery.SQL.Add('FROM <tabla>'); FSQLQuery.SQL.Add('WHERE <condicion> AND ('); FSQLQuery.SQL.Add(':__FILTRO__ IS NULL OR'); FSQLQuery.SQL.Add(':__FILTRO__ = '''''); FSQLQuery.SQL.Add('OR <campo_busqueda_1> LIKE CONCAT(''%'',:__FILTRO__,''%'''); FSQLQuery.SQL.Add('OR <campo_busqueda_2> LIKE CONCAT(''%'',:__FILTRO__,''%'')'); FSQLQuery.SQL.Add('ORDER BY <orden_1>, <orden_2>'); end; end; procedure TControladorGrilla.AgregarExecute(Sender: TObject); var id, idPadre: longint; mr: TModalResult; begin if Assigned(ControlEdicion) and Assigned(SQLQuery) then begin if Assigned (FAntesAgregar) then FAntesAgregar(Self); if Assigned(FCampoIdPadre) then begin idPadre := FCampoIdPadre.AsInteger; ControlEdicion.nuevoRegistro(idPadre); end else ControlEdicion.nuevoRegistro; mr := ControlEdicion.ShowModal; //Si es un subformulario no refresco, porque todavía no se //guardaron los datos if (not ControlEdicion.EsSubform) and ((mr = mrOk) or (mr = mrYes)) then refrescarQuery(True); if Assigned (FDespuesAgregar) then FDespuesAgregar(Self); end; end; procedure TControladorGrilla.BuscarExecute(Sender: TObject); var filtro: string; CampoIndice: string; begin if Assigned(FAntesBuscar) then FAntesBuscar(Self); if TipoBuscador = tbParametro then refrescarQuery() else //Establezco el filtro begin if Assigned(SQLQuery) and Assigned(Buscador) and (ExpresionFiltro<>'') then begin if Buscador.Text<>'' then begin //Armo la cadena de filtro reemplazando con la búsqueda filtro:=StringReplace(ExpresionFiltro, CAD_FILTRO, Buscador.Text, [rfReplaceAll, rfIgnoreCase]); if TipoBuscador=tbFiltro then begin SQLQuery.Filter:=filtro; SQLQuery.Filtered:=true; end else begin //Busco en la expresión del filtro el nombre del campo a buscar CampoIndice:=LeftStr(ExpresionFiltro, Pos('=',ExpresionFiltro)-1); if CampoIndice<>'' then begin try SQLQuery.Locate(CampoIndice, Buscador.Text,[loCaseInsensitive]); finally end; end; end; end else begin SQLQuery.Filter:=''; SQLQuery.Filtered:=false; end; end; end; if Assigned(FDespuesBuscar) then FDespuesBuscar(Self); end; procedure TControladorGrilla.CancelarExecute(Sender: TObject); begin end; procedure TControladorGrilla.EliminarExecute(Sender: TObject); var id: integer; mr: TModalResult; begin if Assigned(ControlEdicion) and Assigned(SQLQuery) and (SQLQuery.RecordCount > 0) then begin if Assigned (FAntesEliminar) then FAntesEliminar(Self); id := SQLQuery.Fields[0].AsInteger; ControlEdicion.eliminarRegistro(id, AvisarBorrado); mr := ControlEdicion.ShowModal; //Si es un subformulario no refresco, porque todavía no se //guardaron los datos if (not ControlEdicion.EsSubform) and ((mr = mrOk) or (mr = mrYes)) then refrescarQuery(True); if Assigned (FDespuesEliminar) then FDespuesEliminar(Self); end; end; procedure TControladorGrilla.EditarExecute(Sender: TObject); var id: integer; mr: TModalResult; begin if Assigned(ControlEdicion) and Assigned(SQLQuery) and (SQLQuery.RecordCount > 0) then begin if Assigned (FAntesEditar) then FAntesEditar(Self); id := SQLQuery.Fields[0].AsInteger; ControlEdicion.editarRegistro(id); mr := ControlEdicion.ShowModal; //Si es un subformulario no refresco, porque todavía no se //guardaron los datos if (not ControlEdicion.EsSubform) and ((mr = mrOk) or (mr = mrYes)) then begin refrescarQuery(True); SQLQuery.Locate(SQLQuery.Fields[0].FieldName, id, []); end; if Assigned (FDespuesEditar) then FDespuesEditar(Self); end; end; procedure TControladorGrilla.SeleccionarExecute(Sender: TObject); begin end; procedure TControladorGrilla.GrillaDblClick(Sender: TObject); begin EditarExecute(self); end; procedure TControladorGrilla.QueryBeforeOpen(DataSet: TDataSet); begin end; procedure TControladorGrilla.edBuscarKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin if Key = VK_RETURN then begin BuscarExecute(self); end else if (Key = VK_ESCAPE) and (Buscador <> nil) then begin if Buscador.Focused then Buscador.Text := '' else Buscador.SelectAll; end; end; procedure TControladorGrilla.GrillaKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin if Buscador <> nil then begin Buscador.SetFocus; Buscador.SelectAll; end; end else if Key = VK_RETURN then begin if BotonEditar <> nil then EditarExecute(self) else if BotonSeleccionar <> nil then SeleccionarExecute(self); end else if Key = VK_INSERT then begin if BotonAgregar <> nil then AgregarExecute(self); end else if Key = VK_DELETE then begin if BotonEliminar <> nil then EliminarExecute(self); end; end; procedure TControladorGrilla.SetTipoBuscador(AValue: TTipoBuscador); begin if FTipoBuscador=AValue then Exit; FTipoBuscador:=AValue; end; procedure TControladorGrilla.refrescarQuery(enfocarBuscador: boolean); begin if SQLQuery <> nil then begin if SQLQuery.Active then SQLQuery.Close; if Buscador <> nil then begin SQLQuery.Params.ParamByName(CAD_FILTRO).AsString := Buscador.Text; end else begin if SQLQuery.Params.FindParam(CAD_FILTRO) <> nil then begin SQLQuery.Params.ParamByName(CAD_FILTRO).AsString := ''; end; end; SQLQuery.Prepare; SQLQuery.Open; if Buscador <> nil then begin if SQLQuery.RecordCount = 0 then begin Buscador.SetFocus; Buscador.SelectAll; end else if enfocarBuscador then begin Buscador.SetFocus; end else begin if Grilla <> nil then begin Grilla.SetFocus; end; end; end; end; end; procedure TControladorGrilla.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) then begin if (FBotonBuscar <> nil) and (AComponent = BotonBuscar) then BotonBuscar := nil; if (FBotonCancelar <> nil) and (AComponent = BotonCancelar) then BotonCancelar := nil; if (FBotonCerrar <> nil) and (AComponent = BotonCerrar) then BotonCerrar := nil; if (FBotonEliminar <> nil) and (AComponent = BotonEliminar) then BotonEliminar := nil; if (FBotonEditar <> nil) and (AComponent = BotonEditar) then BotonEditar := nil; if (FBotonAgregar <> nil) and (AComponent = BotonAgregar) then BotonAgregar := nil; if (FGrilla <> nil) and (AComponent = Grilla) then Grilla := nil; if (FBuscador <> nil) and (AComponent = Buscador) then Buscador := nil; if (FSQLQuery <> nil) and (AComponent = SQLQuery) then SQLQuery := nil; if (FCampoIdPadre <> nil) and (AComponent = CampoIdPadre) then CampoIdPadre := nil; if (FControlEdicion <> nil) and (AComponent = ControlEdicion) then ControlEdicion := nil; end; end; constructor TControladorGrilla.Create(AOwner: TComponent); begin inherited Create(AOwner); FAltoBotones := 26; FAnchoBotones := 86; FAvisarBorrado := True; TipoBuscador := tbParametro; end; destructor TControladorGrilla.Destroy; begin inherited Destroy; end; initialization {$I bt_controladorgrilla.lrs} {$I mis_componentes.lrs} end.
PROGRAM Phonebook; CONST MAX = 10; TYPE FirstNameString = STRING[20]; TYPE LastNameString = STRING[30]; TYPE Entry = RECORD firstName: FirstNameString; lastName: LastNameString; phoneNumber: INTEGER; END; TYPE EntryArray = ARRAY[1..MAX] OF Entry; FUNCTION NrOfEntries(VAR entries: EntryArray): INTEGER; VAR count: INTEGER; BEGIN count := 1; WHILE (count <= MAX) AND ((entries[count].firstName <> '') OR (entries[count].lastName <> '') OR (entries[count].phoneNumber <> 0)) DO BEGIN count := count + 1; END; NrOfEntries := count; END; FUNCTION GetIndexOfName(VAR entries: EntryArray; startIndex: INTEGER; fName: FirstNameString; lName: LastNameString): INTEGER; VAR i: INTEGER; VAR indexPhonebook: INTEGER; BEGIN i := startIndex; indexPhonebook := MAX + 1; WHILE i <= MAX DO BEGIN IF (entries[i].firstName = fName) AND (entries[i].lastName = lName) THEN BEGIN indexPhonebook := i; i := MAX; END ELSE BEGIN i := i + 1; END; END; GetIndexOfName := indexPhonebook; END; PROCEDURE SearchNumber(VAR entries: EntryArray; fName: FirstNameString; lName : LastNameString); VAR matchCount: INTEGER; VAR i: INTEGER; BEGIN matchCount := 0; i := 1; REPEAT BEGIN i := GetIndexOfName(entries, i, fName, lName); IF i <= MAX THEN BEGIN matchCount := matchCount + 1; WriteLn(entries[i].phoneNumber, ': ', entries[i].firstName, ' ', entries[i].lastName); END; i := i + 1; END UNTIL i >= MAX; IF matchCount = 0 THEN BEGIN WriteLn('No phone numbers found.'); END; END; PROCEDURE SearchName(VAR entries: EntryArray; numberToSearch: INTEGER); VAR i: WORD; BEGIN i := 1; WHILE i <= MAX DO BEGIN IF entries[i].phoneNumber = numberToSearch THEN BEGIN WriteLn(numberToSearch, ': ', entries[i].firstName, ' ', entries[i].lastName); END; i := i + 1; END; END; PROCEDURE AddEntry(VAR entries: EntryArray; fName: FirstNameString; lName: LastNameString; number: INTEGER); VAR newEntry: Entry; entryCount: INTEGER; BEGIN entryCount := NrOfEntries(entries); IF entryCount <= MAX THEN BEGIN WITH newEntry DO BEGIN firstName := fName; lastName := lName; phoneNumber := number; END; entries[entryCount] := newEntry; END ELSE BEGIN WriteLn('You have too many entries in your phonebook. Please delete at least on entry.'); END; END; PROCEDURE DeleteEntry(VAR entries: EntryArray; fName: FirstNameString; lName: LastNameString); VAR count: INTEGER; entryIndex: INTEGER; moveCounter: INTEGER; BEGIN count := NrOfEntries(entries); entryIndex := GetIndexOfName(entries, 1, fName, lName); IF entryIndex <= count THEN BEGIN FOR moveCounter := entryIndex + 1 TO count DO BEGIN entries[moveCounter - 1] := entries[moveCounter]; END; END ELSE BEGIN WriteLn('Entry ', fName, ' ', lName, ' not found.'); END; END; VAR entries: EntryArray; BEGIN AddEntry(entries, 'Jimi', 'Hendrix', 42); AddEntry(entries, 'Michael', 'Stipe', 586); AddEntry(entries, 'Double Michael', 'Stipe', 586); AddEntry(entries, 'Maca', 'Rena', 6); AddEntry(entries, 'Jimi', 'Hendrix', 1180); SearchNumber(entries, 'Michael', 'Stipe'); SearchNumber(entries, 'Jimi', 'Hendrix'); SearchName(entries, 586); DeleteEntry(entries, 'Double Michael', 'Stipe'); SearchNumber(entries, 'Double Michael', 'Stipe'); DeleteEntry(entries, 'Double Michael', 'Stipe'); END.
unit Delphi.Mocks.Tests.Stubs; interface uses DUnitX.TestFramework; type {$M+} [TestFixture] TStubTests = class published procedure Test_WillReturnDefault; procedure Test_CanStubInheritedMethods; end; {$M-} {$M+} ITestable = interface function DoSomething(const value : string) : string; end; {$M-} implementation uses Classes, Delphi.Mocks; { TUtilsTests } { TStubTests } procedure TStubTests.Test_CanStubInheritedMethods; var stub : TStub<TStringList>; begin stub := TStub<TStringList>.Create; stub.Setup.BehaviorMustBeDefined := false; stub.Setup.WillReturnDefault('Add', 0); // stub.Setup.WillReturn(1).When.Add(It(0).IsAny<string>); stub.Instance.Add('2'); end; procedure TStubTests.Test_WillReturnDefault; var stub : TStub<ITestable>; intf : ITestable; actual : string; begin stub := TStub<ITestable>.Create; stub.Setup.WillReturnDefault('DoSomething','hello'); intf := stub.Instance; actual := intf.DoSomething('world'); Assert.AreEqual('hello', actual); end; initialization TDUnitX.RegisterTestFixture(TStubTests); end.