text
stringlengths
14
6.51M
unit z80ctc; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} z80daisy,timer_engine,main_engine,cpu_misc; function ctc0_irq_state(num:byte):byte; function ctc0_irq_ack(num:byte):byte; procedure ctc0_irq_reti(num:byte); const NOTIMER_0=(1 shl 0); NOTIMER_1=(1 shl 1); NOTIMER_2=(1 shl 2); NOTIMER_3=(1 shl 3); CTC0_TRG00=0; CTC0_TRG01=1; CTC0_TRG02=2; CTC0_TRG03=3; CTC0_NONE=4; type zc_call=procedure(state:boolean); tctc_channel=class constructor create(num_cpu,index:byte;notimer:boolean;write_line:zc_call); destructor free; public procedure reset; private zc:zc_call; // zero crossing callbacks notimer:boolean; // timer disabled? mode:word; // current mode tconst:word; // time constant down:word; // down counter (clock mode only) extclk:boolean; // current signal from the external clock timer:byte; // array of active timers int_state:byte; // interrupt status (for daisy chain) end; tz80ctc=class constructor create(num_cpu:byte;clock,clock_cpu:uint64;notimer:byte;zc0_call:byte;zc1_call:byte=4;zc2_call:byte=4); destructor free; public procedure reset; function read(chan:byte):byte; procedure write(chan,valor:byte); procedure change_calls(int:cpu_outport_call); procedure trigger(chan:byte;valor:boolean); private intr:cpu_outport_call; // interrupt callback vector:byte; // interrupt vector period16:dword; // 16/system clock period256:dword; // 256/system clock clock_cpu:uint64; ctc_channel:array[0..3] of tctc_channel; // data for each channel procedure interrupt_check; function period(chan:byte):uint64; procedure timer_callback(chan:byte); function irq_state:byte; function irq_ack:byte; procedure irq_reti; end; var ctc_0:tz80ctc; implementation const INTERRUPT = $80; INTERRUPT_ON = $80; INTERRUPT_OFF = $00; MODE = $40; MODE_TIMER = $00; MODE_COUNTER = $40; PRESCALER = $20; PRESCALER_256 = $20; PRESCALER_16 = $00; EDGE = $10; EDGE_FALLING = $00; EDGE_RISING = $10; TRIGGER_ = $08; TRIGGER_AUTO = $00; TRIGGER_CLOCK = $08; CONSTANT = $04; CONSTANT_LOAD = $04; CONSTANT_NONE = $00; RESET_ = $02; RESET_CONTINUE = $00; RESET_ACTIVE = $02; CONTROL = $01; CONTROL_VECTOR = $00; CONTROL_WORD = $01; // these extra bits help us keep things accurate WAITING_FOR_TRIG = $100; var chips_total:integer=-1; //Public procedure ctc0_trg00_w(valor:boolean); begin ctc_0.trigger(0,valor); end; procedure ctc0_trg01_w(valor:boolean); begin ctc_0.trigger(1,valor); end; procedure ctc0_trg02_w(valor:boolean); begin ctc_0.trigger(2,valor); end; procedure ctc0_trg03_w(valor:boolean); begin ctc_0.trigger(3,valor); end; function ctc0_irq_state(num:byte):byte; begin ctc0_irq_state:=ctc_0.irq_state; end; function ctc0_irq_ack(num:byte):byte; begin ctc0_irq_ack:=ctc_0.irq_ack; end; procedure ctc0_irq_reti(num:byte); begin ctc_0.irq_reti; end; //CTC constructor tz80ctc.create(num_cpu:byte;clock,clock_cpu:uint64;notimer:byte;zc0_call:byte;zc1_call:byte=4;zc2_call:byte=4); function select_zc(zc_call:byte):zc_call; begin case zc_call of 0:select_zc:=ctc0_trg00_w; 1:select_zc:=ctc0_trg01_w; 2:select_zc:=ctc0_trg02_w; 3:select_zc:=ctc0_trg03_w; 4:select_zc:=nil; end; end; begin chips_total:=chips_total+1; self.period16:=clock*16; self.period256:=clock*256; self.clock_cpu:=clock_cpu; // start each channel self.ctc_channel[0]:=tctc_channel.create(num_cpu,0,(notimer and NOTIMER_0)<>0,select_zc(zc0_call)); self.ctc_channel[1]:=tctc_channel.create(num_cpu,1,(notimer and NOTIMER_1)<>0,select_zc(zc1_call)); self.ctc_channel[2]:=tctc_channel.create(num_cpu,2,(notimer and NOTIMER_2)<>0,select_zc(zc2_call)); self.ctc_channel[3]:=tctc_channel.create(num_cpu,3,(notimer and NOTIMER_3)<>0,nil); end; destructor tz80ctc.free; var f:byte; begin for f:=0 to 3 do self.ctc_channel[f].free; chips_total:=chips_total-1; end; procedure tz80ctc.reset; var f:byte; begin for f:=0 to 3 do self.ctc_channel[f].reset; self.interrupt_check; end; procedure tz80ctc.change_calls(int:cpu_outport_call); begin self.intr:=int; end; function tz80ctc.read(chan:byte):byte; var period:uint64; begin // if we're in counter mode, just return the count if (((self.ctc_channel[chan].mode and MODE)=MODE_COUNTER) or ((self.ctc_channel[chan].mode and WAITING_FOR_TRIG)<>0)) then begin read:=self.ctc_channel[chan].down; end else begin // else compute the down counter value if ((self.ctc_channel[chan].mode and PRESCALER)=PRESCALER_16) then period:=self.period16 else period:=self.period256; if (@timers.timer[self.ctc_channel[chan].timer].execute_param<>nil) then read:=trunc(timers.timer[self.ctc_channel[chan].timer].actual_time/period) and $ff else read:=0; end; end; procedure tz80ctc.write(chan,valor:byte); var curperiod:uint64; begin // if we're waiting for a time constant, this is it if ((self.ctc_channel[chan].mode and CONSTANT)=CONSTANT_LOAD) then begin // set the time constant (0 -> 0x100) if valor<>0 then self.ctc_channel[chan].tconst:=valor else self.ctc_channel[chan].tconst:=$100; // clear the internal mode -- we're no longer waiting self.ctc_channel[chan].mode:=self.ctc_channel[chan].mode and not(CONSTANT); // also clear the reset, since the constant gets it going again self.ctc_channel[chan].mode:=self.ctc_channel[chan].mode and not(RESET_); // if we're in timer mode.... if ((self.ctc_channel[chan].mode and MODE)=MODE_TIMER) then begin // if we're triggering on the time constant, reset the down counter now if ((self.ctc_channel[chan].mode and TRIGGER_)=TRIGGER_AUTO) then begin if not(self.ctc_channel[chan].notimer) then begin curperiod:=self.period(chan); timers.timer[self.ctc_channel[chan].timer].time_final:=curperiod/self.clock_cpu; timers.enabled(self.ctc_channel[chan].timer,true); end else timers.enabled(self.ctc_channel[chan].timer,false); end else // else set the bit indicating that we're waiting for the appropriate trigger self.ctc_channel[chan].mode:=self.ctc_channel[chan].mode or WAITING_FOR_TRIG; end; // also set the down counter in case we're clocking externally self.ctc_channel[chan].down:=self.ctc_channel[chan].tconst; end else if (((valor and CONTROL)=CONTROL_VECTOR) and (chan=0)) then begin self.vector:=valor and $f8; end else // this must be a control word if ((valor and CONTROL)=CONTROL_WORD) then begin // set the new mode self.ctc_channel[chan].mode:=valor; // if we're being reset, clear out any pending timers for this channel if ((valor and RESET_)=RESET_ACTIVE) then begin timers.enabled(self.ctc_channel[chan].timer,false); end; end; end; function tz80ctc.period(chan:byte):uint64; var temp:uint64; begin // if reset active, no period if ((self.ctc_channel[chan].mode and RESET_)=RESET_ACTIVE) then begin period:=0; exit; end; // if counter mode, no real period if ((self.ctc_channel[chan].mode and MODE)=MODE_COUNTER) then begin period:=0; exit; end; // compute the period if ((self.ctc_channel[chan].mode and PRESCALER)=PRESCALER_16) then temp:=self.period16 else temp:=self.period256; period:=temp*self.ctc_channel[chan].tconst; end; procedure tz80ctc.interrupt_check; var state:byte; begin if (self.irq_state and Z80_DAISY_INT)<>0 then state:=ASSERT_LINE else state:=CLEAR_LINE; self.intr(state); end; function tz80ctc.irq_state:byte; var f,state:byte; begin // loop over all channels state:=0; for f:=0 to 3 do begin // if we're servicing a request, don't indicate more interrupts if (self.ctc_channel[f].int_state and Z80_DAISY_IEO)<>0 then begin state:=state or Z80_DAISY_IEO; break; end; state:=state or self.ctc_channel[f].int_state; end; irq_state:=state; end; function tz80ctc.irq_ack:byte; var f:byte; begin // loop over all channels for f:=0 to 3 do begin // find the first channel with an interrupt requested if (self.ctc_channel[f].int_state and Z80_DAISY_INT)<>0 then begin // clear interrupt, switch to the IEO state, and update the IRQs self.ctc_channel[f].int_state:=Z80_DAISY_IEO; self.interrupt_check; irq_ack:=self.vector+f*2; exit; end; end; irq_ack:=self.vector; end; procedure tz80ctc.irq_reti; var f:byte; begin // loop over all channels for f:=0 to 3 do begin // find the first channel with an IEO pending if (self.ctc_channel[f].int_state and Z80_DAISY_IEO)<>0 then begin // clear the IEO state and update the IRQs self.ctc_channel[f].int_state:=self.ctc_channel[f].int_state and not(Z80_DAISY_IEO); self.interrupt_check; exit; end; end; end; procedure tz80ctc.trigger(chan:byte;valor:boolean); var curperiod:uint64; begin // see if the trigger value has changed if (valor<>self.ctc_channel[chan].extclk) then begin self.ctc_channel[chan].extclk:=valor; // see if this is the active edge of the trigger if ((((self.ctc_channel[chan].mode and EDGE)=EDGE_RISING) and valor) or (((self.ctc_channel[chan].mode and EDGE)=EDGE_FALLING) and not(valor))) then begin // if we're waiting for a trigger, start the timer if (((self.ctc_channel[chan].mode and WAITING_FOR_TRIG)<>0) and ((self.ctc_channel[chan].mode and MODE)=MODE_TIMER)) then begin if not(self.ctc_channel[chan].notimer) then begin curperiod:=self.period(chan); timers.timer[self.ctc_channel[chan].timer].time_final:=curperiod/self.clock_cpu; timers.enabled(self.ctc_channel[chan].timer,true); end else begin timers.enabled(self.ctc_channel[chan].timer,false); end; end; // we're no longer waiting self.ctc_channel[chan].mode:=self.ctc_channel[chan].mode and not(WAITING_FOR_TRIG); // if we're clocking externally, decrement the count if ((self.ctc_channel[chan].mode and MODE)=MODE_COUNTER) then begin // if we hit zero, do the same thing as for a timer interrupt self.ctc_channel[chan].down:=self.ctc_channel[chan].down-1; if (self.ctc_channel[chan].down=0) then self.timer_callback(chan); end; end; end; end; procedure tz80ctc.timer_callback(chan:byte); begin // down counter has reached zero - see if we should interrupt if ((self.ctc_channel[chan].mode and INTERRUPT)=INTERRUPT_ON) then begin self.ctc_channel[chan].int_state:=self.ctc_channel[chan].int_state or Z80_DAISY_INT; self.interrupt_check; end; // generate the clock pulse if @self.ctc_channel[chan].zc<>nil then begin self.ctc_channel[chan].zc(true); self.ctc_channel[chan].zc(false); end; // reset the down counter self.ctc_channel[chan].down:=self.ctc_channel[chan].tconst; end; procedure ctc0_channnel(index:byte); begin ctc_0.timer_callback(index); end; //Channel constructor tctc_channel.create(num_cpu,index:byte;notimer:boolean;write_line:zc_call); begin self.zc:=write_line; self.notimer:=notimer; case chips_total of 0:self.timer:=timers.init(num_cpu,0,nil,ctc0_channnel,false,index); end; end; destructor tctc_channel.free; begin end; procedure tctc_channel.reset; begin self.mode:=RESET_ACTIVE; self.tconst:=$100; timers.enabled(self.timer,false); self.int_state:=0; end; end.
{ translationstc.pas Class to store and translate user interface strings Copyright (C) 2007 Felipe Monteiro de Carvalho This file is part of Turbo Circuit. Turbo Circuit is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Turbo Circuit 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. Please note that the General Public License version 2 does not permit incorporating Turbo Circuit into proprietary programs. AUTHORS: Felipe Monteiro de Carvalho } unit translationstc; {$IFDEF FPC} {$MODE DELPHI}{$H+} {$ENDIF} {$IFDEF Win32} {$DEFINE Windows} {$ENDIF} interface uses Classes, SysUtils, constants; type { TTranslations } TTranslations = class(TObject) public { Main menu strings } lpFile, lpDocument, lpComponents, lpHelp: string; lpDocumentOptions: string; lpFileNew, lpFileOpen, lpFileSave, lpFileSaveAs, lpFileExportPng, lpFileExit: string; lpRecreateComponentsDatabase, lpComponentsEditor: string; lpHelpAbout: string; { Main Form } lpMainFormArrow, lpMainFormComponent, lpMainFormWire, lpMainFormText, lpMainFormPolyline, lpMainFormRasterImage: string; lpMainFormChooseComponent: string; { I/O strings } lpSaveDiagramFilter, lpSavePngFilter: string; { Document state related } lpUntitled: string; { Components editor dialog } lpCEInstructions, lpCEID, lpCENameEN, lpCENamePT, lpCEWidth, lpCEHeight, lpCEPins, lpCEDrawingCode, lpCEClose, lpCEPreview, lpCECaption: string; { Methods } procedure TranslateToEnglish; procedure TranslateToPortuguese; end; var vTranslations: TTranslations; implementation {$ifndef fpc} uses Windows; {$endif} { TTranslations } {@@ Translates the user interface strings to english } procedure TTranslations.TranslateToEnglish; begin { Main menu strings } lpFile := 'File'; lpDocument := 'Document'; lpComponents := 'Components'; lpHelp := 'Help'; lpDocumentOptions := 'Document Options'; lpFileNew := 'New'; lpFileOpen := 'Open'; lpFileSave := 'Save'; lpFileSaveAs := 'Save As'; lpFileExportPng := 'Export as PNG'; lpFileExit := 'Exit'; lpRecreateComponentsDatabase := 'Recreate Components Database'; lpComponentsEditor := 'Components Editor'; lpHelpAbout := 'About'; { Main Form } lpMainFormArrow := 'Arrow'; lpMainFormComponent := 'Component'; lpMainFormWire := 'Wire'; lpMainFormText := 'Text'; lpMainFormPolyline := 'Polyline'; lpMainFormRasterImage := 'Raster Image'; lpMainFormChooseComponent := 'Component type:'; { I/O strings } lpSaveDiagramFilter := 'All supported formats|*.tc;*.eps|Turbo Circuit Diagrams|*.tc|All files|*.*'; lpSavePngFilter := 'Portable Network Graphic|*.png|All files|*.*'; { Document state related } lpUntitled := 'Untitled'; { Components editor dialog } lpCEInstructions := 'Atention: Changes are saved automatically and ' + 'cannot be undone except by reloading the database from the backup.'; lpCEID := 'ID:'; lpCENameEN := 'English:'; lpCENamePT := 'Português:'; lpCEWidth := 'Width:'; lpCEHeight := 'Height:'; lpCEPins := 'Pins'; lpCEDrawingCode := 'Drawing Code:'; lpCEClose := 'Close'; lpCEPreview := 'Preview'; lpCECaption := 'Components Editor'; end; {@@ Translates the user interface strings to portuguese } procedure TTranslations.TranslateToPortuguese; begin { Document state related } lpUntitled := 'Sem Título'; end; {******************************************************************* * Initialization section * * DESCRIPTION: Initializes the translations. * *******************************************************************} initialization vTranslations := TTranslations.Create; vTranslations.TranslateToEnglish; // Default {******************************************************************* * Finalization section * * DESCRIPTION: Free memory allocated on the initialization section * *******************************************************************} finalization FreeAndNil(vTranslations); end.
unit EmailOrdering.Controllers.MainController; interface uses System.SysUtils, EmailOrdering.Controllers.Controller, Wddc.API.OrderApi, Wddc.Inventory.OrderDetail, IdMessage, EmailOrdering.Controllers.MainControllerInt, Wddc.AVIMark.ParseOrder, IdAttachmentFile, EmailOrdering.Views.MessageForm, EmailOrdering.Views.MainForm, EmailOrdering.Models.EmailMsg, Wddc.Inventory.Order, REST.Client, System.Classes, Windows, EmailOrdering.Models.EmailServer, EmailOrdering.Models.Config, System.UITypes, ShellApi; type TMainController = class(TInterfacedObject, IMainController) private Fform: TMainForm; FConfig: TConfig; EmailServer: TEmailServer; MsgForm: TMessageForm; procedure SetupEmailServer(); function ValidateSettings(): TStringList; procedure Success(order:TOrder); procedure Failure(msg:string; errors:TStringList; order:TOrder); public property MainForm: TMainForm read Fform write Fform; procedure NewOrder(const msg: TEmailMsg); procedure ShowMessageForm(); procedure OpenSuccess(); procedure OpenFailure(); procedure StartEmailServer(portNumber: string); procedure StopEmailServer(); procedure ClearOrderLog(); procedure UpdateConfig(); procedure ShowHelp(); procedure OpenSettingsForm(); procedure OpenConfirmation(orderId: integer); function GetApi(): TOrderApi; class function GetInstance(MainForm: TMainForm): IMainController; static; end; implementation uses Vcl.Dialogs, Vcl.Forms, IdAttachment, REST.Json, REST.Types, Vcl.Controls, Vcl.ExtCtrls, Vcl.Graphics, EmailOrdering.Views.ErrorForm, EmailOrdering.Views.SettingsForm, System.Math, EmailOrdering.SharedData; { TMainController } function TMainController.GetApi: TOrderApi; begin Result := TOrderApi.Create(FConfig.requestBaseUrl, FConfig.requestResource, FConfig.requestAccept); end; class function TMainController.GetInstance(MainForm: TMainForm): IMainController; var LController: TMainController; LIcon: TIcon; begin LController := TMainController.Create; LIcon:= TIcon.Create; try LIcon.LoadFromFile('symbol.ico'); LController.MainForm := mainForm; LController.MainForm.TrayIcon1.Visible := True; LController.MainForm.TrayIcon1.Icon := LIcon; LController.MainForm.Hide; LController.FConfig := TConfig.GetInstance; LController.MsgForm := TMessageForm.Create(LController.MainForm); LController.MsgForm.PopupParent := LController.MainForm; LController.MsgForm.Icon := LIcon; LController.MsgForm.Controller := LController; LController.SetupEmailServer(); Result := LController; finally LIcon.Free; end; end; /// New Email Message found. procedure TMainController.NewOrder(const msg: TEmailMsg); var LOrder : TOrder; LErrorList : TStringList; LApi: TOrderApi; begin if (msg = nil) then raise Exception.Create('Not a valid AVIMark Order'); // parse email message attachment into order. try LOrder := TParseOrder.GetAviItems(msg.GetTextFromAttachment(1)); except on E: Exception do begin LErrorList := TStringList.Create; LErrorList.Add(E.ToString); Failure('Critical application failure', LErrorList, nil); exit; end; end; LOrder.SourceCode := 'AVI'; // check order for basic errors LErrorList := LOrder.Validate(); try if (LErrorList.Count > 0) then begin Failure('Failure validating order', LErrorList, LOrder); exit; end; LApi := self.GetApi(); try LApi.SendOrder(LOrder, FConfig.apiKey); if LApi.E <> nil then begin LErrorList.Text:= LApi.E.ToString; Failure('Failure sending order', LErrorList, LOrder); exit; end; LOrder := TJson.JsonToObject<TOrder>(LApi.Response); Success(Lorder); except On E: Exception do begin LErrorList.Add('Error sending request to web service, check request resource string in settings'); LErrorList.Add(E.ToString); Failure('Critical application failure', LErrorList, LOrder );; end; end; finally LErrorList.Free; end; end; /// Opens the WDDC confirmation web page. procedure TMainController.OpenConfirmation(orderId: integer); begin TOrderApi.OpenOrderConfPage(FConfig.requestConfirmationURL, inttostr(orderId), FConfig.apiKey); end; /// Opens the failure error message. procedure TMainController.OpenFailure; var LErrorDForm: TErrorDForm; LIcon: TIcon; begin LErrorDForm := TErrorDForm.Create(nil); LIcon:= TIcon.Create; try LIcon.LoadFromFile('symbol.ico'); LErrorDForm.SetErrors(self.MsgForm.ClientDataSet1.FieldByName('Error').AsString); LErrorDForm.Icon := LIcon; LErrorDForm.Visible:= False; LErrorDForm.ShowModal; finally LErrorDForm.Free; end; end; /// Opens the settings form. procedure TMainController.OpenSettingsForm; var LSettingsForm: TSettingsForm; begin LSettingsForm:= TSettingsForm.Create(self.MsgForm); try LSettingsForm.ShowModal; self.UpdateConfig; finally end; end; /// Opens a successful message. procedure TMainController.OpenSuccess; var LOrder : TOrder; begin LOrder := TJson.JsonToObject<TOrder>(self.MsgForm.ClientDataSet1.FieldByName('Order').AsString); try TOrderApi.OpenOrderConfPage(FConfig.requestConfirmationURL, inttostr(LOrder.ID), FConfig.apiKey); finally LOrder.Free; end; end; /// Sets up the email procedure TMainController.SetupEmailServer(); var LConfig: TConfig; LApi: TOrderApi; begin LConfig := TConfig.GetInstance; LApi := self.GetApi; try if LConfig.serverPort = '' then begin LConfig.serverPort := '587'; LConfig.Save; end; try LApi.CheckApiConntection; self.StartEmailServer(LConfig.serverPort); self.MsgForm.Connected := True; except on E: Exception do begin self.MsgForm.Connected := False; messagedlg(E.ToString, mtError, [mbyes], 0, mbYes); end; end; finally self.MsgForm.UpdateStatus; LConfig.Free; LApi.Free; end; end; /// Starts email server. procedure TMainController.StartEmailServer(portNumber: string); var LErrorList: TStringList; begin // check if settings filled in LErrorList := self.ValidateSettings(); try if (LErrorList.Count > 0) then begin Failure('Failure in settings', LErrorList, nil); exit; end; self.EmailServer := TEmailServer.Create(strtoint(portNumber)); self.EmailServer.OnAviEmail := self.NewOrder; self.MsgForm.Connected := True; self.MsgForm.UpdateStatus; self.EmailServer.Execute; finally LErrorList.Free; end; end; /// Stops email server. procedure TMainController.StopEmailServer; begin self.EmailServer.Free; self.MsgForm.Connected := False; self.MsgForm.StatusBar1.Repaint; self.MsgForm.StatusBar1.Panels[1].Text := 'Offline'; self.MsgForm.Connect1.Enabled:= True; self.MsgForm.Disconnect1.Enabled:= False; end; procedure TMainController.ShowHelp; begin ShellExecute(0, 'open', PChar(TSharedData.HelpUrl), nil, nil, SW_SHOWNORMAL); end; procedure TMainController.ShowMessageForm; begin self.MsgForm.Show; self.MsgForm.WindowState := wsNormal; end; procedure TMainController.Success(order: TOrder); var I: Integer; LStringList: TStringList; begin LStringList:= TStringList.Create; try self.MainForm.ShowBalloonMessage('Order successful','Click to view order confimation.',TBalloonFlags.bfInfo, order.ID); LStringList.Add(format('Order Successful:%sOrder Number:%d%s' ,[chr(9), order.ID, chr(9)])); LStringList.Add(format('%sTotal Items:%d%sTotal Price:%s' ,[chr(9), order.OrderTotalNumItems, chr(9), CurrToStrF(order.OrderTotalMoney, ffCurrency, 2)])); LStringList.Add(format('%sOrder Details:',[chr(9)])); for I := 0 to length(order.OrderDetails) - 1 do begin LStringList.Add(format('%s%sItem Number:%s%sQuantity:%d%sIndividual Price:%s' ,[ chr(9), chr(9),order.OrderDetails[I].Product.Id, chr(9), order.OrderDetails[I].UnitQty, chr(9) ,CurrToStrF(order.OrderDetails[I].UnitPrice, ffCurrency, 2)])); end; self.MsgForm.ClientDataSet1.InsertRecord([now , 1, 'Order successful', 'Order Number:' + inttostr(Order.ID), Order.ToJson]); self.MsgForm.ClientDataSet1.SaveToFile(TSharedData.OrderLogPath); finally LStringList.Free; end; end; procedure TMainController.UpdateConfig; begin self.FConfig := TConfig.GetInstance; end; function TMainController.ValidateSettings :TStringList; var LMissingMessage: string; begin Result := TStringList.Create; LMissingMessage := '%s is blank. Please open the settings and add a value.'; if FConfig.requestBaseUrl = '' then Result.Add(LMissingMessage.Replace('%s', 'requestBaseUrl')); if FConfig.requestResource = '' then Result.Add(LMissingMessage.Replace('%s', 'requestResource')); if FConfig.requestConfirmationURL = '' then Result.Add(LMissingMessage.Replace('%s', 'requestConfirmationURL')); if FConfig.memberNumber = '' then Result.Add(LMissingMessage.Replace('%s', 'memberNumber')); if FConfig.apiKey = '' then Result.Add(LMissingMessage.Replace('%s', 'apiKey')); end; procedure TMainController.ClearOrderLog; begin self.MsgForm.ClientDataSet1.DisableControls; self.MsgForm.ClientDataSet1.EmptyDataSet; self.MsgForm.ClientDataSet1.SaveToFile(TSharedData.OrderLogPath);; self.MsgForm.ClientDataSet1.EnableControls; end; procedure TMainController.Failure(msg: string; errors:TStringList; order: TOrder); var LConfig: TConfig; begin LConfig:= TConfig.GetInstance; try self.MainForm.ShowBalloonMessage('Failure',msg, bfError, 0); self.MsgForm.ClientDataSet1.InsertRecord([now , 0, 'Error', msg, nil , errors.Text]); self.MsgForm.ClientDataSet1.SaveToFile(TSharedData.OrderLogPath); finally LConfig.Free; end; end; end.
unit atNewConsultation; {* Работа с новой консультацией } // Модуль: "w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atNewConsultation.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatNewConsultation" MUID: (4A54B2EB00FF) interface uses l3IntfUses , atQuery ; type TatNewConsultation = class(TObject) {* Работа с новой консультацией } private f_Query: TatQuery; f_UserName: AnsiString; f_CityCode: AnsiString; f_PhoneNumber: AnsiString; f_QuestionText: AnsiString; f_EMail: AnsiString; protected procedure pm_SetUserName(const aValue: AnsiString); procedure pm_SetCityCode(const aValue: AnsiString); procedure pm_SetPhoneNumber(const aValue: AnsiString); procedure pm_SetQuestionText(const aValue: AnsiString); procedure pm_SetEMail(const aValue: AnsiString); public constructor Create; reintroduce; procedure Send; virtual; destructor Destroy; override; public property UserName: AnsiString read f_UserName write pm_SetUserName; property CityCode: AnsiString read f_CityCode write pm_SetCityCode; property PhoneNumber: AnsiString read f_PhoneNumber write pm_SetPhoneNumber; property QuestionText: AnsiString read f_QuestionText write pm_SetQuestionText; property EMail: AnsiString read f_EMail write pm_SetEMail; end;//TatNewConsultation implementation uses l3ImplUses , SearchUnit , atStringHelper , SysUtils //#UC START# *4A54B2EB00FFimpl_uses* //#UC END# *4A54B2EB00FFimpl_uses* ; procedure TatNewConsultation.pm_SetUserName(const aValue: AnsiString); //#UC START# *4A54B65D01D0_4A54B2EB00FFset_var* const TAG = 'AT_USER_NAME'; //#UC END# *4A54B65D01D0_4A54B2EB00FFset_var* begin //#UC START# *4A54B65D01D0_4A54B2EB00FFset_impl* if (f_UserName <> aValue) then begin f_UserName := aValue; f_Query.ClearAttribute(TAG); if (f_UserName <> '') then f_Query.SaveContextAttribute(TAG, QLO_AND, f_UserName); end; //#UC END# *4A54B65D01D0_4A54B2EB00FFset_impl* end;//TatNewConsultation.pm_SetUserName procedure TatNewConsultation.pm_SetCityCode(const aValue: AnsiString); //#UC START# *4A54B674018C_4A54B2EB00FFset_var* const TAG= 'AT_USER_PHONE'; //#UC END# *4A54B674018C_4A54B2EB00FFset_var* begin //#UC START# *4A54B674018C_4A54B2EB00FFset_impl* if (f_CityCode <> aValue) then begin f_CityCode := aValue; if (f_CityCode <> '') then f_Query.SavePhoneAttribute(TAG, f_CityCode, f_PhoneNumber); end; //#UC END# *4A54B674018C_4A54B2EB00FFset_impl* end;//TatNewConsultation.pm_SetCityCode procedure TatNewConsultation.pm_SetPhoneNumber(const aValue: AnsiString); //#UC START# *4A54B68C024F_4A54B2EB00FFset_var* const TAG= 'AT_USER_PHONE'; //#UC END# *4A54B68C024F_4A54B2EB00FFset_var* begin //#UC START# *4A54B68C024F_4A54B2EB00FFset_impl* if (f_PhoneNumber <> aValue) then begin f_PhoneNumber := aValue; if (f_PhoneNumber <> '') then f_Query.SavePhoneAttribute(TAG, f_CityCode, f_PhoneNumber); end; //#UC END# *4A54B68C024F_4A54B2EB00FFset_impl* end;//TatNewConsultation.pm_SetPhoneNumber procedure TatNewConsultation.pm_SetQuestionText(const aValue: AnsiString); //#UC START# *4A54B6AE0370_4A54B2EB00FFset_var* const TAG = 'AT_LAW_SUPPORT_TEXT'; //#UC END# *4A54B6AE0370_4A54B2EB00FFset_var* begin //#UC START# *4A54B6AE0370_4A54B2EB00FFset_impl* if (f_QuestionText <> aValue) then begin f_QuestionText := aValue; f_Query.ClearAttribute(TAG); if (f_QuestionText <> '') then f_Query.SaveContextAttribute(TAG, QLO_OR, f_QuestionText); end; //#UC END# *4A54B6AE0370_4A54B2EB00FFset_impl* end;//TatNewConsultation.pm_SetQuestionText procedure TatNewConsultation.pm_SetEMail(const aValue: AnsiString); //#UC START# *4A54C04003B8_4A54B2EB00FFset_var* const TAG = 'AT_EMAIL'; //#UC END# *4A54C04003B8_4A54B2EB00FFset_var* begin //#UC START# *4A54C04003B8_4A54B2EB00FFset_impl* if (f_EMail <> aValue) then begin f_EMail := aValue; f_Query.ClearAttribute(TAG); if (f_EMail <> '') then f_Query.SaveContextAttribute(TAG, QLO_AND, f_EMail); end; //#UC END# *4A54C04003B8_4A54B2EB00FFset_impl* end;//TatNewConsultation.pm_SetEMail constructor TatNewConsultation.Create; //#UC START# *4A54B41C00D9_4A54B2EB00FF_var* //#UC END# *4A54B41C00D9_4A54B2EB00FF_var* begin //#UC START# *4A54B41C00D9_4A54B2EB00FF_impl* inherited; f_Query := TatQuery.CreateByType(QT_HANDYCRAFT_CONSULT); Assert(f_Query <> nil, 'f_Query <> nil'); f_QuestionText := ''; f_UserName := ''; f_PhoneNumber := ''; f_CityCode := ''; //#UC END# *4A54B41C00D9_4A54B2EB00FF_impl* end;//TatNewConsultation.Create procedure TatNewConsultation.Send; //#UC START# *4A54B5E90298_4A54B2EB00FF_var* //#UC END# *4A54B5E90298_4A54B2EB00FF_var* begin //#UC START# *4A54B5E90298_4A54B2EB00FF_impl* f_Query.Query.SendQuery; //#UC END# *4A54B5E90298_4A54B2EB00FF_impl* end;//TatNewConsultation.Send destructor TatNewConsultation.Destroy; //#UC START# *48077504027E_4A54B2EB00FF_var* //#UC END# *48077504027E_4A54B2EB00FF_var* begin //#UC START# *48077504027E_4A54B2EB00FF_impl* FreeAndNil(f_Query); inherited; //#UC END# *48077504027E_4A54B2EB00FF_impl* end;//TatNewConsultation.Destroy end.
unit atOperationBase; // Модуль: "w:\quality\test\garant6x\AdapterTest\OperationsFramework\atOperationBase.pas" // Стереотип: "UtilityPack" // Элемент модели: "atOperationBase" MUID: (48089D120398) interface uses l3IntfUses , l3_Base , atExecutionContext , atOperationParametersList , atOperationParameter , atOperationEnv , Contnrs , SysUtils ; type CTatOperationBase = class of TatOperationBase; TatOperationsList = class; EInvalidOpParams = class(Exception) end;//EInvalidOpParams TatOperationBase = class(Tl3_Base) private f_ChildOperations: TatOperationsList; f_ExecutionContext: TatExecutionContext; protected f_ParamList: TatOperationParametersList; protected function pm_GetParameters(const aName: AnsiString): TatOperationParameter; function pm_GetEnv: TatOperationEnv; procedure InitParamList; virtual; procedure ExecuteSelf; virtual; abstract; procedure ExecuteChilds; virtual; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public class function GetName: AnsiString; virtual; procedure Execute(eCtxt: TatExecutionContext); procedure AddChild(childOperation: TatOperationBase); procedure AfterFillingParamList; virtual; {* Вызывается генератором сценария после заполнения значений параметров. Если операции надо что-то инициализировать, и для этого нужны значения параметров из сценария. } protected property ExecutionContext: TatExecutionContext read f_ExecutionContext write f_ExecutionContext; property Env: TatOperationEnv read pm_GetEnv; public property Parameters[const aName: AnsiString]: TatOperationParameter read pm_GetParameters; end;//TatOperationBase _ObjectListElement_ = TatOperationBase; _atTypedObjectList_Parent_ = TObjectList; {$Include w:\quality\test\garant6x\AdapterTest\MixIns\atTypedObjectList.imp.pas} TatOperationsList = class(_atTypedObjectList_) end;//TatOperationsList implementation uses l3ImplUses , Math , atLogger {$If NOT Defined(NoScripts)} , TtfwTypeRegistrator_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *48089D120398impl_uses* //#UC END# *48089D120398impl_uses* ; function TatOperationBase.pm_GetParameters(const aName: AnsiString): TatOperationParameter; //#UC START# *4808A004003A_48076E9D013Eget_var* //#UC END# *4808A004003A_48076E9D013Eget_var* begin //#UC START# *4808A004003A_48076E9D013Eget_impl* Result := f_ParamList.ParamByName[aName]; //#UC END# *4808A004003A_48076E9D013Eget_impl* end;//TatOperationBase.pm_GetParameters function TatOperationBase.pm_GetEnv: TatOperationEnv; //#UC START# *5396F1F60329_48076E9D013Eget_var* //#UC END# *5396F1F60329_48076E9D013Eget_var* begin //#UC START# *5396F1F60329_48076E9D013Eget_impl* Result := TatOperationEnv.Instance; //#UC END# *5396F1F60329_48076E9D013Eget_impl* end;//TatOperationBase.pm_GetEnv procedure TatOperationBase.InitParamList; //#UC START# *48089F3701B4_48076E9D013E_var* //#UC END# *48089F3701B4_48076E9D013E_var* begin //#UC START# *48089F3701B4_48076E9D013E_impl* with f_ParamList do Add( ParamType.Create('iterations', 'Количество итераций', '1') ); //#UC END# *48089F3701B4_48076E9D013E_impl* end;//TatOperationBase.InitParamList procedure TatOperationBase.ExecuteChilds; //#UC START# *48089F660238_48076E9D013E_var* var i, childsCount : integer; //#UC END# *48089F660238_48076E9D013E_var* begin //#UC START# *48089F660238_48076E9D013E_impl* childsCount := f_ChildOperations.Count; if (childsCount <> 0) then begin Logger.Info('Начинаем выполнять детей операции "' + GetName + '"'); for i := 0 to childsCount-1 do f_ChildOperations.Items[i].Execute(ExecutionContext); Logger.Info('Закончили выполнять детей операции "' + GetName + '"'); end; //#UC END# *48089F660238_48076E9D013E_impl* end;//TatOperationBase.ExecuteChilds class function TatOperationBase.GetName: AnsiString; //#UC START# *48089F8B00C5_48076E9D013E_var* //#UC END# *48089F8B00C5_48076E9D013E_var* begin //#UC START# *48089F8B00C5_48076E9D013E_impl* Result := Copy(ClassName, 4, Length(ClassName)); //#UC END# *48089F8B00C5_48076E9D013E_impl* end;//TatOperationBase.GetName procedure TatOperationBase.Execute(eCtxt: TatExecutionContext); //#UC START# *48089FA50390_48076E9D013E_var* var i, iterCount, sleepTime : Integer; //#UC END# *48089FA50390_48076E9D013E_var* begin //#UC START# *48089FA50390_48076E9D013E_impl* Assert(eCtxt <> nil, 'eCtxt <> nil'); ExecutionContext := eCtxt; // sleepTime := RandomRange(eCtxt.MinDelay, eCtxt.MaxDelay); if (sleepTime > 0) then begin Logger.Info('Задержка на ' + IntToStr(sleepTime) + ' мс.'); Sleep(sleepTime); end; // iterCount := Parameters['iterations'].AsInt; for i := 1 to iterCount do begin // выполняем себя Logger.Info('Начинаем выполнять операцию "' + GetName + '". Итерация ' + IntToStr(i) + '/' + IntToStr(iterCount)); try ExecuteSelf; except on EAbort do begin Logger.Info('Выполнение операций прервано'); Raise; end; on ex : Exception do begin Logger.Exception(ex, 'Исключение во время выполнения операции "' + GetName + '"'); Raise; end; end; Logger.Info('Закончили выполнять операцию "' + GetName + '"'); // выполняем детей ExecuteChilds; end; //#UC END# *48089FA50390_48076E9D013E_impl* end;//TatOperationBase.Execute procedure TatOperationBase.AddChild(childOperation: TatOperationBase); //#UC START# *48089FBE0004_48076E9D013E_var* //#UC END# *48089FBE0004_48076E9D013E_var* begin //#UC START# *48089FBE0004_48076E9D013E_impl* f_ChildOperations.Add(childOperation); //#UC END# *48089FBE0004_48076E9D013E_impl* end;//TatOperationBase.AddChild procedure TatOperationBase.AfterFillingParamList; {* Вызывается генератором сценария после заполнения значений параметров. Если операции надо что-то инициализировать, и для этого нужны значения параметров из сценария. } //#UC START# *492188F70140_48076E9D013E_var* //#UC END# *492188F70140_48076E9D013E_var* begin //#UC START# *492188F70140_48076E9D013E_impl* // ничего не делаем //#UC END# *492188F70140_48076E9D013E_impl* end;//TatOperationBase.AfterFillingParamList procedure TatOperationBase.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48076E9D013E_var* //#UC END# *479731C50290_48076E9D013E_var* begin //#UC START# *479731C50290_48076E9D013E_impl* FreeAndNil(f_ParamList); FreeAndNil(f_ChildOperations); inherited; //#UC END# *479731C50290_48076E9D013E_impl* end;//TatOperationBase.Cleanup procedure TatOperationBase.InitFields; //#UC START# *47A042E100E2_48076E9D013E_var* //#UC END# *47A042E100E2_48076E9D013E_var* begin //#UC START# *47A042E100E2_48076E9D013E_impl* inherited; f_ParamList := TatOperationParametersList.Create; f_ChildOperations := TatOperationsList.Create(true); InitParamList; //#UC END# *47A042E100E2_48076E9D013E_impl* end;//TatOperationBase.InitFields {$Include w:\quality\test\garant6x\AdapterTest\MixIns\atTypedObjectList.imp.pas} initialization {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(EInvalidOpParams)); {* Регистрация типа EInvalidOpParams } {$IfEnd} // NOT Defined(NoScripts) end.
unit ACM; interface uses Windows, MMSystem; type HINSTANCE = THandle; HACMSTREAM = THandle; HACMDRIVER = THandle; PWAVEFILTER = pointer; // acmFormatDetails() const ACMFORMATDETAILS_FORMAT_CHARS = 128; type PACMFORMATDETAILS = ^TACMFORMATDETAILS; TACMFORMATDETAILS = packed record cbStruct : DWORD; dwFormatIndex : DWORD; dwFormatTag : DWORD; fdwSupport : DWORD; pwfx : PWAVEFORMATEX; cbwfx : DWORD; szFormat : array[0..pred(ACMFORMATDETAILS_FORMAT_CHARS)] of char; end; function acmFormatDetails( had : HACMDRIVER; pafd : PACMFORMATDETAILS; fdwDetails : DWORD ) : MMRESULT; stdcall; const ACM_FORMATDETAILSF_INDEX = $00000000; ACM_FORMATDETAILSF_FORMAT = $00000001; ACM_FORMATDETAILSF_QUERYMASK = $0000000F; // acmFormatTagDetails() const ACMFORMATTAGDETAILS_FORMATTAG_CHARS = 48; type PACMFORMATTAGDETAILS = ^TACMFORMATTAGDETAILS; TACMFORMATTAGDETAILS = packed record cbStruct : DWORD; dwFormatTagIndex : DWORD; dwFormatTag : DWORD; cbFormatSize : DWORD; fdwSupport : DWORD; cStandardFormats : DWORD; szFormatTag : array[0..pred(ACMFORMATTAGDETAILS_FORMATTAG_CHARS)] of char; end; function acmFormatTagDetails( had : HACMDRIVER; paftd : PACMFORMATTAGDETAILS; fdwDetails : DWORD ) : MMRESULT; stdcall; const ACM_FORMATTAGDETAILSF_INDEX = $00000000; ACM_FORMATTAGDETAILSF_FORMATTAG = $00000001; ACM_FORMATTAGDETAILSF_LARGESTSIZE = $00000002; ACM_FORMATTAGDETAILSF_QUERYMASK = $0000000F; // acmStreamOpen() type PACMSTREAMHEADER = ^TACMSTREAMHEADER; TACMSTREAMHEADER = packed record cbStruct : DWORD; fdwStatus : DWORD; dwUser : DWORD; pbSrc : pointer; cbSrcLength : DWORD; cbSrcLengthUsed : DWORD; dwSrcUser : DWORD; pbDst : pointer; cbDstLength : DWORD; cbDstLengthUsed : DWORD; dwDstUser : DWORD; dwReservedDriver : array[0..9] of DWORD; end; const // ACMSTREAMHEADER.fdwStatus ACMSTREAMHEADER_STATUSF_DONE = $00010000; // done bit for async conversions. ACMSTREAMHEADER_STATUSF_PREPARED = $00020000; ACMSTREAMHEADER_STATUSF_INQUEUE = $00100000; function acmStreamOpen( var phas : HACMSTREAM; // pointer to stream handle had : HACMDRIVER; // optional driver handle pwfxSrc : PWAVEFORMATEX; // source format to convert pwfxDst : PWAVEFORMATEX; // required destination format pwfltr : PWAVEFILTER; // optional filter dwCallback : DWORD; // callback dwInstance : DWORD; // callback instance data fdwOpen : DWORD // ACM_STREAMOPENF_* and CALLBACK_* ) : MMRESULT; stdcall; const ACM_STREAMOPENF_QUERY = $00000001; ACM_STREAMOPENF_ASYNC = $00000002; ACM_STREAMOPENF_NONREALTIME = $00000004; // acmStreamClose() function acmStreamClose(has : HACMSTREAM; fdwClose : DWORD) : MMRESULT; stdcall; // acmStreamSize() function acmStreamSize( has : HACMSTREAM; cbInput : DWORD; var pdwOutputBytes : DWORD; fdwSize : DWORD ) : MMRESULT; stdcall; const ACM_STREAMSIZEF_SOURCE = $00000000; ACM_STREAMSIZEF_DESTINATION = $00000001; ACM_STREAMSIZEF_QUERYMASK = $0000000F; // acmStreamReset() function acmStreamReset(has : HACMSTREAM; fdwReset : DWORD) : MMRESULT; stdcall; // acmStreamMessage() function acmStreamMessage( has : HACMSTREAM; uMsg : UINT; lParam1 : LPARAM; lParam2 : LPARAM ) : MMRESULT; stdcall; // acmStreamConvert() function acmStreamConvert( has : HACMSTREAM; pash : PACMSTREAMHEADER; fdwConvert : DWORD ) : MMRESULT; stdcall; const ACM_STREAMCONVERTF_BLOCKALIGN = $00000004; ACM_STREAMCONVERTF_START = $00000010; ACM_STREAMCONVERTF_END = $00000020; // acmStreamPrepareHeader() function acmStreamPrepareHeader( has : HACMSTREAM; pash : PACMSTREAMHEADER; fdwPrepare : DWORD ) : MMRESULT; stdcall; // acmStreamUnprepareHeader() function acmStreamUnprepareHeader( has : HACMSTREAM; pash : PACMSTREAMHEADER; fdwUnprepare : DWORD ) : MMRESULT; stdcall; // acmMetrics() type HACMOBJ = THandle; function acmMetrics( hao : HACMOBJ; uMetric : UINT; var Metric ) : MMRESULT; stdcall; const ACM_METRIC_COUNT_DRIVERS = 1; ACM_METRIC_COUNT_CODECS = 2; ACM_METRIC_COUNT_CONVERTERS = 3; ACM_METRIC_COUNT_FILTERS = 4; ACM_METRIC_COUNT_DISABLED = 5; ACM_METRIC_COUNT_HARDWARE = 6; ACM_METRIC_COUNT_LOCAL_DRIVERS = 20; ACM_METRIC_COUNT_LOCAL_CODECS = 21; ACM_METRIC_COUNT_LOCAL_CONVERTERS = 22; ACM_METRIC_COUNT_LOCAL_FILTERS = 23; ACM_METRIC_COUNT_LOCAL_DISABLED = 24; ACM_METRIC_HARDWARE_WAVE_INPUT = 30; ACM_METRIC_HARDWARE_WAVE_OUTPUT = 31; ACM_METRIC_MAX_SIZE_FORMAT = 50; ACM_METRIC_MAX_SIZE_FILTER = 51; ACM_METRIC_DRIVER_SUPPORT = 100; ACM_METRIC_DRIVER_PRIORITY = 101; // acmFormatSuggest() function acmFormatSuggest( had : HACMDRIVER; pwfxSrc : PWAVEFORMATEX; pwfxDst : PWAVEFORMATEX; cbwfxDst : DWORD; fdwSuggest : DWORD ) : MMRESULT; stdcall; const ACM_FORMATSUGGESTF_WFORMATTAG = $00010000; ACM_FORMATSUGGESTF_NCHANNELS = $00020000; ACM_FORMATSUGGESTF_NSAMPLESPERSEC = $00040000; ACM_FORMATSUGGESTF_WBITSPERSAMPLE = $00080000; ACM_FORMATSUGGESTF_TYPEMASK = $00FF0000; // acmFormatChoose() const ACMHELPMSGSTRING = 'acmchoose_help'; ACMHELPMSGCONTEXTMENU = 'acmchoose_contextmenu'; ACMHELPMSGCONTEXTHELP = 'acmchoose_contexthelp'; // MM_ACM_FORMATCHOOSE is sent to hook callbacks by the Format Chooser // Dialog... MM_ACM_FORMATCHOOSE = $8000; FORMATCHOOSE_MESSAGE = 0; FORMATCHOOSE_FORMATTAG_VERIFY = (FORMATCHOOSE_MESSAGE + 0); FORMATCHOOSE_FORMAT_VERIFY = (FORMATCHOOSE_MESSAGE + 1); FORMATCHOOSE_CUSTOM_VERIFY = (FORMATCHOOSE_MESSAGE + 2); type TACMFORMATCHOOSEHOOKPROC = function(wnd : hWnd; uMsg : uint; awParam : wParam; alParam : lParam) : uint; stdcall; PACMFORMATCHOOSE = ^TACMFORMATCHOOSE; TACMFORMATCHOOSE = packed record cbStruct : DWORD; // sizeof(ACMFORMATCHOOSE) fdwStyle : DWORD; // chooser style flags hwndOwner : HWND; // caller's window handle pwfx : PWAVEFORMATEX; // ptr to wfx buf to receive choice cbwfx : DWORD; // size of mem buf for pwfx pszTitle : LPCSTR; // dialog box title bar szFormatTag : array[0..pred(ACMFORMATTAGDETAILS_FORMATTAG_CHARS)] of char; szFormat : array[0..pred(ACMFORMATDETAILS_FORMAT_CHARS)] of char; pszName : LPSTR; // custom name selection cchName : DWORD; // size in chars of mem buf for pszName fdwEnum : DWORD; // format enumeration restrictions pwfxEnum : PWAVEFORMATEX ; // format describing restrictions hInstance : HINSTANCE; // app instance containing dlg template pszTemplateName : LPCSTR; // custom template name lCustData : LPARAM; // data passed to hook fn. pfnHook : TACMFORMATCHOOSEHOOKPROC; // ptr to hook function end; const // ACMFORMATCHOOSE.fdwStyle ACMFORMATCHOOSE_STYLEF_SHOWHELP = $00000004; ACMFORMATCHOOSE_STYLEF_ENABLEHOOK = $00000008; ACMFORMATCHOOSE_STYLEF_ENABLETEMPLATE = $00000010; ACMFORMATCHOOSE_STYLEF_ENABLETEMPLATEHANDLE = $00000020; ACMFORMATCHOOSE_STYLEF_INITTOWFXSTRUCT = $00000040; ACMFORMATCHOOSE_STYLEF_CONTEXTHELP = $00000080; function acmFormatChoose(pafmtc : PACMFORMATCHOOSE) : MMRESULT; stdcall; implementation const ACMlib = 'msacm32.dll'; function acmFormatDetails; stdcall; external ACMlib; function acmFormatTagDetails; stdcall; external ACMlib; function acmStreamOpen; stdcall; external ACMlib; function acmStreamClose; stdcall; external ACMlib; function acmStreamSize; stdcall; external ACMlib; function acmStreamReset; stdcall; external ACMlib; function acmStreamMessage; stdcall; external ACMlib; function acmStreamConvert; stdcall; external ACMlib; function acmStreamPrepareHeader; stdcall; external ACMlib; function acmStreamUnprepareHeader; stdcall; external ACMlib; function acmMetrics; stdcall; external ACMlib; function acmFormatSuggest; stdcall; external ACMlib; function acmFormatChoose; stdcall; external ACMlib; end.
unit xn.timers; interface uses System.Classes; type TxnTimer = class strict private fStart: TDateTime; fStop: TDateTime; fElapsed: Cardinal; public constructor Create; destructor Destroy; override; procedure Start; procedure Stop; procedure Reset; function Elapsed: Cardinal; procedure Print(aStrings: TStrings; aCaption: string); overload; procedure Print(aStrings: TStrings); overload; end; TxnTimers = class const MAX_TIMERS = 100; strict private fTimers: array [0 .. MAX_TIMERS] of TxnTimer; procedure IndexCheck(aIndex: integer); public constructor Create; destructor Destroy; override; procedure Start(aIndex: integer); procedure Stop(aIndex: integer); procedure Reset(aIndex: integer); function Elapsed(aIndex: integer): Cardinal; procedure Print(aIndex: integer; aStrings: TStrings; aCaption: string); overload; procedure Print(aIndex: integer; aStrings: TStrings); overload; end; var xnTimers: TxnTimers; implementation uses Vcl.Forms, System.SysUtils; { TTimer } constructor TxnTimer.Create; begin Reset; end; destructor TxnTimer.Destroy; begin inherited; end; function TxnTimer.Elapsed: Cardinal; begin Result := fElapsed; end; procedure TxnTimer.Print(aStrings: TStrings); begin Print(aStrings, ''); end; procedure TxnTimer.Print(aStrings: TStrings; aCaption: string); begin if aCaption <> '' then aCaption := aCaption + ' '; aStrings.Add(aCaption + IntToStr(Elapsed())); end; procedure TxnTimer.Reset; begin fElapsed := 0; end; procedure TxnTimer.Start; begin Application.ProcessMessages; fStart := Now; end; procedure TxnTimer.Stop; begin Application.ProcessMessages; fStop := Now; fElapsed := fElapsed + Trunc((fStop - fStart) * 24 * 60 * 60 * 1000); end; { TTimers } constructor TxnTimers.Create; var i: integer; begin for i := 0 to MAX_TIMERS do fTimers[i] := TxnTimer.Create; end; destructor TxnTimers.Destroy; var i: integer; begin for i := 0 to MAX_TIMERS do fTimers[i].Free; inherited; end; function TxnTimers.Elapsed(aIndex: integer): Cardinal; begin IndexCheck(aIndex); Result := fTimers[aIndex].Elapsed(); end; procedure TxnTimers.IndexCheck(aIndex: integer); begin if (aIndex < 0) or (aIndex > MAX_TIMERS) then raise Exception.Create('Invalid timer index.'); end; procedure TxnTimers.Print(aIndex: integer; aStrings: TStrings); begin Print(aIndex, aStrings, ''); end; procedure TxnTimers.Print(aIndex: integer; aStrings: TStrings; aCaption: string); begin IndexCheck(aIndex); fTimers[aIndex].Print(aStrings, aCaption); end; procedure TxnTimers.Reset(aIndex: integer); begin IndexCheck(aIndex); fTimers[aIndex].Reset; end; procedure TxnTimers.Start(aIndex: integer); begin IndexCheck(aIndex); fTimers[aIndex].Start; end; procedure TxnTimers.Stop(aIndex: integer); begin IndexCheck(aIndex); fTimers[aIndex].Stop; end; initialization xnTimers := TxnTimers.Create; finalization xnTimers.Free; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ Prior revision history: Rev 1.17 2/8/05 6:07:16 PM RLebeau Removed AddToInternalBuffer() method, using new AppendString() function from IdGlobal instead Rev 1.16 10/26/2004 10:29:30 PM JPMugaas Updated refs. Rev 1.15 7/16/04 12:02:16 PM RLebeau Reverted FileName fields to not strip off folder paths anymore. Rev 1.14 7/5/04 1:19:06 PM RLebeau Updated IdRead() to check the calculated byte count before copying data into the caller's buffer. Rev 1.13 5/31/04 9:28:58 PM RLebeau Updated FileName fields to strip off folder paths. Added "Content-Transfer-Encoding" header to file fields Updated "Content-Type" headers to be the appropriate media types when applicable Rev 1.12 5/30/04 7:39:02 PM RLebeau Moved FormatField() method from TIdMultiPartFormDataStream to TIdFormDataField instead Misc. tweaks and bug fixes Rev 1.11 2004.05.20 11:37:02 AM czhower IdStreamVCL Rev 1.10 3/1/04 8:57:34 PM RLebeau Format() fixes for TIdMultiPartFormDataStream.FormatField() and TIdFormDataField.GetFieldSize(). Rev 1.9 2004.02.03 5:44:08 PM czhower Name changes Rev 1.8 2004.02.03 2:12:16 PM czhower $I path change Rev 1.7 25/01/2004 21:56:42 CCostelloe Updated IdSeek to use new IdFromBeginning Rev 1.6 24/01/2004 19:26:56 CCostelloe Cleaned up warnings Rev 1.5 22/11/2003 12:05:26 AM GGrieve Get working on both win32 and DotNet after other DotNet changes Rev 1.4 11/10/2003 8:03:54 PM BGooijen Did all todo's ( TStream to TIdStream mainly ) Rev 1.3 2003.10.24 10:43:12 AM czhower TIdSTream to dos Rev 1.2 10/17/2003 12:49:52 AM DSiders Added localization comments. Added resource string for unsupported operation exception. Rev 1.1 10/7/2003 10:07:06 PM GGrieve Get HTTP compiling for DotNet Rev 1.0 11/13/2002 07:57:42 AM JPMugaas Initial version control checkin. 2001-Nov-23 changed spelling error from XxxDataFiled to XxxDataField 2001-Nov Doychin Bondzhev Now it descends from TStream and does not do buffering. Changes in the way the form parts are added to the stream. } unit IdMultipartFormData; { Implementation of the Multipart Form data Based on Internet standards outlined in: RFC 1867 - Form-based File Upload in HTML RFC 2388 - Returning Values from Forms: multipart/form-data Author: Shiv Kumar } interface {$I IdCompilerDefines.inc} uses Classes, IdGlobal, IdException, IdCharsets, IdCoderHeader, IdResourceStringsProtocols; const sContentTypeFormData = 'multipart/form-data; boundary='; {do not localize} sContentTypeOctetStream = 'application/octet-stream'; {do not localize} sContentTypeTextPlain = 'text/plain'; {do not localize} CRLF = #13#10; sContentDispositionPlaceHolder = 'Content-Disposition: form-data; name="%s"'; {do not localize} sFileNamePlaceHolder = '; filename="%s"'; {do not localize} sContentTypePlaceHolder = 'Content-Type: %s'; {do not localize} sCharsetPlaceHolder = '; charset="%s"'; {do not localize} sContentTransferPlaceHolder = 'Content-Transfer-Encoding: %s'; {do not localize} sContentTransferQuotedPrintable = 'quoted-printable'; {do not localize} sContentTransferBinary = 'binary'; {do not localize} type TIdMultiPartFormDataStream = class; TIdFormDataField = class(TCollectionItem) protected FFileName: string; FCharset: string; FContentType: string; FContentTransfer: string; FFieldName: string; FFieldStream: TStream; FFieldValue: String; FCanFreeFieldStream: Boolean; FHeaderCharSet: string; FHeaderEncoding: Char; function FormatHeader: string; function PrepareDataStream(var VCanFree: Boolean): TStream; function GetFieldSize: Int64; function GetFieldStream: TStream; function GetFieldValue: string; procedure SetCharset(const Value: string); procedure SetContentType(const Value: string); procedure SetContentTransfer(const Value: string); procedure SetFieldName(const Value: string); procedure SetFieldStream(const Value: TStream); procedure SetFieldValue(const Value: string); procedure SetFileName(const Value: string); procedure SetHeaderCharSet(const Value: string); procedure SetHeaderEncoding(const Value: Char); public constructor Create(Collection: TCollection); override; destructor Destroy; override; // procedure Assign(Source: TPersistent); override; property ContentTransfer: string read FContentTransfer write SetContentTransfer; property ContentType: string read FContentType write SetContentType; property Charset: string read FCharset write SetCharset; property FieldName: string read FFieldName write SetFieldName; property FieldStream: TStream read GetFieldStream write SetFieldStream; property FileName: string read FFileName write SetFileName; property FieldValue: string read GetFieldValue write SetFieldValue; property FieldSize: Int64 read GetFieldSize; property HeaderCharSet: string read FHeaderCharSet write SetHeaderCharSet; property HeaderEncoding: Char read FHeaderEncoding write SetHeaderEncoding; end; TIdFormDataFields = class(TCollection) protected FParentStream: TIdMultiPartFormDataStream; function GetFormDataField(AIndex: Integer): TIdFormDataField; public constructor Create(AMPStream: TIdMultiPartFormDataStream); function Add: TIdFormDataField; property MultipartFormDataStream: TIdMultiPartFormDataStream read FParentStream; property Items[AIndex: Integer]: TIdFormDataField read GetFormDataField; end; TIdMultiPartFormDataStream = class(TIdBaseStream) protected FInputStream: TStream; FFreeInputStream: Boolean; FBoundary: string; FRequestContentType: string; FCurrentItem: integer; FInitialized: Boolean; FInternalBuffer: TIdBytes; FPosition: Int64; FSize: Int64; FFields: TIdFormDataFields; function GenerateUniqueBoundary: string; procedure CalculateSize; function IdRead(var VBuffer: TIdBytes; AOffset, ACount: Longint): Longint; override; function IdWrite(const ABuffer: TIdBytes; AOffset, ACount: Longint): Longint; override; function IdSeek(const AOffset: Int64; AOrigin: TSeekOrigin): Int64; override; procedure IdSetSize(ASize : Int64); override; public constructor Create; destructor Destroy; override; function AddFormField(const AFieldName, AFieldValue: string; const ACharset: string = ''; const AContentType: string = ''; const AFileName: string = ''): TIdFormDataField; overload; function AddFormField(const AFieldName, AContentType, ACharset: string; AFieldValue: TStream; const AFileName: string = ''): TIdFormDataField; overload; function AddObject(const AFieldName, AContentType, ACharset: string; AFileData: TObject; const AFileName: string = ''): TIdFormDataField; {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'Use overloaded version of AddFormField()'{$ENDIF};{$ENDIF} function AddFile(const AFieldName, AFileName: String; const AContentType: string = ''): TIdFormDataField; procedure Clear; property Boundary: string read FBoundary; property RequestContentType: string read FRequestContentType; end; EIdInvalidObjectType = class(EIdException); EIdUnsupportedOperation = class(EIdException); EIdUnsupportedTransfer = class(EIdException); EIdUnsupportedEncoding = class(EIdException); implementation uses SysUtils, IdCoderQuotedPrintable, IdCoderMIME, IdStream, IdGlobalProtocols; const cAllowedContentTransfers: array[0..4] of String = ( '7bit', '8bit', 'binary', 'quoted-printable', 'base64' {do not localize} ); cAllowedHeaderEncodings: array[0..2] of String = ( 'Q', 'B', '8' {do not localize} ); { TIdMultiPartFormDataStream } constructor TIdMultiPartFormDataStream.Create; begin inherited Create; FSize := 0; FInitialized := False; FBoundary := GenerateUniqueBoundary; FRequestContentType := sContentTypeFormData + FBoundary; FFields := TIdFormDataFields.Create(Self); end; destructor TIdMultiPartFormDataStream.Destroy; begin FreeAndNil(FFields); inherited Destroy; end; function TIdMultiPartFormDataStream.AddObject(const AFieldName, AContentType, ACharset: string; AFileData: TObject; const AFileName: string = ''): TIdFormDataField; begin if not (AFileData is TStream) then begin raise EIdInvalidObjectType.Create(RSMFDInvalidObjectType); end; Result := AddFormField(AFieldName, AContentType, ACharset, TStream(AFileData), AFileName); end; function TIdMultiPartFormDataStream.AddFile(const AFieldName, AFileName: String; const AContentType: string = ''): TIdFormDataField; var LStream: TIdReadFileExclusiveStream; LItem: TIdFormDataField; begin LStream := TIdReadFileExclusiveStream.Create(AFileName); try LItem := FFields.Add; except FreeAndNil(LStream); raise; end; with LItem do begin FFieldName := AFieldName; FFileName := ExtractFileName(AFileName); FFieldStream := LStream; FCanFreeFieldStream := True; if AContentType <> '' then begin FContentType := AContentType; end else begin FContentType := GetMIMETypeFromFile(AFileName); end; FContentTransfer := sContentTransferBinary; end; Result := LItem; end; function TIdMultiPartFormDataStream.AddFormField(const AFieldName, AFieldValue: string; const ACharset: string = ''; const AContentType: string = ''; const AFileName: string = ''): TIdFormDataField; var LItem: TIdFormDataField; begin LItem := FFields.Add; with LItem do begin FFieldName := AFieldName; FFileName := ExtractFileName(AFileName); FFieldValue := AFieldValue; if AContentType <> '' then begin ContentType := AContentType; end else begin FContentType := sContentTypeTextPlain; end; if ACharset <> '' then begin FCharset := ACharset; end; FContentTransfer := sContentTransferQuotedPrintable; end; Result := LItem; end; function TIdMultiPartFormDataStream.AddFormField(const AFieldName, AContentType, ACharset: string; AFieldValue: TStream; const AFileName: string = ''): TIdFormDataField; var LItem: TIdFormDataField; begin if not Assigned(AFieldValue) then begin raise EIdInvalidObjectType.Create(RSMFDInvalidObjectType); end; LItem := FFields.Add; with LItem do begin FFieldName := AFieldName; FFileName := ExtractFileName(AFileName); FFieldStream := AFieldValue; if AContentType <> '' then begin ContentType := AContentType; end else begin FContentType := GetMIMETypeFromFile(AFileName); end; if ACharset <> '' then begin FCharSet := ACharset; end; FContentTransfer := sContentTransferBinary; end; Result := LItem; end; procedure TIdMultiPartFormDataStream.Clear; begin FInitialized := False; FFields.Clear; if FFreeInputStream then begin FInputStream.Free; end; FInputStream := nil; FFreeInputStream := False; FCurrentItem := 0; FPosition := 0; FSize := 0; SetLength(FInternalBuffer, 0); end; function TIdMultiPartFormDataStream.GenerateUniqueBoundary: string; begin Result := '--------' + FormatDateTime('mmddyyhhnnsszzz', Now); {do not localize} end; procedure TIdMultiPartFormDataStream.CalculateSize; var I: Integer; begin FSize := 0; if FFields.Count > 0 then begin for I := 0 to FFields.Count-1 do begin FSize := FSize + FFields.Items[I].FieldSize; end; FSize := FSize + 2{'--'} + Length(Boundary) + 4{'--'+CRLF}; end; end; // RLebeau - IdRead() should wrap multiple files of the same field name // using a single "multipart/mixed" MIME part, as recommended by RFC 1867 function TIdMultiPartFormDataStream.IdRead(var VBuffer: TIdBytes; AOffset, ACount: Longint): Longint; var LTotalRead, LCount, LBufferCount, LRemaining : Integer; LItem: TIdFormDataField; begin if not FInitialized then begin FInitialized := True; FCurrentItem := 0; SetLength(FInternalBuffer, 0); end; LTotalRead := 0; LBufferCount := 0; while (LTotalRead < ACount) and ((Length(FInternalBuffer) > 0) or Assigned(FInputStream) or (FCurrentItem < FFields.Count)) do begin if (Length(FInternalBuffer) = 0) and (not Assigned(FInputStream)) then begin LItem := FFields.Items[FCurrentItem]; AppendString(FInternalBuffer, LItem.FormatHeader, -1, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); FInputStream := LItem.PrepareDataStream(FFreeInputStream); if not Assigned(FInputStream) then begin AppendString(FInternalBuffer, CRLF); Inc(FCurrentItem); end; end; if Length(FInternalBuffer) > 0 then begin LCount := IndyMin(ACount - LBufferCount, Length(FInternalBuffer)); if LCount > 0 then begin LRemaining := Length(FInternalBuffer) - LCount; CopyTIdBytes(FInternalBuffer, 0, VBuffer, LBufferCount, LCount); if LRemaining > 0 then begin CopyTIdBytes(FInternalBuffer, LCount, FInternalBuffer, 0, LRemaining); end; SetLength(FInternalBuffer, LRemaining); LBufferCount := LBufferCount + LCount; FPosition := FPosition + LCount; LTotalRead := LTotalRead + LCount; end; end; if (LTotalRead < ACount) and (Length(FInternalBuffer) = 0) and Assigned(FInputStream) then begin LCount := TIdStreamHelper.ReadBytes(FInputStream, VBuffer, ACount - LTotalRead, LBufferCount); if LCount > 0 then begin LBufferCount := LBufferCount + LCount; LTotalRead := LTotalRead + LCount; FPosition := FPosition + LCount; end else begin SetLength(FInternalBuffer, 0); if FFreeInputStream then begin FInputStream.Free; end else begin FInputStream.Position := 0; AppendString(FInternalBuffer, CRLF); end; FInputStream := nil; FFreeInputStream := False; Inc(FCurrentItem); end; end; if (Length(FInternalBuffer) = 0) and (not Assigned(FInputStream)) and (FCurrentItem = FFields.Count) then begin AppendString(FInternalBuffer, '--' + Boundary + '--' + CRLF); {do not localize} Inc(FCurrentItem); end; end; Result := LTotalRead; end; function TIdMultiPartFormDataStream.IdSeek(const AOffset: Int64; AOrigin: TSeekOrigin): Int64; begin Result := 0; case AOrigin of soBeginning: begin if (AOffset = 0) then begin FInitialized := False; FPosition := 0; Result := 0; end else begin Result := FPosition; end; end; soCurrent: begin Result := FPosition; end; soEnd: begin if (AOffset = 0) then begin CalculateSize; Result := FSize; end else begin Result := FPosition; end; end; end; end; function TIdMultiPartFormDataStream.IdWrite(const ABuffer: TIdBytes; AOffset, ACount: Longint): Longint; begin raise EIdUnsupportedOperation.Create(RSUnsupportedOperation); end; procedure TIdMultiPartFormDataStream.IdSetSize(ASize: Int64); begin raise EIdUnsupportedOperation.Create(RSUnsupportedOperation); end; { TIdFormDataFields } function TIdFormDataFields.Add: TIdFormDataField; begin Result := TIdFormDataField(inherited Add); end; constructor TIdFormDataFields.Create(AMPStream: TIdMultiPartFormDataStream); begin inherited Create(TIdFormDataField); FParentStream := AMPStream; end; function TIdFormDataFields.GetFormDataField(AIndex: Integer): TIdFormDataField; begin Result := TIdFormDataField(inherited Items[AIndex]); end; { TIdFormDataField } constructor TIdFormDataField.Create(Collection: TCollection); var LDefCharset: TIdCharSet; begin inherited Create(Collection); FFieldStream := nil; FFileName := ''; FFieldName := ''; FContentType := ''; FCanFreeFieldStream := False; // it's not clear when FHeaderEncoding should be Q not B. // Comments welcome on atozedsoftware.indy.general LDefCharset := IdGetDefaultCharSet; case LDefCharset of idcs_ISO_8859_1: begin FHeaderEncoding := 'Q'; { quoted-printable } {Do not Localize} FHeaderCharSet := IdCharsetNames[LDefCharset]; end; idcs_UNICODE_1_1: begin FHeaderEncoding := 'B'; { base64 } {Do not Localize} FHeaderCharSet := IdCharsetNames[idcs_UTF_8]; end; else begin FHeaderEncoding := 'B'; { base64 } {Do not Localize} FHeaderCharSet := IdCharsetNames[LDefCharset]; end; end; end; destructor TIdFormDataField.Destroy; begin if Assigned(FFieldStream) then begin if FCanFreeFieldStream then begin FFieldStream.Free; end; end; inherited Destroy; end; function TIdFormDataField.FormatHeader: string; var LBoundary: string; begin LBoundary := '--' + TIdFormDataFields(Collection).MultipartFormDataStream.Boundary; {do not localize} Result := IndyFormat('%s' + CRLF + sContentDispositionPlaceHolder, [LBoundary, EncodeHeader(FieldName, '', FHeaderEncoding, FHeaderCharSet)]); {do not localize} if Length(FileName) > 0 then begin Result := Result + IndyFormat(sFileNamePlaceHolder, [EncodeHeader(FileName, '', FHeaderEncoding, FHeaderCharSet)]); {do not localize} end; Result := Result + CRLF; if Length(ContentType) > 0 then begin Result := Result + IndyFormat(sContentTypePlaceHolder, [ContentType]); {do not localize} if Length(CharSet) > 0 then begin Result := Result + IndyFormat(sCharsetPlaceHolder, [Charset]); {do not localize} end; Result := Result + CRLF; end; if Length(FContentTransfer) > 0 then begin Result := Result + IndyFormat(sContentTransferPlaceHolder + CRLF, [FContentTransfer]); end; Result := Result + CRLF; end; function TIdFormDataField.GetFieldSize: Int64; var LEncoding: TIdTextEncoding; LStream: TStream; LOldPos: TIdStreamSize; {$IFDEF STRING_IS_ANSI} LBytes: TIdBytes; {$ENDIF} I: Integer; begin {$IFDEF STRING_IS_ANSI} LBytes := nil; // keep the compiler happy {$ENDIF} Result := Length(FormatHeader); if Assigned(FFieldStream) then begin I := PosInStrArray(ContentTransfer, cAllowedContentTransfers, False); if I <= 2 then begin // need to include an explicit CRLF at the end of the data Result := Result + FFieldStream.Size + 2{CRLF}; end else begin LStream := TIdCalculateSizeStream.Create; try LOldPos := FFieldStream.Position; try if I = 3 then begin TIdEncoderQuotedPrintable.EncodeStream(FFieldStream, LStream); // the encoded text always includes a CRLF at the end... Result := Result + LStream.Size {+2}; end else begin TIdEncoderMime.EncodeStream(FFieldStream, LStream); // the encoded text does not include a CRLF at the end... Result := Result + LStream.Size + 2; end; finally FFieldStream.Position := LOldPos; end; finally LStream.Free; end; end; end else if Length(FFieldValue) > 0 then begin LEncoding := nil; {$IFNDEF DOTNET} try {$ENDIF} I := PosInStrArray(FContentTransfer, cAllowedContentTransfers, False); if I = 0 then begin // 7bit {$IFDEF STRING_IS_UNICODE} I := IndyASCIIEncoding.GetByteCount(FFieldValue); {$ELSE} // the methods useful for calculating a length without actually // encoding are protected, so have to actually encode the // string to find out the final length... LEncoding := CharsetToEncoding(FCharset); LBytes := RawToBytes(FFieldValue[1], Length(FFieldValue)); if LEncoding <> IndyASCIIEncoding then begin LBytes := TIdTextEncoding.Convert(LEncoding, IndyASCIIEncoding, LBytes); end; I := Length(LBytes); {$ENDIF} // need to include an explicit CRLF at the end of the data Result := Result + I + 2{CRLF}; end else if (I = -1) or (I = 1) or (I = 2) then begin // 8bit/binary {$IFDEF STRING_IS_UNICODE} LEncoding := CharsetToEncoding(FCharset); I := LEncoding.GetByteCount(FFieldValue); {$ELSE} I := Length(FFieldValue); {$ENDIF} // need to include an explicit CRLF at the end of the data Result := Result + I + 2{CRLF}; end else begin LStream := TIdCalculateSizeStream.Create; try {$IFDEF STRING_IS_UNICODE} LEncoding := CharsetToEncoding(FCharset); {$ELSE} LBytes := RawToBytes(FFieldValue[1], Length(FFieldValue)); {$ENDIF} if I = 3 then begin // quoted-printable {$IFDEF STRING_IS_UNICODE} TIdEncoderQuotedPrintable.EncodeString(FFieldValue, LStream, LEncoding); {$ELSE} TIdEncoderQuotedPrintable.EncodeBytes(LBytes, LStream); {$ENDIF} // the encoded text always includes a CRLF at the end... Result := Result + LStream.Size {+2}; end else begin // base64 {$IFDEF STRING_IS_UNICODE} TIdEncoderMIME.EncodeString(FFieldValue, LStream, LEncoding{$IFDEF STRING_IS_ANSI}, IndyOSDefaultEncoding{$ENDIF}); {$ELSE} TIdEncoderMIME.EncodeBytes(LBytes, LStream); {$ENDIF} // the encoded text does not include a CRLF at the end... Result := Result + LStream.Size + 2; end; finally LStream.Free; end; end; {$IFNDEF DOTNET} finally LEncoding.Free; end; {$ENDIF} end else begin // need to include an explicit CRLF at the end of blank text Result := Result + 2{CRLF}; end; end; function TIdFormDataField.PrepareDataStream(var VCanFree: Boolean): TStream; var I: Integer; LEncoding: TIdTextEncoding; {$IFDEF STRING_IS_ANSI} LBytes: TIdBytes; {$ENDIF} begin {$IFDEF STRING_IS_ANSI} LBytes := nil; // keep the compiler happy {$ENDIF} Result := nil; VCanFree := False; if Assigned(FFieldStream) then begin FFieldStream.Position := 0; I := PosInStrArray(FContentTransfer, cAllowedContentTransfers, False); if I <= 2 then begin Result := FFieldStream; end else begin Result := TMemoryStream.Create; try if I = 3 then begin TIdEncoderQuotedPrintable.EncodeStream(FFieldStream, Result); // the encoded text always includes a CRLF at the end... end else begin TIdEncoderMime.EncodeStream(FFieldStream, Result); // the encoded text does not include a CRLF at the end... WriteStringToStream(Result, CRLF); end; Result.Position := 0; except FreeAndNil(Result); raise; end; VCanFree := True; end; end else if Length(FFieldValue) > 0 then begin Result := TMemoryStream.Create; try LEncoding := nil; {$IFNDEF DOTNET} try {$ENDIF} {$IFDEF STRING_IS_ANSI} LBytes := RawToBytes(FFieldValue[1], Length(FFieldValue)); {$ENDIF} I := PosInStrArray(FContentTransfer, cAllowedContentTransfers, False); if I = 0 then begin // 7bit {$IFDEF STRING_IS_UNICODE} WriteStringToStream(Result, FFieldValue, IndyASCIIEncoding); {$ELSE} LEncoding := CharsetToEncoding(FCharset); if LEncoding <> IndyASCIIEncoding then begin LBytes := TIdTextEncoding.Convert(LEncoding, IndyASCIIEncoding, LBytes); end; WriteTIdBytesToStream(Result, LBytes); {$ENDIF} // need to include an explicit CRLF at the end of the data WriteStringToStream(Result, CRLF); end else if (I = -1) or (I = 1) or (I = 2) then begin // 8bit/binary {$IFDEF STRING_IS_UNICODE} LEncoding := CharsetToEncoding(FCharset); WriteStringToStream(Result, FFieldValue, LEncoding); {$ELSE} WriteTIdBytesToStream(Result, LBytes); {$ENDIF} // need to include an explicit CRLF at the end of the data WriteStringToStream(Result, CRLF); end else begin {$IFDEF STRING_IS_UNICODE} LEncoding := CharsetToEncoding(FCharset); {$ENDIF} if I = 3 then begin // quoted-printable {$IFDEF STRING_IS_UNICODE} TIdEncoderQuotedPrintable.EncodeString(FFieldValue, Result, LEncoding); {$ELSE} TIdEncoderQuotedPrintable.EncodeBytes(LBytes, Result); {$ENDIF} // the encoded text always includes a CRLF at the end... end else begin // base64 {$IFDEF STRING_IS_UNICODE} TIdEncoderMIME.EncodeString(FFieldValue, Result, LEncoding); {$ELSE} TIdEncoderMIME.EncodeBytes(LBytes, Result); {$ENDIF} // the encoded text does not include a CRLF at the end... WriteStringToStream(Result, CRLF); end; end; {$IFNDEF DOTNET} finally LEncoding.Free; end; {$ENDIF} except FreeAndNil(Result); raise; end; Result.Position := 0; VCanFree := True; end; end; function TIdFormDataField.GetFieldStream: TStream; begin if not Assigned(FFieldStream) then begin raise EIdInvalidObjectType.Create(RSMFDInvalidObjectType); end; Result := FFieldStream; end; function TIdFormDataField.GetFieldValue: string; begin if Assigned(FFieldStream) then begin raise EIdInvalidObjectType.Create(RSMFDInvalidObjectType); end; Result := FFieldValue; end; procedure TIdFormDataField.SetCharset(const Value: string); begin FCharset := Value; end; procedure TIdFormDataField.SetContentTransfer(const Value: string); begin if Length(Value) > 0 then begin if PosInStrArray(Value, cAllowedContentTransfers, False) = -1 then begin raise EIdUnsupportedTransfer.Create(RSMFDInvalidTransfer); end; end; FContentTransfer := Value; end; procedure TIdFormDataField.SetContentType(const Value: string); var LContentType, LCharSet: string; begin if Length(Value) > 0 then begin LContentType := Value; end else if Length(FFileName) > 0 then begin LContentType := GetMIMETypeFromFile(FFileName); end else begin LContentType := sContentTypeOctetStream; end; FContentType := RemoveHeaderEntry(LContentType, 'charset', LCharSet, QuoteMIME); {do not localize} // RLebeau: per RFC 2045 Section 5.2: // // Default RFC 822 messages without a MIME Content-Type header are taken // by this protocol to be plain text in the US-ASCII character set, // which can be explicitly specified as: // // Content-type: text/plain; charset=us-ascii // // This default is assumed if no Content-Type header field is specified. // It is also recommend that this default be assumed when a // syntactically invalid Content-Type header field is encountered. In // the presence of a MIME-Version header field and the absence of any // Content-Type header field, a receiving User Agent can also assume // that plain US-ASCII text was the sender's intent. Plain US-ASCII // text may still be assumed in the absence of a MIME-Version or the // presence of an syntactically invalid Content-Type header field, but // the sender's intent might have been otherwise. if (LCharSet = '') and IsHeaderMediaType(FContentType, 'text') then begin {do not localize} LCharSet := 'us-ascii'; {do not localize} end; {RLebeau: override the current CharSet only if the header specifies a new value} if LCharSet <> '' then begin FCharSet := LCharSet; end; end; procedure TIdFormDataField.SetFieldName(const Value: string); begin FFieldName := Value; end; procedure TIdFormDataField.SetFieldStream(const Value: TStream); begin if not Assigned(Value) then begin raise EIdInvalidObjectType.Create(RSMFDInvalidObjectType); end; if Assigned(FFieldStream) and FCanFreeFieldStream then begin FFieldStream.Free; end; FFieldValue := ''; FFieldStream := Value; FCanFreeFieldStream := False; end; procedure TIdFormDataField.SetFieldValue(const Value: string); begin if Assigned(FFieldStream) then begin if FCanFreeFieldStream then begin FFieldStream.Free; end; FFieldStream := nil; FCanFreeFieldStream := False; end; FFieldValue := Value; end; procedure TIdFormDataField.SetFileName(const Value: string); begin FFileName := ExtractFileName(Value); end; procedure TIdFormDataField.SetHeaderCharSet(const Value: string); begin FHeaderCharset := Value; end; procedure TIdFormDataField.SetHeaderEncoding(const Value: Char); begin if FHeaderEncoding <> Value then begin if PosInStrArray(Value, cAllowedHeaderEncodings, False) = -1 then begin raise EIdUnsupportedEncoding.Create(RSMFDInvalidEncoding); end; FHeaderEncoding := Value; end; end; end.
unit pbOutput; interface uses Classes, SysUtils, StrBuffer, pbPublic; type TProtoBufOutput = class; IpbMessage = interface function getSerializedSize: integer; procedure writeTo(buffer: TProtoBufOutput); end; TProtoBufOutput = class(TInterfacedObject, IpbMessage) private FBuffer: TSegmentBuffer; procedure DoWriteRawVarint32(value: integer); public constructor Create; destructor Destroy; override; procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); procedure Clear; (* Encode and write varint. *) procedure writeRawVarint32(value: integer); (* Encode and write varint. *) procedure writeRawVarint64(value: int64); (* Encode and write tag. *) procedure writeTag(fieldNumber: integer; wireType: integer); (* Write the data with specified size. *) procedure writeRawData(const p: Pointer; size: integer); overload; procedure writeRawData(const buf; size: integer); overload; (* Get the result as a string *) function GetText: AnsiString; (* Write a double field, including tag. *) procedure writeDouble(fieldNumber: integer; value: double); (* Write a single field, including tag. *) procedure writeFloat(fieldNumber: integer; value: single); (* Write a int64 field, including tag. *) procedure writeInt64(fieldNumber: integer; value: int64); (* Write a int64 field, including tag. *) procedure writeInt32(fieldNumber: integer; value: integer); (* Write a fixed64 field, including tag. *) procedure writeFixed64(fieldNumber: integer; value: int64); (* Write a fixed32 field, including tag. *) procedure writeFixed32(fieldNumber: integer; value: integer); (* Write a sfixed64 field, including tag. *) procedure writeSFixed64(fieldNumber: integer; value: int64); (* Write a sfixed32 field, including tag. *) procedure writeSFixed32(fieldNumber: integer; value: integer); (* Write a boolean field, including tag. *) procedure writeRawBoolean(value: Boolean); procedure writeBoolean(fieldNumber: integer; value: Boolean); (* Write a string field, including tag. *) procedure writeString(fieldNumber: integer; const value: string); { * Write a bytes field, including tag. * } procedure writeBytes(fieldNumber: integer; const value: TBytes); (* Write a message field, including tag. *) procedure writeMessage(fieldNumber: integer; const value: IpbMessage); (* Write a unsigned int32 field, including tag. *) procedure writeUInt32(fieldNumber: integer; value: cardinal); procedure writeRawSInt32(value: integer); procedure writeRawSInt64(value: int64); procedure writeSInt32(fieldNumber: integer; value: integer); procedure writeSInt64(fieldNumber: integer; value: int64); (* Get serialized size *) function getSerializedSize: integer; (* Write to buffer *) procedure writeTo(buffer: TProtoBufOutput); end; function EncodeZigZag32(const A: LongInt): LongWord; function EncodeZigZag64(const A: int64): UInt64; implementation {$R-} // returns SInt32 encoded to LongWord using 'ZigZag' encoding function EncodeZigZag32(const A: LongInt): LongWord; var I: int64; begin if A < 0 then begin // use Int64 value to negate A without overflow I := A; I := -I; // encode ZigZag Result := (LongWord(I) - 1) * 2 + 1 end else Result := LongWord(A) * 2; end; // returns SInt64 encoded to UInt64 using 'ZigZag' encoding function EncodeZigZag64(const A: int64): UInt64; var I: UInt64; begin if A < 0 then begin // use two's complement to negate A without overflow I := not A; Inc(I); // encode ZigZag Dec(I); I := I * 2; Inc(I); Result := I; end else Result := UInt64(A) * 2; end; { TProtoBuf } constructor TProtoBufOutput.Create; begin FBuffer := TSegmentBuffer.Create; inherited Create; end; destructor TProtoBufOutput.Destroy; begin FBuffer.Free; inherited Destroy; end; procedure TProtoBufOutput.Clear; begin FBuffer.Clear; end; procedure TProtoBufOutput.writeRawBoolean(value: Boolean); var b: ShortInt; begin b := ord(value); writeRawData(b, SizeOf(Byte)); end; procedure TProtoBufOutput.writeRawData(const buf; size: integer); begin {$IFDEF MACOS} //workaround for Delphi macOS64 compiler bug: //https://quality.embarcadero.com/browse/RSP-29451 //compiler calls the wrong overload "writeRawData(const buf; size: integer)" //i.e. ourself, resulting in a stack overflow; just copied the implementation //of the intended overload "writeRawData(const p: Pointer; size: integer)" //here FBuffer.Add(@buf, size); {$ELSE} writeRawData(@buf, size); {$ENDIF MACOS} end; procedure TProtoBufOutput.writeRawSInt32(value: integer); begin writeRawVarint32(EncodeZigZag32(value)); end; procedure TProtoBufOutput.writeRawSInt64(value: int64); begin writeRawVarint64(EncodeZigZag64(value)); end; procedure TProtoBufOutput.writeRawData(const p: Pointer; size: integer); begin FBuffer.Add(p, size); end; procedure TProtoBufOutput.writeTag(fieldNumber, wireType: integer); begin writeRawVarint32(makeTag(fieldNumber, wireType)); end; procedure TProtoBufOutput.writeRawVarint32(value: integer); begin if value < 0 then writeRawVarint64(value) else DoWriteRawVarint32(value); end; procedure TProtoBufOutput.DoWriteRawVarint32(value: integer); var b: ShortInt; begin repeat b := value and $7F; value := value shr 7; if value <> 0 then b := b + $80; writeRawData(b, SizeOf(ShortInt)); until value = 0; end; procedure TProtoBufOutput.writeRawVarint64(value: int64); var b: ShortInt; begin repeat b := value and $7F; value := value shr 7; if value <> 0 then b := b + $80; writeRawData(b, SizeOf(ShortInt)); until value = 0; end; procedure TProtoBufOutput.writeBoolean(fieldNumber: integer; value: Boolean); begin writeTag(fieldNumber, WIRETYPE_VARINT); writeRawBoolean(value); end; procedure TProtoBufOutput.writeBytes(fieldNumber: integer; const value: TBytes); begin writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); writeRawVarint32(length(value)); if length(value) > 0 then writeRawData(value[0], length(value)); end; procedure TProtoBufOutput.writeDouble(fieldNumber: integer; value: double); begin writeTag(fieldNumber, WIRETYPE_FIXED64); writeRawData(@value, SizeOf(value)); end; procedure TProtoBufOutput.writeFloat(fieldNumber: integer; value: single); begin writeTag(fieldNumber, WIRETYPE_FIXED32); writeRawData(@value, SizeOf(value)); end; procedure TProtoBufOutput.writeFixed32(fieldNumber, value: integer); begin writeTag(fieldNumber, WIRETYPE_FIXED32); writeRawData(@value, SizeOf(value)); end; procedure TProtoBufOutput.writeFixed64(fieldNumber: integer; value: int64); begin writeTag(fieldNumber, WIRETYPE_FIXED64); writeRawData(@value, SizeOf(value)); end; procedure TProtoBufOutput.writeInt32(fieldNumber, value: integer); begin writeTag(fieldNumber, WIRETYPE_VARINT); writeRawVarint32(value); end; procedure TProtoBufOutput.writeInt64(fieldNumber: integer; value: int64); begin writeTag(fieldNumber, WIRETYPE_VARINT); writeRawVarint64(value); end; procedure TProtoBufOutput.writeSFixed32(fieldNumber, value: integer); begin writeTag(fieldNumber, WIRETYPE_FIXED32); writeRawData(@value, SizeOf(value)); end; procedure TProtoBufOutput.writeSFixed64(fieldNumber: integer; value: int64); begin writeTag(fieldNumber, WIRETYPE_FIXED64); writeRawData(@value, SizeOf(value)); end; procedure TProtoBufOutput.writeSInt32(fieldNumber, value: integer); begin writeTag(fieldNumber, WIRETYPE_VARINT); writeRawSInt32(value); end; procedure TProtoBufOutput.writeSInt64(fieldNumber: integer; value: int64); begin writeTag(fieldNumber, WIRETYPE_VARINT); writeRawSInt64(value); end; procedure TProtoBufOutput.writeString(fieldNumber: integer; const value: string); var buf: TBytes; begin writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); buf := TEncoding.UTF8.GetBytes(value); writeRawVarint32(length(buf)); if length(buf) > 0 then writeRawData(buf[0], length(buf)); end; procedure TProtoBufOutput.writeUInt32(fieldNumber: integer; value: cardinal); begin writeTag(fieldNumber, WIRETYPE_VARINT); writeRawVarint32(value); end; procedure TProtoBufOutput.writeMessage(fieldNumber: integer; const value: IpbMessage); begin writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); writeRawVarint32(value.getSerializedSize()); value.writeTo(self); end; function TProtoBufOutput.GetText: AnsiString; begin Result := FBuffer.GetText; end; procedure TProtoBufOutput.SaveToFile(const FileName: string); begin FBuffer.SaveToFile(FileName); end; procedure TProtoBufOutput.SaveToStream(Stream: TStream); begin FBuffer.SaveToStream(Stream); end; function TProtoBufOutput.getSerializedSize: integer; begin Result := FBuffer.GetCount; end; procedure TProtoBufOutput.writeTo(buffer: TProtoBufOutput); begin buffer.FBuffer.Add(GetText); end; end.
{***************************************************************************} { } { ICollections - Copyright (C) 2013 - Víctor de Souza Faria } { } { victor@victorfaria.com } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit ICollections.Tree; interface uses System.Generics.Defaults, ICollections.Default; type INode<T> = interface procedure SetContent(node: T); function GetContent: T; property Content: T read GetContent write SetContent; end; ITree<T> = interface(ICollections.Default.IEnumerable<T>) function GetRoot: INode<T>; property Root: INode<T> read GetRoot; function Add(value: T): INode<T>; function GetNode(value: T): INode<T>; function Remove(value: T): Boolean; function Count: Integer; end; TNodeColor = (Black, Red); IRBNode<T> = interface(INode<T>) procedure SetLeft(node: IRBNode<T>); function GetLeft: IRBNode<T>; property Left: IRBNode<T> read GetLeft write SetLeft; procedure SetRight(node: IRBNode<T>); function GetRight: IRBNode<T>; property Right: IRBNode<T> read GetRight write SetRight; procedure SetParent(node: IRBNode<T>); function GetParent: IRBNode<T>; property Parent: IRBNode<T> read GetParent write SetParent; procedure SetColor(color: TNodeColor); function GetColor: TNodeColor; property Color: TNodeColor read GetColor write SetColor; function Grandparent: IRBNode<T>; end; TRBNode<T> = class(TInterfacedObject, IRBNode<T>) private FLeft: IRBNode<T>; FRight: IRBNode<T>; FParent: IRBNode<T>; FContent: T; FColor: TNodeColor; procedure SetLeft(node: IRBNode<T>); function GetLeft: IRBNode<T>; procedure SetRight(node: IRBNode<T>); function GetRight: IRBNode<T>; procedure SetParent(node: IRBNode<T>); function GetParent: IRBNode<T>; procedure SetColor(color: TNodeColor); function GetColor: TNodeColor; procedure SetContent(value: T); function GetContent: T; public property Right: IRBNode<T> read GetRight write SetRight; property Parent: IRBNode<T> read GetParent write SetParent; property Left: IRBNode<T> read GetLeft write SetLeft; property Color: TNodeColor read GetColor write SetColor; property Content: T read GetContent write SetContent; function Grandparent: IRBNode<T>; end; TTreeRB<T> = class(TInterfacedObject, ITree<T>) private FComparer: IComparer<T>; FRoot: IRBNode<T>; FCount: Integer; procedure Balance2(node: IRBNode<T>); function Successor(node: IRBNode<T>): IRBNode<T>; procedure DeleteBalance(node: IRBNode<T>); procedure RotateLeft(node: IRBNode<T>); procedure RotateRight(node: IRBNode<T>); function GetRoot: INode<T>; function FindValue(value: T; node: IRBNode<T>): IRBNode<T>; public constructor Create; overload; constructor Create(comparer: IComparer<T>); overload; property Root: INode<T> read GetRoot; function Add(value: T): INode<T>; function Count: Integer; function GetNode(value: T): INode<T>; function Remove(value: T): Boolean; function GetEnumerator: IEnumerator<T>; type TEnumerator = class(TInterfacedObject, IEnumerator<T>) private FITems: array of T; FIndex: Integer; function GetCurrent: T; procedure FillArray(node: IRBNode<T>); public constructor Create(tree: TTreeRB<T>); property Current: T read GetCurrent; function MoveNext: Boolean; end; end; implementation { TTreeRB<T> } function TTreeRB<T>.Add(value: T): INode<T>; var node, newNode, parent: IRBNode<T>; i: Integer; begin newNode := TRBNode<T>.Create; newNode.Content := value; if FRoot = nil then begin FRoot := newNode; newNode.Color := Black; end else begin node := FRoot; repeat begin parent := node; i := FComparer.Compare(parent.Content, newNode.Content); if i < 0 then begin node := parent.Right; end else begin if i > 0 then begin node := parent.Left; end; end; end; until not Assigned(node); newNode.Color := Red; newNode.Parent := parent; if i < 0 then begin parent.Right := newNode; end else begin parent.Left := newNode; end; Balance2(newNode); end; Inc(FCount); Result := newNode; end; procedure TTreeRB<T>.Balance2(node: IRBNode<T>); var node2: IRBNode<T>; begin node.Color := RED; while (node.Parent <> nil) and (node.Parent.Color = Red) do begin if node.Parent = node.Grandparent.Left then begin node2 := node.Grandparent.Right; if (node2 <> nil) and (node2.Color = Red) then begin node.Parent.Color := Black; node2.Color := Black; node2.Grandparent.Color := Red; node := node.Grandparent; end else begin if node = node.Parent.Right then begin node := node.Parent; RotateLeft(node); end; node.Parent.Color := Black; node.Grandparent.Color := Red; RotateRight(node.Grandparent); end; end else begin node2 := node.Grandparent.Left; if (node2 <> nil) and (node2.Color = Red) then begin node.Parent.Color := Black; node2.Color := Black; node.Grandparent.Color := Red; node := node.Grandparent; end else begin if node = node.Parent.Left then begin node := node.Parent; RotateRight(node); end; node.Parent.Color := Black; node.Grandparent.Color := Red; RotateLeft(node.Grandparent); end; end; end; FRoot.Color := Black; end; function TTreeRB<T>.Count: Integer; begin Result := FCount; end; constructor TTreeRB<T>.Create(comparer: IComparer<T>); begin FComparer := comparer; FCount := 0; end; constructor TTreeRB<T>.Create; begin Create(TComparer<T>.Default); end; procedure TTreeRB<T>.DeleteBalance(node: IRBNode<T>); var sibling: IRBNode<T>; begin while(node <> FRoot) and (node.Color = Black) and (node <> nil) do begin if (node.Parent.Left <> nil) and (node = node.Parent.Left) then begin sibling := node.Parent.Right; if (sibling <> nil) and (sibling.Color = Red) then begin sibling.Color := Black; node.Parent.Color := Red; RotateLeft(node.Parent); sibling := node.Parent.Right; end; if ((sibling.Left = nil) or (sibling.Left.Color = Black)) and ((sibling.Right = nil) or (sibling.Right.Color = Black)) then begin sibling.Color := Red; node := node.Parent; end else begin if (sibling.Right = nil) and (sibling.Right.Color = Black) then begin sibling.Left.Color := Black; sibling.Color := Red; RotateRight(sibling); sibling := node.Parent.Right; end; sibling.Color := node.Parent.Color; node.Parent.Color := Black; sibling.Right.Color := Black; RotateLeft(node.Parent); node := FRoot; end; end else begin sibling := node.Parent.Left; if (sibling <> nil) and (sibling.Color = Red) then begin sibling.Color := Black; node.Parent.Color := Red; RotateRight(node.Parent); sibling := node.Parent.Left; end; if (sibling = nil) or ((sibling <> nil) and ((sibling.Left = nil) or (sibling.Left.Color = Black)) and ((sibling.Right = nil) or(sibling.Right.Color = Black))) then begin if (sibling <> nil) then sibling.Color := Red; node := node.Parent; end else begin if (sibling <> nil) and ((sibling.Left = nil) or (sibling.Left.Color = Black)) then begin sibling.Right.Color := Black; sibling.Color := Red; RotateLeft(sibling); sibling := node.Parent.Left; end; if (sibling <> nil) then begin sibling.Color := node.Parent.Color; if (sibling.Left <> nil) then begin sibling.Left.Color := Black; end; end; node.Parent.Color := Black; RotateRight(node.Parent); node := FRoot; end; end; end; end; function TTreeRB<T>.FindValue(value: T; node: IRBNode<T>): IRBNode<T>; var cmp: Integer; begin Result := nil; if node <> nil then begin cmp := FComparer.Compare(node.Content, value); if cmp = 0 then begin Result := node; end else begin if cmp < 0 then begin Result := FindValue(value, node.Right); end else begin Result := FindValue(value, node.Left); end; end; end; end; function TTreeRB<T>.GetEnumerator: IEnumerator<T>; begin Result := TTreeRB<T>.TEnumerator.Create(self); end; function TTreeRB<T>.GetNode(value: T): INode<T>; begin Result := FindValue(value, FRoot); end; function TTreeRB<T>.GetRoot: INode<T>; begin Result := FRoot; end; function TTreeRB<T>.Remove(value: T): Boolean; var currentNode: IRBNode<T>; successorNode: IRBNode<T>; replace: IRBNode<T>; begin Dec(FCount); currentNode := FindValue(value, FRoot); Result := False; if currentNode <> nil then begin if (currentNode.Left <> nil) and (currentNode.Right <> nil) then begin successorNode := Successor(currentNode); currentNode.Content := successorNode.Content; currentNode := successorNode; end; if (currentNode.Left <> nil) then begin replace := currentNode.Left; end else begin replace := currentNode.Right; end; if (replace <> nil) then begin replace.Parent := currentNode.Parent; if (currentNode.Parent = nil) then begin FRoot := replace; end else begin if (currentNode = currentNode.Parent.Left) then begin currentNode.Parent.Left := replace; end else begin currentNode.Parent.Right := replace; end; end; currentNode.Left := nil; currentNode.Right := nil; currentNode.Parent := nil; if currentNode.Color = Black then begin DeleteBalance(replace); end; end else begin if (currentNode.Parent = nil) then begin FRoot := nil; end else begin if currentNode.Color = Black then begin DeleteBalance(currentNode); end; if currentNode.Parent <> nil then begin if currentNode = currentNode.Parent.Left then begin currentNode.Parent.Left := nil; end else begin if currentNode = currentNode.Parent.Right then begin currentNode.Parent.Right := nil; end; end; currentNode.Parent := nil; end; end; end; Result := True; end; end; procedure TTreeRB<T>.RotateLeft(node: IRBNode<T>); var rigth: IRBNode<T>; begin rigth := node.Right; node.Right := rigth.Left; if (rigth.Left <> nil) then begin rigth.Left.Parent := node; end; rigth.Left := node; if (node.Parent <> nil) then begin if (node.Parent.Right = node) then begin node.Parent.Right := rigth; end else begin node.Parent.Left := rigth; end; rigth.Parent := node.Parent; end else begin rigth.Parent := node.Parent; FRoot := rigth; end; node.Parent := rigth; end; procedure TTreeRB<T>.RotateRight(node: IRBNode<T>); var left: IRBNode<T>; begin left := node.Left; node.Left := left.Right; if (left.Right <> nil) then begin left.Right.Parent := node; end; left.Right := node; if (node.Parent <> nil) then begin if (node.Parent.Right = node) then begin node.Parent.Right := left; end else begin node.Parent.Left := left; end; left.Parent := node.Parent; end else begin left.Parent := node.Parent; FRoot := left; end; node.Parent := left; end; function TTreeRB<T>.Successor(node: IRBNode<T>): IRBNode<T>; var currentNode: IRBNode<T>; nodeAux: IRBNode<T>; begin if node = nil then begin Result := nil; end else begin if node.Right <> nil then begin currentNode := node.Right; while(currentNode.Left <> nil) do begin currentNode := currentNode.Left; end; Result := currentNode; end else begin currentNode := node.Parent; nodeAux := node; while(currentNode <> nil) and (nodeAux = currentNode.Right) do begin nodeAux := currentNode; currentNode := currentNode.Parent; end; Result := currentNode; end; end; end; { TRBNode<T> } function TRBNode<T>.GetColor: TNodeColor; begin Result := FColor; end; function TRBNode<T>.GetContent: T; begin Result := FContent; end; function TRBNode<T>.GetLeft: IRBNode<T>; begin Result := FLeft; end; function TRBNode<T>.GetParent: IRBNode<T>; begin Result := FParent; end; function TRBNode<T>.GetRight: IRBNode<T>; begin Result := FRight; end; function TRBNode<T>.Grandparent: IRBNode<T>; begin Result := nil; if Parent <> nil then begin Result := Parent.Parent; end; end; procedure TRBNode<T>.SetColor(color: TNodeColor); begin FColor := color; end; procedure TRBNode<T>.SetContent(value: T); begin FContent := value; end; procedure TRBNode<T>.SetLeft(node: IRBNode<T>); begin FLeft := node; end; procedure TRBNode<T>.SetParent(node: IRBNode<T>); begin FParent := node; end; procedure TRBNode<T>.SetRight(node: IRBNode<T>); begin FRight := node; end; { TTreeRB<T>.TEnumerator } constructor TTreeRB<T>.TEnumerator.Create(tree: TTreeRB<T>); begin SetLength(FITems, tree.FCount); FIndex := 0; FillArray(tree.FRoot); FIndex := -1; end; procedure TTreeRB<T>.TEnumerator.FillArray(node: IRBNode<T>); begin if (node <> nil) then begin FillArray(node.Left); FITems[FIndex] := node.Content; Inc(FIndex); FillArray(node.Right); end; end; function TTreeRB<T>.TEnumerator.GetCurrent: T; begin Result := FItems[FIndex]; end; function TTreeRB<T>.TEnumerator.MoveNext: Boolean; begin if (FIndex < (Length(FItems) - 1)) then begin Inc(FIndex); Result := True; end else begin Result := False; end; end; end.
unit UMap; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeMKMapView, FMX.TMSNativeUIBaseControl, FMX.TMSNativeUIToolBar, iOSApi.Foundation, FMX.TMSNativeUIImageView, iOSApi.UIKit, FMX.TMSNativeUIPopoverController, FMX.TMSNativeUIButton, FMX.TMSNativeUICore; type TForm913 = class(TForm) TMSFMXNativeUIToolBar1: TTMSFMXNativeUIToolBar; TMSFMXNativeMKMapView1: TTMSFMXNativeMKMapView; TMSFMXNativeUIPopoverController1: TTMSFMXNativeUIPopoverController; TMSFMXNativeUIImageView1: TTMSFMXNativeUIImageView; procedure FormCreate(Sender: TObject); procedure TMSFMXNativeUIToolBar1ItemClick(ASender: TObject; AItem: TTMSFMXNativeUIToolBarItem); procedure TMSFMXNativeMKMapView1DidUpdateUserLocation(Sender: TObject; AUserLocation: TTMSFMXNativeMKMapLocation); procedure TMSFMXNativeMKMapView1AnnotationRightCalloutAccessoryTapped( Sender: TObject; AAnnotation: TTMSFMXNativeMKAnnotation); procedure TMSFMXNativeUIButton1Click(Sender: TObject); private { Private declarations } procedure AddItems; public { Public declarations } end; var Form913: TForm913; implementation {$R *.fmx} function GetRootDirectory: String; begin Result := ExtractFilePath(ParamStr(0)); end; procedure TForm913.AddItems; var lat, lon: Double; lc: TTMSFMXNativeMKMapLocation; b: TTMSFMXNativeUIButton; begin TMSFMXNativeMKMapView1.RemoveAllAnnotations; TMSFMXNativeMKMapView1.BeginUpdate; with TMSFMXNativeMKMapView1.Annotations.Add do begin Title := 'Paris'; SubTitle := 'The capital and most populous city of France'; lat := 48.856667; lon := 2.350833; lc.Latitude := lat; lc.Longitude := lon; Location := lc; PinColor := TTMSFMXNativeMKPinAnnotationColor(Random(3)); AnimatesDrop := True; b := TTMSFMXNativeUIButton.Create(Self); b.Width := 32; b.Height := 32; b.Style := bsButtonTypeDetailDisclosure; RightCalloutAccessoryView := b; DataString := GetRootDirectory + 'Paris.jpg'; end; with TMSFMXNativeMKMapView1.Annotations.Add do begin Title := 'Berlin'; SubTitle := 'The capital city of Germany and one of the 16 states of Germany'; lat := 52.519171; lon := 13.406091199999992; lc.Latitude := lat; lc.Longitude := lon; Location := lc; PinColor := TTMSFMXNativeMKPinAnnotationColor(Random(3)); AnimatesDrop := True; b := TTMSFMXNativeUIButton.Create(Self); b.Width := 32; b.Height := 32; b.Style := bsButtonTypeDetailDisclosure; RightCalloutAccessoryView := b; DataString := GetRootDirectory + 'Berlin.jpg'; end; with TMSFMXNativeMKMapView1.Annotations.Add do begin Title := 'Brussels'; SubTitle := 'The capital city of Belgium.'; lat := 50.8503396; lon := 4.351710300000036; lc.Latitude := lat; lc.Longitude := lon; Location := lc; PinColor := TTMSFMXNativeMKPinAnnotationColor(Random(3)); AnimatesDrop := True; b := TTMSFMXNativeUIButton.Create(Self); b.Width := 32; b.Height := 32; b.Style := bsButtonTypeDetailDisclosure; RightCalloutAccessoryView := b; DataString := GetRootDirectory + 'Brussels.jpg'; end; with TMSFMXNativeMKMapView1.Annotations.Add do begin Title := 'Dubai'; SubTitle := 'A city in the United Arab Emirates, located within the emirate'; lat := 25.271139; lon := 55.30748500000004; lc.Latitude := lat; lc.Longitude := lon; Location := lc; PinColor := TTMSFMXNativeMKPinAnnotationColor(Random(3)); AnimatesDrop := True; b := TTMSFMXNativeUIButton.Create(Self); b.Width := 32; b.Height := 32; b.Style := bsButtonTypeDetailDisclosure; RightCalloutAccessoryView := b; DataString := GetRootDirectory + 'Dubai.jpg'; end; with TMSFMXNativeMKMapView1.Annotations.Add do begin Title := 'New York City'; SubTitle := 'The most populous city in the United States'; lat := 40.7142; lon := -74.0064; lc.Latitude := lat; lc.Longitude := lon; Location := lc; PinColor := TTMSFMXNativeMKPinAnnotationColor(Random(3)); AnimatesDrop := True; b := TTMSFMXNativeUIButton.Create(Self); b.Width := 32; b.Height := 32; b.Style := bsButtonTypeDetailDisclosure; RightCalloutAccessoryView := b; DataString := GetRootDirectory + 'NewYorkCity.jpg'; end; with TMSFMXNativeMKMapView1.Annotations.Add do begin Title := 'Tunis'; SubTitle := 'The capital of both the Tunisian Republic and the Tunis Governorate'; lat := 36.81881; lon := 10.16596; lc.Latitude := lat; lc.Longitude := lon; Location := lc; PinColor := TTMSFMXNativeMKPinAnnotationColor(Random(3)); AnimatesDrop := True; b := TTMSFMXNativeUIButton.Create(Self); b.Width := 32; b.Height := 32; b.Style := bsButtonTypeDetailDisclosure; RightCalloutAccessoryView := b; DataString := GetRootDirectory + 'Tunis.jpg'; end; with TMSFMXNativeMKMapView1.Annotations.Add do begin Title := 'Budapest'; SubTitle := 'The capital and the largest city of Hungary'; lat := 47.497912; lon := 19.04023499999994; lc.Latitude := lat; lc.Longitude := lon; Location := lc; PinColor := TTMSFMXNativeMKPinAnnotationColor(Random(3)); AnimatesDrop := True; b := TTMSFMXNativeUIButton.Create(Self); b.Width := 32; b.Height := 32; b.Style := bsButtonTypeDetailDisclosure; RightCalloutAccessoryView := b; DataString := GetRootDirectory + 'Budapest.jpg'; end; TMSFMXNativeMKMapView1.EndUpdate; end; procedure TForm913.FormCreate(Sender: TObject); var rgn: TTMSFMXNativeMKMapRegion; begin TMSFMXNativeUIToolBar1.BeginUpdate; TMSFMXNativeUIToolBar1.Items.Add.Text := 'Toggle Current Location'; TMSFMXNativeUIToolBar1.Items.Add.Text := 'Toggle Zooming'; TMSFMXNativeUIToolBar1.Items.Add.Text := 'Toggle Scrolling'; TMSFMXNativeUIToolBar1.Items.Add.Text := 'Add Annotations'; TMSFMXNativeUIToolBar1.Items.Add.Text := 'Locate Bermuda Triangle'; TMSFMXNativeUIToolBar1.Items.Add.Text := 'Add Circle'; TMSFMXNativeUIToolBar1.Items.Add.Text := 'Add Image'; TMSFMXNativeUIToolBar1.EndUpdate; rgn.Center.Latitude := TMSFMXNativeMKMapView1.MapView.centerCoordinate.latitude; rgn.Center.Longitude := TMSFMXNativeMKMapView1.MapView.centerCoordinate.longitude; rgn.Span.latitudeDelta := 180; rgn.Span.longitudeDelta := 360; TMSFMXNativeMKMapView1.SetRegion(rgn, True); end; procedure TForm913.TMSFMXNativeMKMapView1AnnotationRightCalloutAccessoryTapped( Sender: TObject; AAnnotation: TTMSFMXNativeMKAnnotation); var r: TRectF; rs: NSRect; vw: UIView; begin if Assigned(AAnnotation.AnnotationView) then begin vw := AAnnotation.AnnotationView.rightCalloutAccessoryView; if Assigned(vw) then begin rs := vw.bounds; r.Left := rs.origin.x; r.Top := rs.origin.y; r.Width := rs.size.width; r.Height := rs.size.height; TMSFMXNativeUIImageView1.Bitmap.Assign(nil); TMSFMXNativeUIImageView1.Bitmap.LoadFromFile(AAnnotation.DataString); TMSFMXNativeUIImageView1.Width := TMSFMXNativeUIImageView1.Bitmap.Width; TMSFMXNativeUIImageView1.Height := TMSFMXNativeUIImageView1.Bitmap.Height; TMSFMXNativeUIPopoverController1.ShowFromRectInView(r, vw); end; end; end; procedure TForm913.TMSFMXNativeMKMapView1DidUpdateUserLocation(Sender: TObject; AUserLocation: TTMSFMXNativeMKMapLocation); begin TMSFMXNativeMKMapView1.SetCenterLocation(AUserLocation, True); end; procedure TForm913.TMSFMXNativeUIButton1Click(Sender: TObject); begin TMSFMXNativeMKMapView1.BeginUpdate; TMSFMXNativeMKMapView1.AddTiling('http://mt0.google.com/vt/x={x}&y={y}&z={z}'); TMSFMXNativeMKMapView1.EndUpdate; end; procedure TForm913.TMSFMXNativeUIToolBar1ItemClick(ASender: TObject; AItem: TTMSFMXNativeUIToolBarItem); var arr: TArray<TTMSFMXNativeMKMapLocation>; c: TTMSFMXNativeMKOverlay; tl, tr, bl, br, mr: TTMSFMXNativeMKMapLocation; splat, splon: Double; rgn: TTMSFMXNativeMKMapRegion; begin case AItem.Index of 0: TMSFMXNativeMKMapView1.ShowsUserLocation := not TMSFMXNativeMKMapView1.ShowsUserLocation; 1: TMSFMXNativeMKMapView1.ZoomEnabled := not TMSFMXNativeMKMapView1.ZoomEnabled; 2: TMSFMXNativeMKMapView1.ScrollEnabled := not TMSFMXNativeMKMapView1.ScrollEnabled; 3: AddItems; 4: begin TMSFMXNativeMKMapView1.BeginUpdate; SetLength(arr, 4); //Bermuda triangle arr[0].Latitude := 25.774252; arr[0].Longitude := -80.190262; arr[1].Latitude := 18.466465; arr[1].Longitude := -66.118292; arr[2].Latitude := 32.321384; arr[2].Longitude := -64.75737; arr[3] := arr[0]; c := TMSFMXNativeMKMapView1.AddPolyline(arr); c.LineColor := TAlphaColorRec.Red; TMSFMXNativeMKMapView1.EndUpdate; end; 5: begin TMSFMXNativeMKMapView1.BeginUpdate; c := TMSFMXNativeMKMapView1.AddCircle(TMSFMXNativeMKMapView1.XYToCoordinate(TMSFMXNativeMKMapView1.Width / 2, TMSFMXNativeMKMapView1.Height / 2), 500000); c.LineWidth := 3; c.LineColor := TAlphaColorRec.Greenyellow; c.Color := TAlphaColorRec.Darkgoldenrod; c.Opacity := 0.5; c.LineOpacity := 0.5; TMSFMXNativeMKMapView1.EndUpdate; end; 6: begin TMSFMXNativeMKMapView1.BeginUpdate; tl := MakeMapLocation(34.4311, -118.6012); tr := MakeMapLocation(34.4311, -118.5912); bl := MakeMapLocation(34.4194, -118.6012); br := MakeMapLocation(34.4194, -118.5912); mr := MakeMapLocation(34.4248, -118.5971); splat := Abs(br.Latitude - tl.Latitude); splon := Abs(br.Longitude - tl.Longitude); rgn.Center.Latitude := mr.Latitude; rgn.Center.Longitude := mr.Longitude; rgn.Span.latitudeDelta := splat; rgn.Span.longitudeDelta := splon; TMSFMXNativeMKMapView1.SetRegion(rgn, True); TMSFMXNativeMKMapView1.AddImage(ExtractFilePath(ParamStr(0)) + 'overlay_park.png', tl, br); TMSFMXNativeMKMapView1.EndUpdate; end; end; end; end.
UNIT deftypes; INTERFACE TYPE Tree = ^TreeNode; TreeNode = RECORD desc : String; count : Integer; left : Tree; right : Tree END; ElemPtr = ^ListElem; ListElem = RECORD tr : Tree; next : ElemPtr END; Queue = RECORD front : ElemPtr; backend : ElemPtr; size : Integer END; IMPLEMENTATION (* *) END.
unit Unit2; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.StdCtrls, FMX.Layouts, FMX.Controls.Presentation; type TForm2 = class(TForm) VSB: TVertScrollBox; Layout1: TLayout; Button1: TButton; Button2: TButton; Image1: TImage; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure LabelPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); end; var Form2: TForm2; implementation {$R *.fmx} procedure TForm2.Button1Click(Sender: TObject); var CR: TCalloutRectangle; L: TText; TmpImg: TImage; begin CR := TCalloutRectangle.Create(Self); CR.Parent := VSB; CR.Align := TAlignLayout.alTop; CR.CalloutPosition := TCalloutPosition.cpLeft; CR.Margins.Top := 10; CR.Margins.Bottom := 10; CR.Margins.Right := 5; CR.Height := 75; L := TText.Create(Self); L.Parent := CR; L.Align := TAlignLayout.alClient; L.Text := 'A quick brown fox jumped over the yellow log running away from the pink dog and ran down the lane.'; L.Margins.Left := 15; L.Margins.Right := 5; L.Width := CR.Width-20; L.WordWrap := True; L.AutoSize := True; L.OnPaint := LabelPaint; TmpImg := TImage.Create(Self); TmpImg.Parent := CR; TmpImg.Align := TAlignLayout.alRight; TmpImg.Bitmap.Assign(Image1.Bitmap); TmpImg.Width := 75; end; procedure TForm2.Button2Click(Sender: TObject); var CR: TCalloutRectangle; L: TText; TmpImg: TImage; begin CR := TCalloutRectangle.Create(Self); CR.Parent := VSB; CR.Align := TAlignLayout.alTop; CR.CalloutPosition := TCalloutPosition.cpRight; CR.Margins.Top := 10; CR.Margins.Bottom := 10; CR.Margins.Left := 5; CR.Height := 75; L := TText.Create(Self); L.Parent := CR; L.Align := TAlignLayout.alClient; L.Text := 'A quick brown fox jumped over the yellow log running away from the pink dog and ran down the lane.'; L.Margins.Right := 15; L.Margins.Left := 5; L.Width := CR.Width-20; L.WordWrap := True; L.AutoSize := True; L.OnPaint := LabelPaint; TmpImg := TImage.Create(Self); TmpImg.Parent := CR; TmpImg.Align := TAlignLayout.alLeft; TmpImg.Bitmap.Assign(Image1.Bitmap); TmpImg.Width := 75; end; procedure TForm2.LabelPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); begin //TCalloutRectangle(TText(Sender).Parent).Height := TText(Sender).Height; end; end.
unit dcCalcEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ToolEdit, CurrEdit, DataController, db, dbctrls; type TdcCalcEdit = class(TRxCalcEdit) private FClearing: boolean; procedure SetClearing(const Value: boolean); function GetDataBufIndex: integer; procedure SetDataBufIndex(const Value: integer); private { Private declarations } fdcLink : TdcLink; fTranData : String; frequired : boolean; OldReadOnly : boolean; OriginalData : Double; property Clearing:boolean read FClearing write SetClearing; protected { Protected declarations } function GetDataField:string; procedure SetDataField(value:string); // data controller function GetDataController:TDataController; procedure SetDataController(value:TDataController); function GetDataSource:TDataSource; procedure SetDataSource(value:TDataSource); procedure ReadData(sender:TObject); procedure WriteData(sender:TObject); procedure ClearData(sender:TObject); procedure DoEnter;override; procedure DoExit;override; procedure Change;override; public { Public declarations } constructor Create(AOwner:Tcomponent);override; destructor Destroy;override; property TranData : String read fTranData; published { Published declarations } property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property Required : boolean read fRequired write fRequired; property DataSource : TDataSource read getDataSource write SetDataSource; property DataBufIndex:integer read GetDataBufIndex write SetDataBufIndex; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Data Entry', [TdcCalcEdit]); end; constructor TdcCalcEdit.Create(AOwner:Tcomponent); begin inherited; fdclink := tdclink.create(self); with fdcLink do begin OnReadData := ReadData; OnWriteData := WriteData; OnClearData := ClearData; end; end; destructor TdcCalcEdit.Destroy; begin fdclink.Free; inherited; end; function TdcCalcEdit.getdatasource; begin result := fdclink.DataSource; end; procedure TdcCalcEdit.SetDatasource(value:TDataSource); begin end; procedure TdcCalcEdit.SetDataController(value:TDataController); begin fdcLink.datacontroller := value; end; function TdcCalcEdit.GetDataController:TDataController; begin result := fdcLink.DataController; end; function TdcCalcEdit.GetDataField:string; begin result := fdcLink.FieldName; end; procedure TdcCalcEdit.SetDataField(value:string); begin fdcLink.FieldName := value; end; procedure TdcCalcEdit.ReadData; begin if fdclink.DataController <> nil then begin OriginalData := 0; if assigned(fdclink.datacontroller.databuf) then case fdclink.datacontroller.databuf.FieldType(DataBufIndex) of ftInteger : OriginalData := fdclink.datacontroller.databuf.asInt[DataBufIndex]; ftFloat : OriginalData := fdclink.datacontroller.databuf.asFloat[DataBufIndex]; ftCurrency : OriginalData := fdclink.datacontroller.databuf.asCurrency[DataBufIndex]; else OriginalData := 0; end; Value := OriginalData; end; end; procedure TdcCalcEdit.ClearData; begin Clearing := true; Value := 0; OriginalData := 0; Clearing := false; end; procedure TdcCalcEdit.WriteData; var olddata : string; newdata : string; begin if ReadOnly then exit; if fdclink.DataController <> nil then begin if assigned(fdclink.field) then begin olddata := FormatFloat(DisplayFormat, fdclink.Field.AsFloat); newdata := FormatFloat(DisplayFormat, Value); if olddata <> newdata then fTranData := FormatFloat('0.00', Value); end; if assigned(fdclink.datacontroller.databuf) then case fdclink.datacontroller.databuf.FieldType(DataBufIndex) of ftInteger : fdclink.datacontroller.databuf.asInt[DataBufIndex] := AsInteger; ftFloat : fdclink.datacontroller.databuf.asFloat[DataBufIndex] := Value; ftCurrency : fdclink.datacontroller.databuf.asCurrency[DataBufIndex] := Value; else OriginalData := 0; end; end; end; procedure TdcCalcEdit.Change; begin // if assigned(fdclink) then if not clearing then fdclink.BeginEdit; inherited; end; procedure TdcCalcEdit.DoEnter; begin oldReadonly := ReadOnly; if DataController <> nil then begin if datacontroller.ReadOnly then ReadOnly := true; end; inherited; end; procedure TdcCalcEdit.DoExit; begin ReadOnly := OldReadOnly; inherited; end; procedure TdcCalcEdit.SetClearing(const Value: boolean); begin FClearing := Value; end; function TdcCalcEdit.GetDataBufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; procedure TdcCalcEdit.SetDataBufIndex(const Value: integer); begin end; end.
unit Backup; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, System.UITypes, ComCtrls, StdCtrls, Buttons, ErrorListDialog, AbZipKit, AbUtils, AbArcTyp, ExtCtrls; type TBackupProgress = procedure(percent: integer) of object; TBackup = class(TComponent) private zip: TAbZipKit; ErrorList: TStringList; // passed the pointer - not created FOnProgress: TBackupProgress; FZipFileName: TFileName; procedure ZipSkippingFile(Sender: TObject; Item: TAbArchiveItem; ProcessType: TAbProcessType; ErrorClass: TAbErrorClass; ErrorCode: integer); procedure ZipOnPercentDone(Sender: TObject; Progress: Byte; var Abort: Boolean); procedure SetOnProgress(const Value: TBackupProgress); procedure SetZipFileName(const Value: TFileName); public constructor Create(AOwner: TComponent; AErrorList: TStringList); reintroduce; destructor Destroy; override; procedure Backup; procedure Restore; property OnProgress: TBackupProgress read FOnProgress write SetOnProgress; property ZipFileName: TFileName read FZipFileName write SetZipFileName; end; TfrmBackup = class(TForm) SaveDialog1: TSaveDialog; OpenDialog1: TOpenDialog; Label1: TLabel; Elist: TErrorListDialog; StatusBar1: TStatusBar; Label2: TLabel; Label3: TLabel; Label4: TLabel; btnBackup: TBitBtn; btnClose: TBitBtn; btnRestore: TBitBtn; btnLenderBackup: TBitBtn; btnLenderRestore: TBitBtn; procedure btnBackupClick(Sender: TObject); procedure btnRestoreClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); procedure btnLenderBackupClick(Sender: TObject); procedure btnLenderRestoreClick(Sender: TObject); private { Private declarations } ErrorList: TStringList; Zipper: TAbZipKit; procedure DoOnProgress(percent: integer); procedure ArchiveOnProgress(Sender: TObject; Progress: Byte; var Abort: Boolean); public { Public declarations } SiteID: string; Flag: string; end; var frmBackup: TfrmBackup; implementation uses FFSUtils, ProgramSettings, TicklerTypes, TicklerGlobals, datamod; {$R *.DFM} { TBackup } constructor TBackup.Create(AOwner: TComponent; AErrorList: TStringList); begin inherited Create(AOwner); ErrorList := AErrorList; zip := TAbZipKit.Create(self); zip.OnProcessItemFailure := ZipSkippingFile; zip.OnArchiveProgress := ZipOnPercentDone; end; procedure TBackup.ZipOnPercentDone(Sender: TObject; Progress: Byte; var Abort: Boolean); begin if Assigned(OnProgress) then OnProgress(Progress); end; destructor TBackup.Destroy; begin inherited; end; procedure TBackup.Backup; begin try try zip.BaseDirectory := Dir(drData); zip.FileName := ZipFileName; zip.Password := 'ZIPRX'; zip.AddFiles('*.DAT', faAnyFile); zip.AddFiles('*.IDX', faAnyFile); zip.AddFiles('*.BLB', faAnyFile); zip.Save; except on e: Exception do ErrorList.Add(e.Message); end; finally end; end; procedure TBackup.Restore; begin try try zip.BaseDirectory := Dir(drData); zip.FileName := ZipFileName; zip.Password := 'ZIPRX'; zip.ExtractFiles('*.*'); except on e: Exception do ErrorList.Add(e.Message); end; finally end; end; procedure TBackup.SetOnProgress(const Value: TBackupProgress); begin FOnProgress := Value; end; procedure TBackup.ZipSkippingFile(Sender: TObject; Item: TAbArchiveItem; ProcessType: TAbProcessType; ErrorClass: TAbErrorClass; ErrorCode: integer); begin ErrorList.Add(Item.FileName + ' not processed.'); end; procedure TBackup.SetZipFileName(const Value: TFileName); begin FZipFileName := Value; end; { TfrmBackup } procedure TfrmBackup.DoOnProgress(percent: integer); begin StatusBar1.Panels[1].Text := IntToStr(percent); Application.ProcessMessages; end; procedure TfrmBackup.btnBackupClick(Sender: TObject); var bkup: TBackup; begin SaveDialog1.InitialDir := Dir(drExport); SaveDialog1.FileName := 'TTS' + SiteID + AnyDateToyyyymmdd(SystemDateString) + '.ZIP'; if SaveDialog1.Execute then begin Elist.Items.Clear; btnBackup.Enabled := false; btnClose.Enabled := false; btnRestore.Enabled := false; StatusBar1.Panels[0].Text := 'Backing Up Data...'; StatusBar1.Panels[1].Text := '0'; update; try DeleteFile(SaveDialog1.FileName); // if we got this far, overwrite if it exists // zip up the database bkup := TBackup.Create(self, ErrorList); bkup.ZipFileName := SaveDialog1.FileName; bkup.OnProgress := DoOnProgress; bkup.Backup; bkup.Free; finally StatusBar1.Panels[0].Text := 'Idle'; StatusBar1.Panels[1].Text := '0'; btnRestore.Enabled := true; btnBackup.Enabled := true; btnClose.Enabled := true; if ErrorList.Count > 0 then begin Elist.Items.AddStrings(ErrorList); Elist.Execute; end; end; end; end; procedure TfrmBackup.btnRestoreClick(Sender: TObject); var bkup: TBackup; begin OpenDialog1.InitialDir := Dir(drExport); if OpenDialog1.Execute then begin if MessageDlg('WARNING: You are about to overwrite your current data ' + 'files with a backup. Are you sure you wish to continue?', mtConfirmation, mbYesNoCancel, 0) <> mrYes then exit; Elist.Items.Clear; btnBackup.Enabled := false; btnClose.Enabled := false; btnRestore.Enabled := false; StatusBar1.Panels[0].Text := 'Restoring Data...'; StatusBar1.Panels[1].Text := '0'; update; try // zip up the database bkup := TBackup.Create(self, ErrorList); bkup.ZipFileName := OpenDialog1.FileName; bkup.OnProgress := DoOnProgress; bkup.Restore; bkup.Free; finally StatusBar1.Panels[0].Text := 'Idle'; StatusBar1.Panels[1].Text := '0'; btnRestore.Enabled := true; btnBackup.Enabled := true; btnClose.Enabled := true; if ErrorList.Count > 0 then begin Elist.Items.AddStrings(ErrorList); Elist.Execute; end; end; end; end; procedure TfrmBackup.FormCreate(Sender: TObject); begin Zipper := TAbZipKit.Create(nil); Zipper.OnArchiveProgress := ArchiveOnProgress; ErrorList := TStringList.Create; StatusBar1.Panels[0].Text := 'Idle'; StatusBar1.Panels[1].Text := '0'; end; procedure TfrmBackup.FormDestroy(Sender: TObject); begin Zipper.Free; ErrorList.Free; end; procedure TfrmBackup.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); var X, Y, pct: integer; newrect: TRect; s: string; size: TSize; begin try pct := StrToInt(Panel.Text); StatusBar.Canvas.Brush.Color := StatusBar.Color; StatusBar.Canvas.FillRect(Rect); // if pct=0 then Exit; StatusBar.Canvas.Brush.Color := clNavy; newrect := Rect; newrect.Right := Rect.Left + Trunc((pct / 100) * Panel.Width); StatusBar.Canvas.FillRect(newrect); s := Format('%d%%', [pct]); size := StatusBar.Canvas.TextExtent(s); X := Rect.Left + ((Panel.Width - size.cx) div 2); Y := Rect.Top + (((Rect.bottom - Rect.Top) - size.cy) div 2); SetBkMode(StatusBar.Canvas.Handle, TRANSPARENT); StatusBar.Canvas.Font.Color := clGreen; StatusBar.Canvas.TextOut(X, Y, s); except end; end; procedure TfrmBackup.btnLenderBackupClick(Sender: TObject); begin {$IFDEF SERVER} Flag := 'LB'; btnClose.Click; exit; {$ENDIF} {$IFDEF THINVER} exit; {$ENDIF} if CurrentLend.Number = '' then begin ShowMessage('Current Lender is empty. Please select lender from Main screen and retry'); btnClose.Click; exit; end; // CIF StatusBar1.Panels[0].Text := 'Backing Up CIF...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'CIF', StatusBar1); // CITM StatusBar1.Panels[0].Text := 'Backing Up CITM...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'CITM', StatusBar1); // CODE StatusBar1.Panels[0].Text := 'Backing Up CODE...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'CODE', StatusBar1); // COLL StatusBar1.Panels[0].Text := 'Backing Up COLL...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'COLL', StatusBar1); // DCRUN StatusBar1.Panels[0].Text := 'Backing Up DCRUN...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'DCRUN', StatusBar1); // GUAR StatusBar1.Panels[0].Text := 'Backing Up GUAR...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'GUAR', StatusBar1); // HITM StatusBar1.Panels[0].Text := 'Backing Up HITM...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'HITM', StatusBar1); // LDOC StatusBar1.Panels[0].Text := 'Backing Up LDOC...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'LDOC', StatusBar1); // LEND StatusBar1.Panels[0].Text := 'Backing Up LEND...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'LEND', StatusBar1); // LOAN StatusBar1.Panels[0].Text := 'Backing Up LOAN...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'LOAN', StatusBar1); // NCOL StatusBar1.Panels[0].Text := 'Backing Up NCOL...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'NCOL', StatusBar1); // NOTE StatusBar1.Panels[0].Text := 'Backing Up NOTE...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'NOTE', StatusBar1); // PLDG StatusBar1.Panels[0].Text := 'Backing Up PLDG...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'PLDG', StatusBar1); // PROCESS StatusBar1.Panels[0].Text := 'Backing Up PROCESS...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'PROCESS', StatusBar1); // RPTSAVE StatusBar1.Panels[0].Text := 'Backing Up RPTSAVE...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'RPTSAVE', StatusBar1); // TDOC StatusBar1.Panels[0].Text := 'Backing Up TDOC...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'TDOC', StatusBar1); // TITM StatusBar1.Panels[0].Text := 'Backing Up TITM...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'TITM', StatusBar1); // TRAK StatusBar1.Panels[0].Text := 'Backing Up TRAK...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'TRAK', StatusBar1); // UTL StatusBar1.Panels[0].Text := 'Backing Up UTL...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'UTL', StatusBar1); // UTLNOMAT StatusBar1.Panels[0].Text := 'Backing Up UTLNOMAT...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderBackUp(CurrentLend.Number, 'UTLNOMAT', StatusBar1); StatusBar1.Panels[0].Text := 'Idle'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; StatusBar1.Panels[0].Text := 'Zipping...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; Zipper.BaseDirectory := Dir(drUpdate); Zipper.FileName := Dir(drExport) + 'BKUP' + CurrentLend.Number + '.zip'; Zipper.Password := 'ZIPRX'; Zipper.AddFiles('*.csv', 0); StatusBar1.Panels[0].Text := 'Idle'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; end; procedure TfrmBackup.btnLenderRestoreClick(Sender: TObject); var TmpFile: String; SearchRec: TSearchRec; filemask: string; err: integer; FileList: TStringList; TIdx: integer; TLen: integer; TableName: String; begin {$IFDEF SERVER} Flag := 'LR'; btnClose.Click; exit; {$ENDIF} {$IFDEF THINVER} exit; {$ENDIF} TmpFile := Dir(drExport) + 'BKUP' + CurrentLend.Number + '.zip'; if not fileexists(TmpFile) then begin ShowMessage('There is no archive for Lender: ' + CurrentLend.Number); exit; end; StatusBar1.Panels[0].Text := 'Unzipping...'; Zipper.FileName := TmpFile; Zipper.BaseDirectory := Dir(drExport); Zipper.TempDirectory := Dir(drUpdate); Zipper.Password := 'ZIPRX'; Zipper.ExtractFiles('*'); FileList := TStringList.Create; filemask := Dir(drUpdate) + '*.csv'; err := FindFirst(filemask, faAnyFile, SearchRec); while (err = 0) do begin FileList.Add(SearchRec.Name); err := FindNext(SearchRec); end; FindClose(SearchRec); for TIdx := 0 to FileList.Count - 1 do begin TLen := length(FileList.Strings[TIdx]); TableName := copy(FileList.Strings[TIdx], 1, TLen - 8); StatusBar1.Panels[0].Text := 'Restoring ' + TableName + '...'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; daapi.LenderRestore(CurrentLend.Number, TableName, StatusBar1); DeleteFile(Dir(drUpdate) + FileList.Strings[TIdx]); end; StatusBar1.Panels[0].Text := 'Idle'; StatusBar1.Panels[1].Text := '0'; Application.ProcessMessages; FileList.Free; end; procedure TfrmBackup.ArchiveOnProgress(Sender: TObject; Progress: Byte; var Abort: Boolean); begin StatusBar1.Panels[1].Text := Progress.ToString; Application.ProcessMessages; end; end.
unit nsJournalBookmarkNode; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Common\nsJournalBookmarkNode.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsJournalBookmarkNode" MUID: (4ADDF4D901D1) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3IntfUses , nsWrapperNode , MainMenuDomainInterfaces , DocumentUnit , l3Interfaces , l3Tree_TLB , l3IID ; type TnsJournalBookmarkNode = class(TnsWrapperNode, InsJournalBookmarkNode) private f_Bookmark: IJournalBookmark; f_DocName: Il3CString; protected function Get_DocName: Il3CString; function Get_Bookmark: IJournalBookmark; procedure Cleanup; override; {* Функция очистки полей объекта. } function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } public constructor Create(const aBookmark: IJournalBookmark; aFullDocName: Boolean); reintroduce; class function Make(const aBookmark: IJournalBookmark; aFullDocName: Boolean = False): Il3Node; reintroduce; end;//TnsJournalBookmarkNode {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3ImplUses , l3String , IOUnit , nsTypes , BaseTypesUnit //#UC START# *4ADDF4D901D1impl_uses* //#UC END# *4ADDF4D901D1impl_uses* ; constructor TnsJournalBookmarkNode.Create(const aBookmark: IJournalBookmark; aFullDocName: Boolean); //#UC START# *4ADF23C202CF_4ADDF4D901D1_var* procedure lp_MakeText; const c_MaxLenght = 170; c_Suffix = ' ...'; var l_Index : Integer; l_Str : IString; begin // Показывать полное имя: if aFullDocName then begin Get_DocName; // - инициализация поля f_DocName; with f_DocName.AsWStr do if SLen > c_MaxLenght then begin // Обрезаем размер текста до c_MaxLenght, по ближайшему к 170 символу // пробелу: for l_Index := Pred(c_MaxLenght) downto 0 do if l3Compare(S[l_Index], ' ') = 0 then begin l3SetLen(f_DocName, l_Index); Break; end;//if l3Compare(S[l_Index], ' ') = 0 then // Добавим троеточие: f_DocName := l3Cat(f_DocName, c_Suffix); end;//if SLen > c_MaxLenght then // Установим название: pm_SetName(f_DocName.AsWStr); end//if aFullDocName then else // Показывать короткое имя: begin // Name f_Bookmark.GetName(l_Str); try pm_SetName(nsWStr(l_Str)); finally l_Str := nil; end;//try..finally end;//if aFullDocName then end;//lp_MakeText; procedure lp_MakeComment; var l_Str : IString; begin // Comment f_Bookmark.GetFullName(l_Str); try pm_SetComment(nsWStr(l_Str)); finally l_Str := nil; end;//try..finally end;//lp_MakeComment //#UC END# *4ADF23C202CF_4ADDF4D901D1_var* begin //#UC START# *4ADF23C202CF_4ADDF4D901D1_impl* inherited Create; if not Assigned(aBookmark) then Exit; f_Bookmark := aBookmark; lp_MakeText; lp_MakeComment; //#UC END# *4ADF23C202CF_4ADDF4D901D1_impl* end;//TnsJournalBookmarkNode.Create class function TnsJournalBookmarkNode.Make(const aBookmark: IJournalBookmark; aFullDocName: Boolean = False): Il3Node; var l_Inst : TnsJournalBookmarkNode; begin l_Inst := Create(aBookmark, aFullDocName); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnsJournalBookmarkNode.Make function TnsJournalBookmarkNode.Get_DocName: Il3CString; //#UC START# *4A8BAAA50229_4ADDF4D901D1get_var* var l_Str : IString; //#UC END# *4A8BAAA50229_4ADDF4D901D1get_var* begin //#UC START# *4A8BAAA50229_4ADDF4D901D1get_impl* Result := nil; // Фиктивный узел if not Assigned(f_Bookmark) then Exit; // Получим имя документа if not Assigned(f_DocName) then begin // Document try f_Bookmark.GetFullName(l_Str); f_DocName := nsCStr(l_Str); except // Документа нет on ECanNotFindData do begin end; end; // DocName end;//not Assigned(f_Document) Result := f_DocName; //#UC END# *4A8BAAA50229_4ADDF4D901D1get_impl* end;//TnsJournalBookmarkNode.Get_DocName function TnsJournalBookmarkNode.Get_Bookmark: IJournalBookmark; //#UC START# *4A8BAACC02D5_4ADDF4D901D1get_var* //#UC END# *4A8BAACC02D5_4ADDF4D901D1get_var* begin //#UC START# *4A8BAACC02D5_4ADDF4D901D1get_impl* Result := f_Bookmark; //#UC END# *4A8BAACC02D5_4ADDF4D901D1get_impl* end;//TnsJournalBookmarkNode.Get_Bookmark procedure TnsJournalBookmarkNode.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4ADDF4D901D1_var* //#UC END# *479731C50290_4ADDF4D901D1_var* begin //#UC START# *479731C50290_4ADDF4D901D1_impl* f_Bookmark := nil; f_DocName := nil; inherited; //#UC END# *479731C50290_4ADDF4D901D1_impl* end;//TnsJournalBookmarkNode.Cleanup function TnsJournalBookmarkNode.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {* Реализация запроса интерфейса } //#UC START# *4A60B23E00C3_4ADDF4D901D1_var* //#UC END# *4A60B23E00C3_4ADDF4D901D1_var* begin //#UC START# *4A60B23E00C3_4ADDF4D901D1_impl* Result := inherited COMQueryInterface(IID, Obj); if Result.Fail then begin if (f_Bookmark = nil) then Result.SetNOINTERFACE else Result := Tl3HResult_C(f_Bookmark.QueryInterface(IID.IID, Obj)); end; //#UC END# *4A60B23E00C3_4ADDF4D901D1_impl* end;//TnsJournalBookmarkNode.COMQueryInterface {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) end.
unit MD5windows; interface type MD4_CTX = packed record _Buf : array[0..3] of LongWord; _I : array[0..1] of LongWord; input : array[0..63] of byte; digest : Array[0..15] of Byte; end; Procedure MD4Init(Var Context: MD4_CTX); StdCall; Procedure MD4Update(Var Context: MD4_CTX; const Input; inLen: LongWord); StdCall; Procedure MD4Final(Var Context: MD4_CTX); StdCall; function MD4_Selftest:Boolean; type MD5_CTX = packed Record i: Array[0.. 1] of LongWord; buf: Array[0.. 3] of LongWord; input: Array[0..63] of Byte; digest: Array[0..15] of Byte; End; Procedure MD5Init(Var Context: MD5_CTX); StdCall; Procedure MD5Update(Var Context: MD5_CTX; const Input; inLen: LongWord); StdCall; Procedure MD5Final(Var Context: MD5_CTX); StdCall; function MD5string(const data : Ansistring):AnsiString; function MD5_Selftest:Boolean; // SHA1 type SHA_CTX = packed record Unknown : array[0..5] of LongWord; State : array[0..4] of LongWord; Count : array[0..1] of LongWord; Buffer : array[0..63] of Byte; end; SHA_DIG = packed record Dig : array[0..19] of Byte; end; procedure A_SHAInit(var Context: SHA_CTX); StdCall; procedure A_SHAUpdate(var Context: SHA_CTX; const Input; inlen: LongWord); StdCall; procedure A_SHAFinal(var Context: SHA_CTX; out Digest:SHA_DIG); StdCall; function SHA_Selftest:Boolean; implementation uses SysUtils; const LIB_ADVAPI32 = 'advapi32.dll'; Procedure MD4Init; external LIB_ADVAPI32; Procedure MD4Update; external LIB_ADVAPI32; Procedure MD4Final; external LIB_ADVAPI32; Procedure MD5Init; external LIB_ADVAPI32; Procedure MD5Update; external LIB_ADVAPI32; Procedure MD5Final; external LIB_ADVAPI32; procedure A_SHAInit; external LIB_ADVAPI32; procedure A_SHAUpdate; external LIB_ADVAPI32; procedure A_SHAFinal; external LIB_ADVAPI32; function MD4_Selftest:Boolean; const test : AnsiString = 'Franz jagt im komplett verwahrlosten Taxi quer durch Bayern'; digest_test : array[0..15] of Byte = ( $32,$70,$fd,$28,$f1,$b2,$8c,$d2,$19,$bb,$94,$6b,$d3,$72,$fc,$00 ); var context : MD4_CTX; begin MD4Init(context); MD4Update(context, test[1], Length(test)); MD4Final(context); Result := CompareMem(@context.digest[0], @digest_test, sizeof(digest_test)); end; function MD5string(const data : Ansistring):AnsiString; var ctx : MD5_CTX; begin MD5Init(ctx); MD5Update(ctx, data[1], length(data)); MD5Final(ctx); SetString(Result, PChar(@ctx.digest[0]), 16); end; function MD5_Selftest:Boolean; const test : AnsiString = 'Franz jagt im komplett verwahrlosten Taxi quer durch Bayern'; digest_test : array[0..15] of Byte = ( $a3,$cc,$a2,$b2,$aa,$1e,$3b,$5b,$3b,$5a,$ad,$99,$a8,$52,$90,$74 ); var hash : AnsiString; begin hash := MD5string(test); Result := CompareMem(@hash[1], @digest_test, sizeof(digest_test)); end; function SHA_Selftest:Boolean; const // FIPS PUB 180.1 example A.1 digest_abc : array[0..19] of Byte = ( $a9, $99, $3e, $36, $47, $06, $81, $6a, $ba, $3e, $25, $71, $78, $50, $c2, $6c, $9c, $d0, $d8, $9d ); test : AnsiString = 'abc'; var context: SHA_CTX; digest : SHA_DIG; begin A_SHAInit(context); A_SHAUpdate(context, test[1], Length(test)); A_SHAFinal(context, digest); Result := CompareMem(@digest_abc[0], @digest, sizeof(digest)); end; end.
unit mnSynHighlighterPy; {$mode objfpc}{$H+} {** * * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey https://github.com/jangko/nppPy/blob/master/nppPy.Py https://github.com/saem/vscode-Py/blob/main/snippets/Py.json *} interface uses Classes, SysUtils, SynEdit, SynEditTypes, SynEditHighlighter, SynHighlighterHashEntries, mnSynHighlighterMultiProc; type { TPyProcessor } TPyProcessor = class(TCommonSynProcessor) private protected function GetIdentChars: TSynIdentChars; override; function GetEndOfLineAttribute: TSynHighlighterAttributes; override; procedure Created; override; public procedure QuestionProc; procedure DirectiveProc; procedure SharpProc; procedure DQProc; procedure SQProc; procedure GreaterProc; procedure LowerProc; procedure Next; override; procedure Prepare; override; procedure MakeProcTable; override; end; { TmnSynPySyn } TmnSynPySyn = class(TSynMultiProcSyn) private protected function GetSampleSource: string; override; public class function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; procedure InitProcessors; override; published end; const SYNS_LangPy = 'Py'; SYNS_FilterPy = 'Py Lang Files (*.Py)|*.Py'; cPySample = '#defines function'#13#10+ 'func fact(n: int)'#13#10+ ' return @[10]'#13#10+ ''#13#10; {$INCLUDE 'PyKeywords.inc'} implementation uses mnUtils; procedure TPyProcessor.GreaterProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); if Parent.Peek in ['=', '>'] then Inc(Parent.Run); end; procedure TPyProcessor.LowerProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); case Parent.Peek of '=': Inc(Parent.Run); '<': begin Inc(Parent.Run); if Parent.Peek = '=' then Inc(Parent.Run); end; end; end; procedure TPyProcessor.SharpProc; begin Inc(Parent.Run); CommentSLProc; end; procedure TPyProcessor.DQProc; begin SetRange(rscStringDQ); Inc(Parent.Run); case Parent.Peek of '"': begin if Parent.Peek(1) = '"' then begin Inc(Parent.Run); SpecialStringProc; end else StringProc; end; else StringProc; end; end; procedure TPyProcessor.SQProc; begin SetRange(rscStringSQ); Inc(Parent.Run); case Parent.Peek of '''': begin if Parent.Peek(1) = '''' then begin Inc(Parent.Run); SpecialDocumentMLProc; end else StringProc; end; else StringProc; end; end; procedure TPyProcessor.MakeProcTable; var I: Char; begin inherited; for I := #0 to #255 do case I of '?': ProcTable[I] := @QuestionProc; '''': ProcTable[I] := @SQProc; '"': ProcTable[I] := @DQProc; '#': ProcTable[I] := @SharpProc; '>': ProcTable[I] := @GreaterProc; '<': ProcTable[I] := @LowerProc; '0'..'9': ProcTable[I] := @NumberProc; 'A'..'Z', 'a'..'z', '_': ProcTable[I] := @IdentProc; end; end; procedure TPyProcessor.QuestionProc; begin Inc(Parent.Run); case Parent.Peek of '>': begin Parent.Processors.Switch(Parent.Processors.MainProcessor); Inc(Parent.Run); Parent.FTokenID := tkProcessor; end else Parent.FTokenID := tkSymbol; end; end; procedure TPyProcessor.DirectiveProc; begin Parent.FTokenID := tkProcessor; WordProc; end; procedure TPyProcessor.Next; begin Parent.FTokenPos := Parent.Run; if (Parent.Peek in [#0, #10, #13]) then ProcTable[Parent.Peek] else case Range of rscComment: CommentMLProc; rscDocument: DocumentMLProc; rscSpecialComment: SpecialCommentMLProc; rscSpecialDocument: SpecialDocumentMLProc; rscStringSQ, rscStringDQ, rscStringBQ: StringProc; rscSpecialString: SpecialStringProc; else if ProcTable[Parent.Peek] = nil then UnknownProc else ProcTable[Parent.Peek]; end; end; procedure TPyProcessor.Prepare; begin inherited; EnumerateKeywords(Ord(tkKeyword), sPyKeywords, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkType), sPyTypes, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkValue), sPyValues, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkFunction), sPyFunctions, TSynValidStringChars, @DoAddKeyword); SetRange(rscUnknown); end; function TPyProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes; begin if (Range = rscDocument) or (LastRange = rscDocument) then Result := Parent.DocumentAttri else Result := inherited GetEndOfLineAttribute; end; procedure TPyProcessor.Created; begin inherited Created; CloseSpecialString := '"""'; CloseComment := ''; CloseSpecialDocument := ''''''''; end; function TPyProcessor.GetIdentChars: TSynIdentChars; begin Result := TSynValidStringChars + ['.']; end; constructor TmnSynPySyn.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultFilter := SYNS_FilterPy; end; procedure TmnSynPySyn.InitProcessors; begin inherited; Processors.Add(TPyProcessor.Create(Self, 'Py')); Processors.MainProcessor := 'Py'; Processors.DefaultProcessor := 'Py'; end; class function TmnSynPySyn.GetLanguageName: string; begin Result := 'Py'; end; function TmnSynPySyn.GetSampleSource: string; begin Result := cPySample; end; end.
{$MODE OBJFPC} unit model; interface type Vertexes=record x,y,z:extended; r,g,b,a:extended; end; TSurface=array of Vertexes; TSurfaces=array of TSurface; type TModel=class private sfc:TSurfaces; public constructor Create; procedure LoadFromFile(fnm:string); procedure SaveToFile(fnm:string); property Surfaces:TSurfaces read sfc write sfc; end; implementation constructor TModel.Create; begin SetLength(sfc,0); end; procedure TModel.LoadFromFile(fnm:string); var f:file of extended; len,i,ll,j:longint; t:extended; begin assign(f,fnm); reset(f); read(f,t); len:=round(t); SetLength(sfc,len); for i:=0 to len-1 do begin read(f,t); ll:=round(t); SetLength(sfc[i],ll); for j:=0 to ll-1 do begin read(f,sfc[i][j].x,sfc[i][j].y,sfc[i][j].z, sfc[i][j].r,sfc[i][j].g,sfc[i][j].b,sfc[i][j].a); end; end; close(f); end; procedure TModel.SaveToFile(fnm:string); var f:file of extended; len,i,ll,j:longint; t:extended; begin assign(f,fnm); reset(f); len:=length(sfc); t:=len; write(f,t); for i:=0 to len-1 do begin ll:=length(sfc[i]); t:=ll; write(f,t); for j:=0 to ll-1 do begin write(f,sfc[i][j].x,sfc[i][j].y,sfc[i][j].z, sfc[i][j].r,sfc[i][j].g,sfc[i][j].b,sfc[i][j].a); end; end; close(f); end; end.
Unit MarkdownCommonMarkTests; { Copyright (c) 2011+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses Windows, SysUtils, Classes, {$IFDEF FPC} DUnitFpc {$ELSE}DUnitX.TestFramework {$ENDIF}, Character, ShellApi, Generics.Collections, Json, MarkdownCommonMark; var TestFile : String = 'C:\work\markdown\resources\commonmark\spec.json'; type CommonMarkDownParserTestCaseAttribute = class (CustomTestCaseSourceAttribute) protected function GetCaseInfoArray : TestCaseInfoArray; override; end; [TextFixture] TMarkdownCommonMarkTest = class private function findTest(name : String) : TJSONObject; public [CommonMarkDownParserTestCase] procedure TestCase(Name : String); end; implementation var gTests : TJSONArray = nil; procedure FreeTests; begin gTests.Free; end; function leftPad(s : String; c : char; l :integer) : String; begin result := s; while result.Length < l do insert(c, result, 1); end; { CommonMarkDownParserTestCaseAttribute } function CommonMarkDownParserTestCaseAttribute.GetCaseInfoArray: TestCaseInfoArray; var f : TFileStream; b : TBytes; s : String; i : integer; t : TJSONObject; begin if gTests = nil then begin f := TFileStream.Create(TestFile, fmOpenRead + fmShareDenyWrite); try SetLength(b, f.Size); f.Read(b[0], f.Size); finally f.Free; end; s := TEncoding.UTF8.GetString(b); gTests := TJSONObject.ParseJSONValue(s) as TJSONArray; end; SetLength(result, gTests.Count); for i := 0 to gTests.Count - 1 do begin t := gTests.Items[i] as TJSONObject; result[i].Name := leftPad(t.Values['example'].ToString, '0', 4); SetLength(result[i].Values, 1); result[i].Values[0] := result[i].Name; end; end; { TMarkdownCommonMarkTest } function TMarkdownCommonMarkTest.findTest(name: String): TJSONObject; var v : TJSONValue; o : TJSONObject; begin result := nil; for v in gTests do begin o := v as TJSONObject; if leftPad((o.Values['example'] as TJSONNumber).value, '0', 4) = name then exit(o); end; end; procedure TMarkdownCommonMarkTest.TestCase(name : String); var test : TJSONObject; doc : TCommonMarkDocument; html, exp : String; begin test := findTest(name); writeln(name); doc := TCommonMarkEngine.parse((test.values['markdown'] as TJsonString).value.replace('\n', #10)); try html := TCommonMarkEngine.render(doc); finally doc.Free; end; exp := (test.values['html'] as TJsonString).value.replace('\n', #10); if (test.Values['mode'] = nil) then Assert.isTrue(html = exp); end; initialization TDUnitX.RegisterTestFixture(TMarkdownCommonMarkTest); finalization freeTests; end.
unit evHotSpotProxy; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Everest/evHotSpotProxy.pas" // Начат: 13.07.2011 14:44 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::HotSpots::TevHotSpotProxy // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses nevTools, nevGUIInterfaces, l3CProtoObject, afwInterfaces, l3Interfaces ; type TevHotSpotProxy = class(Tl3CProtoObject, IevMouseMoveHandler, IevHotSpot) private // private fields f_HotSpot : IevHotSpot; protected // realized methods function TransMouseMove(const aView: InevControlView; const aKeys: TevMouseState; out theActiveElement: InevActiveElement): Boolean; {* Собственно реальный MouseMove, передаваемый редактору } function MouseMove(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает перемещение мыши } function LButtonDown(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* Обрабатывает нажатие левой кнопки мыши } function LButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание левой кнопки мыши } function LButtonDoubleClick(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* Обрабатывает двойное нажатие левой кнопки мыши } function RButtonDown(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает нажатие правой кнопки мыши } function RButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание правой конопки мыши } function MButtonDown(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает нажатие колеса мыши } function MButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание колеса мыши } function CanDrag: Boolean; public // realized methods procedure HitTest(const aView: InevControlView; const aState: TafwCursorState; var theInfo: TafwCursorInfo); protected // overridden protected methods procedure ClearFields; override; public // overridden public methods function QueryInterface(const IID: TGUID; out Obj): HResult; override; {* Приводит базовый интерфейс к запрашиваемуму, если это возможно. } protected // protected methods function DoLButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; virtual; function DoLButtonDoubleClick(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; virtual; function DoTransMouseMove(const aView: InevControlView; const aKeys: TevMouseState; out theActiveElement: InevActiveElement): Boolean; virtual; function DoLButtonDown(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; virtual; public // public methods constructor Create(const aHotSpot: IevHotSpot); reintroduce; class function Make(const aHotSpot: IevHotSpot): IevHotSpot; reintroduce; {* Сигнатура фабрики TevHotSpotProxy.Make } end;//TevHotSpotProxy implementation uses SysUtils, l3InterfacesMisc ; // start class TevHotSpotProxy constructor TevHotSpotProxy.Create(const aHotSpot: IevHotSpot); //#UC START# *4E1D77B700A5_4E1D76D101D0_var* //#UC END# *4E1D77B700A5_4E1D76D101D0_var* begin //#UC START# *4E1D77B700A5_4E1D76D101D0_impl* Assert(aHotSpot <> nil); inherited Create; f_HotSpot := aHotSpot; //#UC END# *4E1D77B700A5_4E1D76D101D0_impl* end;//TevHotSpotProxy.Create class function TevHotSpotProxy.Make(const aHotSpot: IevHotSpot): IevHotSpot; var l_Inst : TevHotSpotProxy; begin l_Inst := Create(aHotSpot); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TevHotSpotProxy.DoLButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; //#UC START# *4E1D7BDF01C4_4E1D76D101D0_var* //#UC END# *4E1D7BDF01C4_4E1D76D101D0_var* begin //#UC START# *4E1D7BDF01C4_4E1D76D101D0_impl* Result := f_HotSpot.LButtonUp(aView, Keys); //#UC END# *4E1D7BDF01C4_4E1D76D101D0_impl* end;//TevHotSpotProxy.DoLButtonUp function TevHotSpotProxy.DoLButtonDoubleClick(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; //#UC START# *4E1D7C16028B_4E1D76D101D0_var* //#UC END# *4E1D7C16028B_4E1D76D101D0_var* begin //#UC START# *4E1D7C16028B_4E1D76D101D0_impl* Result := f_HotSpot.LButtonDoubleClick(aView, Keys, Effect); //#UC END# *4E1D7C16028B_4E1D76D101D0_impl* end;//TevHotSpotProxy.DoLButtonDoubleClick function TevHotSpotProxy.DoTransMouseMove(const aView: InevControlView; const aKeys: TevMouseState; out theActiveElement: InevActiveElement): Boolean; //#UC START# *4E1D94EF002C_4E1D76D101D0_var* var l_MMH : IevMouseMoveHandler; //#UC END# *4E1D94EF002C_4E1D76D101D0_var* begin //#UC START# *4E1D94EF002C_4E1D76D101D0_impl* if Supports(f_HotSpot, IevMouseMoveHandler, l_MMH) then try Result := l_MMH.TransMouseMove(aView, aKeys, theActiveElement); finally l_MMH := nil; end//try..finally else Result := false; //#UC END# *4E1D94EF002C_4E1D76D101D0_impl* end;//TevHotSpotProxy.DoTransMouseMove function TevHotSpotProxy.DoLButtonDown(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; //#UC START# *4E1DC2FF02BB_4E1D76D101D0_var* //#UC END# *4E1DC2FF02BB_4E1D76D101D0_var* begin //#UC START# *4E1DC2FF02BB_4E1D76D101D0_impl* Result := f_HotSpot.LButtonDown(aView, Keys, Effect); //#UC END# *4E1DC2FF02BB_4E1D76D101D0_impl* end;//TevHotSpotProxy.DoLButtonDown procedure TevHotSpotProxy.HitTest(const aView: InevControlView; const aState: TafwCursorState; var theInfo: TafwCursorInfo); //#UC START# *48E2622A03C4_4E1D76D101D0_var* //#UC END# *48E2622A03C4_4E1D76D101D0_var* begin //#UC START# *48E2622A03C4_4E1D76D101D0_impl* f_HotSpot.HitTest(aView, aState, theInfo); //#UC END# *48E2622A03C4_4E1D76D101D0_impl* end;//TevHotSpotProxy.HitTest function TevHotSpotProxy.TransMouseMove(const aView: InevControlView; const aKeys: TevMouseState; out theActiveElement: InevActiveElement): Boolean; //#UC START# *48E2638F0358_4E1D76D101D0_var* //#UC END# *48E2638F0358_4E1D76D101D0_var* begin //#UC START# *48E2638F0358_4E1D76D101D0_impl* Result := DoTransMouseMove(aView, aKeys, theActiveElement); //#UC END# *48E2638F0358_4E1D76D101D0_impl* end;//TevHotSpotProxy.TransMouseMove function TevHotSpotProxy.MouseMove(const aView: InevControlView; const Keys: TevMouseState): Boolean; //#UC START# *48E266730188_4E1D76D101D0_var* //#UC END# *48E266730188_4E1D76D101D0_var* begin //#UC START# *48E266730188_4E1D76D101D0_impl* Result := f_HotSpot.MouseMove(aView, Keys); //#UC END# *48E266730188_4E1D76D101D0_impl* end;//TevHotSpotProxy.MouseMove function TevHotSpotProxy.LButtonDown(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; //#UC START# *48E266AA00A4_4E1D76D101D0_var* //#UC END# *48E266AA00A4_4E1D76D101D0_var* begin //#UC START# *48E266AA00A4_4E1D76D101D0_impl* Result := DoLButtonDown(aView, Keys, Effect); //#UC END# *48E266AA00A4_4E1D76D101D0_impl* end;//TevHotSpotProxy.LButtonDown function TevHotSpotProxy.LButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; //#UC START# *48E266C70128_4E1D76D101D0_var* //#UC END# *48E266C70128_4E1D76D101D0_var* begin //#UC START# *48E266C70128_4E1D76D101D0_impl* Result := DoLButtonUp(aView, Keys); //#UC END# *48E266C70128_4E1D76D101D0_impl* end;//TevHotSpotProxy.LButtonUp function TevHotSpotProxy.LButtonDoubleClick(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; //#UC START# *48E266DE026B_4E1D76D101D0_var* //#UC END# *48E266DE026B_4E1D76D101D0_var* begin //#UC START# *48E266DE026B_4E1D76D101D0_impl* Result := DoLButtonDoubleClick(aView, Keys, Effect); //#UC END# *48E266DE026B_4E1D76D101D0_impl* end;//TevHotSpotProxy.LButtonDoubleClick function TevHotSpotProxy.RButtonDown(const aView: InevControlView; const Keys: TevMouseState): Boolean; //#UC START# *48E266FB01FC_4E1D76D101D0_var* //#UC END# *48E266FB01FC_4E1D76D101D0_var* begin //#UC START# *48E266FB01FC_4E1D76D101D0_impl* Result := f_HotSpot.RButtonDown(aView, Keys); //#UC END# *48E266FB01FC_4E1D76D101D0_impl* end;//TevHotSpotProxy.RButtonDown function TevHotSpotProxy.RButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; //#UC START# *48E267150266_4E1D76D101D0_var* //#UC END# *48E267150266_4E1D76D101D0_var* begin //#UC START# *48E267150266_4E1D76D101D0_impl* Result := f_HotSpot.RButtonUp(aView, Keys); //#UC END# *48E267150266_4E1D76D101D0_impl* end;//TevHotSpotProxy.RButtonUp function TevHotSpotProxy.MButtonDown(const aView: InevControlView; const Keys: TevMouseState): Boolean; //#UC START# *49DB4675025E_4E1D76D101D0_var* //#UC END# *49DB4675025E_4E1D76D101D0_var* begin //#UC START# *49DB4675025E_4E1D76D101D0_impl* Result := f_HotSpot.MButtonDown(aView, Keys); //#UC END# *49DB4675025E_4E1D76D101D0_impl* end;//TevHotSpotProxy.MButtonDown function TevHotSpotProxy.MButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; //#UC START# *49DB468302A5_4E1D76D101D0_var* //#UC END# *49DB468302A5_4E1D76D101D0_var* begin //#UC START# *49DB468302A5_4E1D76D101D0_impl* Result := f_HotSpot.MButtonUp(aView, Keys); //#UC END# *49DB468302A5_4E1D76D101D0_impl* end;//TevHotSpotProxy.MButtonUp function TevHotSpotProxy.CanDrag: Boolean; //#UC START# *4ECCD6840014_4E1D76D101D0_var* //#UC END# *4ECCD6840014_4E1D76D101D0_var* begin //#UC START# *4ECCD6840014_4E1D76D101D0_impl* Result := True; //#UC END# *4ECCD6840014_4E1D76D101D0_impl* end;//TevHotSpotProxy.CanDrag function TevHotSpotProxy.QueryInterface(const IID: TGUID; out Obj): HResult; //#UC START# *47A0AD3A01F7_4E1D76D101D0_var* //#UC END# *47A0AD3A01F7_4E1D76D101D0_var* begin //#UC START# *47A0AD3A01F7_4E1D76D101D0_impl* Result := inherited QueryInterface(IID, Obj); if l3IFail(Result) then Result := f_HotSpot.QueryInterface(IID, Obj); //#UC END# *47A0AD3A01F7_4E1D76D101D0_impl* end;//TevHotSpotProxy.QueryInterface procedure TevHotSpotProxy.ClearFields; {-} begin f_HotSpot := nil; inherited; end;//TevHotSpotProxy.ClearFields end.
unit Base.Def; interface Uses System.SysUtils, Vcl.Forms; {$REGION '-># Header'} type sHeader = Record Size: Word; Key: Byte; ChkSum: Byte; Code: Word; Index: Word; Time: LongWord; end; {$ENDREGION} {$REGION '-># 20D - Login : Tentativa'} type p20D = Record Header: sHeader; Pass: array [0 .. 9] of Byte; Inu: Word; ID: array [0 .. 11] of Byte; End; {$ENDREGION} {$REGION '-># Header DB'} Type sHeaderDB = Record cod: Word; clientid: Word; end; {$ENDREGION} {$REGION '-># solicitação de login'} Type p20DDB = Record Header: sHeaderDB; Pass: array [0 .. 9] of Byte; ID: array [0 .. 11] of Byte; end; {$ENDREGION} {$REGION '-># Cliente Online'} type ClientOn = Record Handle: Cardinal; Conect: Word; ActiveChar: Byte; StatusChar: Word; // Mapa que o jogador esta | 0 Numerica 1 Charlist 2 Kersef // SubCharStatus : byte; CharSpawn: array [0 .. 65000] of Boolean; // Outro personagem em seu visual // Group: tGroup; // Diz quem é o lider e membros do grupo LastPM: Array [0 .. 11] of Byte; // Nome de quem mandou o ultimo pm LastHeader: sHeader; // checa se o ultimo head é igual, se for, deixa conta em analise Summon: Word; // Skill teleporte FM usa esse para ver se pode teleportar Invisible: Byte; // Registra se tem invisibilidade da HT BlockAntSpeed: Byte; // conta quantos atks em 1 segundos, 10 atk = DC End; {$ENDREGION} {$REGION '# ITEM '} type sItem = Record Index: Word; EF1, EFV1: Byte; EF2, EFV2: Byte; EF3, EFV3: Byte; end; {$ENDREGION} {$REGION '# sQuest - Diarias/unicas'} type sQuest = Record CristalArch: Byte; // Dia de conclusão Pill: Byte; // Dia de conclusão ChanceComp: Boolean; BalanceComp: Boolean; Amulets: Boolean; Molar: Boolean; Cube: Byte; // Dia de conclusão CrazyLetter: Byte; // Dia de conclusão CrazyMail: Byte; // Dia de conclusão aDefine: array [0 .. 500] of Byte; // 501 bytes para criar missões depois End; {$ENDREGION} {$REGION '# sMissao - Contador de mobs para uma missão especifica'} type sQuest2 = Record QuestID: Word; Amount: Byte; End; {$ENDREGION} {$REGION '# BaseStatus '} type sStatusBase = Record Str, Int: Word; Dex, Con: Word; wMaster: Word; fMaster: Word; sMaster: Word; tMaster: Word; End; {$ENDREGION} {$REGION '# sStatus '} type sStatus = Record // 48 Level: Cardinal; Defence: Cardinal; Attack: Cardinal; Merchant: Byte; Speed: Byte; Inu1: Byte; Inu2: Byte; MaxHP, MaxMP: Cardinal; // integer HP, MP: Cardinal; // integer Str, Int: Word; // smallint Dex, Con: Word; // smallint wMaster: Word; fMaster: Word; sMaster: Word; tMaster: Word; End; {$ENDREGION} {$REGION '# sPontos - pontos para add no sStatus / Habilidades / Comprar Skill'} type sPoint = Record Abiliity: Word; // smallint Learning: Word; Skill: Word; // smallint End; {$ENDREGION} {$REGION '# sResistencia - Resistências dos personagens'} type sResistance = Record Fire: Byte; Ice: Byte; Sacred: Byte; Thunder: Byte; End; {$ENDREGION} {$REGION ' Buffs e Debuffs'} Type sBuffsControl = Record ID: Word; Amount: Word; Time: Cardinal; End; // cBuffs Buffs que ficam na estrutura do jogador Type sBuffs = Record ID: Word; Amount: Word; Time: Cardinal; End; {$ENDREGION} {$REGION '# Personagem'} type sCharacter = Record Name: array [0 .. 11] of Byte; // 12 caracteres Status: sStatus; bStatus: sStatusBase; _Class: Byte; // 0~3 PosX: Word; PosY: Word; GemX: Word; GemY: Word; Point: sPoint; // Pontos para add habilidades Critical: Byte; // 1 = 0.4% - 255 = 102% skillbar1to4: Array [0 .. 3] of Byte; // 4 SkillBar5to20: array [4 .. 19] of Byte; // 16 - ok MagicAttack: Word; // 1 - ok Resistence: sResistance; // 4 - ok Equip: Array [0 .. 15] of sItem; EquipColor: array [0 .. 15] of Byte; Bag: Array [0 .. 62] of sItem; Gold: Cardinal; // integer Exp: Cardinal; // Int 64 GuildIndex: Word; Learn: Cardinal; Learn2: Cardinal; Cp: Byte; // 0 Pisca em vermelho | 1 - 30 PK | 36.000 = 1 SecondsPK: Word; aAbs: Word; aPerfu: Word; aExp: Word; aDrop: Word; DailyQuest: sQuest; Quest: sQuest2; TimeBoxExp: Word; Tab: Array [0 .. 19] of Byte; Range: Byte; Buffs: Array [0 .. 31] of sBuffs; City: Byte; SkillReceived: Array [0 .. 42] of Byte; end; {$ENDREGION} {$REGION '# Jogador'} Type sPlayer = Record ID_ACC: Cardinal; User: String[12]; Pass: String[32]; Numeric: String[6]; NumericError: Byte; // errar 3 numericas = conta em restauro Online: Byte; // 0 offline 1 e 2 Errou senha 3 Bloqueio efetuado 4 online 5 Analise 6 banida 7 Precisa Restaurar Bank: array [0 .. 119] of sItem; BankGold: Cardinal; Character: Array [0 .. 3] of sCharacter; End; Type sPlayerDB = Record ID_ACC: Cardinal; User: String[12]; Pass: String[32]; Numeric: String[6]; NumericError: Byte; // errar 3 numericas = conta em restauro Online: Byte; // 0 offline 1 e 2 Errou senha 3 Bloqueio efetuado 4 online 5 Analise 6 banida 7 Precisa Restaurar Bank: array [0 .. 119] of sItem; BankGold: Cardinal; Character: Array [0 .. 3] of sCharacter; End; {$ENDREGION} {$REGION '# Envia a conta aos canais'} Type sLoadedAcc = Record Header: sHeaderDB; Player: sPlayer; end; {$ENDREGION} {$REGION '# solicitação create char'} Type p20FDB = Record Header: sHeaderDB; char: Cardinal; Name: array [0 .. 11] of Byte; _Class: Byte; end; {$ENDREGION} {$REGION '# 10A - Login : Charlist'} type p10A = Record Header: sHeader; // 12 Inu1: array [0 .. 19] of Byte; // 20 bytes até entao random PosX: array [0 .. 3] of Word; // Pos X PosY: array [0 .. 3] of Word; // Pos Y Name: array [0 .. 3] of array [0 .. 15] of Byte; // Nomes Status: array [0 .. 3] of sStatus; // Status Equip: array [0 .. 3] of array [0 .. 15] of sItem; // Equipamentos GuildIndex: array [0 .. 3] of Word; // Clã Gold: array [0 .. 3] of Cardinal; // Gold Exp: array [0 .. 3] of Cardinal; // test exp Inu2: array [0 .. 3] of Cardinal; // inutil Bank: array [0 .. 119] of sItem; // End; {$ENDREGION} {$REGION '# 110 - CharCreat'} type p110 = Record Header: sHeader; // 12 Inu1: Cardinal; // PosX: array [0 .. 3] of Word; // 8 PosY: array [0 .. 3] of Word; // 8 Name: array [0 .. 3] of array [0 .. 15] of Byte; // 64 Status: array [0 .. 3] of sStatus; // 112 Equipe: array [0 .. 3] of array [0 .. 15] of sItem; // 512 GuildIndex: array [0 .. 3] of Word; // 8 Gold: array [0 .. 3] of Cardinal; // 16 Exp: array [0 .. 3] of Cardinal; // 32 Inu2: array [0 .. 3] of Cardinal; // inutil End; {$ENDREGION} {$REGION '# 101 - Mensagem'} type p101 = Record Header: sHeader; menssagem: String[95]; End; {$ENDREGION} {$REGION '# Guarda a numérica vinda do Mysql para enviar ao canal'} Type sPlayerBase = Record User: String[12]; Numeric: String[6]; NumericError: Byte; // errar 3 numericas = reset senha Online: Byte; // 0 offline 1 e 2 Errou senha 3 Bloqueio efetuado 4 online 5 Analise 6 banida 7 Precisa Restaurar end; {$ENDREGION} {$REGION '# FDE - Numerica'} Type pFDE = Record Header: sHeader; Pass: Array [0 .. 5] of Byte; End; {$ENDREGION} {$REGION '# 20F - CharList : Solicita Create Char'} type p20F = Record Header: sHeader; char: Cardinal; Name: array [0 .. 11] of Byte; inutil: integer; // char so pode ter 12 caracteres _Class: Byte; End; {$ENDREGION} {$REGION '# Recebe as contas dos canais para salvar'} Type sAccountSave = Record Header: sHeaderDB; StatusOnline: Byte; NumericError: Byte; Player: sPlayer; end; {$ENDREGION} {$REGION '# 213 - RequestSend To World'} type p213 = Record Header: sHeader; // 12 Character: Cardinal; // 4 End; {$ENDREGION} {$REGION '# [X] MOB' } Type sCoord = Record PosX, PosY: Word; End; Type sTarget = Record AttackReceive: Boolean; Damage: Array [1 .. 1999] of Word; End; type sSkill = Record Skill: Word; Area: Byte; End; Type sMob = Record Header: sHeader; // 12 index = clientid PosX: Word; PosY: Word; Index: Word; Name: array [0 .. 15] of Byte; Equip: array [0 .. 15] of Word; Buffs: Array [0 .. 31] of Word; GuildIndex: Word; Inu1: Cardinal; Status: sStatus; SpawnType: Word; // 2 : 0 - normal 2 - Nascendo 3- Teleportando 16- pos1 32 - post2 EquipColor: array [0 .. 15] of Byte; // 16 Tab: array [0 .. 25] of Byte; // 26 Inu2: Cardinal; // Fim do pacote 364 Spanw Generate: Cardinal; // segundos para nascer - 0 nao nasce automatico Npc: Boolean; // NPC ou mOB MovementType: Byte; // byte fixo aleatorio seguir predefinido MovementInfo: Word; // aleatorio=quantos pontos mover seguir=id para ir atraz pre-definido=qual dos movimentos Route: Array [0 .. 5] of sCoord; Target: sTarget; // alvos que estao atacando e seus danos Perfu: Word; Abs: Word; DropList: Word; Resistence: Byte; // 4 - ok Skills: Array [0 .. 9] of sSkill; End; {$ENDREGION} {$REGION '# 165 - MobDelete'} Type p165 = Record Header: sHeader; // index alvo _Type: Cardinal; // { 0 - desaparece 1 - ação morto 2 - luz azul e some em 5s 3++ - teleport amarelo } End; {$ENDREGION} {$REGION '# [X] Itemlist'} type sItemList = Record Name: String[65]; Level: Word; Str: Word; Int: Word; Dex: Word; Con: Word; Price: Cardinal; Position: Word; Grade: Byte; Add: Array [0 .. 110] of Word; end; {$ENDREGION} {$REGION '# Log DB'} Type sLogDB = Record Header: sHeaderDB; MSG: String[250]; end; {$ENDREGION} implementation end.
unit Model.VerbaFixa; interface type TVerbaFixa = Class private var FId: System.Integer; FGrupo: System.Integer; FData: System.TDate; FDescricao: System.string; FValor: System.Double; FAtivo: System.Integer; FLog: System.string; public property ID: System.Integer read FId write FId; property Grupo: System.Integer read FGrupo write FGrupo; property Data: System.TDate read FData write FData; property Descricao: System.string read FDescricao write FDescricao; property Valor: System.Double read FValor write FValor; property Ativo: System.Integer read FAtivo write FAtivo; property Log: System.string read FLog write FLog; constructor Create; overload; constructor Create(pFId: System.Integer; pFGrupo: System.Integer; pFData: System.TDate; pFDescricao: System.string; pFValor: System.Double; pFAtivo: System.Integer; pFLog: System.string); overload; end; implementation constructor TVerbaFixa.Create; begin Inherited Create; end; constructor TVerbaFixa.Create(pFId: System.Integer; pFGrupo: System.Integer; pFData: System.TDate; pFDescricao: System.string; pFValor: System.Double; pFAtivo: System.Integer; pFLog: System.string); begin FId := pFId; FGrupo := pFGrupo; FData := pFData; FDescricao := pFDescricao; FValor := pFValor; FAtivo := pFAtivo; FLog := pFLog; end; end.
unit uHero; interface uses Types, uPathFind; const WalkTickTrigger = 3; type THero = class private FPos: TPoint; FTicks: Cardinal; FPath: TPath; FPathMap: TPathMap; FPathMapStart: TPoint; FCurPathCellIdx: Integer; FIsMoving: Boolean; FDest: TPoint; function GetPath(Index: Integer): TPoint; procedure SetCurPathCellIdx(const Value: Integer); procedure SetPath(const Value: TPath); function GetPathLen: Integer; function GetIsValidPath: Boolean; function GetIsFinished: Boolean; procedure SetDest(const Value: TPoint); protected procedure Step(); function MovingCost (X, Y, Direction: Integer): Integer; property ThePath: TPath read FPath write SetPath; property CurPathCellIdx: Integer read FCurPathCellIdx write SetCurPathCellIdx; property Dest: TPoint read FDest write SetDest; public constructor Create(APos: TPoint); overload; constructor Create(AX, AY: Byte); overload; destructor Destroy; property Pos: TPoint read FPos write FPos; procedure Update(); function SearchPath(ADest: TPoint): Boolean; procedure ProceedPath(ADest: TPoint); procedure StartMove; property IsMoving: Boolean read FIsMoving; property Path[Index: Integer]: TPoint read GetPath; property PathLen: Integer read GetPathLen; property IsValidPath: Boolean read GetIsValidPath; property IsFinished: Boolean read GetIsFinished; end; var Hero: THero; implementation uses uUtils, uMap, uSceneGame; { THero } constructor THero.Create(APos: TPoint); begin Pos := APos; end; constructor THero.Create(AX, AY: Byte); begin Create(Point(AX, AY)); end; destructor THero.Destroy; begin end; function THero.GetIsFinished: Boolean; begin Result := CurPathCellIdx = PathLen - 1; end; function THero.GetIsValidPath: Boolean; begin Result := (PathLen > 0); end; function THero.GetPath(Index: Integer): TPoint; begin Result := Point(-1, -1); if not IsValidPath or ((Index >= 0) and (Index > PathLen)) or ((Index < 0) and (PathLen + Index {negative value} < 0)) then Exit; if Index < 0 then Result := FPath[PathLen + Index] else Result := FPath[Index]; end; function THero.GetPathLen: Integer; begin Result := Length(ThePath); end; function THero.MovingCost(X, Y, Direction: Integer): Integer; var I : Integer; Pt: TPoint; begin Result := -1; Pt := Point(X, Y); if ((Map.FMap[Y, X, lrObj] >= 0) and not EqualPoints(pt, Dest)) or ((SceneGame.IsMapCreature(X, Y) >= 0) and not EqualPoints(pt, Dest, AggrZone)) then Exit; // cost of terrain if (Map.FMap[Y][X][lrTerrain] in GroundSet) then Result := 2 else Result := 5; if (Direction and 1 > 0) then // 150% cost for diagonal Inc(Result, Result div 2); end; procedure THero.ProceedPath(ADest: TPoint); begin if IsValidPath and not IsMoving then if EqualPoints(Dest, ADest) then StartMove else SearchPath(ADest); if not IsValidPath or IsFinished then SearchPath(ADest); end; function THero.SearchPath(ADest: TPoint): Boolean; begin Dest := ADest; if not EqualPoints(FPathMapStart, FPos) or (Length(FPathMap) = 0) then FPathMap := MakePathMap(Map.Width, Map.Height, FPos.X, FPos.Y, MovingCost); ThePath := FindPathOnMap(FPathMap, ADest.X, ADest.Y); end; procedure THero.SetCurPathCellIdx(const Value: Integer); begin FCurPathCellIdx := Value; Map.SetPath(Path[CurPathCellIdx], lrNone); end; procedure THero.SetDest(const Value: TPoint); begin FDest := Value; end; procedure THero.SetPath(const Value: TPath); var I: Integer; begin for I := CurPathCellIdx to PathLen - 1 do Map.SetPath(Path[i], lrNone); FPath := Value; if not IsValidPath then CurPathCellIdx := -1 else CurPathCellIdx := 0; for I := CurPathCellIdx + 1 to PathLen - 1 do Map.SetPath(Path[i], 1); end; procedure THero.StartMove; begin FIsMoving := True; end; procedure THero.Step(); begin if not IsValidPath or not IsMoving then Exit; if IsFinished then begin FIsMoving := False; Exit; end; CurPathCellIdx := CurPathCellIdx + 1; Pos := Path[CurPathCellIdx]; end; procedure THero.Update(); begin Inc(FTicks); if FTicks mod WalkTickTrigger = 0 then Step(); end; initialization Hero := THero.Create(0, 0); finalization Hero.Free; end.
unit DropTarget; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DragDrop; type TDragDropTarget = class( TComponent ) protected fDropTarget : TDropTarget; fTargetControl : TWinControl; function GetOnFileDropped : TFileDroppedEvent; procedure SetOnFileDropped( Handler : TFileDroppedEvent ); function GetOnFileListDropped : TFileListDroppedEvent; procedure SetOnFileListDropped( Handler : TFileListDroppedEvent ); function GetAcceptOnlyOneFile : boolean; procedure SetAcceptOnlyOneFile( flag : boolean ); procedure AttachTo( aControl : TWinControl ); virtual; published property TargetControl : TWinControl read fTargetControl write AttachTo; property OnFileDropped : TFileDroppedEvent read GetOnFileDropped write SetOnFileDropped; property OnFileListDropped : TFileListDroppedEvent read GetOnFileListDropped write SetOnFileListDropped; property AcceptOnlyOneFile : boolean read GetAcceptOnlyOneFile write SetAcceptOnlyOneFile default false; public constructor Create( anOwner : TComponent ); override; destructor Destroy; override; end; // Component registration procedure Register; implementation {$R *.dcr} procedure TDragDropTarget.AttachTo( aControl : TWinControl ); var bakAcceptOnlyOneFile : boolean; bakOnFileDropped : TFileDroppedEvent; bakOnFileListDropped : TFileListDroppedEvent; begin if aControl <> nil then fTargetControl := aControl else fTargetControl := TWinControl( Owner ); bakAcceptOnlyOneFile := AcceptOnlyOneFile; bakOnFileDropped := OnFileDropped; bakOnFileListDropped := OnFileListDropped; fDropTarget.Free; fDropTarget := TDropTarget.Create( fTargetControl.Handle ); with fDropTarget do begin AcceptOnlyOneFile := bakAcceptOnlyOneFile; OnFileDropped := bakOnFileDropped; OnFileListDropped := bakOnFileListDropped; end; end; constructor TDragDropTarget.Create( anOwner : TComponent ); begin inherited; AttachTo( Owner as TWinControl ); end; destructor TDragDropTarget.Destroy; begin fDropTarget.Free; inherited; end; function TDragDropTarget.GetAcceptOnlyOneFile : boolean; begin if Assigned( fDropTarget ) then Result := fDropTarget.AcceptOnlyOneFile else Result := false; end; procedure TDragDropTarget.SetAcceptOnlyOneFile( flag : boolean ); begin if Assigned( fDropTarget ) then fDropTarget.AcceptOnlyOneFile := flag; end; function TDragDropTarget.GetOnFileDropped : TFileDroppedEvent; begin if Assigned( fDropTarget ) then Result := fDropTarget.OnFileDropped else Result := nil; end; procedure TDragDropTarget.SetOnFileDropped( Handler : TFileDroppedEvent ); begin if Assigned( fDropTarget ) then fDropTarget.OnFileDropped := Handler; end; function TDragDropTarget.GetOnFileListDropped : TFileListDroppedEvent; begin if Assigned( fDropTarget ) then Result := fDropTarget.OnFileListDropped else Result := nil; end; procedure TDragDropTarget.SetOnFileListDropped( Handler : TFileListDroppedEvent ); begin if Assigned( fDropTarget ) then fDropTarget.OnFileListDropped := Handler; end; // Component registration procedure Register; begin RegisterComponents( 'Merchise', [TDragDropTarget] ); end; end.
(***************************************************************************; * * Modyfied: 20.7.98 * * Download: http://www.bigfoot.com/~ungerik/ * E-Mail: ungerik@bigfoot.com * ***************************************************************************) unit DXTools; interface uses Windows, SysUtils, Graphics, DirectDraw, Direct3D; const UnrecognizedError = 'Unrecognized Error'; NoError = 'No error'; // This string is displayed when an EDirectX exception occurs: var DXStat : string; Exceptions : boolean; type PTrueColor = ^TTrueColor; TTrueColor = record case integer of 1 : (Data : DWORD); 2 : (R,G,B,A : byte); end; PColorTable = ^TColorTable; TColorTable = array [0..255] of TTrueColor; TSingleQuadruppel = array[0..4-1] of single; EDirectX = class (Exception) public constructor Create(Error: integer); end; const IdentityMatrix : TD3DMatrix = ( _11: 1; _12: 0; _13: 0; _14: 0; _21: 0; _22: 1; _23: 0; _24: 0; _31: 0; _32: 0; _33: 1; _34: 0; _41: 0; _42: 0; _43: 0; _44: 1 ); ZeroMatrix : TD3DMatrix = ( _11: 0; _12: 0; _13: 0; _14: 0; _21: 0; _22: 0; _23: 0; _24: 0; _31: 0; _32: 0; _33: 0; _34: 0; _41: 0; _42: 0; _43: 0; _44: 0 ); type PMatrix1D = ^TMatrix1D; TMatrix1D = record case integer of 0 : (D3DVector: TD3DVector); 1 : (D3DColorValue: TD3DColorValue); 2 : (a: array [0..4-1] of TD3DValue); end; PMatrix4D = ^TMatrix4D; TMatrix4D = record case integer of 0 : (D3DMatrix: TD3DMatrix); 1 : (a: array [0..4*4-1] of TD3DValue); end; // Camera settings for Direct3D: function ProjectionMatrix(near_plane, // distance to near clipping plane far_plane, // distance to far clipping plane fov: TD3DValue) : TD3DMatrix; // field of view angle, // in radians // Camera positioning for Direct3D: function ViewMatrix(from, // camera location at, // camera look-at target world_up: TD3DVector; // world's up, usually 0, 1, 0 roll: TD3DValue) : TD3DMatrix; // clockwise roll around // viewing direction, // in radians function TransformationYZ(y, z: TD3DVector) : TD3DMatrix; function TranslateMatrix(dx, dy, dz: TD3DValue) : TD3DMatrix; function RotateXMatrix(rads: TD3DValue) : TD3DMatrix; function RotateYMatrix(rads: TD3DValue) : TD3DMatrix; function RotateZMatrix(rads: TD3DValue) : TD3DMatrix; function ScaleMatrix(size: TD3DValue) : TD3DMatrix; function MatrixMul(const a, b: TD3DMatrix) : TD3DMatrix; // Fills a DirectX-record with zero and sets the size in the first DWORD: procedure InitRecord(var DXRecord; Size: integer); // Computes the brightness of a RGB-color: function GetBrightness(Red,Green,Blue: TD3DValue) : TD3DValue; procedure SetBrightness(var Red,Green,Blue: TD3DValue; Brightness: TD3DValue); // Releases an Object (initialised or not) and sets the pointer to nil: function ReleaseObj(var Obj) : boolean; // Releases an Delphi2 or 3 COM-interface (initialised or not) and sets the pointer to nil: function ReleaseCOM(var COM) : boolean; // Releases an initialised Delphi2 or 3 COM-interface and sets the pointer to nil: procedure ReleaseCOMe(var COM); // Increases the reference-counter of an Delphi2 or 3 COM-interface function AddCOM(const COM) : IUnknown; // Computes the bounding box of an retained mode frame: procedure SM(Message: string); // Loads colorpalette-data from a Paint Shop Pro file: function LoadPaletteFromJASCFile(Filename: string; var Palette: TColorTable) : boolean; // Fills a DirectDraw suface with black (0): procedure ClearSurface(Surface: IDirectDrawSurface; Color: integer); // Finds out, how many bit per pixel of a TBitmap are used: function GetBitsPerPixelFromBitmap(Bitmap: Graphics.TBitmap) : integer; // Delivers an interface for the default DirectDraw2 Object: function GetDefaultDirectDraw2 : IDirectDraw2; // Delivers an interface for the primary DirectDraw2 Object: function GetFirstDirectDraw2 : IDirectDraw2; // Delivers an interface for the secondary DirectDraw2 Object: function GetSecondDirectDraw2 : IDirectDraw2; procedure ReadOnlyProperty; procedure NotReady; // Error handling: function DXErrorString(Value: HResult) : string; // Checks a Direct3D returnvalue for an error, // and raises an EDirect3D exception if necessary: procedure D3DCheck(Value: HResult); // Checks a DirectDraw returnvalue for an error, // and raises an EDirectDraw exception if necessary: procedure DDCheck(Value: HResult); // Checks a DirectInput returnvalue for an error, // and raises an EDirectInput exception if necessary: procedure DICheck(Value: HResult); // Checks a DirectPlay returnvalue for an error, // and raises an EDirectPlay exception if necessary: procedure DPCheck(Value: HResult); // Checks a DirectSound returnvalue for an error, // and raises an EDirectSound exception if necessary: procedure DSCheck(Value: HResult); // Checks a DirectSetup returnvalue for an error, // and raises an EDirectSetup exception if necessary: procedure DSetupCheck(Value: HResult); // Checks a DirectSetup returnvalue for an error, // and raises an EDirectSetup exception if necessary: procedure DXFCheck(Value: HResult); // Checks a DirectX returnvalue for an error, // and raises an EDirectX exception if necessary: procedure DXCheck(Value: HResult); function D3DVECTOR( x, y, z : TD3DValue ) : TD3DVECTOR; function D3DVERTEX( v, n : TD3DVector; _u, _v : TD3DValue ) : TD3DVERTEX; implementation //////////////////////////////////////////////////////////////////////////////// // DXTools //////////////////////////////////////////////////////////////////////////////// function GetDefaultDirectDraw2 : IDirectDraw2; var DD : IDirectDraw; begin Result := nil; DD := nil; try DDCheck( DirectDrawCreate(nil,DD,nil) ); DDCheck( DD.QueryInterface(IDirectDraw2,Result) ); finally ReleaseCOM(DD); end; end; function GetFirstDirectDraw2_DDEnumCallback (lpGUID: PGUID; lpDriverDescription: LPSTR; lpDriverName: LPSTR; lpContext: pointer) : BOOL; stdcall; begin Result := True; PGUID(lpContext^) := lpGUID; if Assigned(lpGUID) then Result := False; end; function GetFirstDirectDraw2 : IDirectDraw2; var DD : IDirectDraw; GUID : PGUID; begin Result := nil; DD := nil; GUID := nil; try DDCheck( DirectDrawEnumerateA(GetFirstDirectDraw2_DDEnumCallback,@GUID) ); DDCheck( DirectDrawCreate(GUID,DD,nil) ); DDCheck( DD.QueryInterface(IDirectDraw2,Result) ); finally ReleaseCOM(DD); end; end; function GetSecondDirectDraw2_DDEnumCallback (lpGUID: PGUID; lpDriverDescription: LPSTR; lpDriverName: LPSTR; lpContext: pointer) : BOOL; stdcall; begin Result := True; if Assigned(pointer(lpContext^)) then Result := False; PGUID(lpContext^) := lpGUID; end; function GetSecondDirectDraw2 : IDirectDraw2; var DD : IDirectDraw; GUID : PGUID; begin Result := nil; DD := nil; GUID := nil; try DDCheck( DirectDrawEnumerateA(GetSecondDirectDraw2_DDEnumCallback,@GUID) ); if not Assigned(GUID) then exit; DDCheck( DirectDrawCreate(GUID,DD,nil) ); DDCheck( DD.QueryInterface(IDirectDraw2,Result) ); finally ReleaseCOM(DD); end; end; function ArcTan2(Y, X: Extended): Extended; asm FLD Y FLD X FPATAN FWAIT end; function TransformationYZ(y, z: TD3DVector) : TD3DMatrix; var ret : TD3DMatrix; begin with y do if X <> 0.0 then ret := RotateZMatrix( ArcTan2(Y,X) ) else ret := IdentityMatrix; with z do if Z <> 0.0 then ret := MatrixMul(ret, RotateYMatrix( ArcTan2(X,Z) )); with y do if Z <> 0.0 then ret := MatrixMul(ret, RotateXMatrix( ArcTan2(Y,Z) )); Result := ret; end; function ProjectionMatrix(near_plane, // distance to near clipping plane far_plane, // distance to far clipping plane fov: TD3DValue) : TD3DMatrix; // field of view angle, in radians var c, s, Q : TD3DValue; begin c := cos(fov*0.5); s := sin(fov*0.5); Q := s/(1.0 - near_plane/far_plane); Result := ZeroMatrix; Result._11 := c; Result._22 := c; Result._33 := Q; Result._43 := -Q*near_plane; Result._34 := s; end; function TranslateMatrix(dx, dy, dz: TD3DValue) : TD3DMatrix; begin Result := IdentityMatrix; Result._41 := dx; Result._42 := dy; Result._43 := dz; end; function RotateXMatrix(rads: TD3DValue) : TD3DMatrix; var cosine, sine : TD3DValue; begin cosine := cos(rads); sine := sin(rads); Result := IdentityMatrix; Result._22 := cosine; Result._33 := cosine; Result._23 := -sine; Result._32 := sine; end; function RotateYMatrix(rads: TD3DValue) : TD3DMatrix; var cosine, sine : TD3DValue; begin cosine := cos(rads); sine := sin(rads); Result := IdentityMatrix; Result._11 := cosine; Result._33 := cosine; Result._13 := sine; Result._31 := -sine; end; function RotateZMatrix(rads: TD3DValue) : TD3DMatrix; var cosine, sine : TD3DValue; begin cosine := cos(rads); sine := sin(rads); Result := IdentityMatrix; Result._11 := cosine; Result._22 := cosine; Result._12 := -sine; Result._21 := sine; end; function ScaleMatrix(size: TD3DValue) : TD3DMatrix; begin Result := IdentityMatrix; Result._11 := size; Result._22 := size; Result._33 := size; end; function ViewMatrix(from, // camera location at, // camera look-at target world_up: TD3DVector; // world's up, usually 0, 1, 0 roll: TD3DValue) : TD3DMatrix; // clockwise roll around // viewing direction, // in radians var up, right, view_dir : TD3DVector; begin Result := IdentityMatrix; view_dir := VectorNormalize(VectorSub(at,from)); right := VectorCrossProduct(world_up, view_dir); up := VectorCrossProduct(view_dir, right); right := VectorNormalize(right); up := VectorNormalize(up); Result._11 := right.x; Result._21 := right.y; Result._31 := right.z; Result._12 := up.x; Result._22 := up.y; Result._32 := up.z; Result._13 := view_dir.x; Result._23 := view_dir.y; Result._33 := view_dir.z; Result._41 := -VectorDotProduct(right, from); Result._42 := -VectorDotProduct(up, from); Result._43 := -VectorDotProduct(view_dir, from); if roll <> 0.0 then // MatrixMult function shown below Result := MatrixMul(RotateZMatrix(-roll), TD3DMatrix(Result)); end; // Multiplies two matrices. function MatrixMul(const a, b: TD3DMatrix) : TD3DMatrix; var i,j,k : integer; begin Result := ZeroMatrix; for i := 0 to 3 do for j := 0 to 3 do for k := 0 to 3 do Result.m[i,j] := Result.m[i,j] + (a.m[k,j] * b.m[i,k]); end; function GetBitsPerPixelFromBitmap(Bitmap: Graphics.TBitmap) : integer; var bm : Windows.TBitmap; begin if GetObject(Bitmap.Handle, sizeof(bm), @bm) = 0 then Result := 0 else Result := bm.bmBitsPixel; end; procedure InitRecord(var DXRecord; Size: integer); begin ZeroMemory(@DXRecord,Size); DWORD(DXRecord) := Size; end; function GetDDFromDevice2(Device2: IDirect3DDevice2) : IDirectDraw; var DirectDraw : IDirectDraw; Target : IDirectDrawSurface; Target2 : IDirectDrawSurface2; begin DirectDraw := nil; Target := nil; Target2 := nil; try // get the render target (we need it to get the IDirectDraw) DxCheck( Device2.GetRenderTarget(Target) ); // get the DirectDraw object, but first we need a IDirectDrawSurface2 DxCheck( Target.QueryInterface(IDirectDrawSurface2,Target2) ); DxCheck( Target2.GetDDInterface(DirectDraw) ); finally ReleaseCOM( Target ); ReleaseCOM( Target2 ); Result := DirectDraw; end end; procedure ReadOnlyProperty; begin if Exceptions then Exception.Create('Property is Read-Only !'); end; procedure NotReady; begin if Exceptions then Exception.Create('Not implemented, yet !'); end; procedure ClearSurface(Surface: IDirectDrawSurface; Color: integer); var bltfx : TDDBltFX; begin InitRecord(bltfx,sizeof(bltfx)); bltfx.dwFillColor := Color; dxCheck( Surface.Blt(nil,nil,nil,DDBLT_COLORFILL + DDBLT_WAIT,@bltfx) ); end; function LoadPaletteFromJASCFile(Filename: string; var Palette: TColorTable) : boolean; var f : text; i : integer; s : string; b : byte; Code : integer; procedure ReadWd; var c : AnsiChar; begin s := ''; repeat read(f,c); if c <> ' ' then s := s + c; until c = ' '; end; label ende; begin Result := false; assign(f,Filename); {$i-} reset(f); if ioResult <> 0 then goto ende; readln(f,s); readln(f,s); readln(f,s); for i := 0 to 255 do begin ReadWd; Val(s,b,Code); if Code <> 0 then goto ende; Palette[i].R := b; ReadWd; Val(s,b,Code); if Code <> 0 then goto ende; Palette[i].G := b; ReadLn(f,s); Val(s,b,Code); if Code <> 0 then goto ende; Palette[i].B := b; Palette[i].A := PC_EXPLICIT; end; Result := true; ende: close(f); {$I+} end; function GetBrightness(Red,Green,Blue: TD3DValue) : TD3DValue; begin Result := (Red * 0.3) + (Green * 0.59) + (Blue * 0.11); end; procedure SetBrightness(var Red,Green,Blue: TD3DValue; Brightness: TD3DValue); // var factor : TD3DValue; begin // Setzt entsprechenden Grauton: Red := Brightness; Green := Brightness; Blue := Brightness; //Behält Farbe bei Helligkeitsänderung bei: { if GetBrightness(Red,Green,Blue) = 0.0 then begin Red := 0.0; Green := 0.0; Blue := 0.0; end else begin factor := Brightness / GetBrightness(Red,Green,Blue); Red := Red * factor; if Red > 1.0 then Red := 1.0; Green := Green * factor; if Green > 1.0 then Green := 1.0; Blue := Blue * factor; if Blue > 1.0 then Blue := 1.0; end;} end; procedure SM(Message: string); begin MessageBox(0,PChar(Message),'DirectX-Application:',MB_APPLMODAL); end; function AddCOM(const COM) : IUnknown; begin {$IFDEF D2COM} if Assigned( IUnknown(COM) ) then IUnknown(COM).AddRef; {$ELSE} if Assigned( IUnknown(COM) ) then IUnknown(COM)._AddRef; {$ENDIF} Result := IUnknown(COM); end; function ReleaseObj(var Obj) : boolean; begin if assigned( TObject(Obj) ) then begin TObject(Obj).Destroy; TObject(Obj) := nil; Result := True; end else Result := False; end; function ReleaseCOM(var COM) : boolean; // Interfaceobjekt freigeben begin if Assigned( IUnknown(COM) ) then // wenn Zeigerwert nicht nil dann: begin {$IFDEF D2COM} IUnknown(COM).Release; // Referenzzähler um eins erniedrigen {$ENDIF} IUnknown(COM) := nil; // Zeiger auf null setzt, Result := True; end // um weitere versehentlicher Zugriffe zu vermeiden else Result := false; end; procedure ReleaseCOMe(var COM); begin if Assigned( IUnknown(COM) ) then begin {$IFDEF D2COM} IUnknown(COM).Release; {$ELSE} IUnknown(COM)._Release; {$ENDIF} IUnknown(COM) := nil; end else raise Exception.Create(DXStat+#13+'ReleaseCOM of NULL object'); end; function FormatError(ErrorString,At: string) : string; begin Result := #13+#13+ErrorString+#13+#13; if At <> '' then Result := Result +'At: '+At+ #13+#13; end; constructor EDirectX.Create(Error: integer); begin inherited Create( FormatError(DXErrorString(Error),DXStat) ); end; function DXErrorString(Value: HResult) : string; begin if Value = 0 then Result := NoError else begin Result := 'Error '; end; end; procedure DXCheck(Value: HResult); { Check the Result of a COM operation } begin if Value <> 0 then raise EDirectX.Create(Value); end; procedure DXCheck_(Value: HResult); { Check the Result of a COM operation } var s : string; begin if Value <> 0 then begin s := IntToHex(Value,8); // for debugging raise EDirectX.Create(Value); end; end; procedure DDCheck(Value: HResult); begin end; procedure D3DCheck(Value: HResult); begin end; procedure DICheck(Value: HResult); begin end; procedure DPCheck(Value: HResult); begin end; procedure DSCheck(Value: HResult); begin end; procedure DSetupCheck(Value: HResult); begin end; procedure DXFCheck(Value: HResult); begin end; function D3DVECTOR( x, y, z : TD3DValue ) : TD3DVECTOR; begin result.x := x; result.y := y; result.z := z; end; function D3DVERTEX( v, n : TD3DVector; _u, _v : TD3DValue ) : TD3DVERTEX; begin with result do begin x := v.x; (* Homogeneous coordinates *) y := v.y; z := v.z; nx := n.x; (* Normal *) ny := n.y; nz := n.z; tu := _u; (* Texture coordinates *) tv := _v; end; end; initialization begin DXStat := ''; Exceptions := True; end; finalization begin end; end.
unit FMX.BezierAnimation; interface type TBezier = class public const epsilon = 1.0E-5; private ax, bx, cx, ay, by, cy: Double; public constructor Create(p1x, p1y, p2x, p2y: Double); procedure SetData(p1x, p1y, p2x, p2y: Double); function SampleCurveX(t: Double): Double; function SampleCurveY(t: Double): Double; function SampleCurveDerivativeX(t: Double): Double; function SolveCurveX(x, epsilon: Double): Double; function Solve(x, epsilon: Double): Double; end; function GetEaseInOut: TBezier; implementation var EaseInOut: TBezier = nil; function GetEaseInOut: TBezier; begin if not Assigned(EaseInOut) then EaseInOut := TBezier.Create(0.42,0,0.58,1); Result := EaseInOut; end; { TBezier } constructor TBezier.Create(p1x, p1y, p2x, p2y: Double); begin SetData(p1x, p1y, p2x, p2y); end; function TBezier.SampleCurveDerivativeX(t: Double): Double; begin Result := (3.0 * ax * t + 2.0 * bx) * t + cx; end; function TBezier.SampleCurveX(t: Double): Double; begin // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. Result := ((ax * t + bx) * t + cx) * t; end; function TBezier.SampleCurveY(t: Double): Double; begin Result := ((ay * t + by) * t + cy) * t; end; procedure TBezier.SetData(p1x, p1y, p2x, p2y: Double); begin // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). cx := 3.0 * p1x; bx := 3.0 * (p2x - p1x) - cx; ax := 1.0 - cx -bx; cy := 3.0 * p1y; by := 3.0 * (p2y - p1y) - cy; ay := 1.0 - cy - by; end; // Given an x value, find a parametric value it came from. function TBezier.Solve(x, epsilon: Double): Double; begin Result := SampleCurveY(SolveCurveX(x, epsilon)); end; function TBezier.SolveCurveX(x, epsilon: Double): Double; var t0, t1, t2, x2, d2: Double; i: Integer; begin // First try a few iterations of Newton's method -- normally very fast. t2 := x; for i := 0 to 7 do begin x2 := sampleCurveX(t2) - x; if (Abs(x2) < epsilon) then Exit(t2); d2 := SampleCurveDerivativeX(t2); if (Abs(d2) < 1e-6) then break; t2 := t2 - x2 / d2; end; // Fall back to the bisection method for reliability. t0 := 0.0; t1 := 1.0; t2 := x; if (t2 < t0) then Exit(t0); if (t2 > t1) then Exit(t1); while (t0 < t1) do begin x2 := SampleCurveX(t2); if (Abs(x2 - x) < epsilon) then Exit(t2); if (x > x2) then t0 := t2 else t1 := t2; t2 := (t1 - t0) * 0.5 + t0; end; // Failure. Exit(t2); end; initialization finalization EaseInOut.Free; end.
unit dealHistoryForm; interface uses Forms, Classes, Controls, StdCtrls, SysUtils, ExtCtrls, VirtualTrees, BaseApp, BaseForm; type TfrmDealHistory = class(TfrmBase) pnlTop: TPanel; pnlBottom: TPanel; pnlMain: TPanel; pnlDeal: TPanel; vtDeal: TVirtualStringTree; procedure vtDealGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); protected procedure InitializeDealTree; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Initialize(App: TBaseApp); override; end; implementation {$R *.dfm} uses define_deal; (*// -- 账号 A --> { 总资产 } 投资分析 全部投资记录 2016 2016-03 2016-02 2016-01 2016-01-28 2016-01-03 2015 2015-12 2015-11 -- 账号 B //*) type TSummaryNodeType = ( nodeUndefine, nodeAnalysis ); PDealSummaryNode = ^TDealSummaryNode; TDealSummaryNode = record NodeType : TSummaryNodeType; Caption : string; end; PDealItemNode = ^TDealItemNode; TDealItemNode = record ID: Integer; end; { TfrmDealHistory } constructor TfrmDealHistory.Create(AOwner: TComponent); begin inherited; // mmo1.Lines.Add('TDealRequest:' + IntToStr(SizeOf(TDealRequest))); // mmo1.Lines.Add('TDealResultClose:' + IntToStr(SizeOf(TDealResultClose))); // mmo1.Lines.Add('TDealResultCancel:' + IntToStr(SizeOf(TDealResultCancel))); end; destructor TfrmDealHistory.Destroy; begin inherited; end; procedure TfrmDealHistory.Initialize(App: TBaseApp); begin inherited; InitializeDealTree; end; procedure TfrmDealHistory.InitializeDealTree; var tmpVNode_Account: PVirtualNode; tmpVNode_Analysis: PVirtualNode; tmpVNode_DealHistorys: PVirtualNode; tmpVNode_DealPeriod: PVirtualNode; tmpVNodeData: PDealSummaryNode; begin vtDeal.NodeDataSize := SizeOf(TDealSummaryNode); vtDeal.OnGetText := vtDealGetText; tmpVNode_Account := nil; // // tmpVNode_Account := vtDeal.AddChild(nil); // tmpVNodeData := vtDeal.GetNodeData(tmpVNode_Account); // tmpVNodeData.Caption := '账户[39008900]'; // 多个账户同时显示在右边 tmpVNode_Analysis := vtDeal.AddChild(nil); tmpVNodeData := vtDeal.GetNodeData(tmpVNode_Analysis); tmpVNodeData.Caption := '投资分析'; tmpVNode_DealHistorys := vtDeal.AddChild(tmpVNode_Account); tmpVNodeData := vtDeal.GetNodeData(tmpVNode_DealHistorys); tmpVNodeData.Caption := '全部投资记录'; tmpVNode_DealPeriod := vtDeal.AddChild(tmpVNode_DealHistorys); tmpVNodeData := vtDeal.GetNodeData(tmpVNode_DealPeriod); tmpVNodeData.Caption := '2016-06'; tmpVNode_DealPeriod := vtDeal.AddChild(tmpVNode_DealHistorys); tmpVNodeData := vtDeal.GetNodeData(tmpVNode_DealPeriod); tmpVNodeData.Caption := '2016-05'; tmpVNode_DealPeriod := vtDeal.AddChild(tmpVNode_DealHistorys); tmpVNodeData := vtDeal.GetNodeData(tmpVNode_DealPeriod); tmpVNodeData.Caption := '2016-04'; vtDeal.FullExpand(tmpVNode_Account); end; procedure TfrmDealHistory.vtDealGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var tmpVNodeData: PDealSummaryNode; begin inherited; CellText := ''; tmpVNodeData := Sender.GetNodeData(Node); if nil <> tmpVNodeData then begin CellText := tmpVNodeData.Caption; end; // end; end.
unit ModelOpf; { //////////////////////////////// This project aims to study the persistence of business objects in one application FPC/Lazarus using BrookFramework and dOPF from Silvio Clecio. This project is not intended to provide warranties of any kind for any purpose! //////////////////////////////// } {$mode objfpc}{$H+} interface uses //Classes, SysUtils, model, dSQLdbBroker, dbutils; type { TUfOpf } { TStateOpf } TStateOpf = class(specialize TdGSQLdbEntityOpf<TState>) public constructor Create; overload; end; { TCityOpf } TCityOpf = class(specialize TdGSQLdbEntityOpf<TCity>) public constructor Create; overload; end; { TDistrictOpf } TDistrictOpf = class(specialize TdGSQLdbEntityOpf<TDistrict>) public constructor Create; overload; end; { TStreetOpf } TStreetOpf = class(specialize TdGSQLdbEntityOpf<TStreet>) public constructor Create; overload; end; { TAddressTypeOpf } TAddressTypeOpf = class(specialize TdGSQLdbEntityOpf<TAddressType>) public constructor Create; overload; end; { TAddressOpf } TAddressOpf = class(specialize TdGSQLdbEntityOpf<TAddress>) public constructor Create; overload; end; { TPersonOpf } TPersonOpf = class(specialize TdGSQLdbEntityOpf<TPerson>) public constructor Create; overload; end; { TIndividualCustomerOpf } TIndividualCustomerOpf = class(specialize TdGSQLdbEntityOpf<TIndCust>) public constructor Create; overload; end; { TCompanyCustomerOpf } TCompanyCustomerOpf = class(specialize TdGSQLdbEntityOpf<TCompCust>) public constructor Create; overload; end; { TUnitOpf } TUnitOpf = class(specialize TdGSQLdbEntityOpf<TUnit>) public constructor Create; overload; end; { TProductOpf } TProductOpf = class(specialize TdGSQLdbEntityOpf<TProduct>) public constructor Create; overload; end; { TOrderOpf } TOrderOpf = class(specialize TdGSQLdbEntityOpf<TOrder>) public constructor Create; overload; end; { TOrderItemsOpf } TOrderItemsOpf = class(specialize TdGSQLdbEntityOpf<TOrderItems>) public constructor Create; overload; end; implementation { TOrderItemsOpf } constructor TOrderItemsOpf.Create; begin inherited Create(dbutils.con, 'orderitem'); end; { TOrderOpf } constructor TOrderOpf.Create; begin inherited Create(dbutils.con, 'order'); end; { TProductOpf } constructor TProductOpf.Create; begin inherited Create(dbutils.con, 'product'); end; { TUnitOpf } constructor TUnitOpf.Create; begin inherited Create(dbutils.con, 'unit'); end; { TCompanyCustomerOpf } constructor TCompanyCustomerOpf.Create; begin inherited Create(dbutils.con, 'companycustomer'); end; { TIndividualCustomerOpf } constructor TIndividualCustomerOpf.Create; begin inherited Create(dbutils.con, 'individualcustomer'); end; { TPersonOpf } constructor TPersonOpf.Create; begin inherited Create(dbutils.con, 'person'); end; { TAddressOpf } constructor TAddressOpf.Create; begin inherited Create(dbutils.con, 'address'); end; { TAddressTypeOpf } constructor TAddressTypeOpf.Create; begin inherited Create(dbutils.con, 'addresstype'); end; { TStreetOpf } constructor TStreetOpf.Create; begin inherited Create(dbutils.con, 'street'); end; { TDistrictOpf } constructor TDistrictOpf.Create; begin inherited Create(dbutils.con, 'district'); end; { TCityOpf } constructor TCityOpf.Create; begin inherited Create(dbutils.con, 'city'); end; constructor TStateOpf.Create; begin inherited Create(dbutils.con, 'state'); end; end.
unit PopupWindowData; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Layouts, FMX.Edit, FMX.StdCtrls, FMX.Clipboard, FMX.Platform, FMX.Objects, System.Types, StrUtils, CrossPlatformHeaders ,fmx.dialogs , math; {type A = class i : integer; constructor create(); end; type B = class(A) constructor create(); end; } type popupWindow = class(TPopup) public messageLabel: TLabel; procedure _onEnd(sender: TObject); constructor Create(mess: AnsiString); end; type popupWindowOK = class(TPopup) private _ImageLayout: TLayout; _Image: TImage; _OKbutton: TButton; _lblMessage: TLabel; _onOKButtonPress: TProc; procedure _OKButtonpress(sender: TObject); procedure _onEnd(sender: TObject); public constructor Create(OK: TProc; mess: AnsiString; ButtonText: AnsiString = 'OK'; icon: integer = 1); end; {type popupWindowYesNo = class(TPopup) private _lblMessage: TLabel; _ImageLayout: TLayout; _Image: TImage; _ButtonLayout: TLayout; _YesButton: TButton; _NoButton: TButton; _onYesPress: TProc; _onNoPress: TProc; procedure _onYesClick(sender: TObject); procedure _onNoClick(sender: TObject); procedure _OnExit(sender: TObject); public constructor Create(Yes, No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); end; } {type PopupWindowProtectYesNo = class(popupWindowYesNo) private _edit : Tedit; protectWord : AnsiString; procedure checkProtect( Sender : TObject ); public constructor Create(Yes, No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); end; } implementation uses Uhome; {constructor PopupWindowProtectYesNo.Create(Yes: TProc; No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: Integer = 2); var panel : TPanel; begin inherited Create( yes , no , mess , yesText , noText , icon ); panel := _imageLayout.Parent as Tpanel; _edit := Tedit.Create( Panel ); _edit.Parent := Panel; _edit.Align := TAlignLayout.Bottom; _edit.Height := 48; _edit.Visible := true; _edit.DisableFocusEffect := false; protectWord := 'dupa'; _YesButton.OnClick := checkProtect; //PopupModal := TModalResult; //popup(); end; procedure PopupWindowProtectYesNo.checkProtect(Sender : TObject ); begin if _edit.text = protectWord then begin _onYesClick(Sender); end else begin popupWindow.Create('wrong word'); end; end; } {constructor popupWindowYesNo.Create(Yes: TProc; No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); var panel, Panel2: TPanel; rect: TRectangle; i: integer; begin inherited Create(frmhome); _onYesPress := Yes; _onNoPress := No; parent := frmhome; Height := 250; Width := min( 400 , frmhome.Width ); //PlacementRectangle := TBounds.Create(RectF(0, 0, 0, 0)); PlacementRectangle := TBounds.Create( frmhome.Bounds ); //PlacementTarget := frmhome.StatusBarFixer; Placement := TPlacement.center; //VerticalOffset := ( frmhome.Height / 2 ) - ( height / 2) - 10 + Height; //HorizontalOffset := 0 ; //AnimateFloat('VerticalOffset', ( frmhome.Height / 2 ) - ( height / 2) - 10 , 10 ); //position.X := 0; //position.Y := 0; Visible := true; panel := TPanel.Create(self); panel.Align := TAlignLayout.Client; panel.Height := 48; panel.Visible := true; panel.tag := i; panel.parent := self; rect := TRectangle.Create(panel); rect.parent := panel; rect.Align := TAlignLayout.Contents; rect.Fill.Color := frmhome.StatusBarFixer.Fill.Color; _ImageLayout := TLayout.Create(panel); _ImageLayout.Visible := true; _ImageLayout.Align := TAlignLayout.MostTop; _ImageLayout.parent := panel; _ImageLayout.Height := 96; _Image := TImage.Create(_ImageLayout); _Image.Align := TAlignLayout.Center; _Image.Width := 64; _Image.Height := 64; _Image.Visible := true; _Image.parent := _ImageLayout; case icon of 0: _Image.Bitmap := frmhome.OKImage.Bitmap; 1: _Image.Bitmap := frmhome.InfoImage.Bitmap; 2: _Image.Bitmap := frmhome.warningImage.Bitmap; 3: _Image.Bitmap := frmhome.ErrorImage.Bitmap; end; _lblMessage := TLabel.Create(panel); _lblMessage.Align := TAlignLayout.Client; _lblMessage.Visible := true; _lblMessage.parent := panel; _lblMessage.Text := mess; _lblMessage.TextSettings.HorzAlign := TTextAlign.Center; _lblMessage.Margins.Left := 10; _lblMessage.Margins.Right := 10; _ButtonLayout := TLayout.Create(panel); _ButtonLayout.Visible := true; _ButtonLayout.Align := TAlignLayout.MostBottom; _ButtonLayout.parent := panel; _ButtonLayout.Height := 48; _YesButton := TButton.Create(_ButtonLayout); _YesButton.Align := TAlignLayout.Right; _YesButton.Width := _ButtonLayout.Width / 2; _YesButton.Visible := true; _YesButton.parent := _ButtonLayout; _YesButton.Text := YesText; _YesButton.OnClick := _onYesClick; _NoButton := TButton.Create(_ButtonLayout); _NoButton.Align := TAlignLayout.Left; _NoButton.Width := _ButtonLayout.Width / 2; _NoButton.Visible := true; _NoButton.parent := _ButtonLayout; _NoButton.Text := NoText; _NoButton.OnClick := _onNoClick; Popup(); OnClosePopup := _OnExit; end; procedure popupWindowYesNo._OnExit(sender: TObject); begin parent := nil; Tthread.CreateAnonymousThread( procedure begin Tthread.Synchronize(nil, procedure begin DisposeOf(); end); end).start; end; procedure popupWindowYesNo._onYesClick; begin IsOpen := false; _onYesPress(); ClosePopup(); // Release; end; procedure popupWindowYesNo._onNoClick; begin IsOpen := false; _onNoPress(); ClosePopup(); // Release; end; } constructor popupWindowOK.Create(OK: TProc; mess: AnsiString; ButtonText: AnsiString = 'OK'; icon: integer = 1); var panel, Panel2: TPanel; i: integer; rect: TRectangle; begin inherited Create(frmhome.pageControl); parent := frmhome.pageControl; Height := 200; Width := 300; Placement := TPlacement.Center; Visible := true; PlacementRectangle := TBounds.Create(RectF(0, 0, 0, 0)); panel := TPanel.Create(self); panel.Align := TAlignLayout.Client; panel.Height := 48; panel.Visible := true; panel.tag := i; panel.parent := self; rect := TRectangle.Create(panel); rect.parent := panel; rect.Align := TAlignLayout.Contents; rect.Fill.Color := frmhome.StatusBarFixer.Fill.Color; _ImageLayout := TLayout.Create(panel); _ImageLayout.Visible := true; _ImageLayout.Align := TAlignLayout.MostTop; _ImageLayout.parent := panel; _ImageLayout.Height := 96; _Image := TImage.Create(_ImageLayout); _Image.Align := TAlignLayout.Center; _Image.Width := 64; _Image.Height := 64; _Image.Visible := true; _Image.parent := _ImageLayout; case icon of 0: _Image.Bitmap := frmhome.OKImage.Bitmap; 1: _Image.Bitmap := frmhome.InfoImage.Bitmap; 2: _Image.Bitmap := frmhome.warningImage.Bitmap; 3: _Image.Bitmap := frmhome.ErrorImage.Bitmap; end; _lblMessage := TLabel.Create(panel); _lblMessage.Align := TAlignLayout.Client; _lblMessage.Visible := true; _lblMessage.parent := panel; _lblMessage.Text := mess; _lblMessage.TextSettings.HorzAlign := TTextAlign.Center; _OKbutton := TButton.Create(panel); _OKbutton.Align := TAlignLayout.Bottom; _OKbutton.Height := 48; _OKbutton.Visible := true; _OKbutton.parent := panel; _OKbutton.OnClick := _OKButtonpress; _OKbutton.Text := ButtonText; _onOKButtonPress := OK; self.OnClosePopup := _onEnd; Popup(); end; procedure popupWindowOK._OKButtonpress(sender: TObject); begin IsOpen := false; _onOKButtonPress(); ClosePopup(); end; procedure popupWindowOK._onEnd(sender: TObject); begin parent := nil; Tthread.CreateAnonymousThread( procedure begin Tthread.Synchronize(nil, procedure begin DisposeOf(); end); end).start; end; constructor popupWindow.Create(mess: AnsiString); var panel, Panel2: TPanel; i: integer; rect: TRectangle; begin //exit(); inherited Create(frmhome.pageControl); Placement := TPlacement.Center; parent := frmhome.pagecontrol; PlacementTarget := frmhome.pageControl; Height := 100; Width := 300; PlacementTarget := frmhome.pageControl; Visible := true; //PlacementRectangle := TBounds.Create(RectF(0, 0, 0, 0)); panel := TPanel.Create(self); panel.Align := TAlignLayout.Client; panel.Visible := true; panel.tag := i; panel.parent := self; rect := TRectangle.Create(panel); rect.parent := panel; rect.Align := TAlignLayout.Contents; rect.Fill.Color := frmhome.StatusBarFixer.Fill.Color; messageLabel := TLabel.Create(panel); messageLabel.Align := TAlignLayout.Client; messageLabel.Visible := true; messageLabel.parent := panel; messageLabel.Text := mess; messageLabel.TextSettings.HorzAlign := TTextAlign.Center; self.OnClosePopup := _onEnd; //Placement := TPlacement.Center; Popup(); end; procedure popupWindow._onEnd(sender: TObject); begin IsOpen := false; parent := nil; Tthread.CreateAnonymousThread( procedure begin Tthread.Synchronize(nil, procedure begin DisposeOf(); end); end).start; end; end.
unit GX_GrepRegExSearch; interface {$I GX_CondDefine.inc} uses SysUtils, Classes, RegExpr, GX_GenericUtils, GX_CodeFormatterUnicode, GX_OtaUtils; type TFoundEvent = procedure(LineNo, StartCol, EndCol: Integer; const Line: TGXUnicodeString) of object; TSearcher = class(TObject) private FPattern: TGXUnicodeString; FData: TGXUnicodeStringList; FOnFound: TFoundEvent; FRegEx: TRegExpr; FCaseSensitive: Boolean; FWholeWord: Boolean; FRegularExpression: Boolean; FFileName: string; FNoCode: Boolean; FNoStrings: Boolean; FNoComments: Boolean; FIsPascalSourceFile: Boolean; FSectionInterface: Boolean; FSectionInitialization: Boolean; FSectionImplementation: Boolean; FSectionFinalization: Boolean; procedure SearchLineRegEx(const LineStr: string; LineNo: Integer); procedure SearchLineRaw(const LineStr: string; LineNo: Integer); procedure SetFileName(const Value: string); function CheckWholeWord(Line: TGXUnicodeString; StartCol, EndCol: Integer): Boolean; public constructor Create; destructor Destroy; override; property Pattern: TGXUnicodeString read FPattern write FPattern; property OnFound: TFoundEvent read FOnFound write FOnFound; property NoCode: Boolean read FNoCode write FNoCode; property NoStrings: Boolean read FNoStrings write FNoStrings; property NoComments: Boolean read FNoComments write FNoComments; property IsPascalSourceFile: Boolean read FIsPascalSourceFile write FIsPascalSourceFile; property SectionInterface: Boolean read FSectionInterface write FSectionInterface; property SectionImplementation: Boolean read FSectionImplementation write FSectionImplementation; property SectionInitialization: Boolean read FSectionInitialization write FSectionInitialization; property SectionFinalization: Boolean read FSectionFinalization write FSectionFinalization; property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive; property RegularExpression: Boolean read FRegularExpression write FRegularExpression; property WholeWord: Boolean read FWholeWord write FWholeWord; property FileName: string read FFileName write SetFileName; procedure Execute; overload; end; implementation const CReplacementChar: TGXUnicodeChar = #1; // don't match false-positives when searcing for spaces { TSearcher } function TSearcher.CheckWholeWord(Line: TGXUnicodeString; StartCol, EndCol: Integer): Boolean; var PrevChar: TGXUnicodeChar; NextChar: TGXUnicodeChar; FirstMatchChar: TGXUnicodeChar; LastMatchChar: TGXUnicodeChar; begin PrevChar := ' '; NextChar := ' '; if StartCol >= 2 then PrevChar := Line[StartCol - 1]; if Length(Line) > EndCol then NextChar := Line[EndCol + 1]; FirstMatchChar := Line[StartCol]; LastMatchChar := Line[EndCol]; Result := (((not IsCharIdentifier(PrevChar)) or (not IsCharIdentifier(FirstMatchChar))) and ((not IsCharIdentifier(NextChar)) or (not IsCharIdentifier(LastMatchChar)))); end; constructor TSearcher.Create; begin FRegEx := TRegExpr.Create; end; destructor TSearcher.Destroy; begin FreeAndNil(FRegEx); inherited; end; type TCodeFragment = ( cfCode, cfLineComment, // This type of comment, ends on newline. cfCurlyComment, // {...newlines...} cfBlockComment, // (*...newlines...*) cfString, // = '...' // cfEndOfCode, TODO : Switch to this after usEnd cfEndOfComment, // Last char of comment; Either #10, ')' or '}' cfEndOfString // Last char of string; Always ' ); TCodeFragments = set of TCodeFragment; TUnitSection = ( usStart, usInterface, usImplementation, usInitialization, usFinalization, usEnd); TUnitSections = set of TUnitSection; const CodeFragments = [cfCode]; StringFragments = [cfString, cfEndOfString]; CommentFragments = [cfLineComment, cfCurlyComment, cfBlockComment, cfEndOfComment]; CSections: array [TUnitSection] of string = ( '', 'interface', 'implementation', 'initialization', 'finalization', 'end.'); procedure TSearcher.Execute; var i, index, index2: Integer; UnitSectionsToSkip: TUnitSections; CodeFragmentsToSkip: TCodeFragments; ActiveSection: TUnitSection; ActiveCodeFragment: TCodeFragment; s: TGXUnicodeString; function _TrySwitchToSection(const aNextSection: TUnitSection): Boolean; begin if ActiveSection < aNextSection then if Length(s) >= index + Length(CSections[aNextSection]) then if StrLIComp(@(s[index]), CSections[aNextSection], Length(CSections[aNextSection])) = 0 then if (aNextSection = usEnd) or (not IsCharIdentifier(s[index + Length(CSections[aNextSection])])) then begin ActiveSection := aNextSection; Result := True; Exit; end; Result := False; end; // _TrySwitchToSection begin // Execute if not Assigned(FData) then raise Exception.Create('Data to search not provided'); if IsEmpty(Pattern) then raise Exception.Create('Search pattern is empty'); if RegularExpression then begin FRegEx.ModifierI := not CaseSensitive; FRegEx.Expression := Pattern; FRegEx.Compile; end; UnitSectionsToSkip := []; CodeFragmentsToSkip := []; if IsPascalSourceFile then begin // Determine which sections must be skipped : if not SectionInterface then Include(UnitSectionsToSkip, usInterface); if not SectionImplementation then Include(UnitSectionsToSkip, usImplementation); if not SectionInitialization then Include(UnitSectionsToSkip, usInitialization); if not SectionFinalization then Include(UnitSectionsToSkip, usFinalization); // Determine which code fragments must be skipped : if NoCode then CodeFragmentsToSkip := CodeFragmentsToSkip + CodeFragments; if NoStrings then CodeFragmentsToSkip := CodeFragmentsToSkip + StringFragments; if NoComments then CodeFragmentsToSkip := CodeFragmentsToSkip + CommentFragments; end; ActiveSection := usStart; ActiveCodeFragment := cfCode; for i := 0 to FData.Count - 1 do begin // Read the input line, skip if empty. s := FData[i]; if s = EmptyString then Continue; if (UnitSectionsToSkip <> []) or (CodeFragmentsToSkip <> []) then begin Assert(Length(s) > 0); // On each new line, switch line comment mode back to code : if ActiveCodeFragment = cfLineComment then ActiveCodeFragment := cfCode; s := s + CReplacementChar; // Extend the input line to avoid out of bounds errors. index := 1; // This (and prior) code scans Delphi syntax. TODO : Handle IsC and IsDFM syntax too. repeat Assert(s[index] <> #10, 'unexpected linefeed'); Assert(s[index] <> #13, 'unexpected carriage return'); index2 := index + 1; case ActiveCodeFragment of cfLineComment: ; // skip everything, active fragment switches back to code on the next line cfCurlyComment: if s[index] = '}' then ActiveCodeFragment := cfEndOfComment; cfBlockComment: if s[index] = '*' then if s[index2] = ')' then begin Inc(index2); // skip both closing characters ActiveCodeFragment := cfEndOfComment; end; cfString: // already seen one ' if s[index] = #39 then // Is this single quote followed by another? if s[index2] = #39 then Inc(index2) // skip double-escaped single quote character else ActiveCodeFragment := cfEndOfString; else // cfCode, cfEndOfString, cfEndOfComment: ActiveCodeFragment := cfCode; case s[index] of #39: ActiveCodeFragment := cfString; '{': ActiveCodeFragment := cfCurlyComment; '/': if s[index2] = '/' then ActiveCodeFragment := cfLineComment; '(': if s[index2] = '*' then ActiveCodeFragment := cfBlockComment; end; // case s[index] end; // case ActiveCodeFragment // Do we need to detect unit section-changes? if UnitSectionsToSkip <> [] then if ActiveCodeFragment = cfCode then if ActiveSection < usEnd then // Is this the start of an identifier (looking back in the UNALTERED line)? if (index = 1) or ((not IsCharIdentifier(FData[i][index - 1])) and (FData[i][index - 1] <> '&')) then if _TrySwitchToSection(usInterface) or _TrySwitchToSection(usImplementation) or _TrySwitchToSection(usInitialization) or _TrySwitchToSection(usFinalization) or _TrySwitchToSection(usEnd) then // When detected, step over the activated section keyword : Inc(index2, Length(CSections[ActiveSection]) - 1); // Lastly, put a CReplacementChar over fragments and sections that must not be searched : if (ActiveSection in UnitSectionsToSkip) or (ActiveCodeFragment in CodeFragmentsToSkip) then repeat s[index] := CReplacementChar; Inc(index); until index = index2 else index := index2; until index >= Length(s); // Stop at the extra character we added // To here, s has had all content removed that must not be searched. // For the search, we trim all trailing CReplacementChar's out of s. while (index > 0) and (s[index] = CReplacementChar) do Dec(index); // If s is empty we skip the search. if index = 0 then Continue; SetLength(s, index); end; if RegularExpression then SearchLineRegEx(s, i) else SearchLineRaw(s, i); end; // for i FData end; // Execute procedure TSearcher.SearchLineRaw(const LineStr: string; LineNo: Integer); var StartCol: Integer; EndCol: Integer; Line: TGXUnicodeString; StartIndex: Integer; MatchPos: Integer; procedure GetNextMatch; begin if CaseSensitive then MatchPos := PosFrom(Pattern, LineStr, StartIndex) else MatchPos := CaseInsensitivePosFrom(Pattern, LineStr, StartIndex); end; begin { Added passed string called LineStr. Example: Line[i]: ShowMessage(' Test '); // Comment goes here LineStr: ShowMessage(' '); These ONLY differ if the user searches for NO COMMENTS. The search then finds index matches in LineStr, but highlights them using the original Line[i]. } Line := FData[LineNo]; StartIndex := 1; GetNextMatch; while MatchPos > 0 do begin StartCol := MatchPos; EndCol := MatchPos + Length(Pattern) - 1; Assert(StartCol > 0); Assert(EndCol > 0); if (not WholeWord) or (CheckWholeWord(LineStr, StartCol, EndCol)) then if Assigned(FOnFound) then FOnFound(LineNo + 1, StartCol, EndCol, Line); StartIndex := StartCol + 1; GetNextMatch; end; end; procedure TSearcher.SearchLineRegEx(const LineStr: string; LineNo: Integer); var StartCol: Integer; EndCol: Integer; Line: TGXUnicodeString; begin Line := FData[LineNo]; if FRegEx.Exec(LineStr) then repeat begin //if FRegEx.SubExprMatchCount > 0 then // raise Exception.Create('Subexpression searches are not supported'); StartCol := FRegEx.MatchPos[0]; EndCol := StartCol + FRegEx.MatchLen[0] - 1; Assert(StartCol > 0); Assert(EndCol > 0, 'Invalid regular expression match, try escaping any special characters using ''\'''); if WholeWord then if not CheckWholeWord(LineStr, StartCol, EndCol) then Continue; if Assigned(FOnFound) then FOnFound(LineNo + 1, StartCol, EndCol, Line); end until not FRegEx.ExecNext; end; procedure TSearcher.SetFileName(const Value: string); begin FFileName := Value; if not Assigned(FData) then FData := TGXUnicodeStringList.Create else FData.Clear; GxOtaLoadFileToUnicodeStrings(FFileName, FData); end; end.
unit uObserver; interface uses Classes; type TObservable = class; IObserver = interface procedure Update(ASubject: TObservable); end; /// <author>Oscar Worell</author> /// <Descricao>Esta classe é a classe basica de teste</Descricao> TObservable = class strict private FObservers: TList; public constructor Create; procedure Attach(AObserver: IObserver); procedure Detach(AObserver: IObserver); strict protected procedure NotifyObservers; end; TCotacao = class(TObservable) end; TProduto = class(TInterfacedObject, IObserver) public procedure Update(ASubject: TObservable); end; implementation constructor TObservable.Create; begin inherited Create; FObservers := TList.Create; end; procedure TObservable.Attach(AObserver: IObserver); begin FObservers.Add(@AObserver); end; procedure TObservable.Detach(AObserver: IObserver); var idx: Integer; begin idx := FObservers.IndexOf(@AObserver); If idx <> -1 Then begin FObservers.Delete(idx); end; end; procedure TObservable.NotifyObservers; var Current: ^IObserver; begin for Current in FObservers do begin Current.Update(self); end; end; procedure TProduto.Update(ASubject: TObservable); begin // put your code here end; end.
{ WinSock Demo: How to get IP by hostname and how to get hostname by IP. Designed by Alex Popkov, 2000 Uploaded to Code Central, http://codecentral.borland.com, 12.09.2000 Copyrights: open source. Purpose: There was some questions about hostname <-> address resolving. This demo containts sample code as illustration. Usage: Very easy. Just select/enter hostname or IP address and hit [Resolve] button. Note: Some hosts may have many IP addresses. Sometimes, one IP address can be resolved to many hostnames. } unit MainFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls; type TMainForm = class(TForm) PageControl: TPageControl; StatusBar: TStatusBar; GetIPByNameTabSheet: TTabSheet; NameComboBox: TComboBox; NameToIPButton: TButton; AddressListBox: TListBox; IPToNameTabSheet: TTabSheet; AddressComboBox: TComboBox; IPToNameButton: TButton; NameListBox: TListBox; procedure StatusBarResize(Sender: TObject); procedure NameToIPButtonClick(Sender: TObject); procedure IPToNameButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure StatusText( Text: String ); procedure NameToIP; public { Public declarations } end; var MainForm: TMainForm; implementation uses WinSock, WinSock2; // I did not found any *.hlp files about WinSock library in my D5Pro. {$R *.DFM} procedure TMainForm.StatusBarResize(Sender: TObject); begin StatusBar.Panels[0].Width := StatusBar.Width; StatusText( 'Idle' ); end; // Just show given text in StatusBar procedure TMainForm.StatusText( Text: String ); begin StatusBar.Panels[0].Text := ' ' + Text; end; // Resolve hostname to IP address procedure TMainForm.NameToIPButtonClick(Sender: TObject); begin NameToIPButton.Enabled := False; Cursor := crHourGlass; AddressListBox.Clear(); StatusText( 'Busy' ); NameToIp; Cursor := crDefault; NameToIPButton.Enabled := True; StatusText( 'Idle' ); end; // Resolve host IP address to hostname procedure TMainForm.IPToNameButtonClick(Sender: TObject); type TAPInAddr = Array[0..100] of PInAddr; PAPInAddr = ^TAPInAddr; var WSAData: TWSAData; Address: String; InetAddr: u_long; HostEntPtr: PHostEnt; HostEnt: THostEnt; HostName: String; pptr: PAPInAddr; len, struct: Integer; i: Integer; begin IPToNameButton.Enabled := False; Cursor := crHourGlass; NameListBox.Clear(); StatusText( 'Busy' ); WSAStartUp( $101, WSAData ); try Address := Trim( AddressComboBox.Text ); if Address = '' then raise Exception.Create( 'IP address not entered' ); // Convert textual IP address to binary format InetAddr := inet_addr( PChar(Address) ); if InetAddr = SOCKET_ERROR then raise Exception.Create( 'Invalid address entered' ); // Get hist entry by IP HostEntPtr := GetHostByAddr( @InetAddr, len, struct ); if HostEntPtr = NIL then raise Exception.Create( 'WinSock error: ' + IntToStr( WSAGetLastError() ) ); // Insert hostname into list HostName := String( HostEntPtr^.h_name ); NameListBox.Items.Add( HostName ); // Add aliases into list (if aliases are present in host entry) pptr := PAPInAddr( HostEntPtr^.h_aliases ); i := 0; while pptr^[i] <> NIL do begin NameListBox.Items.Add( String( pptr^[i] ) ); Inc( i ); end; { ; i := 0; while HostEntPtr^.h_addr_list[i] <> nil do begin NameListBox.Items.Add( String( HostEntPtr^.h_addr_list^[i] ) ); Inc( i ); end; } except on E: Exception do begin StatusText( 'Exception' ); Beep(); ShowMessage( E.Message ); end; end; WSACleanUp(); Cursor := crDefault; IPToNameButton.Enabled := True; StatusText( 'Idle' ); end; procedure TMainForm.FormCreate(Sender: TObject); var buffer: Array[0..63] of Char; WSAData: TWSAData; begin // Get local host name WSAStartUp( $101, WSAData ); GetHostName( buffer, SizeOf(buffer) ); NameComboBox.Items.Add( String( buffer ) ); WSACleanUp(); end; procedure TMainForm.NameToIP; type TAPInAddr = Array[0..100] of PInAddr; PAPInAddr = ^TAPInAddr; var WSAData: TWSAData; Host: String; HostEntPtr: PHostEnt; pptr: PAPInAddr; i: Integer; begin // WinSock initialisation WSAStartUp( $101, WSAData ); try Host := Trim( NameComboBox.Text ); if Host = '' then raise Exception.Create( 'Host name not entered' ); // Get host entry by hostname HostEntPtr := GetHostByName( PChar( Host ) ); if HostEntPtr = NIL then raise Exception.Create( 'WinSock error: ' + IntToStr( WSAGetLastError() ) ); // Make list of host IPs pptr := PAPInAddr( HostEntPtr^.h_addr_list ); i := 0; while pptr^[i] <> NIL do begin AddressListBox.Items.Add( inet_ntoa( pptr^[i]^ ) ); Inc( i ); end; except on E: Exception do begin StatusText( 'Exception' ); Beep(); ShowMessage( E.Message ); end; end; WSACleanUp(); // uninitialise WinSock end; end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.Arrays.Helper Description : Array helpers Author : Kike Pérez Version : 1.0 Created : 24/03/2019 Modified : 29/03/2019 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** 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 Quick.Arrays.Helper; {$i QuickLib.inc} interface uses Generics.Defaults; type TArrayHelper<T> = class public class function Count(var aArray : TArray<T>) : Integer; class procedure Add(var aArray : TArray<T>; aItem : T); static; class procedure Insert(var aArray : TArray<T>; aItem : T; aIndex : Integer); static; class procedure Remove(var aArray : TArray<T>; aIndex : Integer); static; class function Contains(var aArray : TArray<T>; aItem : T) : Boolean; class function IndexOf(var aArray : TArray<T>; aItem : T) : Integer; end; {$IFDEF FPC} TStringArray = TArray<string>; {$ENDIF} TStringArrayHelper = record Helper for {$IFNDEF FPC}TArray<string>{$ELSE}TStringArray{$ENDIF} function Count : Integer; procedure Add(const aValue : string); procedure Insert(const aValue : string; aIndex : Integer); procedure Remove(aIndex : Integer); function Contains(const aItem : string) : Boolean; function IndexOf(const aItem : string) : Integer; end; {$IFDEF FPC} TIntegerArray = TArray<Integer>; {$ENDIF} TIntegerArrayHelper = record Helper for {$IFNDEF FPC}TArray<Integer>{$ELSE}TIntegerArray{$ENDIF} function Count : Integer; procedure Add(aValue : Integer); procedure Insert(const aValue : Integer; aIndex : Integer); procedure Remove(aIndex : Integer); function Contains(aItem : Integer) : Boolean; function IndexOf(aItem : Integer) : Integer; end; implementation { TArray } class function TArrayHelper<T>.Count(var aArray : TArray<T>) : Integer; begin Result := High(aArray)+1; end; class procedure TArrayHelper<T>.Add(var aArray : TArray<T>; aItem : T); begin SetLength(aArray, Length(aArray) + 1); aArray[High(aArray)] := aItem; end; class procedure TArrayHelper<T>.Remove(var aArray : TArray<T>; aIndex : Integer); begin {$IFDEF DELPHIXE7_UP} System.Delete(aArray,aIndex,1); {$ELSE} TArrayUtil<T>.Delete(aArray,aIndex); {$ENDIF} end; class procedure TArrayHelper<T>.Insert(var aArray : TArray<T>; aItem : T; aIndex : Integer); begin System.Insert(aItem,aArray,aIndex); end; class function TArrayHelper<T>.Contains(var aArray : TArray<T>; aItem : T) : Boolean; var icomparer : IEqualityComparer<T>; i : Integer; begin Result := False; icomparer := TEqualityComparer<T>.Default; for i := Low(aArray) to High(aArray) do begin if icomparer.Equals(aArray[i],aItem) then Exit(True); end; end; class function TArrayHelper<T>.IndexOf(var aArray : TArray<T>; aItem : T) : Integer; var icomparer : IEqualityComparer<T>; i : Integer; begin icomparer := TEqualityComparer<T>.Default; for i := Low(aArray) to High(aArray) do begin if icomparer.Equals(aArray[i],aItem) then Exit(i); end; Result := -1; end; { TStringArrayHelper } function TStringArrayHelper.Count : Integer; begin Result := TArrayHelper<string>.Count(Self); end; procedure TStringArrayHelper.Add(const aValue : string); begin TArrayHelper<string>.Add(Self,aValue); end; procedure TStringArrayHelper.Insert(const aValue : string; aIndex : Integer); begin TArrayHelper<string>.Insert(Self,aValue,aIndex); end; procedure TStringArrayHelper.Remove(aIndex : Integer); begin TArrayHelper<string>.Remove(Self,aIndex); end; function TStringArrayHelper.Contains(const aItem : string) : Boolean; begin Result := TArrayHelper<string>.Contains(Self,aItem); end; function TStringArrayHelper.IndexOf(const aItem : string) : Integer; begin Result := TArrayHelper<string>.IndexOf(Self,aItem); end; { TIntegerArrayHelper } function TIntegerArrayHelper.Count : Integer; begin Result := TArrayHelper<Integer>.Count(Self); end; procedure TIntegerArrayHelper.Add(aValue : Integer); begin TArrayHelper<Integer>.Add(Self,aValue); end; procedure TIntegerArrayHelper.Insert(const aValue : Integer; aIndex : Integer); begin TArrayHelper<Integer>.Insert(Self,aValue,aIndex); end; procedure TIntegerArrayHelper.Remove(aIndex : Integer); begin TArrayHelper<Integer>.Remove(Self,aIndex); end; function TIntegerArrayHelper.Contains(aItem : Integer) : Boolean; begin Result := TArrayHelper<Integer>.Contains(Self,aItem); end; function TIntegerArrayHelper.IndexOf(aItem : Integer) : Integer; begin Result := TArrayHelper<Integer>.IndexOf(Self,aItem); end; end.
unit fpcorm_dbcore_types_test; {$mode objfpc}{$H+} interface uses Classes, sysutils, sqldb, syncobjs, FGL, fpcorm_dbcore_types; type TSchoolClass = class; TSchoolClassList = specialize TFPGList<TSchoolClass>; TSchoolPerson = class; TSchoolPersonList = specialize TFPGList<TSchoolPerson>; { TSchoolClass } TSchoolClass = class(TfoDBTableObject) private fREC_ID: TfoDBTableFieldLongInt; fClassName: TfoDBTableFieldString; fSchoolPersonList_by_fk_Class_ID: TSchoolPersonList; // TfoDBFKReferencingListFunction function GetSchoolPersonList_by_fk_Class_ID(): TSchoolPersonList; public constructor Create(aConnection: TSQLConnector; aMutex: TCriticalSection); destructor Destroy; override; published property REC_ID: TfoDBTableFieldLongInt read fREC_ID; property ClassName: TfoDBTableFieldString read fClassName; property PersonList: TSchoolPersonList read GetSchoolPersonList_by_fk_Class_ID; { named by the UI, istead of "SchoolPersonList_by_fk_Class_ID" } end; { TSchoolPerson } TSchoolPerson = class(TfoDBTableObject) private fREC_ID: TfoDBTableFieldLongInt; fFirstName: TfoDBTableFieldString; fLastName: TfoDBTableFieldString; fAge: TfoDBTableFieldLongInt; ffk_Class_ID: TfoDBTableFieldLongInt; fSchoolClass_by_fk_Class_ID: TSchoolClass; function GetSchoolClass_by_fk_Class_ID(): TSchoolClass; procedure SetSchoolClass_by_fk_Class_ID(aSchoolClass: TSchoolClass); public constructor Create(aConnection: TSQLConnector; aMutex: TCriticalSection); destructor Destroy; override; function InsertAsNew(): Boolean; override; function Update(): Boolean; override; published property REC_ID: TfoDBTableFieldLongInt read fREC_ID; property FirstName: TfoDBTableFieldString read fFirstName; property LastName: TfoDBTableFieldString read fLastName; property Age: TfoDBTableFieldLongInt read fAge; property fk_Class_ID: TfoDBTableFieldLongInt read ffk_Class_ID; property SchoolClass: TSchoolClass read GetSchoolClass_by_fk_Class_ID write SetSchoolClass_by_fk_Class_ID; end; implementation { TSchoolPerson } function TSchoolPerson.GetSchoolClass_by_fk_Class_ID: TSchoolClass; begin if Assigned(fSchoolClass_by_fk_Class_ID) then Result := fSchoolClass_by_fk_Class_ID else begin fSchoolClass_by_fk_Class_ID := TSchoolClass.Create(Connection, Mutex); { Lazy load } {if not ObjectStatus.IsNew then if not fk_Class_ID.IsNull then fSchoolClass_by_fk_Class_ID.LoadBy_PK_REC_ID(fk_Class_ID.Value);} Result := fSchoolClass_by_fk_Class_ID; end; end; procedure TSchoolPerson.SetSchoolClass_by_fk_Class_ID(aSchoolClass: TSchoolClass); begin if not Assigned(aSchoolClass) then begin // user setting this object to nil ffk_Class_ID.IsNull := True; fSchoolClass_by_fk_Class_ID := nil; end else begin fSchoolClass_by_fk_Class_ID := aSchoolClass; if not aSchoolClass.REC_ID.IsNull then ffk_Class_ID.Value := aSchoolClass.REC_ID.Value else ffk_Class_ID.IsNull := True; end; end; constructor TSchoolPerson.Create(aConnection: TSQLConnector; aMutex: TCriticalSection); begin inherited Create(aConnection, aMutex); with TableInformation do begin TableCatalog := 'Students'; TableSchema := 'dbo'; TableType := 'U'; TableName := 'SchoolPerson'; end; fREC_ID := TfoDBTableFieldLongInt.Create(Self, 'REC_ID'); fREC_ID.IsPrimaryKey := True; fREC_ID.HasDefault := True; fREC_ID.IsIndexed := True; fFirstName := TfoDBTableFieldString.Create(Self, 'FirstName'); fLastName := TfoDBTableFieldString.Create(Self, 'LastName'); fAge := TfoDBTableFieldLongInt.Create(Self, 'Age'); ffk_Class_ID := TfoDBTableFieldLongInt.Create(Self, 'fk_Class_ID'); ffk_Class_ID.IsForeignKey := True; ffk_Class_ID.IsIndexed := True; ffk_Class_ID.IsNullable := True; end; destructor TSchoolPerson.Destroy; begin inherited Destroy; end; function TSchoolPerson.InsertAsNew: Boolean; const lProcedureName = 'InsertAsNew'; begin { Prevent recursive insertion } if ObjectStatus.IsInserting or ObjectStatus.IsUpdating or ObjectStatus.IsDeleting then Exit; if not Assigned(Connection) then raise Exception.Create('Unable to insert object of type: ' + ClassName + ', Connection is not set'); { if not ObjectStatus.IsNew then raise Exception.Create('Unable to insert object of type: ' + ClassName + ', the object is already in the database!'); } if Assigned(fSchoolClass_by_fk_Class_ID) then begin if fSchoolClass_by_fk_Class_ID.ObjectStatus.IsNew then begin if fSchoolClass_by_fk_Class_ID.InsertAsNew then ffk_Class_ID.Value := fSchoolClass_by_fk_Class_ID.REC_ID.Value end else if fSchoolClass_by_fk_Class_ID.ObjectStatus.IsChanged then begin // if end; end; end; function TSchoolPerson.Update: Boolean; begin end; { TSchoolClass } function TSchoolClass.GetSchoolPersonList_by_fk_Class_ID: TSchoolPersonList; begin Result := fSchoolPersonList_by_fk_Class_ID; end; constructor TSchoolClass.Create(aConnection: TSQLConnector; aMutex: TCriticalSection); begin inherited Create(aConnection, aMutex); fREC_ID := TfoDBTableFieldLongInt.Create(Self, 'REC_ID'); fClassName := TfoDBTableFieldString.Create(Self, 'ClassName'); fSchoolPersonList_by_fk_Class_ID := TSchoolPersonList.Create; end; destructor TSchoolClass.Destroy; begin inherited Destroy; end; end.
unit xNumInWords_UKR; interface uses xLngDefs; function numInWords_UKR(Value: int64; inGender: TGender; inpadezh: Tpadezh): string; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses SysUtils, prFun; var gender: TGender; ValueTemp: int64; //======================================================== function Num(Value: byte): String; begin Result := ''; case Value of 1: if gender <> genderFemale then Result := Result + 'один ' else Result := Result + 'одна '; 2: if gender <> genderFemale then Result := Result + 'два ' else Result := Result + 'дві '; 3: Result := Result + 'три '; 4: Result := Result + 'чотири '; 5: Result := Result + 'п'+char(39)+'ять '; 6: Result := Result + 'шість '; 7: Result := Result + 'сім '; 8: Result := Result + 'вісім '; 9: Result := Result + 'дев' + char(39) + 'ять '; 10: Result := Result + 'десять '; 11: Result := Result + 'одинадцять '; 12: Result := Result + 'дванадцять '; 13: Result := Result + 'тринадцять '; 14: Result := Result + 'чотирнадцять '; 15: Result := Result + 'п' + char(39) + 'ятнадцять '; 16: Result := Result + 'шістнадцять '; 17: Result := Result + 'сімнадцять '; 18: Result := Result + 'вісімнадцять '; 19: Result := Result + 'дев' + char(39) + 'ятнадцять '; end end; //======================================================== function Num10(Value: byte): String; begin case Value of 2: Result := Result + 'двадцять '; 3: Result := Result + 'тридцять '; 4: Result := Result + 'сорок '; 5: Result := Result + 'п' + char(39) + 'ятдесят '; 6: Result := Result + 'шістдесят '; 7: Result := Result + 'сімдесят '; 8: Result := Result + 'вісімдесят '; 9: Result := Result + 'дев' + char(39) + 'яносто '; end; end; //======================================================== function Num100(Value: byte): String; begin case Value of 1: Result := Result + 'сто '; 2: Result := Result + 'двісті '; 3: Result := Result + 'триста '; 4: Result := Result + 'чотириста '; 5: Result := Result + 'п' + char(39) + 'ятсот '; 6: Result := Result + 'шістсот '; 7: Result := Result + 'сімсот '; 8: Result := Result + 'вісімсот '; 9: Result := Result + 'дев' + char(39) + 'ятсот '; end end; //======================================================== function Num00:String; begin Result := Num100(ValueTemp div 100); ValueTemp := ValueTemp mod 100; if ValueTemp < 20 then Result := Result + Num(ValueTemp) else begin Result := Result + Num10(ValueTemp div 10); ValueTemp := ValueTemp mod 10; Result := Result + Num(ValueTemp); end; end; //======================================================== function NumMult(Mult: int64; s1,s2,s3: string): String; begin end; //============================================================================================== function _NumInWords_UKR(Value: int64; inGender: Tgender; padezh: Tpadezh): string; Begin if Value = 0 then Result := 'нуль ' else begin Result := ''; gender := genderNone; NumMult(1000000000000, 'трильйон ', 'трильйона ', 'трильйонів '); NumMult(1000000000, 'мільярд ', 'мільярда ', 'мільярдів '); NumMult(1000000, 'мільйон ', 'мільйона ', 'мільйонів '); gender := inGender; NumMult(1000, 'тисяча ', 'тисячі ', 'тисяч '); ValueTemp := Value; Num00; end; Result := AnsiUpperCase(Result[1]) + Copy(Result, 2, Length(Result) - 1); end; // STUB !!!! //============================================================================================== function numInWords_UKR(Value: int64; inGender: TGender; inpadezh: Tpadezh): string; begin Result := PropisUKR(Value, (inGender = genderNone)); end; end.
{ *************************************************************************** } { } { NLDJoystick - www.nldelphi.com Open Source Delphi designtime component } { } { Initiator: Albert de Weerd (aka NGLN) } { License: Free to use, free to modify } { Website: http://www.nldelphi.com/Forum/showthread.php?t=29812 } { SVN path: http://svn.nldelphi.com/nldelphi/opensource/ngln/NLDJoystick } { } { *************************************************************************** } { } { Date: Januar 21, 2013 } { Version: 1.2.0 } { } { *************************************************************************** } unit NLDJoystick; interface uses MMSystem, Windows, Messages, SysUtils, Classes, Math; const JOY_POVCENTERED = $FFFFFFFF; type TNLDJoystick = class; TJoyID = JOYSTICKID1..JOYSTICKID2; TJoyRelPos = record X: Double; Y: Double; Z: Double; R: Double; U: Double; V: Double; end; TJoyAbsPos = packed record X: Word; Y: Word; Z: Word; R: Word; U: Word; V: Word; end; TJoyButton = (JoyBtn1, JoyBtn2, JoyBtn3, JoyBtn4, JoyBtn5, JoyBtn6, JoyBtn7, JoyBtn8, JoyBtn9, JoyBtn10, JoyBtn11, JoyBtn12, JoyBtn13, JoyBtn14, JoyBtn15, JoyBtn16, JoyBtn17, JoyBtn18, JoyBtn19, JoyBtn20, JoyBtn21, JoyBtn22, JoyBtn23, JoyBtn24, JoyBtn25, JoyBtn26, JoyBtn27, JoyBtn28, JoyBtn29, JoyBtn30, JoyBtn31, JoyBtn32); TJoyButtons = set of TJoyButton; TJoyAxis = (axX, axY, axZ, axR, axU, axV); TJoyAxises = set of TJoyAxis; TJoyButtonEvent = procedure(Sender: TNLDJoystick; const Buttons: TJoyButtons) of object; TJoyMoveEvent = procedure(Sender: TNLDJoystick; const JoyPos: TJoyRelPos; const Buttons: TJoyButtons) of object; TJoyPOVChangedEvent = procedure(Sender: TNLDJoystick; Degrees: Single) of object; TMMJoyMsg = packed record Msg: Cardinal; Buttons: Cardinal; {wParam} XZPos: Word; {LoWord(lParam)} YPos: Word; {HiWord(lParam)} Result: Longint; end; TJoyRanges = packed record XDown: Word; XUp: Word; YDown: Word; YUp: Word; ZDown: Word; ZUp: Word; RDown: Word; RUp: Word; UDown: Word; UUp: Word; VDown: Word; VUp: Word; end; ENLDJoystickError = class(EComponentError); TNLDJoystick = class(TComponent) private FActive: Boolean; FAdvanced: Boolean; FAxisCount: Byte; FAxises: TJoyAxises; FButtonCount: Byte; FCenter: TJoyAbsPos; FHasPOV: Boolean; FID: TJoyID; FInterval: Integer; FMax: TJoyAbsPos; FMin: TJoyAbsPos; FOnButtonDown: TJoyButtonEvent; FOnButtonUp: TJoyButtonEvent; FOnIdle: TNotifyEvent; FOnMove: TJoyMoveEvent; FOnPOVChanged: TJoyPOVChangedEvent; FPrevButtons: UINT; FPrevButtonTick: Cardinal; FPrevIdleTick: Cardinal; FPrevMoveTick: Cardinal; FPrevPos: TJoyRelPos; FPrevPOV: Cardinal; FPrevPOVTick: Cardinal; FProcessedButtonOnce: Boolean; FProcessedMoveOnce: Boolean; FProcessedPOVOnce: Boolean; FRanges: TJoyRanges; FRepeatButtonDelay: Cardinal; FRepeatMoveDelay: Cardinal; FRepeatPOVDelay: Cardinal; FSuspendScreensaver: Boolean; FThreshold: Double; FWindowHandle: HWND; function GetInterval: Integer; function Initialize(NeedAdvanced: Boolean = False): Boolean; procedure InitTimer; procedure ProcessAdvanced; procedure ProcessSimple(var Message: TMMJoyMsg); procedure SetActive(Value: Boolean); procedure SetAdvanced(Value: Boolean); procedure SetInterval(Value: Integer); procedure SetThreshold(Value: Double); protected procedure DoButtonDown(Buttons: Cardinal); virtual; procedure DoButtonUp(Buttons: Cardinal); virtual; procedure DoIdle; virtual; procedure DoMove(const JoyPos: TJoyRelPos; Buttons: Cardinal); virtual; procedure DoPOVChanged(POV: Cardinal); virtual; procedure WndProc(var Message: TMessage); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AbsCenter: TJoyAbsPos read FCenter; property AbsMax: TJoyAbsPos read FMax; property AbsMin: TJoyAbsPos read FMin; property Active: Boolean read FActive write SetActive default False; property Advanced: Boolean read FAdvanced write SetAdvanced default False; property AxisCount: Byte read FAxisCount; property Axises: TJoyAxises read FAxises; property ButtonCount: Byte read FButtonCount; property HasPOV: Boolean read FHasPOV; property ID: TJoyID read FID; property OnButtonDown: TJoyButtonEvent read FOnButtonDown write FOnButtonDown; property OnButtonUp: TJoyButtonEvent read FOnButtonUp write FOnButtonUp; property OnIdle: TNotifyEvent read FOnIdle write FOnIdle; property OnMove: TJoyMoveEvent read FOnMove write FOnMove; property OnPOVChanged: TJoyPOVChangedEvent read FOnPOVChanged write FOnPOVChanged; property PollingInterval: Integer read GetInterval write SetInterval default 40; property RepeatButtonDelay: Cardinal read FRepeatButtonDelay write FRepeatButtonDelay default 350; property RepeatMoveDelay: Cardinal read FRepeatMoveDelay write FRepeatMoveDelay default 350; property RepeatPOVDelay: Cardinal read FRepeatPOVDelay write FRepeatPOVDelay default 350; property SuspendScreensaver: Boolean read FSuspendScreensaver write FSuspendScreensaver default False; property ThresholdFactor: Double read FThreshold write SetThreshold; end; function Joystick: TNLDJoystick; function Joystick1: TNLDJoystick; function Joystick2: TNLDJoystick; procedure Register; implementation procedure Register; begin RegisterComponents('NLDelphi', [TNLDJoystick]); end; var FJoystick1: TNLDJoystick = nil; FJoystick2: TNLDJoystick = nil; function Joystick: TNLDJoystick; begin Result := Joystick1; end; function Joystick1: TNLDJoystick; begin if FJoystick1 = nil then FJoystick1 := TNLDJoystick.Create(nil); Result := FJoystick1; end; function Joystick2: TNLDJoystick; begin if FJoystick2 = nil then FJoystick2 := TNLDJoystick.Create(nil); if FJoystick1 = FJoystick2 then FJoystick1 := nil; Result := FJoystick2; end; procedure NotifyKeyboardActivity; begin SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 1, nil, 0); end; { TNLDJoystick } const DefTimerID = 1; resourcestring SErrNoTimersAvail = 'Not enough timers available for joystick support'; SErrNoJoystickAvail = 'Not enough joysticks available for another ' + 'TNLDJoystick instance. Maximum joystick count is two.'; constructor TNLDJoystick.Create(AOwner: TComponent); begin if FJoystick1 = nil then begin FJoystick1 := Self; FID := JOYSTICKID1; end else if FJoystick2 = nil then begin FJoystick2 := Self; FID := JOYSTICKID2; end else raise ENLDJoystickError.Create(SErrNoJoystickAvail); inherited Create(AOwner); FInterval := 40; FRepeatButtonDelay := 350; FRepeatMoveDelay := 350; FRepeatPOVDelay := 350; FWindowHandle := AllocateHWnd(WndProc); FActive := Initialize(FAdvanced); end; destructor TNLDJoystick.Destroy; begin SetActive(False); DeallocateHWnd(FWindowHandle); if FJoystick1 = Self then FJoystick1 := nil else FJoystick2 := nil; inherited Destroy; end; procedure TNLDJoystick.DoButtonDown(Buttons: Cardinal); begin if Assigned(FOnButtonDown) then FOnButtonDown(Self, TJoyButtons(Buttons)); if FSuspendScreensaver then NotifyKeyboardActivity; end; procedure TNLDJoystick.DoButtonUp(Buttons: Cardinal); begin if Assigned(FOnButtonUp) then FOnButtonUp(Self, TJoyButtons(Buttons)); if FSuspendScreensaver then NotifyKeyboardActivity; end; procedure TNLDJoystick.DoIdle; begin if Assigned(FOnIdle) then FOnIdle(Self); end; procedure TNLDJoystick.DoMove(const JoyPos: TJoyRelPos; Buttons: Cardinal); begin if Assigned(FOnMove) then FOnMove(Self, JoyPos, TJoyButtons(Buttons)); if FSuspendScreensaver then NotifyKeyboardActivity; end; procedure TNLDJoystick.DoPOVChanged(POV: Cardinal); begin if Assigned(FOnPOVChanged) then FOnPOVChanged(Self, POV/100); if FSuspendScreensaver then NotifyKeyboardActivity; end; function TNLDJoystick.GetInterval: Integer; begin if FAdvanced then Result := FInterval else Result := -1; end; function TNLDJoystick.Initialize(NeedAdvanced: Boolean = False): Boolean; var JoyInfo: TJoyInfoEx; JoyCaps: TJoyCaps; begin joyReleaseCapture(FID); ZeroMemory(@FPrevPos, SizeOf(FPrevPos)); ZeroMemory(@JoyInfo, SizeOf(JoyInfo)); JoyInfo.dwSize := SizeOf(JoyInfo); JoyInfo.dwFlags := JOY_RETURNCENTERED; if (joyGetNumDevs <= FID) or (joyGetPosEx(FID, @JoyInfo) <> JOYERR_NOERROR) then Result := False else begin joyGetDevCaps(FID, @JoyCaps, SizeOf(JoyCaps)); FAxisCount := Min(JoyCaps.wNumAxes, JoyCaps.wMaxAxes); FButtonCount := Min(JoyCaps.wNumButtons, JoyCaps.wMaxButtons); FAxises := [axX, axY]; FCenter.X := JoyInfo.wXpos; FCenter.Y := JoyInfo.wYpos; FMax.X := JoyCaps.wXmax; FMax.Y := JoyCaps.wYmax; FMin.X := JoyCaps.wXmin; FMin.Y := JoyCaps.wYmin; FRanges.XDown := FCenter.X - FMin.X; FRanges.XUp := FMax.X - FCenter.X; FRanges.YDown := FCenter.Y - FMin.Y; FRanges.YUp := FMax.Y - FCenter.Y; if (JOYCAPS_HASZ and JoyCaps.wCaps) = JOYCAPS_HASZ then begin Include(FAxises, axZ); FCenter.Z := JoyInfo.wZpos; FMax.Z := JoyCaps.wZmax; FMin.Z := JoyCaps.wZmin; FRanges.ZDown := FCenter.Z - FMin.Z; FRanges.ZUp := FMax.Z - FCenter.Z; end; if (not NeedAdvanced) or ((FButtonCount <= 4) and (FAxisCount <= 3)) then begin FAdvanced := False; FHasPOV := False; joySetCapture(FWindowHandle, FID, 0, True); end else begin FAdvanced := True; FInterval := Max(JoyCaps.wPeriodMin, Min(FInterval, JoyCaps.wPeriodMax)); if (JOYCAPS_HASR and JoyCaps.wCaps) = JOYCAPS_HASR then begin Include(FAxises, axR); FCenter.R := JoyInfo.dwRpos; FMax.R := JoyCaps.wRmax; FMin.R := JoyCaps.wRmin; FRanges.RDown := FCenter.R - FMin.R; FRanges.RUp := FMax.R - FCenter.R; end; if (JOYCAPS_HASU and JoyCaps.wCaps) = JOYCAPS_HASU then begin Include(FAxises, axU); FCenter.U := JoyInfo.dwUpos; FMax.U := JoyCaps.wUmax; FMin.U := JoyCaps.wUmin; FRanges.UDown := FCenter.U - FMin.U; FRanges.UUp := FMax.U - FCenter.U; end; if (JOYCAPS_HASV and JoyCaps.wCaps) = JOYCAPS_HASV then begin Include(FAxises, axV); FCenter.V := JoyInfo.dwVpos; FMax.V := JoyCaps.wVmax; FMin.V := JoyCaps.wVmin; FRanges.VDown := FCenter.V - FMin.V; FRanges.VUp := FMax.V - FCenter.V; end; FHasPOV := (JOYCAPS_HASPOV and JoyCaps.wCaps) = JOYCAPS_HASPOV; InitTimer; end; Result := True; end; end; procedure TNLDJoystick.InitTimer; begin KillTimer(FWindowHandle, DefTimerID); if SetTimer(FWindowHandle, DefTimerID, FInterval, nil) = 0 then raise ENLDJoystickError.Create(SErrNoTimersAvail); end; procedure TNLDJoystick.ProcessAdvanced; const JOY_RETURN = JOY_RETURNX or JOY_RETURNY or JOY_RETURNZ or JOY_RETURNR or JOY_RETURNU or JOY_RETURNV or JOY_RETURNPOVCTS or JOY_RETURNBUTTONS; CenterJoyPos: TJoyRelPos = (X:0.0; Y:0.0; Z:0.0; R:0.0; U:0.0; V:0.0); var JoyInfo: TJoyInfoEx; JoyPos: TJoyRelPos; CurrentTick: Cardinal; MustDelay: Boolean; begin ZeroMemory(@JoyInfo, SizeOf(JoyInfo)); JoyInfo.dwSize := SizeOf(JoyInfo); JoyInfo.dwFlags := JOY_RETURN; if joyGetPosEx(FID, @JoyInfo) = JOYERR_NOERROR then with JoyInfo do begin if (FPrevIdleTick = 0) and (LoWord(wXpos) = FCenter.X) and (LoWord(wYpos) = FCenter.Y) and (LoWord(wZpos) = FCenter.Z) and (LoWord(dwRpos) = FCenter.R) and (LoWord(dwUpos) = FCenter.U) and (LoWord(dwVpos) = FCenter.V) and (wButtons = 0) and ((not FHasPOV) or (dwPOV = JOY_POVCENTERED)) then begin FPrevIdleTick := GetTickCount; DoIdle; end else FPrevIdleTick := 0; JoyPos := FPrevPos; if LoWord(wXpos) < FCenter.X then JoyPos.X := (LoWord(wXpos) - FCenter.X) / FRanges.XDown else JoyPos.X := (LoWord(wXpos) - FCenter.X) / FRanges.XUp; if LoWord(wYpos) < FCenter.Y then JoyPos.Y := (LoWord(wYpos) - FCenter.Y) / FRanges.YDown else JoyPos.Y := (LoWord(wYpos) - FCenter.Y) / FRanges.YUp; if axZ in FAxises then if LoWord(wZpos) < FCenter.Z then JoyPos.Z := (LoWord(wZpos) - FCenter.Z) / FRanges.ZDown else JoyPos.Z := (LoWord(wZpos) - FCenter.Z) / FRanges.ZUp; if axR in FAxises then if LoWord(dwRpos) < FCenter.R then JoyPos.R := (LoWord(dwRpos) - FCenter.R) / FRanges.RDown else JoyPos.R := (LoWord(dwRpos) - FCenter.R) / FRanges.RUp; if axU in FAxises then if LoWord(dwUpos) < FCenter.U then JoyPos.U := (LoWord(dwUpos) - FCenter.U) / FRanges.UDown else JoyPos.U := (LoWord(dwUpos) - FCenter.U) / FRanges.UUp; if axV in FAxises then if LoWord(dwVpos) < FCenter.V then JoyPos.V := (LoWord(dwVpos) - FCenter.V) / FRanges.VDown else JoyPos.V := (LoWord(dwVpos) - FCenter.V) / FRanges.VUp; CurrentTick := GetTickCount; MustDelay := CurrentTick < FPrevButtonTick + FRepeatButtonDelay; if (wButtons > 0) or (wButtons <> FPrevButtons) then begin if (not MustDelay) or (not FProcessedButtonOnce) then begin if wButtons >= FPrevButtons then DoButtonDown(wButtons) else DoButtonUp(wButtons); FProcessedButtonOnce := True; end; end else begin FPrevButtonTick := CurrentTick; FProcessedButtonOnce := False; end; FPrevButtons := wButtons; MustDelay := CurrentTick < FPrevMoveTick + FRepeatMoveDelay; if not CompareMem(@JoyPos, @CenterJoyPos, SizeOf(TJoyRelPos)) then begin if (not MustDelay) or (not FProcessedMoveOnce) then begin DoMove(JoyPos, wButtons); FProcessedMoveOnce := True; end; end else begin FPrevMoveTick := CurrentTick; FProcessedMoveOnce := False; end; FPrevPos := JoyPos; MustDelay := CurrentTick < FPrevPOVTick + FRepeatPOVDelay; if FHasPOV and ((dwPOV <> JOY_POVCENTERED) or (dwPOV <> FPrevPOV)) then begin if (not MustDelay) or (not FProcessedPOVOnce) then begin DoPOVChanged(dwPOV); FProcessedPOVOnce := True; end; end else begin FPrevPOVTick := CurrentTick; FProcessedPOVOnce := False; end; FPrevPOV := dwPOV; end; end; procedure TNLDJoystick.ProcessSimple(var Message: TMMJoyMsg); var JoyPos: TJoyRelPos; begin with Message do case Msg of MM_JOY1BUTTONDOWN, MM_JOY2BUTTONDOWN: DoButtonDown(Buttons); MM_JOY1BUTTONUP, MM_JOY2BUTTONUP: DoButtonUp(Buttons); MM_JOY1MOVE, MM_JOY2MOVE: begin JoyPos := FPrevPos; if XZPos < FCenter.X then JoyPos.X := (XZPos - FCenter.X) / FRanges.XDown else JoyPos.X := (XZPos - FCenter.X) / FRanges.XUp; if YPos < FCenter.Y then JoyPos.Y := (YPos - FCenter.Y) / FRanges.YDown else JoyPos.Y := (YPos - FCenter.Y) / FRanges.YUp; FPrevPos := JoyPos; DoMove(JoyPos, Buttons); end; MM_JOY1ZMOVE, MM_JOY2ZMOVE: begin JoyPos := FPrevPos; if XZPos < FCenter.Z then JoyPos.Z := (XZPos - FCenter.Z) / FRanges.ZDown else JoyPos.Z := (XZPos - FCenter.Z) / FRanges.ZUp; FPrevPos := JoyPos; DoMove(JoyPos, Buttons); end; else Dispatch(Message); end; end; procedure TNLDJoystick.SetActive(Value: Boolean); begin if FActive <> Value then begin if Value then FActive := Initialize(FAdvanced) else begin joyReleaseCapture(FID); KillTimer(FWindowHandle, DefTimerID); FActive := False; end; end; end; procedure TNLDJoystick.SetAdvanced(Value: Boolean); begin if FAdvanced <> Value then begin if not Value then FAdvanced := Value else if FActive then Initialize(Value) else FAdvanced := Value; end; end; procedure TNLDJoystick.SetInterval(Value: Integer); var JoyCaps: TJoyCaps; begin if Value <> FInterval then begin if (Value <> 0) and FAdvanced then begin joyGetDevCaps(FID, @JoyCaps, SizeOf(JoyCaps)); FInterval := Max(JoyCaps.wPeriodMin, Min(Value, JoyCaps.wPeriodMax)); InitTimer; end else FInterval := 0; end; end; procedure TNLDJoystick.SetThreshold(Value: Double); var JoyThreshold: UINT; begin if FThreshold <> Value then begin FThreshold := Max(0.0, Min(Value, 1.0)); joySetThreshold(FID, Round(FThreshold * FRanges.XUp)); if joyGetThreshold(FID, @JoyThreshold) = JOYERR_NOERROR then FThreshold := JoyThreshold / FRanges.XUp; end; end; procedure TNLDJoystick.WndProc(var Message: TMessage); begin if not FAdvanced then ProcessSimple(TMMJoyMsg(Message)) else if Message.Msg = WM_TIMER then ProcessAdvanced else Dispatch(Message); end; initialization finalization if FJoystick1 <> nil then FJoystick1.Free; if FJoystick2 <> nil then FJoystick2.Free; end.
{ AutoPanel unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit AutoPanel; {$mode objfpc}{$H+} interface uses SysUtils, Classes, LCLType, ExtCtrls; type TPlacement = packed record Left, Top, Width, Height: Integer; end; PIntArray = ^TRectArray; TRectArray = array[0..4096] of TPlacement; TAutoPanel = class(TPanel) private { Private declarations } protected { Protected declarations } pWidth :Integer; pHeight:Integer; FAutoChildPosLeft : Boolean; FAutoChildPosTop : Boolean; FAutoChildWidth : Boolean; FAutoChildHeight : Boolean; PCtrlsCoordArr:PIntArray; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; procedure Resize; override; published { Published declarations } property AutoChildPosLeft : Boolean read FAutoChildPosLeft write FAutoChildPosLeft default False; property AutoChildPosTop : Boolean read FAutoChildPosTop write FAutoChildPosTop default False; property AutoChildWidth : Boolean read FAutoChildWidth write FAutoChildWidth default False; property AutoChildHeight : Boolean read FAutoChildHeight write FAutoChildHeight default False; property Align; property Alignment; property BevelInner; property BevelOuter; property BevelWidth; property BorderWidth; property BorderStyle; property DragCursor; property DragMode; property Enabled; property Caption; property Color; property Font; //property Locked; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnStartDrag; property Anchors; property AutoSize; //property BiDiMode; property Constraints; property UseDockManager default True; property DockSite; property DragKind; property FullRepaint; //property ParentBiDiMode; //property OnCanResize; property OnConstrainedResize; property OnDockDrop; property OnDockOver; property OnEndDock; property OnGetSiteInfo; property OnStartDock; property OnUnDock; end; //procedure Register; implementation //-------------------------------------- constructor TAutoPanel.Create(AOwner: TComponent); begin inherited; FAutoChildPosLeft := False; FAutoChildPosTop := False; FAutoChildWidth := False; FAutoChildHeight := False; pWidth := -1; pHeight := -1; PCtrlsCoordArr := nil; end; destructor TAutoPanel.Destroy; begin inherited; FreeMem(PCtrlsCoordArr); end; procedure TAutoPanel.Loaded; var i:Integer; begin inherited Loaded; if (csDesigning in ComponentState) then Exit; if (pWidth = -1) and (pHeight = -1) then begin GetMem(PCtrlsCoordArr, ControlCount * sizeof(TRect)); for i := 0 to ControlCount - 1 do begin PCtrlsCoordArr^[i].Left := Controls[i].Left; PCtrlsCoordArr^[i].Top := Controls[i].Top; PCtrlsCoordArr^[i].Width := Controls[i].Width; PCtrlsCoordArr^[i].Height := Controls[i].Height; end; pWidth := Width; pHeight := Height; end; end; procedure TAutoPanel.Resize; var I:Integer; begin inherited; if (csDesigning in ComponentState) then Exit; if not (AutoChildPosLeft or AutoChildWidth or AutoChildPosTop or AutoChildHeight) then Exit; try for i := 0 to ControlCount - 1 do begin if(AutoChildPosLeft = true) then if (AutoChildWidth = true) then begin Controls[i].Left := MulDiv (PCtrlsCoordArr^[i].Left,Width,pWidth); Controls[i].Width := MulDiv (PCtrlsCoordArr^[i].Width,Width,pWidth); end else Controls[i].Left := Round( PCtrlsCoordArr^[i].Left * Width / pWidth + ((PCtrlsCoordArr^[i].Width) * Width / pWidth - (PCtrlsCoordArr^[i].Width))/2 ); if(AutoChildPosTop = true) then if (AutoChildHeight = true) then begin Controls[i].Top := MulDiv (PCtrlsCoordArr^[i].Top,Height,pHeight); Controls[i].Height := MulDiv (PCtrlsCoordArr^[i].Height,Height,pHeight); end else Controls[i].Top := Round( PCtrlsCoordArr^[i].Top * Height / pHeight + ((PCtrlsCoordArr^[i].Height) * Height / pHeight - (PCtrlsCoordArr^[i].Height))/2 ); end; finally end; end; //-------------------------------------- end.
// implements the IConfigReader and IConfigWriter interfaces using a TGExpertsSettings instance // Original Author: Thomas Mueller (http://www.dummzeuch.de) unit GX_CodeFormatterGXConfigWrapper; {$I GX_CondDefine.inc} interface uses Classes, GX_ConfigurationInfo, GX_CodeFormatterConfigHandler; type TGxConfigWrapper = class(TInterfacedObject, IConfigReader, IConfigWriter) private FSettings: TExpertSettings; protected // implementation of IConfigReader function ReadBool(const AName: string; ADefault: Boolean): Boolean; function ReadInteger(const AName: string; ADefault: Integer): Integer; function ReadString(const AName, ADefault: string): string; procedure ReadStrings(const ASection: string; const AList: TStrings); protected // implementatio of IConfigWriter procedure WriteBool(const AName: string; AValue: Boolean); procedure WriteInteger(const AName: string; AValue: Integer); procedure WriteString(const AName: string; const AValue: string); procedure WriteStrings(const ASection: string; const AList: TStrings); public constructor Create(ASettings: TExpertSettings); end; implementation { TGxConfigWrapper } constructor TGxConfigWrapper.Create(ASettings: TExpertSettings); begin inherited Create; FSettings := ASettings; end; function TGxConfigWrapper.ReadBool(const AName: string; ADefault: Boolean): Boolean; begin Result := FSettings.ReadBool(AName, ADefault); end; function TGxConfigWrapper.ReadInteger(const AName: string; ADefault: Integer): Integer; begin Result := FSettings.ReadInteger(AName, ADefault); end; function TGxConfigWrapper.ReadString(const AName, ADefault: string): string; begin Result := FSettings.ReadString(AName, ADefault); end; procedure TGxConfigWrapper.ReadStrings(const ASection: string; const AList: TStrings); begin FSettings.ReadStrings(ASection, AList, 'List'); end; procedure TGxConfigWrapper.WriteBool(const AName: string; AValue: Boolean); begin FSettings.WriteBool(AName, AValue); end; procedure TGxConfigWrapper.WriteInteger(const AName: string; AValue: Integer); begin FSettings.WriteInteger(AName, AValue); end; procedure TGxConfigWrapper.WriteString(const AName, AValue: string); begin FSettings.WriteString(AName, AValue); end; procedure TGxConfigWrapper.WriteStrings(const ASection: string; const AList: TStrings); begin FSettings.WriteStrings(ASection, AList, 'List'); end; end.
program ifChecking; var { local variable declaration } a:integer; begin a:= 10; IF a < 20 THEN write('a is less than 20 ' ); write('value of a is : ', a); end.
unit MainForm; { $Id: MainForm.pas,v 1.1 2004/07/23 13:05:23 step Exp $ } // $Log: MainForm.pas,v $ // Revision 1.1 2004/07/23 13:05:23 step // утилита занесена в CVS // interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TMain = class(TForm) bLoadHLinks: TButton; edArchiIni: TEdit; edHLinkFile: TEdit; FileDialog: TOpenDialog; labIniFile: TLabel; labDataFile: TLabel; bSelectHlinkFile: TButton; bSelectArchiIni: TButton; labDataFile2: TLabel; edDatesFile: TEdit; bSelectDatesFile: TButton; bLoadDates: TButton; procedure bLoadHLinksClick(Sender: TObject); procedure bSelectHlinkFileClick(Sender: TObject); procedure bSelectArchiIniClick(Sender: TObject); procedure bSelectDatesFileClick(Sender: TObject); procedure bLoadDatesClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Main: TMain; implementation {$R *.dfm} uses DataLoader, l3FileUtils; procedure TMain.bLoadHLinksClick(Sender: TObject); begin if not FileExists(edArchiIni.Text) then raise Exception.Create(Format('Не найден файл %s', [edArchiIni.Text])); if not FileExists(edHLinkFile.Text) then raise Exception.Create(Format('Не найден файл %s', [edHLinkFile.Text])); with THLinksLoader.Create(edArchiIni.Text) do try RecalcHLinks(edHLinkFile.Text); finally Free; end; end; procedure TMain.bSelectHlinkFileClick(Sender: TObject); begin with FileDialog do begin InitialDir := Application.ExeName; DefaultExt := '*.*'; FileName := ''; Filter := 'Все файлы|*.*'; FilterIndex := 0; Title := 'Файл с данными о гиперссылках'; end; if FileDialog.Execute then begin edHLinkFile.Text := FileDialog.FileName; end; end; procedure TMain.bSelectArchiIniClick(Sender: TObject); begin with FileDialog do begin InitialDir := Application.ExeName; DefaultExt := '*.ini'; FileName := 'archi.ini'; Filter := 'Ini-файлы|*.ini|Все файлы|*.*'; FilterIndex := 1; Title := 'Файл с настройками БД (archi.ini)'; end; if FileDialog.Execute then begin edArchiIni.Text := FileDialog.FileName; end; end; procedure TMain.bSelectDatesFileClick(Sender: TObject); begin with FileDialog do begin InitialDir := Application.ExeName; DefaultExt := '*.*'; FileName := ''; Filter := 'Все файлы|*.*'; FilterIndex := 0; Title := 'Файл с данными о датах'; end; if FileDialog.Execute then begin edDatesFile.Text := FileDialog.FileName; end; end; procedure TMain.bLoadDatesClick(Sender: TObject); begin if not FileExists(edArchiIni.Text) then raise Exception.Create(Format('Не найден файл %s', [edArchiIni.Text])); if not FileExists(edDatesFile.Text) then raise Exception.Create(Format('Не найден файл %s', [edDatesFile.Text])); with TDatesLoader.Create(edArchiIni.Text) do try AddDates(edDatesFile.Text); finally Free; end; end; procedure TMain.FormCreate(Sender: TObject); var l_Path: string; begin l_Path := ConcatDirName(ExtractDirName(Application.ExeName), 'archi.ini'); if FileExists(l_Path) then edArchiIni.Text := l_Path; end; end.
program TESTCON ; //**************************************************************** //$A+ //**************************************************************** // - Feste CHARs an CONST Strings uebergeben geht schief // - muss mit STR gemacht werden // - auch bei TRIM und anderen BUILTIN Funktionen // - unabhaengig davon funktioniert die Rueckgabe trotzdem nicht //**************************************************************** type REC = record A : INTEGER ; B : INTEGER ; C : CHAR ( 20 ) ; end ; PC20 = -> CHAR ( 20 ) ; SHORTINT = - 32000 .. 32000 ; var T1 : REC := ( 12 , 15 , 'Bernd' ) ; PR : -> REC ; P2 : -> REC ; PX : -> CHAR ( 20 ) ; CX : CHAR ( 20 ) ; S : STRING ( 20 ) ; S2 : STRING ( 20 ) ; function XTRIM ( const S1 : STRING ) : STRING ; var LEN : INTEGER ; LS1 : INTEGER ; CP : -> CHAR ; SP1 : -> SHORTINT ; SP2 : -> SHORTINT ; begin (* XTRIM *) LS1 := LENGTH ( S1 ) ; WRITELN ( 'xtrim: ls1 = ' , LS1 : 1 ) ; if LS1 = 0 then begin XTRIM := S1 ; return ; end (* then *) ; CP := ADDR ( S1 [ LS1 ] ) ; LEN := LS1 ; while LEN > 0 do begin if CP -> <> ' ' then break ; CP := PTRADD ( CP , - 1 ) ; LEN := LEN - 1 ; end (* while *) ; CP := ADDR ( S1 [ 1 ] ) ; while LEN > 0 do begin if CP -> <> ' ' then break ; CP := PTRADD ( CP , 1 ) ; LEN := LEN - 1 ; end (* while *) ; WRITELN ( 'xtrim: len = ' , LEN : 1 ) ; XTRIM := REPEATSTR ( ' ' , LEN ) ; MEMCPY ( STRRESULTP , CP , LEN ) ; WRITELN ( 'xtrim: strres = ' , STRRESULTP ) ; CP := STRRESULTP ; WRITELN ( 'xtrim: strres = ' , CP -> ) ; WRITELN ( 'xtrim: res = ' , RESULTP ) ; SP1 := PTRADD ( RESULTP , 0 ) ; SP2 := PTRADD ( RESULTP , 2 ) ; WRITELN ( 'xtrim: res1 = ' , SP1 -> ) ; WRITELN ( 'xtrim: res2 = ' , SP2 -> ) ; end (* XTRIM *) ; procedure TCON ( X : record A1 : INTEGER ; B1 : INTEGER ; C1 : CHAR ( 20 ) ; end ; const Y : record A1 : INTEGER ; B1 : INTEGER ; C1 : CHAR ( 20 ) ; end ; var Z : record A1 : INTEGER ; B1 : INTEGER ; C1 : CHAR ( 20 ) ; end ) ; begin (* TCON *) WRITELN ( X . A1 , X . B1 , X . C1 ) ; WRITELN ( Y . A1 , Y . B1 , Y . C1 ) ; WRITELN ( Z . A1 , Z . B1 , Z . C1 ) ; end (* TCON *) ; function TPTR ( var Y : -> REC ) : -> REC ; begin (* TPTR *) TPTR := Y end (* TPTR *) ; function T2 ( X : -> CHAR ( 20 ) ) : -> CHAR ( 20 ) ; begin (* T2 *) T2 := X end (* T2 *) ; function T3 ( X : PC20 ) : PC20 ; begin (* T3 *) T3 := X end (* T3 *) ; begin (* HAUPTPROGRAMM *) TCON ( T1 , T1 , T1 ) ; if TRUE then begin P2 := ADDR ( T1 ) ; PR := TPTR ( P2 ) ; WRITELN ( P2 ) ; WRITELN ( PR ) ; end (* then *) ; WRITELN ( T2 ( ADDR ( T1 . C ) ) ) ; CX := T2 ( ADDR ( T1 . C ) ) -> ; WRITELN ( 'CX = ' , CX ) ; CX := T3 ( ADDR ( T1 . C ) ) -> ; WRITELN ( 'CX = ' , CX ) ; S := STR ( CX ) ; S2 := XTRIM ( S ) ; WRITELN ( 'maxlength (s2) = ' , MAXLENGTH ( S2 ) ) ; WRITELN ( 'length (s2) = ' , LENGTH ( S2 ) ) ; WRITELN ( '<' , S2 , '>' ) ; if FALSE then begin PX := T2 ( ADDR ( T1 . C ) ) ; WRITELN ( PX -> ) ; S := XTRIM ( STR ( PX -> ) ) ; WRITELN ( 'maxlength (s) = ' , MAXLENGTH ( S ) ) ; WRITELN ( 'length (s) = ' , LENGTH ( S ) ) ; WRITELN ( '<' , S , '>' ) ; WRITELN ( 'SUBSTR mit 0: ' , SUBSTR ( S , 1 , 0 ) ) ; WRITELN ( 'hat funktioniert' ) ; WRITELN ( 'RIGHT mit 0: ' , RIGHT ( S , 0 ) ) ; WRITELN ( 'hat funktioniert' ) ; WRITELN ( 'LEFT mit 0: ' , LEFT ( S , 0 ) ) ; WRITELN ( 'hat funktioniert' ) ; end (* then *) end (* HAUPTPROGRAMM *) .
{ A Companhia de Água Corredeira armazena os dados de seus clientes (codigo, nome, endereco e mcons). Elabore um programa capaz de ler os dados de n (máximo de 20) clientes (utilizar um vetor de registros para armazenar esses dados). Em seguida, o programa deve imprimir um relatório conforme o modelo abaixo. Nome Endereço Valor da Conta XXX XXXX XX XXX XXXX XX XXX XXXX XX } Program Exercicio8 ; Type reg_cliente = record codigo:integer; nome: string; endereco: string; mcons: real; end; vet_clientes = array[1..20] of reg_cliente; var clientes:vet_clientes; n:integer; procedure verificarQuantidade(var qtd:integer); begin repeat write('Digite a quantidade de clientes entre 1 e 20: '); readln(n); until (qtd >0) and (qtd <= 20); end; Procedure cadastrarClientes(var vet: vet_clientes; n: integer); var sexo: char; i: integer; begin for i := 1 to n do begin write('Nome da pessoa ', i, ': '); readln(vet[i].nome); write('Endereço: ', i, ': '); readln(vet[i].endereco); write('Consumo Médio: ', i, ': '); readln(vet[i].mcons); clrscr; end; end; procedure imprimirRelatorio(clientes:vet_clientes;n:integer); var i:integer; begin gotoxy(1,1); writeln('Nome'); gotoxy(60,1); writeln('Endereço'); gotoxy(120,1); writeln('Valor da Conta'); gotoxy(1,2); for i:= 1 to 134 do begin write('-'); end; for i := 1 to n do begin gotoxy(1,(i+2)); writeln(clientes[i].nome); gotoxy(60,(i+2)); writeln(clientes[i].endereco); gotoxy(120,(i+2)); writeln('R$: ', (clientes[i].mcons*0.35):2:2); end; end; Begin verificarQuantidade(n); cadastrarClientes(clientes, n); imprimirRelatorio(clientes, n); End.
unit ColorUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics; //Amount is 0..100 percent value function Lighten(Color: TColor; Amount: SmallInt = 256 div 2): TColor; function Darken(Color: TColor; Amount: SmallInt): TColor; function MixColors(Color1, Color2: TColor; W1: Integer = 256 div 2): TColor; function BlendColor(Color1, Color2: TColor; W1: Integer): TColor; function InverseColor(Color: TColor): TColor; function GrayLevelColor(const Color: TColor): Integer; function IsDarkColor(const Color: TColor): Boolean; //Bring Black or White depend on the color passed function ContrastColor(const Color: TColor): TColor; //TODO get same color but suite the other brighness amount //function OppositeColor(const Color: TColor): TColor; implementation function Lighten(Color: TColor; Amount: SmallInt): TColor; var C: Integer; R, G, B: Integer; begin Amount := ($FF * Amount) div 100; C := ColorToRgb(Color); R := C and $FF + Amount; G := C shr 8 and $FF + Amount; B := C shr 16 and $FF + Amount; if R < 0 then R := 0 else if R > 255 then R := 255; if G < 0 then G := 0 else if G > 255 then G := 255; if B < 0 then B := 0 else if B > 255 then B := 255; Result := R or (G shl 8) or (B shl 16); end; function Darken(Color: TColor; Amount: SmallInt): TColor; begin Result := Lighten(Color, - Amount); end; function MixColors(Color1, Color2: TColor; W1: Integer): TColor; var W2: Cardinal; C1, C2: Cardinal; begin W2 := W1 xor 255; C1 := ColorToRgb(Color1); C2 := ColorToRgb(Color2); Result := Integer( ((C1 and $FF00FF) * Cardinal(W1) + (C2 and $FF00FF) * W2) and $FF00FF00 + ((C1 and $00FF00) * Cardinal(W1) + (C2 and $00FF00) * W2) and $00FF0000) shr 8; end; function BlendColor(Color1, Color2: TColor; W1: Integer): TColor; var C1, C2: Cardinal; W2, A1, A2, D, F, G: Integer; begin C1 := ColorToRgb(Color1); C2 := ColorToRgb(Color2); if W1 >= 100 then D := 1000 else D := 100; W2 := D - W1; F := D div 2; A2 := C2 shr 16 * Cardinal(W2); A1 := C1 shr 16 * Cardinal(W1); G := (A1 + A2 + F) div D and $FF; Result := G shl 16; A2 := (C2 shr 8 and $FF) * Cardinal(W2); A1 := (C1 shr 8 and $FF) * Cardinal(W1); G := (A1 + A2 + F) div D and $FF; Result := Result or G shl 8; A2 := (C2 and $FF) * Cardinal(W2); A1 := (C1 and $FF) * Cardinal(W1); G := (A1 + A2 + F) div D and $FF; Result := Result or G; end; function InverseColor(Color: TColor): TColor; begin Color := ColorToRGB(Color); Result := RGBToColor(255 - Red(Color), 255 - Green(Color), 255 - Blue(Color)) ; end; //from http://www.delphigroups.info/2/10/314913.html function GrayLevelColor(const Color: TColor): Integer; begin Result := (77 * (Color and $FF) + 151 * (Color shr 8 and $FF) + 28 * (Color shr 16 and $FF)) shr 8; end; function IsDarkColor(const Color: TColor): Boolean; begin Result := GrayLevelColor(Color) < 128; end; function ContrastColor(const Color: TColor): TColor; begin if IsDarkColor(Color) then Result := clWhite else Result := clBlack; end; end.
unit UiCloudDocument; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, rtti, Math, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSNativeMaciCloud, FMX.Layouts, FMX.ListBox, FMX.Objects, FMX.ListView.Types, FMX.Memo, FMX.ListView, IOUtils, FMX.TMSNativeNSCore; type TForm1144 = class(TForm) TMSFMXNativeMaciCloudDocument1: TTMSFMXNativeMaciCloudDocument; Label1: TLabel; Panel1: TPanel; Panel2: TPanel; ListView1: TListView; Panel3: TPanel; Button1: TButton; Button2: TButton; Panel4: TPanel; Panel5: TPanel; Memo1: TMemo; Button3: TButton; Image1: TImage; procedure TMSFMXNativeMaciCloudDocument1Initialized(Sender: TObject; ASuccess: Boolean); procedure TMSFMXNativeMaciCloudDocument1DocumentsLoaded(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure TMSFMXNativeMaciCloudDocument1DocumentDeleted(Sender: TObject; AItem: TTMSFMXNativeMaciCloudDocumentItem; ASuccess: Boolean; AError: string); procedure TMSFMXNativeMaciCloudDocument1DocumentAdded(Sender: TObject; AItem: TTMSFMXNativeMaciCloudDocumentItem; ASuccess: Boolean; AError: string); procedure Button3Click(Sender: TObject); procedure TMSFMXNativeMaciCloudDocument1DocumentsRefreshed(Sender: TObject); procedure ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); procedure TMSFMXNativeMaciCloudDocument1DocumentDataChanged(Sender: TObject; AItem: TTMSFMXNativeMaciCloudDocumentItem); private { Private declarations } ShowContent: Boolean; public { Public declarations } procedure LoadNotes; procedure UpdateActiveNote; function CreateNewNote: string; function GetNoteCount: Integer; procedure AddNoteToList(ANote: TTMSFMXNativeMaciCloudDocumentItem); procedure DeleteNoteFromList(ANote: TTMSFMXNativeMaciCloudDocumentItem); end; var Form1144: TForm1144; implementation {$R *.fmx} procedure TForm1144.AddNoteToList(ANote: TTMSFMXNativeMaciCloudDocumentItem); var lv: TListViewItem; begin if not Assigned(ANote) then Exit; lv := ListView1.Items.Add; lv.Text := ANote.FileSystemName; lv.Bitmap.Assign(Image1.Bitmap); UpdateActiveNote; end; procedure TForm1144.Button1Click(Sender: TObject); var fn: String; begin fn := CreateNewNote; if TFile.Exists(fn) then begin TMSFMXNativeMaciCloudDocument1.AddDocument(fn); ShowContent := True; end; end; procedure TForm1144.Button2Click(Sender: TObject); begin if Assigned(ListView1.Selected) then TMSFMXNativeMaciCloudDocument1.DeleteDocument(ListView1.Selected.Text); end; procedure TForm1144.Button3Click(Sender: TObject); var ANote: TTMSFMXNativeMaciCloudDocumentItem; dt: TMemoryStream; begin if Assigned(ListView1.Selected) then begin ANote := TMSFMXNativeMaciCloudDocument1.DocumentByName[ListView1.Selected.Text]; try dt := TMemoryStream.Create; Memo1.Lines.SaveToStream(dt); TMSFMXNativeMaciCloudDocument1.UpdateDocument(ANote, dt); dt.Free; finally end; end; end; function TForm1144.CreateNewNote: string; var str: TStringList; fn: String; begin Result := ''; str := TStringList.Create; try str.Add('Hello World ' + FormatDateTime('dd/mm/yyyy hh:nn:ss:zzz', Now)); fn := TPath.GetDocumentsPath + '/'+'Note ' + inttostr(GetNoteCount) + '.txt'; str.SaveToFile(fn); Result := fn; finally str.Free; end; end; procedure TForm1144.DeleteNoteFromList(ANote: TTMSFMXNativeMaciCloudDocumentItem); var I: Integer; begin if not Assigned(ANote) then Exit; for I := ListView1.Items.Count - 1 downto 0 do begin if ListView1.Items[I].Text = ANote.FileSystemName then begin ListView1.Items.Delete(I); Break; end; end; ShowContent := True; UpdateActiveNote; end; function TForm1144.GetNoteCount: Integer; var I: Integer; valid: Boolean; begin Result := 1; valid := False; while not valid do begin valid := True; for I := 0 to TMSFMXNativeMaciCloudDocument1.DocumentCount - 1 do begin if TMSFMXNativeMaciCloudDocument1.DocumentByIndex[I].FileSystemName.Contains(inttostr(Result)) then begin valid := False; Break; end; end; if not valid then Inc(Result); end; end; procedure TForm1144.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); begin ShowContent := True; UpdateActiveNote; end; procedure TForm1144.LoadNotes; var lv: TListViewItem; I: Integer; ANote: TTMSFMXNativeMaciCloudDocumentItem; begin ListView1.ClearItems; ListView1.BeginUpdate; for I := 0 to TMSFMXNativeMaciCloudDocument1.DocumentCount - 1 do begin ANote := TMSFMXNativeMaciCloudDocument1.DocumentByIndex[I]; lv := ListView1.Items.Add; lv.Text := ANote.FileSystemName; lv.Bitmap.Assign(Image1.Bitmap); end; ListView1.EndUpdate; end; procedure TForm1144.TMSFMXNativeMaciCloudDocument1DocumentAdded(Sender: TObject; AItem: TTMSFMXNativeMaciCloudDocumentItem; ASuccess: Boolean; AError: string); begin if ASuccess then AddNoteToList(AItem) else ShowMessage(AError); end; procedure TForm1144.TMSFMXNativeMaciCloudDocument1DocumentDataChanged( Sender: TObject; AItem: TTMSFMXNativeMaciCloudDocumentItem); begin ShowContent := True; UpdateActiveNote; end; procedure TForm1144.TMSFMXNativeMaciCloudDocument1DocumentDeleted(Sender: TObject; AItem: TTMSFMXNativeMaciCloudDocumentItem; ASuccess: Boolean; AError: string); begin if ASuccess then DeleteNoteFromList(AItem) else ShowMessage(AError); end; procedure TForm1144.TMSFMXNativeMaciCloudDocument1DocumentsLoaded(Sender: TObject); begin LoadNotes; Button1.Enabled := True; Button2.Enabled := True; Button3.Enabled := True; Memo1.Enabled := True; ListView1.Enabled := True; end; procedure TForm1144.TMSFMXNativeMaciCloudDocument1DocumentsRefreshed( Sender: TObject); begin LoadNotes; end; procedure TForm1144.TMSFMXNativeMaciCloudDocument1Initialized(Sender: TObject; ASuccess: Boolean); begin if ASuccess then TMSFMXNativeMaciCloudDocument1.LoadDocuments else ShowMessage('iCloud is not available'); end; procedure TForm1144.UpdateActiveNote; var doc: TTMSFMXNativeMaciCloudDocumentItem; str: TStringList; begin if not ShowContent then Exit; ShowContent := False; Memo1.Text := ''; if Assigned(ListView1.Selected) then begin doc := TMSFMXNativeMaciCloudDocument1.DocumentByName[ListView1.Selected.Text]; if Assigned(doc) then begin doc.Data.Position := 0; str := TStringList.Create; str.LoadFromStream(doc.Data); Memo1.Text := str.Text; str.Free; end; end; end; end.
unit DAO.Devolucao; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Devolucao; type TDevolucaoDAO = class private FConexao: TConexao; public constructor Create; function GetID(): Integer; function Inserir(ADevolucao: TDevolucao): Boolean; function Alterar(ADevolucao: TDevolucao): Boolean; function Excluir(ADevolucao: TDevolucao): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'tbdevolucoes'; implementation uses Control.Sistema; { TDevolucaoDAO } function TDevolucaoDAO.Alterar(ADevolucao: TDevolucao): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('update ' + TABLENAME + ' set DAT_EXPEDICAO = :DAT_EXPEDICAO, ' + 'NUM_LACRE = :NUM_LACRE, NUM_NOSSONUMERO = :NUM_NOSSONUMERO, QTD_VOLUMES = :QTD_VOLUMES, ' + 'COD_AGENTE = :COD_AGENTE, NOM_MOTORISTA = :NOM_MOTORISTA, DAT_RETIRADA = :DAT_RETIRADA, ' + 'NOM_RECEBEDOR = :NOM_RECEBEDOR, DAT_RECEPCAO = :DAT_RECEPCAO, NOM_CONFERENTE = :NOM_CONFERENTE, ' + 'DAT_CONFERENCIA = :DAT_CONFERENCIA,QTD_PESO_CONTAINER = :QTD_PESO_CONTAINER, ' + 'COD_STATUS_CONTAINER = :COD_STATUS_CONTAINER, DES_DIVERGENCIA = :DES_DIVERGENCIA, ' + 'DES_DEVOLUCAO = :DES_DEVOLUCAO, COD_STATUS_OBJETO = :COD_STATUS_OBJETO, ' + 'NUM_PROTOCOLO = :NUM_PROTOCOLO, DOM_DESCOBERTO = :DOM_DESCOBERTO, DES_OCORRENCIAS = :DES_OCORRENCIAS, ' + 'NOM_USUARIO = :NOM_USUARIO, DAT_MANUTENCAO = :DAT_MANUTENCAO ' + 'where SEQ_DEVOLUCAO = :SEQ_DEVOLUCAO AND SEQ_OBJETO = :SEQ_OBJETO;',[ADevolucao.Expedicao, ADevolucao.Lacre, ADevolucao.NossoNumero, ADevolucao.Volumes, ADevolucao.Agente, ADevolucao.Motorista, ADevolucao.Retirada, ADevolucao.Recebedor, ADevolucao.Recepcao, ADevolucao.Conferente, ADevolucao.Conferencia, ADevolucao.PesoContainer, ADevolucao.StatusContainer, ADevolucao.Divergencia, ADevolucao.Descricao, ADevolucao.Statusobjeto, ADevolucao.Protocolo, ADevolucao.Descoberto, ADevolucao.Ocorrencia, ADevolucao.Usuario, ADevolucao.Manutencao, ADevolucao.Container, ADevolucao.Objeto]); Result := True; finally FDQuery.Free; end; end; constructor TDevolucaoDAO.Create; begin FConexao := TSistemaControl.GetInstance.Conexao; end; function TDevolucaoDAO.Excluir(ADevolucao: TDevolucao): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where SEQ_DEVOLUCAO = :SEQ_DEVOLUCAO AND SEQ_OBJETO = :SEQ_OBJETO;', [aDevolucao.Container, aDevolucao.Objeto]); Result := True; finally FDQuery.Free; end; end; function TDevolucaoDAO.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(SEQ_DEVOLUCAO),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Free; end; end; function TDevolucaoDAO.Inserir(ADevolucao: TDevolucao): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('insert into ' + TABLENAME + '(SEQ_OBJETO, SEQ_DEVOLUCAO, DAT_EXPEDICAO, NUM_LACRE, NUM_NOSSONUMERO, ' + 'QTD_VOLUMES, COD_AGENTE, NOM_MOTORISTA, DAT_RETIRADA, NOM_RECEBEDOR, DAT_RECEPCAO, NOM_CONFERENTE, DAT_CONFERENCIA, ' + 'QTD_PESO_CONTAINER, COD_STATUS_CONTAINER, DES_DIVERGENCIA, DES_DEVOLUCAO, COD_STATUS_OBJETO, NUM_PROTOCOLO, ' + 'DOM_DESCOBERTO, DES_OCORRENCIAS, NOM_USUARIO, DAT_MANUTENCAO) ' + 'values ' + '(:SEQ_OBJETO, :SEQ_DEVOLUCAO, :DAT_EXPEDICAO, :NUM_LACRE, :NUM_NOSSONUMERO, :QTD_VOLUMES, :COD_AGENTE, :NOM_MOTORISTA, ' + ':DAT_RETIRADA, :NOM_RECEBEDOR, :DAT_RECEPCAO, :NOM_CONFERENTE, :DAT_CONFERENCIA, :QTD_PESO_CONTAINER, ' + ':COD_STATUS_CONTAINER, :DES_DIVERGENCIA, :DES_DEVOLUCAO, :COD_STATUS_OBJETO, :NUM_PROTOCOLO, :DOM_DESCOBERTO, ' + ':DES_OCORRENCIAS, :NOM_USUARIO, :DAT_MANUTENCAO);',[ADevolucao.Objeto, ADevolucao.Container, ADevolucao.Expedicao, ADevolucao.Lacre, ADevolucao.NossoNumero, ADevolucao.Volumes, ADevolucao.Agente, ADevolucao.Motorista, ADevolucao.Retirada, ADevolucao.Recebedor, ADevolucao.Recepcao, ADevolucao.Conferente, ADevolucao.Conferencia, ADevolucao.PesoContainer, ADevolucao.StatusContainer, ADevolucao.Divergencia, ADevolucao.Descricao, ADevolucao.Statusobjeto, ADevolucao.Protocolo, ADevolucao.Descoberto, ADevolucao.Ocorrencia, ADevolucao.Usuario, ADevolucao.Manutencao]); Result := True; finally FDQuery.Free; end; end; function TDevolucaoDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CONTAINER' then begin FDQuery.SQL.Add('WHERE SEQ_DEVOLUCAO = :SEQ_DEVOLUCAO'); FDQuery.ParamByName('SEQ_DEVOLUCAO').AsInteger := aParam[1]; end; if aParam[0] = 'OBJETO' then begin FDQuery.SQL.Add('WHERE SEQ_DEVOLUCAO = :SEQ_DEVOLUCAO AND SEQ_OBJETO = :SEQ_OBJETO'); FDQuery.ParamByName('SEQ_DEVOLUCAO').AsInteger := aParam[1]; FDQuery.ParamByName('SEQ_OBJETO').AsInteger := aParam[2]; end; if aParam[0] = 'EXPEDICAO' then begin FDQuery.SQL.Add('WHERE DAT_EXPEDICAO = :DAT_EXPEDICAO'); FDQuery.ParamByName('WHERE DAT_EXPEDICAO').AsDate := aParam[1]; end; if aParam[0] = 'LACRE' then begin FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE AND NUM_LACRE = :NUM_LACRE'); FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1]; FDQuery.ParamByName('NUM_LACRE').AsString := aParam[2]; end; if aParam[0] = 'NN' then begin FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE AND NUM_NOSSONUMERO = :NUM_NOSSONUMERO'); FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1]; FDQuery.ParamByName('NUM_NOSSONUMERO').AsString := aParam[2]; end; if aParam[0] = 'AGENTE' then begin FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE'); FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1]; end; if aParam[0] = 'STATUSAGENTE' then begin FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE AND COD_STATUS_CONTAINER = :COD_STATUS_CONTAINER'); FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1]; FDQuery.ParamByName('COD_STATUS_CONTAINER').AsInteger := aParam[2]; end; if aParam[0] = 'STATUSOBJETO' then begin FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE AND COD_STATUS_CONTAINER = :COD_STATUS_CONTAINER'); FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1]; FDQuery.ParamByName('COD_STATUS_OBJETO').AsInteger := aParam[2]; end; if aParam[0] = 'PROTOCOLO' then begin FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE AND NUM_PROTOCOLO = :NUM_PROTOCOLO'); FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1]; FDQuery.ParamByName('NUM_PROTOCOLO').AsString := aParam[2]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; end.
program ColorCount(input, output); type color = (red, blue, yellow, green, orange, brown, white, black); var primaryColorCount : integer; totalColorCount : integer; count : integer; theColor : color; begin primaryColorCount := 0; totalColorCount := 0; writeln('Count follow: '); for theColor := red to black do begin read(count); writeln(count); totalColorCount := totalColorCount + count; if theColor <= yellow then primaryColorCount := primaryColorCount + count; end; writeln('Primary color count: ', primaryColorCount); writeln('Total color count: ', totalColorCount); for theColor := red to black do writeln(ord(theColor)) end.
unit nevSelection; {* Курсор с выделением. Для конечного использования. } // Модуль: "w:\common\components\gui\Garant\Everest\nevSelection.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnevSelection" MUID: (487B5DD202DF) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evBlockCursor , nevTools , evTypes , l3Variant ; type TnevSelection = class(TevBlockCursor) {* Курсор с выделением. Для конечного использования. } private f_Mouse: InevPoint; f_FoundBlock: InevRange; protected function pm_GetMouse: InevPoint; procedure pm_SetFoundBlock(const aValue: InevRange); procedure Cleanup; override; {* Функция очистки полей объекта. } function DoGetBlock(const aDocument: InevObject): InevRange; override; function GetContains(const C: InevBasePoint): Boolean; override; procedure DoSetDocument(aValue: Tl3Tag); override; function pm_GetCollapsed: Boolean; override; procedure AfterProcessCommand; override; procedure ClearFields; override; public procedure DeleteFoundBlockBeforeSearch; procedure Select(aTarget: TevSelectTarget; const aCursor: InevPoint = nil; Start: Boolean = True); virtual; {* выделить часть документа (выделить текущее слово, строку, параграф etc) } public property Mouse: InevPoint read pm_GetMouse; property FoundBlock: InevRange read f_FoundBlock write pm_SetFoundBlock; end;//TnevSelection implementation uses l3ImplUses , l3InterfacesMisc , evMsgCode , evSelectConst //#UC START# *487B5DD202DFimpl_uses* //#UC END# *487B5DD202DFimpl_uses* ; function TnevSelection.pm_GetMouse: InevPoint; //#UC START# *48E3A5E503CD_487B5DD202DFget_var* //#UC END# *48E3A5E503CD_487B5DD202DFget_var* begin //#UC START# *48E3A5E503CD_487B5DD202DFget_impl* if (View = nil) then Result := nil else begin Result := CheckCursor(f_Mouse); Result.AssignPoint(View, View.PointByPt(View.MousePos)); end;//View = nil //#UC END# *48E3A5E503CD_487B5DD202DFget_impl* end;//TnevSelection.pm_GetMouse procedure TnevSelection.pm_SetFoundBlock(const aValue: InevRange); //#UC START# *48E3A614017E_487B5DD202DFset_var* //#UC END# *48E3A614017E_487B5DD202DFset_var* begin //#UC START# *48E3A614017E_487B5DD202DFset_impl* if not l3IEQ(f_FoundBlock, aValue) then begin f_FoundBlock := aValue; if Assigned(View) and Assigned(View.Control) then begin if (f_FoundBlock = nil) then // - этой проверкой чиним CQ 26553 View.Control.ViewArea.Invalidate else View.Control.UpdateCaretAndInvalidate; end;//Assigned(View).. end;//not l3IEQ(f_FoundBlock, aBlock) //#UC END# *48E3A614017E_487B5DD202DFset_impl* end;//TnevSelection.pm_SetFoundBlock procedure TnevSelection.DeleteFoundBlockBeforeSearch; //#UC START# *48E3A5C203E1_487B5DD202DF_var* //#UC END# *48E3A5C203E1_487B5DD202DF_var* begin //#UC START# *48E3A5C203E1_487B5DD202DF_impl* f_FoundBlock := nil; //#UC END# *48E3A5C203E1_487B5DD202DF_impl* end;//TnevSelection.DeleteFoundBlockBeforeSearch procedure TnevSelection.Select(aTarget: TevSelectTarget; const aCursor: InevPoint = nil; Start: Boolean = True); {* выделить часть документа (выделить текущее слово, строку, параграф etc) } //#UC START# *48E3A6260063_487B5DD202DF_var* var C1 : InevBasePoint; l_Pack : InevOp; l_Cursor : InevBasePoint; //#UC END# *48E3A6260063_487B5DD202DF_var* begin //#UC START# *48E3A6260063_487B5DD202DF_impl* if (StartMark <> nil) AND (FinishMark <> nil) then begin if (aCursor = nil) then l_Cursor := Cursor else l_Cursor := aCursor; l_Pack := Processor.StartOp(ev_msgMove); try if Start then begin (*case aTarget of ev_stChar : StartMark.Assign(l_Cursor); else *) begin StartMark.AssignPoint(View, l_Cursor); if (evSelectBrackets[aTarget].Open <> -1) then StartMark.Move(View, evSelectBrackets[aTarget].Open, l_Pack); FinishMark.AssignPoint(View, l_Cursor); if (evSelectBrackets[aTarget].Close <> -1) then FinishMark.Move(View, evSelectBrackets[aTarget].Close, l_Pack); AddBlock(StartMark, FinishMark); end;//else (*end;//case aTarget*) {Start} end else begin (*case aTarget of ev_stChar : AddBlock(StartMark, aCursor); else *) begin C1 := aCursor.ClonePoint(View); try if (C1.Compare(StartMark) < 0) then begin C1.Move(View, evSelectBrackets[aTarget].Open, l_Pack); AddBlock(C1, FinishMark); end//C1.Compare(StartMark) < 0 else begin C1.Move(View, evSelectBrackets[aTarget].Close, l_Pack); AddBlock(StartMark, C1); end;//C1.Compare(StartMark) < 0 finally FreeCursor(C1); end;//try..finally end;//else (*end;//case aTarget*) end;//Start finally l_Pack := nil; end;//try..finally end;//(StartMark <> nil) AND (FinishMark <> nil) //#UC END# *48E3A6260063_487B5DD202DF_impl* end;//TnevSelection.Select procedure TnevSelection.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_487B5DD202DF_var* //#UC END# *479731C50290_487B5DD202DF_var* begin //#UC START# *479731C50290_487B5DD202DF_impl* FoundBlock := nil; inherited; //#UC END# *479731C50290_487B5DD202DF_impl* end;//TnevSelection.Cleanup function TnevSelection.DoGetBlock(const aDocument: InevObject): InevRange; //#UC START# *48E252D40298_487B5DD202DF_var* //#UC END# *48E252D40298_487B5DD202DF_var* begin //#UC START# *48E252D40298_487B5DD202DF_impl* Result := FoundBlock; if (Result = nil) then Result := inherited DoGetBlock(aDocument); //#UC END# *48E252D40298_487B5DD202DF_impl* end;//TnevSelection.DoGetBlock function TnevSelection.GetContains(const C: InevBasePoint): Boolean; //#UC START# *48E271FC0130_487B5DD202DF_var* //#UC END# *48E271FC0130_487B5DD202DF_var* begin //#UC START# *48E271FC0130_487B5DD202DF_impl* if (FoundBlock <> nil) then Result := FoundBlock.Contains(View, C) else Result := inherited GetContains(C); //#UC END# *48E271FC0130_487B5DD202DF_impl* end;//TnevSelection.GetContains procedure TnevSelection.DoSetDocument(aValue: Tl3Tag); //#UC START# *48E276B10286_487B5DD202DF_var* //#UC END# *48E276B10286_487B5DD202DF_var* begin //#UC START# *48E276B10286_487B5DD202DF_impl* FreeCursor(f_Mouse); FoundBlock := nil; inherited; //#UC END# *48E276B10286_487B5DD202DF_impl* end;//TnevSelection.DoSetDocument function TnevSelection.pm_GetCollapsed: Boolean; //#UC START# *48E3723E0107_487B5DD202DFget_var* //#UC END# *48E3723E0107_487B5DD202DFget_var* begin //#UC START# *48E3723E0107_487B5DD202DFget_impl* Result := (FoundBlock = nil); if Result then Result := inherited pm_GetCollapsed; //#UC END# *48E3723E0107_487B5DD202DFget_impl* end;//TnevSelection.pm_GetCollapsed procedure TnevSelection.AfterProcessCommand; //#UC START# *48E38E83007A_487B5DD202DF_var* //#UC END# *48E38E83007A_487B5DD202DF_var* begin //#UC START# *48E38E83007A_487B5DD202DF_impl* inherited AfterProcessCommand; FoundBlock := nil; //#UC END# *48E38E83007A_487B5DD202DF_impl* end;//TnevSelection.AfterProcessCommand procedure TnevSelection.ClearFields; begin f_Mouse := nil; FoundBlock := nil; inherited; end;//TnevSelection.ClearFields end.
unit GetOrdersUnit; interface uses SysUtils, BaseExampleUnit; type TGetOrders = class(TBaseExample) public procedure Execute; end; implementation uses OrderParametersUnit, OrderUnit; procedure TGetOrders.Execute; var ErrorString: String; Parameters: TOrderParameters; Total: integer; Orders: TOrderList; begin Parameters := TOrderParameters.Create(); try Parameters.Limit := 10; Orders := Route4MeManager.Order.Get(Parameters, Total, ErrorString); try WriteLn(''); if (Orders.Count > 0) then WriteLn(Format( 'GetOrders executed successfully, %d orders returned, total = %d', [Orders.Count, Total])) else WriteLn(Format('GetOrders error: "%s"', [ErrorString])); finally FreeAndNil(Orders); end; finally FreeAndNil(Parameters); end; end; end.
unit nsContextFilterParamsConst; (*----------------------------------------------------------------------------- Название: nsContextFilterParams Автор: Лукьянец Р. В. Назначение: Хранилище для параметров контекстной фильтрации; Описание контекстных фильтров хранящихся в настройках. Версия: $Id: nsContextFilterParamsConst.pas,v 1.4 2012/01/19 14:09:20 lulin Exp $ История: $Log: nsContextFilterParamsConst.pas,v $ Revision 1.4 2012/01/19 14:09:20 lulin {RequestLink:327825257} Revision 1.3 2011/04/13 14:33:53 lulin {RequestLink:258607641}. Revision 1.2 2009/04/17 09:04:26 oman - new: Показываем группу в свойствах пользователя - [$127762671] Revision 1.1 2008/10/29 17:14:00 lulin - <K>: 121159661. Revision 1.8 2008/04/09 11:26:42 mmorozov - параметры контекстной фильтрации для списка препартов. Revision 1.7 2008/04/03 11:19:11 oman - new: Документ-препарат - параметры контекстной фильтрации (cq28562) Revision 1.6 2008/03/31 12:58:46 oman - new: Список фирм-производителей - параметры контекстной фильтрации Revision 1.5 2008/03/06 10:49:32 oman - new: Заготовка для словаря медицинских терминов - параметры контекстной фильтрации Revision 1.4 2008/02/19 07:45:23 oman - new: Параметры контекстной фильтрации для советов дня (cq28223, 16723) Revision 1.3 2007/03/21 11:54:56 oman - выделил фабричную функцию для производства параметров контекстной фильтрации Revision 1.2 2007/03/21 10:30:54 oman - new: Выделил хранителя параметров контекстной фильтрации Revision 1.1 2007/03/20 10:52:54 oman - fix: Параметры контекстнйо фильтрации определяем без nscContextParams -----------------------------------------------------------------------------*) interface uses l3TreeInterfaces, afwInterfaces, nsConst, DynamicTreeUnit ; const SupportedContextsFilterRoots: array [0..25] of String = ( gi_cpKeywordSerch, gi_cpPublishSource, gi_cpDiction, gi_cpNavigator, gi_cpType, AT_CLASS, AT_Source, gi_cpRegNumber, gi_cpMURegNumber, gi_cpMURegStatus, gi_cpStatus, gi_cpNorm, AT_PREFIX, gi_cpTerritory, gi_cpBases, gi_cpContents, gi_cpUserList, gi_cpDayTips, gi_cpDrugContents, gi_cpMedicDiction, gi_cpMedicFirms, gi_cpDrugList, gi_cpGroupList, AT_PREFIX_REVIEW, AT_CLASS_REVIEW, AT_SOURCE_REVIEW ); implementation end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerBoolean; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpAsn1Tags, ClpIAsn1OctetString, ClpIDerBoolean, ClpCryptoLibTypes, ClpDerOutputStream, ClpIProxiedInterface, ClpIAsn1TaggedObject, ClpAsn1Object; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SInvalidValue = 'Byte Value Should Have 1 Byte in it'', "val"'; SInvalidBooleanValue = 'BOOLEAN Value Should Have 1 Byte in it", "Value"'; type TDerBoolean = class(TAsn1Object, IDerBoolean) strict private var Fvalue: Byte; class var FFalse, FTrue: IDerBoolean; function GetIsTrue: Boolean; inline; constructor Create(value: Boolean); overload; class function GetFalse: IDerBoolean; static; inline; class function GetTrue: IDerBoolean; static; inline; class constructor DerBoolean(); strict protected function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; function Asn1GetHashCode(): Int32; override; public constructor Create(const val: TCryptoLibByteArray); overload; procedure Encode(const derOut: TStream); override; function ToString(): String; override; property IsTrue: Boolean read GetIsTrue; class property True: IDerBoolean read GetTrue; class property False: IDerBoolean read GetFalse; /// <summary> /// return a DerBoolean from the passed in object. /// </summary> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TObject): IDerBoolean; overload; static; inline; /// <summary> /// return a DerBoolean from the passed in boolean. /// </summary> class function GetInstance(value: Boolean): IDerBoolean; overload; static; inline; /// <summary> /// return a Boolean from a tagged object. /// </summary> /// <param name="obj"> /// the tagged object holding the object we want /// </param> /// <param name="isExplicit"> /// explicitly true if the object is meant to be explicitly tagged false /// otherwise. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the tagged object cannot be converted. /// </exception> class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerBoolean; overload; static; inline; class function FromOctetString(const value: TCryptoLibByteArray) : IDerBoolean; static; end; implementation { TDerBoolean } function TDerBoolean.GetIsTrue: Boolean; begin result := Fvalue <> 0; end; function TDerBoolean.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerBoolean; begin if (not Supports(asn1Object, IDerBoolean, other)) then begin result := System.False; Exit; end; result := IsTrue = other.IsTrue; end; function TDerBoolean.Asn1GetHashCode: Int32; begin result := Ord(IsTrue); end; constructor TDerBoolean.Create(const val: TCryptoLibByteArray); begin Inherited Create(); if (System.Length(val) <> 1) then begin raise EArgumentCryptoLibException.CreateRes(@SInvalidValue); end; // TODO Are there any constraints on the possible byte values? Fvalue := val[0]; end; constructor TDerBoolean.Create(value: Boolean); begin Inherited Create(); if value then begin Fvalue := Byte($FF) end else begin Fvalue := Byte(0) end; end; class constructor TDerBoolean.DerBoolean; begin FFalse := TDerBoolean.Create(System.False); FTrue := TDerBoolean.Create(System.True); end; procedure TDerBoolean.Encode(const derOut: TStream); begin // TODO Should we make sure the byte value is one of '0' or '0xff' here? (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.Boolean, TCryptoLibByteArray.Create(Fvalue)); end; class function TDerBoolean.FromOctetString(const value: TCryptoLibByteArray) : IDerBoolean; var b: Byte; begin if (System.Length(value) <> 1) then begin raise EArgumentCryptoLibException.CreateRes(@SInvalidBooleanValue); end; b := value[0]; case b of 0: result := FFalse; $FF: result := FTrue else begin result := TDerBoolean.Create(value); end; end; end; class function TDerBoolean.GetInstance(value: Boolean): IDerBoolean; begin if value then begin result := FTrue; end else begin result := FFalse; end; end; class function TDerBoolean.GetInstance(const obj: TObject): IDerBoolean; begin if ((obj = Nil) or (obj is TDerBoolean)) then begin Supports(obj, IDerBoolean, result); Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerBoolean.GetFalse: IDerBoolean; begin result := FFalse; end; class function TDerBoolean.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerBoolean; var o: IAsn1Object; begin o := obj.GetObject(); if ((isExplicit) or (Supports(o, IDerBoolean))) then begin result := GetInstance(o as TAsn1Object); Exit; end; result := FromOctetString((o as IAsn1OctetString).GetOctets()); end; class function TDerBoolean.GetTrue: IDerBoolean; begin result := FTrue; end; function TDerBoolean.ToString: String; begin result := BoolToStr(IsTrue, System.True); end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2014 * } { *********************************************************** } unit tfGNumerics; interface uses tfNumerics, Generics.Defaults, Generics.Collections; function GetBigCardinalComparer: IComparer<BigCardinal>; function GetBigIntegerComparer: IComparer<BigInteger>; function GetBigCardinalEqualityComparer: IEqualityComparer<BigCardinal>; function GetBigIntegerEqualityComparer: IEqualityComparer<BigInteger>; type TBigCardinalList = class(TList<BigCardinal>) public constructor Create; overload; end; TBigIntegerList = class(TList<BigInteger>) public constructor Create; overload; end; TBigCardinalDictionary<TValue> = class(TDictionary<BigCardinal,TValue>) public constructor Create(ACapacity: Integer = 0); overload; end; TBigIntegerDictionary<TValue> = class(TDictionary<BigInteger,TValue>) public constructor Create(ACapacity: Integer = 0); overload; end; implementation function NopAddref(Inst: Pointer): Integer; stdcall; begin Result := -1; end; function NopRelease(Inst: Pointer): Integer; stdcall; begin Result := -1; end; function NopQueryInterface(Inst: Pointer; const IID: TGUID; out Obj): HResult; stdcall; begin Result := E_NOINTERFACE; end; function Compare_BigCardinal(Inst: Pointer; const Left, Right: BigCardinal): Integer; begin Result:= BigCardinal.Compare(Left, Right); end; function Compare_BigInteger(Inst: Pointer; const Left, Right: BigInteger): Integer; begin Result:= BigInteger.Compare(Left, Right); end; function Equals_BigCardinal(Inst: Pointer; const Left, Right: BigCardinal): Boolean; begin Result:= BigCardinal.Equals(Left, Right); end; function GetHashCode_BigCardinal(Inst: Pointer; const Value: BigCardinal): Integer; begin Result:= Value.GetHashCode; end; function Equals_BigInteger(Inst: Pointer; const Left, Right: BigInteger): Boolean; begin Result:= BigInteger.Equals(Left, Right); end; function GetHashCode_BigInteger(Inst: Pointer; const Value: BigInteger): Integer; begin Result:= Value.GetHashCode; end; const Comparer_BigCardinal: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_BigCardinal ); Comparer_BigInteger: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_BigInteger ); EqualityComparer_BigCardinal: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_BigCardinal, @GetHashCode_BigCardinal ); EqualityComparer_BigInteger: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_BigInteger, @GetHashCode_BigInteger ); type PDummyInstance = ^TDummyInstance; TDummyInstance = record VTable: Pointer; end; const Comparer_BigCardinal_Instance: TDummyInstance = (VTable: @Comparer_BigCardinal); Comparer_BigInteger_Instance: TDummyInstance = (VTable: @Comparer_BigInteger); EqualityComparer_BigCardinal_Instance: TDummyInstance = (VTable: @EqualityComparer_BigCardinal); EqualityComparer_BigInteger_Instance: TDummyInstance = (VTable: @EqualityComparer_BigInteger); function GetBigCardinalComparer: IComparer<BigCardinal>; begin Result:= IComparer<BigCardinal>(@Comparer_BigCardinal_Instance); end; function GetBigIntegerComparer: IComparer<BigInteger>; begin Result:= IComparer<BigInteger>(@Comparer_BigInteger_Instance); end; function GetBigCardinalEqualityComparer: IEqualityComparer<BigCardinal>; begin Pointer(Result):= @EqualityComparer_BigCardinal_Instance; end; function GetBigIntegerEqualityComparer: IEqualityComparer<BigInteger>; begin Pointer(Result):= @EqualityComparer_BigInteger_Instance; end; { TBigCardinalList } constructor TBigCardinalList.Create; begin inherited Create(GetBigCardinalComparer); end; { TBigIntegerList } constructor TBigIntegerList.Create; begin inherited Create(GetBigIntegerComparer); end; { TBigCardinalDictionary<TValue> } constructor TBigCardinalDictionary<TValue>.Create(ACapacity: Integer); begin inherited Create(ACapacity, GetBigCardinalEqualityComparer); end; { TBigIntegerDictionary<TValue> } constructor TBigIntegerDictionary<TValue>.Create(ACapacity: Integer); begin inherited Create(ACapacity, GetBigIntegerEqualityComparer); end; end.
unit m3BuffStream; // Модуль: "w:\common\components\rtl\Garant\m3\m3BuffStream.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tm3BuffStream" MUID: (53FDD3D902AA) {$Include w:\common\components\rtl\Garant\m3\m3Define.inc} interface uses l3IntfUses , m3CustomStream , l3Memory , ActiveX , Classes ; type Tm3BuffStream = class(Tm3CustomStream) private FRealSize: Int64; f_Buff: Tl3BufferStreamMemoryPool; FBuffSize: Integer; FBuffCurPos: Int64; FBuffEndPos: Int64; FBuffOffset: Integer; FBuffModifed: LongBool; private procedure LoadBuff; procedure SaveBuff; protected procedure Release; override; {$If NOT Defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} // NOT Defined(DesignTimeLibrary) procedure BeforeRelease; override; procedure DoRead(aBuff: Pointer; aSize: Integer; var theResult: Integer; var theReturn: hResult); override; procedure DoWrite(aBuff: Pointer; aSize: Integer; var theResult: Integer; var theReturn: hResult); override; procedure DoSeek(anOffset: Int64; anOrigin: TSeekOrigin; var theResult: Int64; var theReturn: hResult); override; procedure DoSetSize(aSize: Int64; var theReturn: hResult); override; function DoGetSize: Int64; override; public constructor Create(const aStream: IStream); reintroduce; class function Make(const aStream: IStream): IStream; reintroduce; procedure Commit(aFlags: Integer; var theReturn: hResult); override; end;//Tm3BuffStream implementation uses l3ImplUses , m2COMLib , ComObj , SysUtils , m2S32Lib , m2S64Lib //#UC START# *53FDD3D902AAimpl_uses* //#UC END# *53FDD3D902AAimpl_uses* ; procedure Tm3BuffStream.LoadBuff; //#UC START# *5480693401AA_53FDD3D902AA_var* var LResult: LongInt; //#UC END# *5480693401AA_53FDD3D902AA_var* begin //#UC START# *5480693401AA_53FDD3D902AA_impl* if (FBuffCurPos = FBuffEndPos) then begin m2COMSetPosition(FBuffCurPos, InnerStream); OleCheck(InnerStream.Read(f_Buff.AsPointer,FBuffSize,@LResult)); FBuffEndPos:=FBuffCurPos+Int64(LResult); FBuffOffset:=0; FBuffModifed:=False; end; //#UC END# *5480693401AA_53FDD3D902AA_impl* end;//Tm3BuffStream.LoadBuff procedure Tm3BuffStream.SaveBuff; //#UC START# *5480694400B8_53FDD3D902AA_var* var LResult: LongInt; //#UC END# *5480694400B8_53FDD3D902AA_var* begin //#UC START# *5480694400B8_53FDD3D902AA_impl* if FBuffModifed then begin m2COMSetPosition(FBuffCurPos, InnerStream); OleCheck(InnerStream.Write(f_Buff.AsPointer,LongInt(FBuffEndPos-FBuffCurPos),@LResult)); FBuffCurPos:=FBuffCurPos+Int64(LResult); FBuffOffset:=0; FBuffModifed:=False; end else begin FBuffCurPos:=FBuffEndPos; FBuffOffset:=0; end; //#UC END# *5480694400B8_53FDD3D902AA_impl* end;//Tm3BuffStream.SaveBuff constructor Tm3BuffStream.Create(const aStream: IStream); //#UC START# *548069970154_53FDD3D902AA_var* //#UC END# *548069970154_53FDD3D902AA_var* begin //#UC START# *548069970154_53FDD3D902AA_impl* inherited Create(AStream,m2COMModeAccess(m2COMGetStatStgMode(AStream))); FRealSize := m2COMGetSize(InnerStream); FBuffCurPos:=m2COMGetPosition(InnerStream); FBuffEndPos:=FBuffCurPos; if (f_Buff = nil) then f_Buff := Tl3BufferStreamMemoryPool.Create; FBuffSize := f_Buff.Size; LoadBuff; //#UC END# *548069970154_53FDD3D902AA_impl* end;//Tm3BuffStream.Create class function Tm3BuffStream.Make(const aStream: IStream): IStream; var l_Inst : Tm3BuffStream; begin l_Inst := Create(aStream); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//Tm3BuffStream.Make procedure Tm3BuffStream.Release; //#UC START# *479F2AFB0397_53FDD3D902AA_var* //#UC END# *479F2AFB0397_53FDD3D902AA_var* begin //#UC START# *479F2AFB0397_53FDD3D902AA_impl* // не станем этого делать в Cleanup, //пускай кеширует с буфером, съэкономим на распределении памяти FreeAndNil(f_Buff); inherited; //#UC END# *479F2AFB0397_53FDD3D902AA_impl* end;//Tm3BuffStream.Release {$If NOT Defined(DesignTimeLibrary)} class function Tm3BuffStream.IsCacheable: Boolean; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } //#UC START# *47A6FEE600FC_53FDD3D902AA_var* //#UC END# *47A6FEE600FC_53FDD3D902AA_var* begin //#UC START# *47A6FEE600FC_53FDD3D902AA_impl* //Result := false; Result := True; //#UC END# *47A6FEE600FC_53FDD3D902AA_impl* end;//Tm3BuffStream.IsCacheable {$IfEnd} // NOT Defined(DesignTimeLibrary) procedure Tm3BuffStream.BeforeRelease; //#UC START# *49BFC98902FF_53FDD3D902AA_var* //#UC END# *49BFC98902FF_53FDD3D902AA_var* begin //#UC START# *49BFC98902FF_53FDD3D902AA_impl* SaveBuff; inherited; //#UC END# *49BFC98902FF_53FDD3D902AA_impl* end;//Tm3BuffStream.BeforeRelease procedure Tm3BuffStream.DoRead(aBuff: Pointer; aSize: Integer; var theResult: Integer; var theReturn: hResult); //#UC START# *4FA27CF501C4_53FDD3D902AA_var* var lSize : LongInt; //#UC END# *4FA27CF501C4_53FDD3D902AA_var* begin //#UC START# *4FA27CF501C4_53FDD3D902AA_impl* if SUCCEEDED(theReturn) then begin while (theResult <> ASize) do begin LoadBuff; LSize:=LongInt(FBuffEndPos-(FBuffCurPos+Int64(FBuffOffset))); if (lSize = 0) then Break else LSize:=LongInt(m2S32Min(LSize,(ASize-theResult))); f_Buff.Read(FBuffOffset, PAnsiChar(aBuff) + theResult, LSize); Inc(FBuffOffset,LSize); Inc(theResult,LSize); if ((FBuffCurPos+Int64(FBuffOffset)) = FBuffEndPos) then SaveBuff; end; end; //#UC END# *4FA27CF501C4_53FDD3D902AA_impl* end;//Tm3BuffStream.DoRead procedure Tm3BuffStream.DoWrite(aBuff: Pointer; aSize: Integer; var theResult: Integer; var theReturn: hResult); //#UC START# *4FA27D310344_53FDD3D902AA_var* var LSize : LongInt; //#UC END# *4FA27D310344_53FDD3D902AA_var* begin //#UC START# *4FA27D310344_53FDD3D902AA_impl* if SUCCEEDED(theReturn) then begin while (theResult <> ASize) do begin LoadBuff; lSize := FBuffSize - FBuffOffset; if (lSize = 0) then Break else LSize:=LongInt(m2S32Min(LSize,(ASize-theResult))); f_Buff.Write(FBuffOffset, PAnsiChar(aBuff) + theResult, LSize); Inc(FBuffOffset,LSize); Inc(theResult,LSize); FBuffModifed:=True; FBuffEndPos:=m2S64Max(FBuffEndPos,(FBuffCurPos+Int64(FBuffOffset))); FRealSize:=m2S64Max(FBuffEndPos,FRealSize); if (FBuffOffset = FBuffSize) then SaveBuff; end; end; //#UC END# *4FA27D310344_53FDD3D902AA_impl* end;//Tm3BuffStream.DoWrite procedure Tm3BuffStream.DoSeek(anOffset: Int64; anOrigin: TSeekOrigin; var theResult: Int64; var theReturn: hResult); //#UC START# *4FA27D5302C5_53FDD3D902AA_var* procedure __Seek(APosition: Int64; var theResult: Int64); begin//__Seek if ((APosition >= 0) and (APosition <= FRealSize)) then begin if (APosition <> (FBuffCurPos+Int64(FBuffOffset))) then begin if ((APosition >= FBuffCurPos) and (APosition < FBuffEndPos)) then FBuffOffset:=LongInt(APosition-FBuffCurPos) else begin SaveBuff; FBuffCurPos:=APosition; FBuffEndPos:=FBuffCurPos; end;//((APosition >= FBuffCurPos) and (APosition < FBuffEndPos)) end;//APosition <> (FBuffCurPos+Int64(FBuffOffset)) end//((APosition >= 0) and (APosition <= FRealSize)) else Exit; theResult:=APosition; end;//__Seek //#UC END# *4FA27D5302C5_53FDD3D902AA_var* begin //#UC START# *4FA27D5302C5_53FDD3D902AA_impl* if SUCCEEDED(theReturn) then case anOrigin of soBeginning: __Seek(anOffset,theResult); soCurrent: __Seek(anOffset+FBuffCurPos+Int64(FBuffOffset),theResult); soEnd: __Seek(anOffset+FRealSize,theResult); else OleError(E_UNEXPECTED); end;//case AOrigin //#UC END# *4FA27D5302C5_53FDD3D902AA_impl* end;//Tm3BuffStream.DoSeek procedure Tm3BuffStream.DoSetSize(aSize: Int64; var theReturn: hResult); //#UC START# *4FA27DCD02B4_53FDD3D902AA_var* //#UC END# *4FA27DCD02B4_53FDD3D902AA_var* begin //#UC START# *4FA27DCD02B4_53FDD3D902AA_impl* if SUCCEEDED(theReturn) then begin SaveBuff; m2COMSetSize(ASize, InnerStream); FBuffCurPos := ASize; FBuffEndPos := FBuffCurPos; FRealSize := FBuffEndPos; end; //#UC END# *4FA27DCD02B4_53FDD3D902AA_impl* end;//Tm3BuffStream.DoSetSize function Tm3BuffStream.DoGetSize: Int64; //#UC START# *4FA2802E0231_53FDD3D902AA_var* //#UC END# *4FA2802E0231_53FDD3D902AA_var* begin //#UC START# *4FA2802E0231_53FDD3D902AA_impl* Result := FRealSize; //#UC END# *4FA2802E0231_53FDD3D902AA_impl* end;//Tm3BuffStream.DoGetSize procedure Tm3BuffStream.Commit(aFlags: Integer; var theReturn: hResult); //#UC START# *4FA280DB0288_53FDD3D902AA_var* //#UC END# *4FA280DB0288_53FDD3D902AA_var* begin //#UC START# *4FA280DB0288_53FDD3D902AA_impl* SaveBuff; inherited; //#UC END# *4FA280DB0288_53FDD3D902AA_impl* end;//Tm3BuffStream.Commit end.
unit Model.AtribuicoesExpressas; interface uses Common.ENum, FireDAC.Comp.Client; type TAtribuicoesExpressas = class private FRetorno: TDateTime; FNN: String; FFlagRetorno: ShortInt; FCodigo: String; FID: Integer; FEntregador: Integer; FLote: Integer; FLOG: String; FData: TDateTime; FAcao: TAcao; FBairro: String; FCliente: Integer; FVolumes: Integer; FCEP: String; FNomeEmbarcador: String; FConsumidor: String; FEmbarcador: Integer; FEndereco: String; FTelefone: String; FCodigoRetorno: String; FCodigoInformativo: Integer; public property ID: Integer read FID write FID; property Codigo: String read FCodigo write FCodigo; property Data: TDateTime read FData write FData; property Entregador: Integer read FEntregador write FEntregador; property Cliente: Integer read FCliente write FCliente; property Embarcador: Integer read FEmbarcador write FEmbarcador; property NomeEmbarcador: String read FNomeEmbarcador write FNomeEmbarcador; property NN: String read FNN write FNN; property CodigoRetorno: String read FCodigoRetorno write FCodigoRetorno; property Endereco: String read FEndereco write FEndereco; property CEP: String read FCEP write FCEP; property Bairro: String read FBairro write FBairro; property Consumidor: String read FConsumidor write FConsumidor; property Volumes: Integer read FVolumes write FVolumes; property Telefone: String read FTelefone write FTelefone; property Lote: Integer read FLote write FLote; property Retorno: TDateTime read FRetorno write FRetorno; property FlagRetorno: ShortInt read FFlagRetorno write FFlagRetorno; property CodigoInformativo: Integer read FCodigoInformativo write FCodigoInformativo; property LOG: String read FLOG write FLOG; property Acao: TAcao read FAcao write FAcao; function GetID(): Integer; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TAtribuicoesExpressas } uses DAO.AtribuicoesExpressas; function TAtribuicoesExpressas.GetID: Integer; var atribuicoesDAO: TAtribuicoesExpressasDAO; begin try atribuicoesDAO := TAtribuicoesExpressasDAO.Create; Result := atribuicoesDAO.GetID; finally atribuicoesDAO.Free; end; end; function TAtribuicoesExpressas.Gravar: Boolean; var atribuicoesDAO: TAtribuicoesExpressasDAO; begin try Result := False; atribuicoesDAO := TAtribuicoesExpressasDAO.Create; case FAcao of Common.ENum.tacIncluir: Result := atribuicoesDAO.Inserir(Self); Common.ENum.tacAlterar: Result := atribuicoesDAO.Alterar(Self); Common.ENum.tacExcluir: Result := atribuicoesDAO.Excluir(Self); end; finally atribuicoesDAO.Free; end; end; function TAtribuicoesExpressas.Localizar(aParam: array of variant): TFDQuery; var atribuicoesDAO: TAtribuicoesExpressasDAO; begin try atribuicoesDAO := TAtribuicoesExpressasDAO.Create; Result := atribuicoesDAO.Pesquisar(aParam); finally atribuicoesDAO.Free; end; end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François Piette Description: TMWTrackDataSet keep track of TDataSet insert, delete and update and record that data into a TMWBuffer ready for sending to an application server. Creation: April 3, 1999 Version: 1.03 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list midware@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1999-2007 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software and or any derived or altered versions for any purpose, excluding commercial applications. You can use this software for personal use only. You may distribute it freely untouched. The following restrictions applies: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. 2. If you use this software in a product, an acknowledgment in the product documentation and displayed on screen is required. The text must be: "This product is based on MidWare. Freeware source code is available at http://www.overbyte.be." 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. This notice may not be removed or altered from any source distribution and must be added to the product documentation. Updates: May 31, 2003 V1.01 Frédéric SCHENCKEL <f_schenckel@cab-technologies.fr> added support for float fields. Aug 28, 2004 V1.02 Use MWDefs.inc. Removed unused units. Better NULL field support. Thanks to Stefan Frank <stefan_frank@yahoo.com> for his code. Aug 13, 2010 V1.03 Adepted for Delphi XE * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteMWTrack; {$I OverbyteMwDefs.inc} interface uses Windows, SysUtils, Classes, Db, OverbyteTrackDs, OverbyteRFormat; const MWTrackVersion = 103; CopyRight : String = ' TMWTrack (c) 1999-2010 F. Piette V1.03 '; type TMWTrackDataSet = class(TTrackDataSet) protected FData : TMWBuffer; procedure TriggerDataChanged; override; procedure SaveData(TrackData : TTrackData); procedure Notification(AComponent: TComponent; operation: TOperation); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Clear; virtual; function IsUploadNeeded : Boolean; procedure LoadFromFile(FileName : String); virtual; procedure SaveToFile(FileName : String); virtual; property Data : TMWBuffer read FData; end; implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TMWTrackDataSet.Create(AOwner : TComponent); begin inherited Create(AOwner); FData := TMWBuffer.Create(Self); Clear; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TMWTrackDataSet.Destroy; begin if Assigned(FData) then begin FData.Destroy; FData := nil; end; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMWTrackDataSet.Notification( AComponent: TComponent; operation: TOperation); begin inherited Notification(AComponent, operation); if operation = opRemove then begin if AComponent = FData then FData := nil; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMWTrackDataSet.Clear; begin if Assigned(FData) then FData.Rewrite; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMWTrackDataSet.IsUploadNeeded : Boolean; begin if not Assigned(FData) then begin Result := FALSE; Exit; end; FData.First; Result := not FData.Eof; if Result then Result := Length(FData.Fields[0]) > 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMWTrackDataSet.SaveData(TrackData : TTrackData); var Index : Integer; Field : TTrackDataField; Count : Integer; IntegerData : Integer; FloatData : Extended; DateTimeData : TDateTime; SmallIntData : SmallInt; BooleanData : Boolean; type PDateTimeRec = ^TDateTimeRec; PDateTime = ^TDateTime; begin Count := TrackData.FieldCount - 1; for Index := 0 to Count do begin Field := TrackData.Fields[Index]; case Field.DataType of ftString, ftInteger, ftSmallInt, ftCurrency, { SF 28/09/04 } ftFloat, ftBoolean, ftAutoInc: begin if Field.IsNull then FData.AppendFields(['']) else begin case Field.DataType of ftInteger: begin IntegerData := PInteger(Field.DataPtr)^; FData.AppendFields([IntegerData]); end; ftString: FData.AppendFields([PAnsiChar(Field.DataPtr)]); ftSmallInt: begin SmallIntData := PSmallInt(Field.DataPtr)^; FData.AppendFields([SmallIntData]); end; ftCurrency: begin FloatData := PDouble(Field.DataPtr)^; FData.AppendFields([FloatData]); end; ftFloat: // Frederic SCHENCKEL 27/05/03 begin FloatData := PDouble(Field.DataPtr)^; FData.AppendFields([FloatData]); end; ftBoolean: begin BooleanData := Boolean(Field.DataPtr^); FData.AppendFields([BooleanData]); end; ftAutoInc: begin IntegerData := PInteger(Field.DataPtr)^; FData.AppendFields([IntegerData]); end; end end end; ftBlob, ftMemo, ftGraphic: FData.AppendBinaryField(Field.DataPtr, Field.DataSize, mwString); ftDate: begin DateTimeData := PDateTimeRec(Field.DataPtr)^.Date - DateDelta; FData.AppendFields([DateTimeToMWFormat(DateTimeData)]); end; ftTime: begin DateTimeData := PDateTimeRec(Field.DataPtr)^.Time / MSecsPerDay; FData.AppendFields([DateTimeToMWFormat(DateTimeData)]); end; ftDateTime : begin DateTimeData := (PDateTimeRec(Field.DataPtr)^.DateTime / MSecsPerDay) - DateDelta; FData.AppendFields([DateTimeToMWFormat(DateTimeData)]); end; else raise ETrackDataSetException.Create('unsupported field type'); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMWTrackDataSet.TriggerDataChanged; var OpCode : AnsiString; begin if not Assigned(FData) then raise ETrackDataSetException.Create('FData not assigned'); case Operation of tdsoInsert: begin OpCode := 'INS'; FData.AppendBinaryField(PAnsiChar('INS'), 3, mwString); SaveData(DataAfter); FData.WriteRecordMarker; end; tdsoDelete: begin FData.AppendBinaryField(PAnsiChar('DEL'), 3, mwString); SaveData(DataBefore); FData.WriteRecordMarker; end; tdsoUpdate: begin if not DataBefore.Compare(DataAfter) then begin FData.AppendBinaryField(PAnsiChar('UPD'), 3, mwString); SaveData(DataBefore); FData.WriteRecordMarker; FData.AppendBinaryField(PAnsiChar('CHG'), 3, mwString); SaveData(DataAfter); FData.WriteRecordMarker; end; end; end; inherited TriggerDataChanged; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMWTrackDataSet.LoadFromFile(FileName : String); begin if Assigned(FData) then FData.LoadFromFile(FileName); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMWTrackDataSet.SaveToFile(FileName : String); begin if Assigned(FData) then FData.SaveToFile(FileName); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
{ Double Commander ------------------------------------------------------------------------- This unit contains functions to work with hard and symbolic links on the NTFS file system. Copyright (C) 2012-2017 Alexander Koblov (alexx2000@mail.ru) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit DCNtfsLinks; {$mode delphi} interface uses Windows, SysUtils; const // CreateSymbolicLink flags SYMBOLIC_LINK_FLAG_FILE = 0; SYMBOLIC_LINK_FLAG_DIRECTORY = 1; // CreateFile flags FILE_FLAG_OPEN_REPARSE_POINT = $00200000; // DeviceIoControl control codes FSCTL_SET_REPARSE_POINT = $000900A4; FSCTL_GET_REPARSE_POINT = $000900A8; FSCTL_DELETE_REPARSE_POINT = $000900AC; const REPARSE_DATA_HEADER_SIZE = 8; MOUNT_POINT_HEADER_SIZE = 8; FILE_DOES_NOT_EXIST = DWORD(-1); wsLongFileNamePrefix = UnicodeString('\\?\'); wsNativeFileNamePrefix = UnicodeString('\??\'); wsNetworkFileNamePrefix = UnicodeString('\??\UNC\'); type {$packrecords c} TSymbolicLinkReparseBuffer = record SubstituteNameOffset: USHORT; SubstituteNameLength: USHORT; PrintNameOffset: USHORT; PrintNameLength: USHORT; Flags: ULONG; PathBuffer: array[0..0] of WCHAR; end; TMountPointReparseBuffer = record SubstituteNameOffset: USHORT; SubstituteNameLength: USHORT; PrintNameOffset: USHORT; PrintNameLength: USHORT; PathBuffer: array[0..0] of WCHAR; end; TGenericReparseBuffer = record DataBuffer: array[0..0] of UCHAR; end; REPARSE_DATA_BUFFER = record ReparseTag: ULONG; ReparseDataLength: USHORT; Reserved: USHORT; case Integer of 0: (SymbolicLinkReparseBuffer: TSymbolicLinkReparseBuffer); 1: (MountPointReparseBuffer: TMountPointReparseBuffer); 2: (GenericReparseBuffer: TGenericReparseBuffer); end; TReparseDataBuffer = REPARSE_DATA_BUFFER; PReparseDataBuffer = ^REPARSE_DATA_BUFFER; {$packrecords default} {en Creates a symbolic link. This function is only supported on the NTFS file system. On Windows 2000/XP it works for directories only On Windows Vista/Seven it works for directories and files (for files it works only with Administrator rights) @param(AFileName The name of the existing file) @param(ALinkName The name of the symbolic link) @returns(The function returns @true if successful, @false otherwise) } function CreateSymLink(const ATargetName, ALinkName: UnicodeString): Boolean; {en Established a hard link beetwen an existing file and new file. This function is only supported on the NTFS file system, and only for files, not directories. @param(AFileName The name of the existing file) @param(ALinkName The name of the new hard link) @returns(The function returns @true if successful, @false otherwise) } function CreateHardLink(const AFileName, ALinkName: UnicodeString): Boolean; {en Reads a symbolic link target. This function is only supported on the NTFS file system. @param(aSymlinkFileName The name of the symbolic link) @param(aTargetFileName The name of the target file/directory) @returns(The function returns @true if successful, @false otherwise) } function ReadSymLink(const aSymlinkFileName: UnicodeString; out aTargetFileName: UnicodeString): Boolean; implementation const ERROR_DIRECTORY_NOT_SUPPORTED = 336; type TCreateSymbolicLinkW = function( pwcSymlinkFileName, pwcTargetFileName: PWideChar; dwFlags: DWORD): BOOL; stdcall; TCreateHardLinkW = function ( lpFileName, lpExistingFileName: LPCWSTR; lpSecurityAttributes: LPSECURITY_ATTRIBUTES): BOOL; stdcall; var HasNewApi: Boolean = False; MayCreateSymLink: Boolean = False; function _CreateHardLink_New(AFileName : UnicodeString; ALinkName: UnicodeString): Boolean; var hLib: THandle; CreateHardLinkW: TCreateHardLinkW; begin Result:= False; hLib:= GetModuleHandle('kernel32.dll'); if hLib = 0 then begin Assert(False, 'Can not load library "kernel32.dll"'); Exit; end; CreateHardLinkW:= TCreateHardLinkW(GetProcAddress(hLib, 'CreateHardLinkW')); if not Assigned(CreateHardLinkW) then begin Assert(False, 'Can not get function address for "CreateHardLinkW"'); Exit; end; Result:= CreateHardLinkW(PWideChar(ALinkName), PWideChar(AFileName), nil); end; function _CreateHardLink_Old(aExistingFileName, aFileName: UnicodeString): Boolean; var hFile: THandle; lpBuffer: TWin32StreamId; wcFileName: array[0..MAX_PATH] of WideChar; dwNumberOfBytesWritten: DWORD = 0; lpContext: LPVOID = nil; lpFilePart: LPWSTR = nil; begin Result:= GetFullPathNameW(PWideChar(aFileName), MAX_PATH, wcFileName, lpFilePart) > 0; if Result then begin hFile:= CreateFileW(PWideChar(aExistingFileName), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE, nil, OPEN_EXISTING, 0, 0); Result:= (hFile <> INVALID_HANDLE_VALUE); end; if Result then try ZeroMemory(@lpBuffer, SizeOf(TWin32StreamId)); with lpBuffer do begin dwStreamId:= BACKUP_LINK; Size.LowPart:= (Length(aFileName) + 1) * SizeOf(WideChar); end; // Write stream header Result:= BackupWrite(hFile, @lpBuffer, SizeOf(TWin32StreamId) - SizeOf(PWideChar), dwNumberOfBytesWritten, False, False, lpContext); if not Result then Exit; // Write file name buffer Result:= BackupWrite(hFile, @wcFileName, lpBuffer.Size.LowPart, dwNumberOfBytesWritten, False, False, lpContext); if not Result then Exit; // Finish write operation Result:= BackupWrite(hFile, nil, 0, dwNumberOfBytesWritten, True, False, lpContext); finally CloseHandle(hFile); end; end; function CreateHardLink(const AFileName, ALinkName: UnicodeString): Boolean; var dwAttributes: DWORD; begin dwAttributes := Windows.GetFileAttributesW(PWideChar(AFileName)); if dwAttributes = FILE_DOES_NOT_EXIST then Exit(False); if (dwAttributes and FILE_ATTRIBUTE_DIRECTORY) <> 0 then begin SetLastError(ERROR_DIRECTORY_NOT_SUPPORTED); Exit(False); end; dwAttributes := Windows.GetFileAttributesW(PWideChar(ALinkName)); if dwAttributes <> FILE_DOES_NOT_EXIST then begin SetLastError(ERROR_FILE_EXISTS); Exit(False); end; if HasNewApi then Result:= _CreateHardLink_New(AFileName, ALinkName) else Result:= _CreateHardLink_Old(AFileName, ALinkName) end; function _CreateSymLink_New(const ATargetFileName, ASymlinkFileName: UnicodeString; dwFlags: DWORD): boolean; var hLib: THandle; CreateSymbolicLinkW: TCreateSymbolicLinkW; begin Result:= False; hLib:= GetModuleHandle('kernel32.dll'); if hLib = 0 then begin Assert(False, 'Can not load library "kernel32.dll"'); Exit; end; CreateSymbolicLinkW:= TCreateSymbolicLinkW(GetProcAddress(hLib, 'CreateSymbolicLinkW')); if not Assigned(CreateSymbolicLinkW) then begin Assert(False, 'Can not get function address for "CreateSymbolicLinkW"'); Exit; end; Result:= CreateSymbolicLinkW(PWideChar(ASymlinkFileName), PWideChar(ATargetFileName), dwFlags); end; function _CreateSymLink_Old(aTargetFileName, aSymlinkFileName: UnicodeString): Boolean; var hDevice: THandle; lpInBuffer: PReparseDataBuffer; nInBufferSize, dwPathBufferSize: DWORD; wsNativeFileName: UnicodeString; lpBytesReturned: DWORD = 0; begin Result:= CreateDirectoryW(PWideChar(aSymlinkFileName), nil); if Result then try hDevice:= CreateFileW(PWideChar(aSymlinkFileName), GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_FLAG_OPEN_REPARSE_POINT, 0); if hDevice = INVALID_HANDLE_VALUE then Exit(False); if Pos(wsLongFileNamePrefix, aTargetFileName) <> 1 then wsNativeFileName:= wsNativeFileNamePrefix + aTargetFileName else begin wsNativeFileName:= wsNativeFileNamePrefix + Copy(aTargetFileName, 5, MaxInt); end; // File name length with trailing zero and zero for empty PrintName dwPathBufferSize:= Length(wsNativeFileName) * SizeOf(WideChar) + 4; nInBufferSize:= REPARSE_DATA_HEADER_SIZE + MOUNT_POINT_HEADER_SIZE + dwPathBufferSize; lpInBuffer:= GetMem(nInBufferSize); ZeroMemory(lpInBuffer, nInBufferSize); with lpInBuffer^, lpInBuffer^.MountPointReparseBuffer do begin ReparseTag:= IO_REPARSE_TAG_MOUNT_POINT; ReparseDataLength:= MOUNT_POINT_HEADER_SIZE + dwPathBufferSize; SubstituteNameLength:= Length(wsNativeFileName) * SizeOf(WideChar); PrintNameOffset:= SubstituteNameOffset + SubstituteNameLength + SizeOf(WideChar); CopyMemory(@PathBuffer[0], @wsNativeFileName[1], SubstituteNameLength); end; Result:= DeviceIoControl(hDevice, // handle to file or directory FSCTL_SET_REPARSE_POINT, // dwIoControlCode lpInBuffer, // input buffer nInBufferSize, // size of input buffer nil, // lpOutBuffer 0, // nOutBufferSize lpBytesReturned, // lpBytesReturned nil); // OVERLAPPED structure FreeMem(lpInBuffer); CloseHandle(hDevice); finally if not Result then RemoveDirectoryW(PWideChar(aSymlinkFileName)); end; end; function CreateSymLink(const ATargetName, ALinkName: UnicodeString): Boolean; var dwAttributes: DWORD; lpFilePart: LPWSTR = nil; AFileName, AFullPathName: UnicodeString; begin Result:= False; if (Length(ATargetName) > 1) and CharInSet(ATargetName[2], [':', '\']) then AFullPathName:= ATargetName else begin SetLength(AFullPathName, MaxSmallint); AFileName:= ExtractFilePath(ALinkName) + ATargetName; dwAttributes:= GetFullPathNameW(PWideChar(AFileName), MaxSmallint, PWideChar(AFullPathName), lpFilePart); if dwAttributes > 0 then SetLength(AFullPathName, dwAttributes) else begin AFullPathName:= ATargetName; end; end; dwAttributes:= Windows.GetFileAttributesW(PWideChar(AFullPathName)); if dwAttributes = FILE_DOES_NOT_EXIST then Exit; if HasNewApi = False then begin if (dwAttributes and FILE_ATTRIBUTE_DIRECTORY) <> 0 then Result:= _CreateSymLink_Old(AFullPathName, ALinkName) else SetLastError(ERROR_NOT_SUPPORTED); end else begin if (dwAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then Result:= _CreateSymLink_New(ATargetName, ALinkName, SYMBOLIC_LINK_FLAG_FILE) else begin if (not MayCreateSymLink) and (Pos('\\', AFullPathName) = 0) then Result:= _CreateSymLink_Old(AFullPathName, ALinkName) else begin Result:= _CreateSymLink_New(ATargetName, ALinkName, SYMBOLIC_LINK_FLAG_DIRECTORY); end; end; end; end; function ReadSymLink(const aSymlinkFileName: UnicodeString; out aTargetFileName: UnicodeString): Boolean; var hDevice: THandle; dwFileAttributes: DWORD; caOutBuffer: array[0..4095] of Byte; lpOutBuffer: TReparseDataBuffer absolute caOutBuffer; pwcTargetFileName: PWideChar; lpBytesReturned: DWORD = 0; dwFlagsAndAttributes: DWORD; begin dwFileAttributes:= GetFileAttributesW(PWideChar(aSymlinkFileName)); Result:= dwFileAttributes <> FILE_DOES_NOT_EXIST; if Result then begin if (dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then dwFlagsAndAttributes:= FILE_FLAG_OPEN_REPARSE_POINT else dwFlagsAndAttributes:= FILE_FLAG_BACKUP_SEMANTICS or FILE_FLAG_OPEN_REPARSE_POINT; // Open reparse point hDevice:= CreateFileW(PWideChar(aSymlinkFileName), 0, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, dwFlagsAndAttributes, 0); Result:= hDevice <> INVALID_HANDLE_VALUE; if not Result then Exit; Result:= DeviceIoControl(hDevice, // handle to file or directory FSCTL_GET_REPARSE_POINT, // dwIoControlCode nil, // input buffer 0, // size of input buffer @caOutBuffer, // lpOutBuffer SizeOf(caOutBuffer), // nOutBufferSize lpBytesReturned, // lpBytesReturned nil); // OVERLAPPED structure CloseHandle(hDevice); if Result then begin case lpOutBuffer.ReparseTag of IO_REPARSE_TAG_SYMLINK: with lpOutBuffer.SymbolicLinkReparseBuffer do begin pwcTargetFileName:= @PathBuffer[0]; pwcTargetFileName:= pwcTargetFileName + SubstituteNameOffset div SizeOf(WideChar); SetLength(aTargetFileName, SubstituteNameLength div SizeOf(WideChar)); CopyMemory(PWideChar(aTargetFileName), pwcTargetFileName, SubstituteNameLength); end; IO_REPARSE_TAG_MOUNT_POINT: with lpOutBuffer.MountPointReparseBuffer do begin pwcTargetFileName:= @PathBuffer[0]; pwcTargetFileName:= pwcTargetFileName + SubstituteNameOffset div SizeOf(WideChar); SetLength(aTargetFileName, SubstituteNameLength div SizeOf(WideChar)); CopyMemory(PWideChar(aTargetFileName), pwcTargetFileName, SubstituteNameLength); end; end; if Pos(wsNetworkFileNamePrefix, aTargetFileName) = 1 then Delete(aTargetFileName, 2, Length(wsNetworkFileNamePrefix) - 2) else if Pos(wsNativeFileNamePrefix, aTargetFileName) = 1 then Delete(aTargetFileName, 1, Length(wsNativeFileNamePrefix)); end; end; end; function MayCreateSymbolicLink: Boolean; const SE_CREATE_SYMBOLIC_LINK_NAME = 'SeCreateSymbolicLinkPrivilege'; var I: Integer; hProcess: HANDLE; dwLength: DWORD = 0; seCreateSymbolicLink: LUID = 0; TokenInformation: array [0..1023] of Byte; Privileges: TTokenPrivileges absolute TokenInformation; begin hProcess:= GetCurrentProcess(); if (OpenProcessToken(hProcess, TOKEN_READ, hProcess)) then try if (LookupPrivilegeValueW(nil, SE_CREATE_SYMBOLIC_LINK_NAME, seCreateSymbolicLink)) then begin if (GetTokenInformation(hProcess, TokenPrivileges, @Privileges, SizeOf(TokenInformation), dwLength)) then begin {$PUSH}{$R-} for I:= 0 to Int32(Privileges.PrivilegeCount) - 1 do begin if Privileges.Privileges[I].Luid = seCreateSymbolicLink then Exit(True); end; {$POP} end; end; finally CloseHandle(hProcess); end; Result:= False; end; initialization MayCreateSymLink:= MayCreateSymbolicLink; HasNewApi:= (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 6); end.
unit eventPopup; interface uses Windows, event, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TEventPopupForm = class(TForm) Memo: TMemo; OkButton: TButton; Edit: TEdit; Checkbox: TCheckBox; ComboBox: TComboBox; EditButton: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OkButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); private { Private declarations } FEvent : TRemindEvent; public { Public declarations } function GetEvent():TRemindEvent; procedure SetEvent( value:TRemindEvent ); property Event:TRemindEvent read GetEvent write SetEvent; end; TSnoozeThread = class(TThread) public event : TRemindEvent; sleepFor : integer; protected procedure Execute; override; end; var EventPopupForm: TEventPopupForm; implementation uses main; {$R *.dfm} procedure TEventPopupForm.FormClose(Sender: TObject; var Action: TCloseAction); var snoozeThread : TSnoozeThread; sleepForValue : integer; idx : integer; begin Action := caFree; if Checkbox.Checked then begin // start a snooze thread snoozeThread := TSnoozeThread.Create(true); snoozeThread.event := event; try sleepForValue := strtoint(Edit.Text); except on e: EConvertError do sleepForValue := 10; end; idx := ComboBox.ItemIndex; //if idx... nm, see ItemIndex property in design-time editor //codesite.send('idx',idx); if Combobox.Items[idx] = 'minutes' then begin snoozeThread.sleepFor := sleepForValue*1000*60; end else if Combobox.Items[idx] = 'hours' then begin snoozeThread.sleepFor := sleepForValue*1000*60*60; end; snoozeThread.resume(); end; end; function TEventPopupForm.GetEvent():TRemindEvent; begin result := FEvent; end; procedure TEventPopupForm.SetEvent( value:TRemindEvent ); begin FEvent := value; Memo.Lines.text := value.Notes; self.caption := FormatDateTime(ShortDateFormat,event.date) + ' ' + FormatDateTime(ShortTimeFormat,event.time); end; procedure TSnoozeThread.Execute; begin sleep(sleepFor); Synchronize(event.TakeAction); end; procedure TEventPopupForm.OkButtonClick(Sender: TObject); begin self.close(); end; procedure TEventPopupForm.EditButtonClick(Sender: TObject); begin TMainForm(self.Owner).zEventEditExecute(self,Event); end; end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. For more information, please refer to <http://unlicense.org> } unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Menus, threadunit; type { TForm1 } TForm1 = class(TForm) ButtonOK: TButton; Memo1: TMemo; miShow: TMenuItem; miStart: TMenuItem; miStop: TMenuItem; miExit: TMenuItem; PopupMenu1: TPopupMenu; TrayIcon: TTrayIcon; procedure ButtonOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure miExitClick(Sender: TObject); procedure miStartClick(Sender: TObject); procedure miShowClick(Sender: TObject); procedure miStopClick(Sender: TObject); procedure TrayIconClick(Sender: TObject); private public end; const DS=DirectorySeparator; LE=LineEnding; var Form1: TForm1; Thread1: TThreadUnit; implementation {$R *.lfm} { TForm1 } procedure TForm1.ButtonOKClick(Sender: TObject); begin Form1.Hide; if miStart.Checked then miStart.Checked:=False else miStart.Checked:=True; end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if Assigned(Thread1) then begin Thread1.Terminate; Thread1.WaitFor; if not Thread1.FreeOnTerminate then FreeAndNil(Thread1); end; end; procedure TForm1.FormCreate(Sender: TObject); begin TrayIcon.Hint:='Demo ThreadUnit'; TrayIcon.Visible:=True; Thread1:=TThreadUnit.Create(False); miStartClick(nil); end; procedure TForm1.FormShow(Sender: TObject); begin //don't show the form, only the tray icon end; procedure TForm1.miExitClick(Sender: TObject); begin Form1.Close; end; procedure TForm1.miStartClick(Sender: TObject); begin if miStart.Checked then Exit; miStart.Checked:=True; miStop.Checked:=False; Thread1.Active:=True; Memo1.Append('Thread Started'); end; procedure TForm1.miStopClick(Sender: TObject); begin if miStop.Checked then Exit; miStart.Checked:=False; miStop.Checked:=True; Thread1.Active:=False; Memo1.Append('Thread Stopped'); end; procedure TForm1.miShowClick(Sender: TObject); begin Form1.Show; end; procedure TForm1.TrayIconClick(Sender: TObject); begin Form1.Show; end; end.
unit Gradients; // Copyright (c) 1997-98 Jorge Romero Gomez, Merchise. interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GDI, GdiExt, Buffer, MemUtils, NumUtils; type TGradientEffect = ( gkVertical, gkHorizontal, gkNone, gkCustom ); const // Default gradient colors defStartColor = clBlack; defEndColor = clBlue; const // Default grid size gsDefault = 5; type TGradient = class( TGraphicControl ) protected fGradientEffect : TGradientEffect; fStartColor : TColor; fEndColor : TColor; fVertices : PTriVertices; fVertCount : integer; fCustomVertices : PTriVertices; fCustomVertCount : integer; fCustomTriangles : PTriangles; fCustomTriCount : integer; procedure SetupGradient; virtual; procedure Cleanup; virtual; procedure SetGradientEffect( Value : TGradientEffect ); virtual; procedure SetStartColor( Value : TColor ); virtual; procedure SetEndColor( Value : TColor ); virtual; procedure Changed; virtual; procedure EraseBkgnd( var Msg : TWMEraseBkgnd ); message WM_ERASEBKGND; protected procedure DefineProperties( Filer : TFiler ); override; procedure ReadData( Stream : TStream ); virtual; procedure WriteData( Stream : TStream ); virtual; public function Equals( Value : TGradient ) : boolean; virtual; function Empty : boolean; virtual; procedure SetVertexInfo( Info : TList ); virtual; procedure SetTriangleInfo( Info : TList ); virtual; procedure SetVertexAndTriangleInfo( Vertices, Triangles : TList ); virtual; public procedure Paint; override; procedure SetBounds( aLeft, aTop, aWidth, aHeight : integer ); override; constructor Create( aOwner: TComponent ); override; destructor Destroy; override; published property GradientEffect : TGradientEffect read fGradientEffect write SetGradientEffect default gkVertical; property StartColor : TColor read fStartColor write SetStartColor default defStartColor; property EndColor : TColor read fEndColor write SetEndColor default defEndColor; published property Align; property Visible; property Enabled; property ParentShowHint; property ShowHint; property PopupMenu; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property DragMode; property DragCursor; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnStartDrag; end; procedure Register; implementation {$R *.DCR} // TGradient const fGradientRect : TGradientRect = ( UpperLeft : 0; LowerRight : 1 ); procedure TGradient.EraseBkgnd( var Msg : TWMEraseBkgnd ); begin end; constructor TGradient.Create( aOwner: TComponent ); begin inherited; Width := 40; Height := 40; ControlStyle := ControlStyle + [csOpaque, csDesignInteractive]; fStartColor := defStartColor; fEndColor := defEndColor; fGradientEffect := gkVertical; SetupGradient; end; destructor TGradient.Destroy; begin Cleanup; inherited; end; procedure TGradient.Cleanup; begin if Assigned( fVertices ) then freemem( fVertices ); if Assigned( fCustomVertices ) then freemem( fCustomVertices ); end; function TGradient.Empty : boolean; begin Result := GradientEffect = gkNone; end; procedure TGradient.ReadData( Stream : TStream ); var VertSize, TriSize : integer; tmpGradientEffect : TGradientEffect; begin Cleanup; with Stream do begin ReadBuffer( tmpGradientEffect, sizeof( tmpGradientEffect ) ); if tmpGradientEffect = gkCustom then begin ReadBuffer( fCustomVertCount, sizeof( fCustomVertCount ) ); VertSize := fCustomVertCount * sizeof( fCustomVertices[0] ); getmem( fCustomVertices, VertSize ); ReadBuffer( fCustomVertices^, VertSize ); ReadBuffer( fCustomTriCount, sizeof( fCustomTriCount ) ); TriSize := fCustomTriCount * sizeof( fCustomTriangles[0] ); getmem( fCustomTriangles, TriSize ); ReadBuffer( fCustomTriangles^, TriSize ); end; GradientEffect := tmpGradientEffect; Changed; end; end; procedure TGradient.WriteData( Stream : TStream ); begin with Stream do begin WriteBuffer( fGradientEffect, sizeof( fGradientEffect ) ); if GradientEffect = gkCustom then begin WriteBuffer( fCustomVertCount, sizeof( fCustomVertCount ) ); WriteBuffer( fCustomVertices^, fCustomVertCount * sizeof( fCustomVertices[0] ) ); WriteBuffer( fCustomTriCount, sizeof( fCustomTriCount ) ); WriteBuffer( fCustomTriangles^, fCustomTriCount * sizeof( fCustomTriangles[0] ) ); end; end; end; function TGradient.Equals( Value : TGradient ) : boolean; var MyImage, ValueImage : TMemoryStream; begin if Value = nil then Result := false else if Empty or Value.Empty then Result := Empty and Value.Empty else begin Result := ClassType = Value.ClassType; if Result then begin MyImage := TMemoryStream.Create; try WriteData( MyImage ); ValueImage := TMemoryStream.Create; try Value.WriteData( ValueImage ); Result := ( MyImage.Size = ValueImage.Size ) and CompareMem( MyImage.Memory, ValueImage.Memory, MyImage.Size ); finally ValueImage.Free; end; finally MyImage.Free; end; end; end; end; procedure TGradient.DefineProperties( Filer : TFiler ); function DoWrite : boolean; begin if Filer.Ancestor <> nil then Result := not (Filer.Ancestor is TGradient) or not Equals( TGradient( Filer.Ancestor ) ) else Result := true; end; begin Filer.DefineBinaryProperty( 'Data', ReadData, WriteData, DoWrite ); end; procedure TGradient.SetVertexInfo( Info : TList ); begin freemem( fCustomVertices ); fCustomVertCount := TriVerticesFromList( Info, fCustomVertices ); Changed; end; procedure TGradient.SetTriangleInfo( Info : TList ); begin freemem( fCustomTriangles ); fCustomTriCount := TrianglesFromList( Info, fCustomTriangles ); Changed; end; procedure TGradient.SetVertexAndTriangleInfo( Vertices, Triangles : TList ); begin freemem( fCustomVertices ); fCustomVertCount := TriVerticesFromList( Vertices, fCustomVertices ); freemem( fCustomTriangles ); fCustomTriCount := TrianglesFromList( Triangles, fCustomTriangles ); Changed; end; procedure TGradient.SetupGradient; begin if fVertices <> fCustomVertices then FreePtr( fVertices ); // Free allocated vertex info case GradientEffect of gkNone : begin ControlStyle := ControlStyle - [csOpaque]; end; gkCustom : begin ControlStyle := ControlStyle - [csOpaque]; // !! Esto se puede optimizar fVertCount := fCustomVertCount; fVertices := fCustomVertices; end; gkHorizontal, gkVertical : begin ControlStyle := ControlStyle + [csOpaque]; fVertCount := AllocTriVertices( [TriVertex( 0, 0, StartColor ), TriVertex( Width, Height, EndColor )], fVertices ); end; end; end; procedure TGradient.Paint; begin case GradientEffect of gkHorizontal : begin GradientFill( Canvas.Handle, fVertices, 2, @fGradientRect, 1, gfHorizontalRect ); end; gkVertical : begin GradientFill( Canvas.Handle, fVertices, 2, @fGradientRect, 1, gfVerticalRect ); end; gkCustom : begin if Assigned( fVertices ) then GradientFill( Canvas.Handle, fVertices, fVertCount, fCustomTriangles, fCustomTriCount, gfTriangle ); end; end; end; procedure TGradient.Changed; begin SetupGradient; Invalidate; end; procedure TGradient.SetBounds( aLeft, aTop, aWidth, aHeight : integer ); begin if (aWidth <> Width) or (aHeight <> Height) then begin inherited; Changed; end else inherited; end; procedure TGradient.SetGradientEffect( Value : TGradientEffect ); begin if Value <> GradientEffect then begin fGradientEffect := Value; Changed; end; end; procedure TGradient.SetStartColor( Value : TColor ); begin if Value <> StartColor then begin fStartColor := Value; Changed; end; end; procedure TGradient.SetEndColor( Value : TColor ); begin if Value <> EndColor then begin fEndColor := Value; Changed; end; end; // VCL Registration procedure Register; begin RegisterComponents( 'Merchise', [TGradient] ); end; end.
unit ntvImgBtns; interface uses Messages, SysUtils, Variants, Classes, Graphics, Themes, ImgList, mnUtils, ntvThemes, Controls, StdCtrls, Forms; type TntvImgBtnStyle = (ibsNormal, ibsInvertMask); { TntvImgBtn } TntvImgBtn = class(TGraphicControl) private FCaption: TCaption; FDown: boolean; FChecked: Boolean; FAutoCheck: Boolean; FImageIndex: TImageIndex; FImages: TImageList; FImageChangeLink: TChangeLink; FStyle: TntvImgBtnStyle; FActive: Boolean; procedure SetDown(Value: Boolean); procedure SetCaption(Value: TCaption); procedure SetChecked(const Value: Boolean); procedure SetImageIndex(const Value: TImageIndex); procedure SetImages(const Value: TImageList); procedure SetStyle(const Value: TntvImgBtnStyle); procedure SetActive(const Value: Boolean); procedure ImageListChange(Sender: TObject); protected procedure MouseLeave; override; procedure MouseEnter; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure DblClick; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property Down: Boolean read FDown write SetDown; property Active: Boolean read FActive write SetActive; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; procedure Click; override; property Checked: Boolean read FChecked write SetChecked; published property Action; property Caption: TCaption read FCaption write SetCaption; property Images: TImageList read FImages write SetImages; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex default -1; property Style: TntvImgBtnStyle read FStyle write SetStyle default ibsNormal; property BidiMode; property ParentBidiMode; property ParentColor; property ParentFont; property Anchors; property Align; property Font; property Color; property DragCursor; property DragMode; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property AutoCheck: Boolean read FAutoCheck write FAutoCheck; end; implementation uses Types, GraphType, Menus; procedure TntvImgBtn.SetDown(Value: Boolean); begin if FDown <> Value then begin FDown := Value; Invalidate; end; end; procedure TntvImgBtn.SetCaption(Value: TCaption); begin if FCaption <> Value then begin FCaption := Value; Invalidate; end; end; procedure TntvImgBtn.MouseLeave; begin inherited; if not (csDesigning in ComponentState) then Active := False; end; procedure TntvImgBtn.MouseEnter; begin inherited; Active := True; end; procedure TntvImgBtn.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Down := True; inherited; end; procedure TntvImgBtn.MouseMove(Shift: TShiftState; X, Y: Integer); var PT: TPoint; begin if MouseCapture then begin PT.X := X; PT.Y := Y; if PtInRect(ClientRect, PT) then Down := True else Down := False; end; inherited; end; procedure TntvImgBtn.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Down := False; inherited MouseUp(Button, Shift, X, Y); end; constructor TntvImgBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csSetCaption, csClickEvents, csDoubleClicks]; FImageChangeLink := TChangeLink.Create; FImageChangeLink.OnChange := @ImageListChange; Width := 60; Height := 22; FImageIndex := -1; end; procedure TntvImgBtn.DblClick; begin Click; inherited; end; destructor TntvImgBtn.Destroy; begin FreeAndNil(FImageChangeLink); inherited Destroy; end; procedure TntvImgBtn.Paint; var aImageWidth: Integer; aCaptionRect, aRect: TRect; begin //inherited; Canvas.Font.Assign(Self.Font); aRect := ClientRect; if Active then begin Canvas.Brush.Color := Theme.Active.Background; Canvas.Brush.Style := bsSolid; Canvas.FillRect(ClientRect); end else inherited; if ((Images <> nil) and (ImageIndex >= 0)) then aImageWidth := Images.Width else aImageWidth := 0; aCaptionRect := aRect; if Caption <> '' then begin if UseRightToLeftAlignment then begin aCaptionRect.Right := aCaptionRect.Right - aImageWidth; aRect.Left := aCaptionRect.Right; end else begin aCaptionRect.Left := aCaptionRect.Left + aImageWidth; aRect.Right := aCaptionRect.Left; end; Theme.DrawButton(Canvas, Caption, aImageWidth, aCaptionRect, DrawStates(Enabled, Down, False), UseRightToLeftAlignment); end; if aImageWidth <> 0 then begin if (FImages <> nil) and (FImageIndex >= 0) then begin if Down then OffsetRect(aRect, 1, 1); Theme.DrawImage(Canvas, FImages, FImageIndex, aRect, DrawStates(Enabled, Down, False)); end end; end; procedure TntvImgBtn.Click; var Pt: TPoint; begin inherited; if PopupMenu <> nil then begin Pt.X := BoundsRect.Left; Pt.Y := BoundsRect.Bottom; Pt := Parent.ClientToScreen(Pt); PopupMenu.Popup(Pt.X, Pt.Y); end; end; procedure TntvImgBtn.SetChecked(const Value: Boolean); begin if FChecked <> Value then begin FChecked := Value; Invalidate; end; end; procedure TntvImgBtn.SetImageIndex(const Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; Invalidate; end; end; procedure TntvImgBtn.SetImages(const Value: TImageList); begin if FImages = Value then exit; if FImages <> nil then begin FImages.UnRegisterChanges(FImageChangeLink); FImages.RemoveFreeNotification(Self); end; FImages := Value; if FImages <> nil then begin FImages.RegisterChanges(FImageChangeLink); FImages.FreeNotification(Self); end; end; procedure TntvImgBtn.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FImages) then begin FImages := nil; end; end; procedure TntvImgBtn.SetStyle(const Value: TntvImgBtnStyle); begin FStyle := Value; end; procedure TntvImgBtn.SetActive(const Value: Boolean); begin if FActive <> Value then begin FActive := Value; Invalidate; end; end; procedure TntvImgBtn.ImageListChange(Sender: TObject); begin Invalidate; end; end.
{ rxlookup unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit rxlookup; {$I rx.inc} interface uses LCLType, LCLProc, LCLIntf, Classes, SysUtils, LResources, Forms, types, Controls, Graphics, Dialogs, DB, EditBtn, DBGrids, Buttons, LMessages, DbCtrls, GraphType, dbutils, RxDbGrid, rxpopupunit, Themes; const TextMargin = 5; type TRxCustomDBLookupCombo = class; TRxCustomDBLookupEdit = class; TClosePopup = procedure(Sender: TObject; SearchResult:boolean) of object; {For deciding, what we need to show in combobox in case we cannot find curvalue in lookup table.} TRxDBValueVariant = (rxufNone, rxufLastSuccessful, rxufOriginal); { TLookupSourceLink } TDataSourceLink = class(TDataLink) private FDataControl:TRxCustomDBLookupCombo; protected procedure ActiveChanged; override; procedure LayoutChanged; override; procedure FocusControl(Field: TFieldRef); override; procedure RecordChanged(Field: TField); override; procedure UpdateData; override; end; { TLookupSourceLink } TLookupSourceLink = class(TDataLink) private FOnActiveChanged:TNotifyEvent; FOnLayoutChanged:TNotifyEvent; FOnDataSetChanged:TNotifyEvent; protected procedure ActiveChanged; override; procedure LayoutChanged; override; procedure DataSetChanged; override; end; { TRxCustomDBLookupEdit } TRxCustomDBLookupEdit = class(TEditButton) private FLookupDisplayIndex: Integer; FLookupField: string; FLookupDisplay: string; FKeyField:TField; // FLookupDataLink:TLookupSourceLink; FLocateObject:TLocateObject; FOnClosePopup: TClosePopup; // FRxPopUpForm:TPopUpForm; FFieldList:TStringList; FPopUpFormOptions:TPopUpFormOptions; function GetDropDownCount: Integer; function GetDropDownWidth: Integer; function GetLookupSource: TDataSource; function GetPopupVisible: boolean; procedure SetDropDownCount(const AValue: Integer); procedure SetDropDownWidth(const AValue: Integer); procedure SetLookupDisplay(const AValue: string); procedure SetLookupDisplayIndex(const AValue: Integer); procedure SetLookupField(const AValue: string); procedure SetLookupSource(AValue: TDataSource); procedure SetPopUpFormOptions(const AValue: TPopUpFormOptions); // procedure ShowList; procedure HideList; procedure ShowPopUp; procedure UpdateKeyValue; protected property PopUpFormOptions:TPopUpFormOptions read FPopUpFormOptions write SetPopUpFormOptions; procedure DoButtonClick (Sender: TObject); override; function GetDefaultGlyphName: String; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure InternalClosePopup(AResult:boolean);virtual; // procedure LookupDataSetChanged(Sender: TObject); virtual; procedure ListLinkActiveChanged(Sender: TObject); virtual; // property OnClosePopup:TClosePopup read FOnClosePopup write FOnClosePopup; property DropDownCount: Integer read GetDropDownCount write SetDropDownCount default 8; property DropDownWidth: Integer read GetDropDownWidth write SetDropDownWidth default 0; property LookupDisplay: string read FLookupDisplay write SetLookupDisplay; property LookupDisplayIndex: Integer read FLookupDisplayIndex write SetLookupDisplayIndex default 0; property LookupField: string read FLookupField write SetLookupField; property LookupSource: TDataSource read GetLookupSource write SetLookupSource; property PopupVisible:boolean read GetPopupVisible; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TRxLookupEdit = class(TRxCustomDBLookupEdit) published property DropDownCount; property DropDownWidth; property LookupDisplay; property LookupDisplayIndex; property LookupField; property LookupSource; property PopUpFormOptions; property OnClosePopup; end; { TRxCustomDBLookupCombo } TRxCustomDBLookupCombo = class (TCustomControl) private //FDataLink:TFieldDataLink; FDataLink:TDataSourceLink; FDataFieldName: string; FDataField :TField; // FLookupDataLink:TLookupSourceLink; FLocateObject:TLocateObject; FLookupField: string; FLookupDisplay: string; FDisplayField:TField; FKeyField:TField; FLookupDisplayIndex: Integer; FListActive:boolean; // FEmptyItemColor: TColor; FEmptyValue: string; FOnChange: TNotifyEvent; FOnClosePopup: TClosePopup; FPopUpFormOptions: TPopUpFormOptions; // FRxPopUpForm:TPopUpForm; FFieldList:TStringList; FValuesList:TStringList; FValue:string; //Visual FButton: TSpeedButton; FButtonNeedsFocus: Boolean; FDirectInput : Boolean; FOnButtonClick : TNotifyEvent; FReadOnly: boolean; FDisplayAll: boolean; FUnfindedValue: TRxDBValueVariant; FSuccesfullyFind : boolean; FOnSelect : TNotifyEvent; procedure SetValue(const Value: string); function GetKeyValue: Variant; procedure SetKeyValue(const Value: Variant); function GetDataSource: TDataSource; function GetDisplayAll: Boolean; function GetDropDownCount: Integer; function GetDropDownWidth: Integer; function GetLookupSource: TDataSource; function GetMinHeight: Integer; function GetBorderSize: Integer; procedure CheckButtonVisible; function GetButtonWidth: Integer; function GetFlat: Boolean; function GetGlyph: TBitmap; function GetNumGlyphs: Integer; function GetOnGetGridCellProps: TGetCellPropsEvent; function GetPopupVisible: boolean; procedure SetButtonNeedsFocus(const AValue: Boolean); procedure SetButtonWidth(const AValue: Integer); procedure SetDataFieldName(const AValue: string); procedure SetDataSource(const AValue: TDataSource); procedure SetDisplayAll(const AValue: Boolean); procedure SetDropDownCount(const AValue: Integer); procedure SetDropDownWidth(const AValue: Integer); procedure SetEmptyItemColor(const AValue: TColor); procedure SetEmptyValue(const AValue: string); procedure SetFlat(const AValue: Boolean); procedure SetGlyph(const AValue: TBitmap); procedure SetLookupDisplay(const AValue: string); procedure SetLookupDisplayIndex(const AValue: Integer); procedure SetLookupField(const AValue: string); procedure SetLookupSource(const AValue: TDataSource); procedure SetNumGlyphs(const AValue: Integer); procedure SetOnGetGridCellProps(const AValue: TGetCellPropsEvent); procedure SetPopUpFormOptions(const AValue: TPopUpFormOptions); procedure SetReadOnly(const AValue: boolean); function StoreEmpty: boolean; procedure WMSetFocus(var Message: TLMSetFocus); message LM_SETFOCUS; procedure WMKillFocus(var Message: TLMKillFocus); message LM_KILLFOCUS; procedure CMExit(var Message:TLMessage); message CM_EXIT; procedure PaintDisplayValues(ACanvas: TCanvas; R: TRect; ALeft: Integer); procedure CheckNotCircular; procedure DisplayValueChanged; procedure DataLinkActiveChanged; procedure DataLinkRecordChanged(Field: TField); procedure UpdateFieldValues; procedure SetValueKey(const Value: string); procedure UpdateKeyValue; procedure KeyValueChanged; procedure UpdateData; procedure NeedUpdateData; protected procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: Boolean); override; {procedure GetPreferredSize(var PreferredWidth, PreferredHeight: integer; Raw: boolean = false; WithThemeSpace: boolean = true); override; class function GetControlClassDefaultSize: TSize; override;} procedure ShowList; virtual; procedure OnInternalClosePopup(AResult:boolean);virtual; procedure SetEnabled(Value: Boolean); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure UTF8KeyPress(var UTF8Key: TUTF8Char); override; procedure SetParent(AParent: TWinControl); override; procedure DoSetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure DoPositionButton; virtual; procedure DoChange; virtual; procedure DoButtonClick(Sender: TObject); virtual; Procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure CMVisibleChanged(var Msg: TLMessage); message CM_VISIBLECHANGED; procedure CMEnabledChanged(var Msg: TLMessage); message CM_ENABLEDCHANGED; procedure MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); override; procedure Click; override; function RealGetText: TCaption; override; procedure RealSetText(const Value: TCaption); override; procedure Paint; override; procedure LookupDataSetChanged(Sender: TObject); virtual; procedure ListLinkActiveChanged(Sender: TObject); virtual; // property Button: TSpeedButton read FButton; property ButtonWidth : Integer read GetButtonWidth write SetButtonWidth; property ButtonOnlyWhenFocused : Boolean Read FButtonNeedsFocus Write SetButtonNeedsFocus; property DirectInput : Boolean read FDirectInput write FDirectInput Default True; property DisplayAllFields: Boolean read GetDisplayAll write SetDisplayAll default False; property Flat : Boolean read GetFlat write SetFlat; property Glyph : TBitmap read GetGlyph write SetGlyph; property NumGlyphs : Integer read GetNumGlyphs write SetNumGlyphs; property OnButtonClick : TNotifyEvent read FOnButtonClick write FOnButtonClick; property OnChange : TNotifyEvent read FOnChange write FOnChange; property ReadOnly:boolean read FReadOnly write SetReadOnly; property EmptyValue: string read FEmptyValue write SetEmptyValue stored StoreEmpty; property EmptyItemColor: TColor read FEmptyItemColor write SetEmptyItemColor default clWindow; //data property PopUpFormOptions:TPopUpFormOptions read FPopUpFormOptions write SetPopUpFormOptions; property DataField: string read FDataFieldName write SetDataFieldName; property DataSource: TDataSource read GetDataSource write SetDataSource; property DropDownCount: Integer read GetDropDownCount write SetDropDownCount default 8; property DropDownWidth: Integer read GetDropDownWidth write SetDropDownWidth default 0; property LookupDisplay: string read FLookupDisplay write SetLookupDisplay; property LookupDisplayIndex: Integer read FLookupDisplayIndex write SetLookupDisplayIndex default 0; property LookupField: string read FLookupField write SetLookupField; property LookupSource: TDataSource read GetLookupSource write SetLookupSource; property OnGetGridCellProps: TGetCellPropsEvent read GetOnGetGridCellProps write SetOnGetGridCellProps; property Value: string read FValue write SetValue stored False; property KeyValue: Variant read GetKeyValue write SetKeyValue stored False; property OnSelect: TNotifyEvent read FOnSelect write FOnSelect; property OnClosePopup:TClosePopup read FOnClosePopup write FOnClosePopup; property UnfindedValue : TRxDBValueVariant read FUnfindedValue write FUnfindedValue default rxufNone; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property PopupVisible:boolean read GetPopupVisible; end; { TRxDBLookupCombo } TRxDBLookupCombo = class(TRxCustomDBLookupCombo) protected procedure OnInternalClosePopup(AResult:boolean);override; public property Value; property KeyValue; property Text; published property AutoSize; property Align; property Anchors; property BorderSpacing; property ButtonOnlyWhenFocused; Property ButtonWidth; property Color; property DataField; property DataSource; Property DirectInput; property DragCursor; property DragMode; property Enabled; property PopUpFormOptions; Property Flat; property Font; property Glyph; property EmptyValue; property EmptyItemColor; // property MaxLength; property NumGlyphs; Property OnButtonClick; property OnChange; property OnClick; property OnClosePopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnGetGridCellProps; property OnSelect; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; { property Width default 100; property Height default 23;} property DisplayAllFields; property DropDownCount; property DropDownWidth; property LookupDisplay; property LookupDisplayIndex; property LookupField; property LookupSource; property UnfindedValue; end; implementation uses VCLUtils, Math, rxdconst; type TDbGridAccess = class(TDbGrid) end; TPopUpFormAccess = class(TPopUpForm) end; { TRxCustomDBLookupEdit } function TRxCustomDBLookupEdit.GetLookupSource: TDataSource; begin Result:=FLookupDataLink.DataSource; end; function TRxCustomDBLookupEdit.GetPopupVisible: boolean; begin Result:=Assigned(FRxPopUpForm); end; function TRxCustomDBLookupEdit.GetDropDownCount: Integer; begin Result:=FPopUpFormOptions.DropDownCount; end; function TRxCustomDBLookupEdit.GetDropDownWidth: Integer; begin Result:=FPopUpFormOptions.DropDownWidth; end; procedure TRxCustomDBLookupEdit.SetDropDownCount(const AValue: Integer); begin FPopUpFormOptions.DropDownCount:=AValue; end; procedure TRxCustomDBLookupEdit.SetDropDownWidth(const AValue: Integer); begin FPopUpFormOptions.DropDownWidth:=AValue; end; procedure TRxCustomDBLookupEdit.SetLookupDisplay(const AValue: string); var S1, S2:string; K:integer; begin if FLookupDisplay=AValue then exit; FLookupDisplay:=AValue; FFieldList.Clear; S2:=AValue; while S2<>'' do begin K:=Pos(';', S2); if K>0 then begin S1:=Copy(S2, 1, K-1); Delete(S2, 1, K); end else begin S1:=S2; S2:=''; end; FFieldList.Add(S1); end; end; procedure TRxCustomDBLookupEdit.SetLookupDisplayIndex(const AValue: Integer); begin if FLookupDisplayIndex=AValue then exit; FLookupDisplayIndex:=AValue; end; procedure TRxCustomDBLookupEdit.SetLookupField(const AValue: string); begin if FLookupField = AValue then exit; FLookupField:=AValue; end; procedure TRxCustomDBLookupEdit.SetLookupSource(AValue: TDataSource); begin FLookupDataLink.DataSource:=AValue; end; procedure TRxCustomDBLookupEdit.SetPopUpFormOptions( const AValue: TPopUpFormOptions); begin FPopUpFormOptions.Assign(AValue); end; procedure TRxCustomDBLookupEdit.ShowList; {var i,W:integer; GC:TColumn;} begin if FLookupDataLink.Active and not PopupVisible then begin ShowPopUp; end; end; procedure TRxCustomDBLookupEdit.HideList; begin end; procedure TRxCustomDBLookupEdit.ShowPopUp; var R:TPoint; FValue:string; {$IFDEF LINUX} TempF:TPopUpForm; {$ENDIF} begin if FLookupDataLink.Active then if not PopupVisible then begin FValue := Text; FLocateObject.Locate(FLookupField, FValue, true, false); (* FRxPopUpForm:=ShowRxDBPopUpForm(Self, FLookupDataLink.DataSet, @OnClosePopup, FPopUpFormOptions, FLookupDisplay, LookupDisplayIndex, 0 {ButtonWidth}, Font);*) FRxPopUpForm:=ShowRxDBPopUpForm(Self, FLookupDataLink.DataSet, @InternalClosePopup, FPopUpFormOptions, FLookupDisplay, LookupDisplayIndex, 0 {ButtonWidth}, Font); {$IFDEF LINUX} TempF:=FRxPopUpForm; if FRxPopUpForm.ShowModal = mrOk then InternalClosePopup(true); TempF.Free; FRxPopUpForm:=nil {$ENDIF} end end; procedure TRxCustomDBLookupEdit.UpdateKeyValue; var S:string; begin S:=FFieldList[FLookupDisplayIndex]; if FLookupDataLink.Active then Text:=FLookupDataLink.DataSet.FieldByName(S).AsString; end; procedure TRxCustomDBLookupEdit.DoButtonClick(Sender: TObject); begin inherited DoButtonClick(Sender); if PopupVisible then HideList else ShowList; end; function TRxCustomDBLookupEdit.GetDefaultGlyphName: String; begin Result:='rxbtn_downarrow'; end; procedure TRxCustomDBLookupEdit.KeyDown(var Key: Word; Shift: TShiftState); begin if (Key in [VK_PRIOR, VK_NEXT, VK_UP, VK_DOWN, VK_RETURN]) and PopupVisible then begin { if Key=VK_RETURN then HideList else TDbGridAccess(Flist).KeyDown(Key, Shift); Key := 0;} end else if (Key = VK_DOWN) and ((ssAlt in Shift) or (ssCtrl in Shift)) then begin ShowList; Key := 0; end; inherited KeyDown(Key, Shift); { FIgnoreChange := (SelLength > 0) or (Key = VK_BACK);} if not (PopupVisible or ReadOnly) and (Key in [VK_UP, VK_DOWN]) and (Shift = []) then begin case Key of VK_UP: if not FLookupDataLink.DataSet.BOF then FLookupDataLink.DataSet.Prior; VK_DOWN: if not FLookupDataLink.DataSet.EOF then FLookupDataLink.DataSet.Next; end; Text:=FLookupDataLink.DataSet.FieldByName(FFieldList[FLookupDisplayIndex]).AsString; Key:=0; end; end; procedure TRxCustomDBLookupEdit.InternalClosePopup(AResult: boolean); begin if Assigned(FOnClosePopup) then FOnClosePopup(Self, AResult); {$IFDEF WINDOWS} FRxPopUpForm:=nil; {$ENDIF} end; procedure TRxCustomDBLookupEdit.LookupDataSetChanged(Sender: TObject); begin UpdateKeyValue; Invalidate; end; procedure TRxCustomDBLookupEdit.ListLinkActiveChanged(Sender: TObject); var DataSet: TDataSet; begin FKeyField := nil; DataSet:=nil; if FLookupDataLink.Active and (FLookupField <> '') then begin DataSet := FLookupDataLink.DataSet; FKeyField := DataSet.FieldByName(FLookupField); end; FLocateObject.DataSet := DataSet; UpdateKeyValue end; constructor TRxCustomDBLookupEdit.Create(AOwner: TComponent); var P:TBitmap; begin inherited Create(AOwner); FLocateObject:=CreateLocate(nil); //Lookup FLookupDataLink:=TLookupSourceLink.Create; FLookupDataLink.FOnActiveChanged:=@ListLinkActiveChanged; FLookupDataLink.FOnLayoutChanged:=@ListLinkActiveChanged; FLookupDataLink.FOnDataSetChanged:=@LookupDataSetChanged; // FDropDownCount:=8; FFieldList:=TStringList.Create; P:=CreateArrowBitmap; Glyph.Assign(P); P.Free; ButtonWidth:=15; FPopUpFormOptions:=TPopUpFormOptions.Create(Self); end; destructor TRxCustomDBLookupEdit.Destroy; begin FreeAndNil(FLocateObject); FreeAndNil(FPopUpFormOptions); FFieldList.Clear; FreeAndNil(FFieldList); FreeAndNil(FLookupDataLink); inherited Destroy; end; { TRxCustomDBLookupCombo } function TRxCustomDBLookupCombo.GetMinHeight: Integer; begin Result := 15{DefaultTextHeight} + GetBorderSize + 3; end; function TRxCustomDBLookupCombo.GetDisplayAll: Boolean; begin Result := FDisplayAll; end; function TRxCustomDBLookupCombo.GetDropDownCount: Integer; begin Result:=FPopUpFormOptions.DropDownCount end; function TRxCustomDBLookupCombo.GetDropDownWidth: Integer; begin Result:=FPopUpFormOptions.DropDownWidth; end; function TRxCustomDBLookupCombo.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; function TRxCustomDBLookupCombo.GetLookupSource: TDataSource; begin Result:=FLookupDataLink.DataSource; end; function TRxCustomDBLookupCombo.GetBorderSize: Integer; {var Params: TCreateParams; R: TRect;} begin { CreateParams(Params); SetRect(R, 0, 0, 0, 0); AdjustWindowRectEx(R, Params.Style, False, Params.ExStyle); Result := R.Bottom - R.Top;} Result := 3; end; procedure TRxCustomDBLookupCombo.CheckButtonVisible; begin if Assigned(FButton) then FButton.Visible:=(csdesigning in ComponentState) or (Visible and (Focused or not FButtonNeedsFocus)); end; function TRxCustomDBLookupCombo.GetButtonWidth: Integer; begin if Assigned(FButton) then Result:=FButton.Width else Result:=0; end; function TRxCustomDBLookupCombo.GetFlat: Boolean; begin if Assigned(FButton) then Result:=FButton.Flat else Result:=false; end; function TRxCustomDBLookupCombo.GetGlyph: TBitmap; begin if Assigned(FButton) then Result:=FButton.Glyph else Result:=nil; end; function TRxCustomDBLookupCombo.GetNumGlyphs: Integer; begin if Assigned(FButton) then Result:=FButton.NumGlyphs else Result:=0; end; function TRxCustomDBLookupCombo.GetOnGetGridCellProps: TGetCellPropsEvent; begin Result:=FPopUpFormOptions.OnGetCellProps; end; function TRxCustomDBLookupCombo.GetPopupVisible: boolean; begin Result:=Assigned(FRxPopUpForm); end; procedure TRxCustomDBLookupCombo.SetButtonNeedsFocus(const AValue: Boolean); begin if FButtonNeedsFocus<>AValue then begin FButtonNeedsFocus:=AValue; CheckButtonVisible; end; end; procedure TRxCustomDBLookupCombo.SetButtonWidth(const AValue: Integer); begin if Assigned(FButton) then FButton.Width:=AValue; end; procedure TRxCustomDBLookupCombo.SetDataFieldName(const AValue: string); begin if FDataFieldName <> AValue then begin FDataFieldName := AValue; DataLinkActiveChanged; end; end; procedure TRxCustomDBLookupCombo.SetDataSource(const AValue: TDataSource); begin FDataLink.DataSource := AValue; if AValue <> nil then AValue.FreeNotification(Self); end; procedure TRxCustomDBLookupCombo.SetDisplayAll(const AValue: Boolean); begin if FDisplayAll <> AValue then begin FDisplayAll := AValue; Invalidate; end; end; procedure TRxCustomDBLookupCombo.SetDropDownCount(const AValue: Integer); begin FPopUpFormOptions.DropDownCount:=AValue; end; procedure TRxCustomDBLookupCombo.SetDropDownWidth(const AValue: Integer); begin FPopUpFormOptions.DropDownWidth:=AValue; end; procedure TRxCustomDBLookupCombo.SetEmptyItemColor(const AValue: TColor); begin if FEmptyItemColor=AValue then exit; FEmptyItemColor:=AValue; if not (csReading in ComponentState) then Invalidate; end; procedure TRxCustomDBLookupCombo.SetEmptyValue(const AValue: string); begin if FEmptyValue=AValue then exit; FEmptyValue:=AValue; end; procedure TRxCustomDBLookupCombo.SetFlat(const AValue: Boolean); begin if Assigned(FButton) then FButton.Flat:=AValue; Invalidate; end; procedure TRxCustomDBLookupCombo.SetGlyph(const AValue: TBitmap); begin if Assigned(FButton) then FButton.Glyph:=AValue; end; procedure TRxCustomDBLookupCombo.SetLookupDisplay(const AValue: string); var S1, S2:string; K:integer; begin if FLookupDisplay=AValue then exit; FLookupDisplay:=AValue; FFieldList.Clear; S2:=AValue; while S2<>'' do begin K:=Pos(';', S2); if K>0 then begin S1:=Copy(S2, 1, K-1); Delete(S2, 1, K); end else begin S1:=S2; S2:=''; end; FFieldList.Add(S1); end; DisplayValueChanged; end; procedure TRxCustomDBLookupCombo.SetLookupDisplayIndex(const AValue: Integer); begin if FLookupDisplayIndex=AValue then exit; FLookupDisplayIndex:=AValue; end; procedure TRxCustomDBLookupCombo.SetLookupField(const AValue: string); begin FLookupField:=AValue; end; procedure TRxCustomDBLookupCombo.SetLookupSource(const AValue: TDataSource); begin FLookupDataLink.DataSource:=AValue; FLocateObject.DataSet:=FLookupDataLink.DataSet; FPopUpFormOptions.DataSource:=AValue; end; procedure TRxCustomDBLookupCombo.SetNumGlyphs(const AValue: Integer); begin if Assigned(FButton) then FButton.NumGlyphs:=AValue; end; procedure TRxCustomDBLookupCombo.SetOnGetGridCellProps( const AValue: TGetCellPropsEvent); begin FPopUpFormOptions.OnGetCellProps:=AValue; end; procedure TRxCustomDBLookupCombo.SetPopUpFormOptions( const AValue: TPopUpFormOptions); begin FPopUpFormOptions.Assign(AValue); end; procedure TRxCustomDBLookupCombo.SetReadOnly(const AValue: boolean); begin if FReadOnly=AValue then exit; FReadOnly:=AValue; end; function TRxCustomDBLookupCombo.StoreEmpty: boolean; begin Result:=true; end; procedure TRxCustomDBLookupCombo.WMSetFocus(var Message: TLMSetFocus); begin FButton.Visible:=True; inherited WMSetFocus(Message); Invalidate; end; procedure TRxCustomDBLookupCombo.WMKillFocus(var Message: TLMKillFocus); begin if FButtonNeedsFocus then FButton.Visible:=false; inherited WMKillFocus(Message); Invalidate; end; procedure TRxCustomDBLookupCombo.CMExit(var Message: TLMessage); begin inherited; end; procedure TRxCustomDBLookupCombo.PaintDisplayValues(ACanvas: TCanvas; R: TRect; ALeft: Integer); var I, LastIndex, TxtWidth: Integer; X, W, ATop, ARight: Integer; S: string; F:TField; begin if (FValuesList.Count=0) or (not LookupSource.DataSet.Active) then exit; if ColorToRGB(Self.Color) <> ColorToRGB(clBtnFace) then ACanvas.Pen.Color := clBtnFace else ACanvas.Pen.Color := clBtnShadow; LastIndex := FValuesList.Count-1; TxtWidth := ACanvas.TextWidth('W'); ATop := Max(0, (HeightOf(R) - ACanvas.TextHeight('Xy')) div 2); ARight := R.Right; Inc(R.Left, ALeft); for I := 0 to LastIndex do begin F:=LookupSource.DataSet.FieldByName(FFieldList[i]); S := FValuesList[i]; if (FPopUpFormOptions.Columns.Count>i) and (I<LastIndex) then W := FPopUpFormOptions.Columns[i].Width else begin W := F.DisplayWidth; if I < LastIndex then W := W * TxtWidth + 4 else W := ARight - R.Left; end; X := 2; R.Right := R.Left + W; case F.AlignMent of taRightJustify: X := W - ACanvas.TextWidth(S) - 3; taCenter: X := (W - ACanvas.TextWidth(S)) div 2; end; ACanvas.TextRect(R, R.Left + Max(0, X), ATop, S); Inc(R.Left, W); if I < LastIndex then begin ACanvas.MoveTo(R.Right, R.Top); ACanvas.LineTo(R.Right, R.Bottom); Inc(R.Left); end; if R.Left >= ARight then Break; end; end; procedure TRxCustomDBLookupCombo.CheckNotCircular; begin if FDataLink.Active and ((DataSource = LookupSource) or (FDataLink.DataSet = FLookupDataLink.DataSet)) then _DBError(SCircularDataLink); end; procedure TRxCustomDBLookupCombo.DisplayValueChanged; begin FDisplayField:=nil; if FLookupDataLink.Active and (FLookupDisplay <> '') then begin FDisplayField := FLookupDataLink.DataSet.FieldByName(FFieldList[FLookupDisplayIndex]); if PopupVisible then begin // UpdateData; UpdateFieldValues; end; end; end; procedure TRxCustomDBLookupCombo.DataLinkActiveChanged; begin if FDataLink.Active and (FDataFieldName <> '') then begin CheckNotCircular; FDataField := FDataLink.DataSet.FieldByName(FDataFieldName); end else begin FDataField := nil; end; DataLinkRecordChanged(nil); end; procedure TRxCustomDBLookupCombo.DataLinkRecordChanged(Field: TField); begin if (Field = nil) or (Field = FDataField) then begin if FDataField <> nil then begin SetValueKey(FDataField.AsString); end else SetValueKey(FEmptyValue); end end; procedure TRxCustomDBLookupCombo.UpdateFieldValues; var i, k:integer; F:TField; begin FValuesList.Clear; if not Assigned(FDataField) then begin if FLookupDataLink.Active then if (Self.FSuccesfullyFind) or (Self.UnfindedValue = rxufLastSuccessful) then begin for i:=0 to FFieldList.Count-1 do begin F:=FLookupDataLink.DataSet.FieldByName(FFieldList[i]); k:=FValuesList.Add(F.DisplayText); FValuesList.Objects[k]:=TObject(PtrInt(F.DisplayWidth)); end; end else case Self.UnfindedValue of rxufNone : {Do nothing}; rxufOriginal : FValuesList.Add(FValue);//Show original field value... end; end else if Assigned(FDataField) then begin if FDataField.IsNull then FValuesList.Add(FEmptyValue) else if FLookupDataLink.Active then if (Self.FSuccesfullyFind) or (Self.UnfindedValue = rxufLastSuccessful) then begin for i:=0 to FFieldList.Count-1 do begin F:=FLookupDataLink.DataSet.FieldByName(FFieldList[i]); k:=FValuesList.Add(F.DisplayText); FValuesList.Objects[k]:=TObject(PtrInt(F.DisplayWidth)); end; end else case Self.UnfindedValue of rxufNone : {Do nothing}; rxufOriginal : FValuesList.Add(FValue);//Show original field value... end; end; end; procedure TRxCustomDBLookupCombo.ShowList; {$IFDEF LINUX} var TempF:TPopUpForm; {$ENDIF} begin if Assigned(FLookupDataLink.DataSet) and (FLookupDataLink.DataSet.Active) then if not PopupVisible then begin if FDataField<>nil then if FDataField <> nil then FValue := FDataField.AsString else FValue := FEmptyValue; if not Assigned(FDataField) then begin if not FLocateObject.Locate(FLookupField, FValue, true, false) then FLookupDataLink.DataSet.First; end else if Assigned(FDataField) and not FDataField.IsNull then begin if not FLocateObject.Locate(FLookupField, FValue, true, false) then FLookupDataLink.DataSet.First;//In case we cannot find curvalue... end else if FLookupDataLink.Active then FLookupDataLink.DataSet.First; FRxPopUpForm:=ShowRxDBPopUpForm(Self, FLookupDataLink.DataSet, @OnInternalClosePopup, FPopUpFormOptions, FLookupDisplay, LookupDisplayIndex, 0 {ButtonWidth}, Font); {$IFDEF LINUX} TempF:=FRxPopUpForm; if FRxPopUpForm.ShowModal = mrOk then {OnInternalClosePopup(true)}; TempF.Free; FRxPopUpForm:=nil {$ENDIF} end end; procedure TRxCustomDBLookupCombo.SetValueKey(const Value: string); begin if FValue <> Value then begin FValue := Value; if Assigned(FLookupDataLink.DataSet) and (FLookupDataLink.DataSet.Active) then begin FSuccesfullyFind := FLocateObject.Locate(FLookupField, FValue, true, false); KeyValueChanged; end; end; end; procedure TRxCustomDBLookupCombo.UpdateKeyValue; begin if Assigned(FDataField) then if FDataField <> nil then FValue := FDataField.AsString else FValue := FEmptyValue; if not Assigned(FDataField) then begin if FValue=FEmptyValue then FSuccesfullyFind := false else FSuccesfullyFind := FLocateObject.Locate(FLookupField, FValue, true, false); end else if FDataField.IsNull then FSuccesfullyFind := false else if not FDataField.IsNull then FSuccesfullyFind := FLocateObject.Locate(FLookupField, FValue, true, false); KeyValueChanged; end; procedure TRxCustomDBLookupCombo.KeyValueChanged; begin UpdateFieldValues; Invalidate; DoChange; end; procedure TRxCustomDBLookupCombo.UpdateData; begin //We have nothing to do here... end; procedure TRxCustomDBLookupCombo.NeedUpdateData; begin if FLookupDataLink.Active and Assigned(FDataField) then begin ; if FKeyField.IsNull then FDataField.Clear else FDataField.AsString:=FKeyField.AsString end; end; procedure TRxCustomDBLookupCombo.CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: Boolean); var tmpCanvas: TCanvas; begin inherited CalculatePreferredSize(PreferredWidth, PreferredHeight, WithThemeSpace); // ignore width PreferredWidth:=0; tmpCanvas := GetWorkingCanvas(Canvas); try PreferredHeight:=Canvas.TextHeight('Wg')+12; //PreferredWidth:=Canvas.TextWidth('W')*12; finally if TmpCanvas<>Canvas then FreeWorkingCanvas(tmpCanvas); end; end; {procedure TRxCustomDBLookupCombo.GetPreferredSize(var PreferredWidth, PreferredHeight: integer; Raw: boolean; WithThemeSpace: boolean); begin inherited GetPreferredSize(PreferredWidth, PreferredHeight, Raw, WithThemeSpace); end; class function TRxCustomDBLookupCombo.GetControlClassDefaultSize: TSize; begin Result.CX := 170; Result.CY := 50; end; } procedure TRxCustomDBLookupCombo.OnInternalClosePopup(AResult: boolean); begin if Assigned(FRxPopUpForm) and AResult and (pfgColumnResize in FPopUpFormOptions.Options) then FillPopupWidth(FPopUpFormOptions, FRxPopUpForm); if Assigned(FOnClosePopup) then FOnClosePopup(Self, AResult); if FRxPopUpForm=nil then begin SetFocus; Exit; end; FRxPopUpForm:=nil; if not AResult then UpdateKeyValue else if AResult and not Assigned(FDataLink.DataSource) and (FLookupDataLink.Active) then begin if FKeyField.IsNull then SetValueKey(FEmptyValue) else SetValueKey(FKeyField.AsString); end else if AResult and Assigned(FDataLink.DataSource) then begin FDataLink.Edit; Visible:=true; NeedUpdateData;//We need to update DataField; end; if (AResult) and (Assigned(FOnSelect)) then FOnSelect(Self); end; procedure TRxCustomDBLookupCombo.SetEnabled(Value: Boolean); begin inherited SetEnabled(Value); Invalidate; end; procedure TRxCustomDBLookupCombo.KeyDown(var Key: Word; Shift: TShiftState); begin if (Key in [VK_PRIOR, VK_NEXT, VK_UP, VK_DOWN, VK_RETURN, VK_HOME, VK_END]) and PopupVisible then begin TPopUpFormAccess(FRxPopUpForm).KeyDown(Key, Shift); end else if not PopupVisible then begin if (Key = VK_DOWN) and ((ssAlt in Shift) or (ssCtrl in Shift)) then begin ShowList; Key := 0; end else if (Key = VK_ESCAPE) and not (Assigned(FDataField)) then begin SetValueKey(FEmptyValue); if Assigned(FOnSelect) then FOnSelect(Self); Key:=0; end else if (Key = VK_ESCAPE) and (not FDataField.IsNull) and (FDataLink.Edit) then begin FDataField.Clear; UpdateKeyValue; if Assigned(FOnSelect) then FOnSelect(Self); Key:=0; end; end; inherited KeyDown(Key, Shift); if FLookupDataLink.Active and FDataLink.Active and not (PopupVisible or ReadOnly) then begin if (Key in [VK_UP, VK_DOWN]) and (Shift = []) then begin FDataLink.Edit; if not FDataField.IsNull then begin //FLocateObject.Locate(FLookupField, FDataField.AsString, true, false); If not FLocateObject.Locate(FLookupField, FDataField.AsString, true, false) then FLookupDataLink.DataSet.First; case Key of VK_UP: if not FLookupDataLink.DataSet.BOF then FLookupDataLink.DataSet.Prior; VK_DOWN: if not FLookupDataLink.DataSet.EOF then FLookupDataLink.DataSet.Next; end; end; //FDataLink.UpdateRecord; -- no need more... Self.NeedUpdateData; if Assigned(FOnSelect) then FOnSelect(Self); KeyValueChanged; Key:=0; end end else if FLookupDataLink.Active and not (PopupVisible or ReadOnly) then begin if (Key in [VK_UP, VK_DOWN]) and (Shift = []) then begin case Key of VK_UP: if not FLookupDataLink.DataSet.BOF then FLookupDataLink.DataSet.Prior; VK_DOWN: if not FLookupDataLink.DataSet.EOF then FLookupDataLink.DataSet.Next; end; SetValueKey(FKeyField.AsString); if Assigned(FOnSelect) then FOnSelect(Self); Key:=0; end end; end; procedure TRxCustomDBLookupCombo.UTF8KeyPress(var UTF8Key: TUTF8Char); begin if not (PopupVisible) and ((UTF8Key >= #32) or (UTF8Key = #8)) then ShowList; inherited UTF8KeyPress(UTF8Key); if PopupVisible then FRxPopUpForm.UTF8KeyPress(UTF8Key); end; procedure TRxCustomDBLookupCombo.SetParent(AParent: TWinControl); begin inherited SetParent(AParent); if FButton <> nil then begin // FButton.Parent := Parent; CheckButtonVisible; end; end; procedure TRxCustomDBLookupCombo.DoSetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin if not (csReading in ComponentState) and (Height < GetMinHeight) then AHeight := GetMinHeight else begin if (csDesigning in ComponentState) then if (Height < GetMinHeight) then AHeight := GetMinHeight; end; inherited DoSetBounds(ALeft, ATop, AWidth, AHeight); // DoPositionButton; end; procedure TRxCustomDBLookupCombo.DoPositionButton; begin if FButton <> nil then FButton.SetBounds(Left+Width, Top, FButton.Width, Height); end; procedure TRxCustomDBLookupCombo.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TRxCustomDBLookupCombo.DoButtonClick(Sender: TObject); begin if not FReadOnly then//We can do something if and only if that's not ReadOnly field... Begin if Assigned(FOnButtonClick) then FOnButtonClick(Self); { if PopupVisible then HideList else} ShowList; End; end; procedure TRxCustomDBLookupCombo.Loaded; begin inherited Loaded; CheckButtonVisible; end; procedure TRxCustomDBLookupCombo.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FButton) and (Operation = opRemove) then FButton := nil; end; procedure TRxCustomDBLookupCombo.CMVisibleChanged(var Msg: TLMessage); begin inherited CMVisibleChanged(Msg); CheckButtonVisible; end; procedure TRxCustomDBLookupCombo.CMEnabledChanged(var Msg: TLMessage); begin inherited CMEnabledChanged(Msg); if FButton<>nil then FButton.Enabled:=Enabled; end; procedure TRxCustomDBLookupCombo.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button,Shift, X, Y); { If not Self.PopupVisible then DoButtonClick(Self);} end; procedure TRxCustomDBLookupCombo.Click; begin inherited Click; If not Self.PopupVisible then DoButtonClick(Self); end; function TRxCustomDBLookupCombo.RealGetText: TCaption; begin if PopupVisible then Result:=inherited RealGetText else if (FLookupDisplayIndex>=0) and (FLookupDisplayIndex < FValuesList.Count) then Result:=FValuesList[FLookupDisplayIndex] else Result:=''; end; procedure TRxCustomDBLookupCombo.RealSetText(const Value: TCaption); var LookFieldName:string; begin inherited RealSetText(Value); if not PopupVisible then begin if Assigned(FLookupDataLink.DataSet) and (FLookupDataLink.DataSet.Active) then begin if (FLookupDisplayIndex>=0) and (FLookupDisplayIndex<FFieldList.Count) then begin LookFieldName:=FFieldList[FLookupDisplayIndex]; FSuccesfullyFind := FLocateObject.Locate(LookFieldName, Value, true, false); if FSuccesfullyFind and Assigned(FKeyField) then SetValue(FKeyField.AsString); KeyValueChanged; end; end; end; end; procedure TRxCustomDBLookupCombo.Paint; var Selected:boolean; R, R1: TRect; AText: string; begin Canvas.Font := Font; Canvas.Brush.Color := Color; Selected := Focused and (not (csPaintCopy in ControlState)) and (not PopupVisible); if Selected then begin Canvas.Font.Color := clHighlightText; Canvas.Brush.Color := clHighlight; end else if not Enabled {and NewStyleControls }then begin Canvas.Font.Color := clInactiveCaption; end; SetRect(R, 0, 0, ClientWidth, ClientHeight); if Flat then begin Canvas.Frame3d(R, 3, bvLowered); end else begin RxFrame3D(Canvas, R, clWindowFrame, clBtnHighlight, 1); RxFrame3D(Canvas, R, clBtnShadow, clBtnFace, 1); end; if ClientWidth > 6 then begin SetRect(R1, 3, 3, ClientWidth - 3, ClientHeight - 3); Canvas.FillRect(R1); R.Right:=R.Right - GetButtonWidth; if PopupVisible and (Caption<>'') then begin AText:=Caption; Canvas.TextRect(R, TextMargin, Max(0, (HeightOf(R) - Canvas.TextHeight('Wg')) div 2), AText); end else if FDisplayAll then PaintDisplayValues(Canvas, R, TextMargin) else begin if Assigned(FDataField) and FDataField.IsNull then begin SetRect(R1, 6, 6, ClientWidth - 6 - GetButtonWidth, ClientHeight - 6); Canvas.Brush.Color:=FEmptyItemColor; Canvas.FillRect(R1); AText:=FEmptyValue end else if FValuesList.Count>0 then AText:=FValuesList[FLookupDisplayIndex] else AText:=''; Canvas.TextRect(R, TextMargin, Max(0, (HeightOf(R) - Canvas.TextHeight('Wg')) div 2), AText); end end; end; procedure TRxCustomDBLookupCombo.LookupDataSetChanged(Sender: TObject); begin if PopupVisible then begin FSuccesfullyFind := true; UpdateFieldValues; Invalidate; end; end; procedure TRxCustomDBLookupCombo.ListLinkActiveChanged(Sender: TObject); var DataSet: TDataSet; begin FListActive := False; FKeyField := nil; FDisplayField := nil; DataSet:=nil; if FLookupDataLink.Active and (FLookupField <> '') and (FFieldList.Count>FLookupDisplayIndex) and (FLookupDisplayIndex>=0) then begin CheckNotCircular; DataSet := FLookupDataLink.DataSet; FKeyField := DataSet.FieldByName(FLookupField); FListActive := True; FDisplayField := FLookupDataLink.DataSet.FieldByName(FFieldList[FLookupDisplayIndex]); end; FLocateObject.DataSet := DataSet; if not (csDestroying in ComponentState) then begin if FListActive and Assigned(FDataField) then UpdateKeyValue // else KeyValueChanged; end; end; procedure TRxCustomDBLookupCombo.SetValue(const Value: string); begin if (Value <> FValue) then begin if FListActive and not ReadOnly and (FDataLink.DataSource <> nil) and FDataLink.Edit then FDataField.AsString := Value else SetValueKey(Value); if Assigned(FOnSelect) then FOnSelect(Self); end; end; function TRxCustomDBLookupCombo.GetKeyValue: Variant; begin if Value = FEmptyValue then Result := null else Result := Value; end; procedure TRxCustomDBLookupCombo.SetKeyValue(const Value: Variant); begin Self.Value := Value; end; constructor TRxCustomDBLookupCombo.Create(AOwner: TComponent); var ArrowBmp:TBitmap; begin inherited Create(AOwner); Width := 100; AutoSize:=true; FUnfindedValue:=rxufNone; FFieldList := TStringList.Create; FValuesList:= TStringList.Create; FLocateObject:=CreateLocate(nil); FPopUpFormOptions:=TPopUpFormOptions.Create(Self); //Lookup FLookupDataLink:=TLookupSourceLink.Create; // FLookupDataLink.FDataControl:=Self; FLookupDataLink.FOnActiveChanged:=@ListLinkActiveChanged; FLookupDataLink.FOnLayoutChanged:=@ListLinkActiveChanged; FLookupDataLink.FOnDataSetChanged:=@LookupDataSetChanged; //Data FDataLink:=TDataSourceLink.Create; FDataLink.FDataControl:=Self; FButton := TSpeedButton.Create(Self); FButton.Width := Self.Height; FButton.Height := Self.Height; FButton.FreeNotification(Self); FButton.Parent:=Self; CheckButtonVisible; FButton.OnClick := @DoButtonClick; FButton.Cursor := crArrow; FButton.ControlStyle := FButton.ControlStyle + [csNoDesignSelectable]; FButton.Align:=alRight; FButton.BorderSpacing.Around:=2; //FButton.TabStop:=true; ControlStyle := ControlStyle - [csSetCaption]; FDirectInput := True; ParentColor:=false; // Color:=clWindow; FEmptyItemColor:=clWindow; // Glyph:=CreateArrowBitmap; ArrowBmp:=CreateArrowBitmap; Glyph:=ArrowBmp; FreeAndNil(ArrowBmp); //free bitmap as TSpeedButton setter takes a copy of bitmap ButtonWidth:=15; TabStop:=true; end; destructor TRxCustomDBLookupCombo.Destroy; begin FreeAndNil(FLocateObject); FreeAndNil(FDataLink); FreeAndNil(FLookupDataLink); FreeAndNil(FButton); FFieldList.Clear; FreeAndNil(FFieldList); FreeAndNil(FValuesList); FreeAndNil(FPopUpFormOptions); inherited Destroy; end; { TDataSourceLink } procedure TDataSourceLink.ActiveChanged; begin if FDataControl <> nil then FDataControl.DataLinkActiveChanged; end; procedure TDataSourceLink.LayoutChanged; begin inherited LayoutChanged; end; procedure TDataSourceLink.FocusControl(Field: TFieldRef); begin if Assigned(Field) and (FDataControl.FDataField = Field^) then if FDataControl.CanFocus then begin Field^ := nil; FDataControl.SetFocus; end; end; procedure TDataSourceLink.RecordChanged(Field: TField); begin if FDataControl <> nil then FDataControl.DataLinkRecordChanged(Field); end; procedure TDataSourceLink.UpdateData; begin if FDataControl <> nil then FDataControl.UpdateData; end; { TLookupSourceLink } procedure TLookupSourceLink.ActiveChanged; begin { if FDataControl <> nil then FDataControl.ListLinkActiveChanged;} if Assigned(FOnActiveChanged) then FOnActiveChanged(DataSet); end; procedure TLookupSourceLink.LayoutChanged; begin { if FDataControl <> nil then FDataControl.ListLinkActiveChanged;} if Assigned(FOnLayoutChanged) then FOnLayoutChanged(DataSet); end; procedure TLookupSourceLink.DataSetChanged; begin { if FDataControl <> nil then FDataControl.LookupDataSetChanged;} if Assigned(FOnDataSetChanged) then FOnDataSetChanged(DataSet); end; { TRxDBLookupCombo } procedure TRxDBLookupCombo.OnInternalClosePopup(AResult: boolean); begin inherited OnInternalClosePopup(AResult); // SetFocus; { if (Owner is TWinControl) then TWinControl(Owner).Repaint else Parent.Repaint;} end; end.
//Exercicio 13: Dado um número inteiro positivo que representa uma quantidade de tempo em segundos, escreva um algoritmo //que converta esse número em horas, minutos e segundos. Por exemplo: supondo que o número lido seja 33560, seu algoritmo //deverá exibir: 33560 segundos = 9 horas 19 minutos e 20 segundos. { Solução em Portugol Algoritmo Exercicio13; Var numero,horas,minutos,segundos: inteiro; Inicio exiba("Programa que converte segundos em horas-minutos-segundos."); exiba("Digite um numero de segundos: "); leia(numero); horas <- numero/3600; --> estou usando como divisão inteira, no pascal isso não é possível. minutos <- (numero - 3600 * horas)/60; segundos <- (numero - 3600 * horas) - (minutos * 60); exiba(numero," segundos equivalem a ", horas," horas, ",minutos," minutos e ",segundos," segundos."); Fim. } // Solução em Pascal Program Exercicio13; uses crt; var numero,horas,minutos,segundos: integer; begin clrscr; writeln('Programa que converte segundos em horas-minutos-segundos.'); writeln('Digite um numero de segundos: '); readln(numero); horas := numero div 3600; minutos := (numero mod 3600) div 60; segundos := (numero mod 3600) mod 60; writeln(numero,' segundos equivalem a ', horas,' horas, ',minutos,' minutos e ',segundos,' segundos.'); repeat until keypressed; end.
{ Module of routines to create opcodes. } module sst_r_syo_opc; define sst_r_syo_opc_assign; %include 'sst_r_syo.ins.pas'; { ********************************************************* } procedure sst_r_syo_opc_assign ( {make opcode to assign symbol to variable} in sym1: sst_symbol_t; {variable to assign value to} in sym2: sst_symbol_t); {symbol with value to assign} const max_msg_parms = 1; {max parameters we can pass to a message} var var_p: sst_var_p_t; {scratch pointer to var descriptor} exp_p: sst_exp_p_t; {scratch pointer to exp descriptor} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin sst_mem_alloc_scope (sizeof(var_p^), var_p); {create variable and expression desc} sst_mem_alloc_scope (sizeof(exp_p^), exp_p); sst_opcode_new; {create assignment opcode} sst_opc_p^.opcode := sst_opc_assign_k; sst_opc_p^.assign_var_p := var_p; sst_opc_p^.assign_exp_p := exp_p; { * Fill in variable reference descriptor for the assignment variable. } var_p^.mod1.next_p := nil; var_p^.mod1.modtyp := sst_var_modtyp_top_k; var_p^.mod1.top_str_h := sst_opc_p^.str_h; var_p^.mod1.top_sym_p := addr(sym1); var_p^.dtype_p := sym1.var_dtype_p; if sym1.var_arg_p = nil then begin {variable is not dummy argument} var_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k]; end else begin var_p^.rwflag := sym1.var_arg_p^.rwflag_int; end ; var_p^.vtype := sst_vtype_var_k; { * Fill in expression descriptor assignment value. } exp_p^.term1.next_p := nil; {init static parts of term desciptor} exp_p^.term1.op2 := sst_op2_none_k; exp_p^.term1.op1 := sst_op1_none_k; exp_p^.term1.str_h := sst_opc_p^.str_h; exp_p^.term1.dtype_hard := true; exp_p^.term1.val_eval := false; exp_p^.term1.val_fnd := false; exp_p^.term1.rwflag := [sst_rwflag_read_k]; case sym2.symtype of sst_symtype_const_k: begin {symbol 2 is a mnemonic constant} exp_p^.term1.ttype := sst_term_const_k; exp_p^.term1.dtype_p := sym2.const_exp_p^.dtype_p; exp_p^.term1.dtype_hard := sym2.const_exp_p^.dtype_hard; exp_p^.term1.val_eval := true; exp_p^.term1.val_fnd := true; exp_p^.term1.val := sym2.const_exp_p^.val; end; sst_symtype_enum_k: begin {symbol 2 is enumerated constant} exp_p^.term1.ttype := sst_term_const_k; exp_p^.term1.dtype_p := sym2.enum_dtype_p; exp_p^.term1.dtype_hard := true; exp_p^.term1.val_eval := true; exp_p^.term1.val_fnd := true; exp_p^.term1.val.dtype := sst_dtype_enum_k; exp_p^.term1.val.enum_p := addr(sym2); end; otherwise sys_msg_parm_int (msg_parm[1], ord(sym2.symtype)); sys_message_bomb ('sst', 'symbol_type_unknown', msg_parm, 1); end; exp_p^.str_h := sst_opc_p^.str_h; {fill in rest of expression descriptor} exp_p^.dtype_p := nil; exp_p^.dtype_hard := true; exp_p^.val_eval := false; exp_p^.val_fnd := false; exp_p^.rwflag := exp_p^.term1.rwflag; sst_exp_eval (exp_p^, false); {fully evaluate the expression} end;
unit fastevents; { FastEvents is a high-performance event queue manager for SDL. Copyright (C) 2002 Bob Pendleton This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you do not wish to comply with the terms of the LGPL please contact the author as other terms are available for a fee. Bob Pendleton Bob@Pendleton.com } { Translated to Object Pascal by Mason Wheeler. masonwheeler@yahoo.com The original C library can be found at http://www.gameprogrammer.com/fastevents/fastevents.zip } interface uses sdl; function FE_Init: integer; // Initialize FE procedure FE_Quit; // shutdown FE procedure FE_PumpEvents; // replacement for SDL_PumpEvents function FE_PollEvent(event: PSDL_Event): integer; // replacement for SDL_PollEvent procedure FE_WaitEvent(event: PSDL_Event); // replacement for SDL_WaitEvent procedure FE_PushEvent(event: PSDL_Event); // replacement for SDL_PushEvent function FE_GetError: string; // returns the last FastEvents error implementation //---------------------------------------- // // error handling code // var errorString: string = ''; procedure setError(err: string); inline; begin errorString := err; end; function FE_GetError: string; begin result := errorString; end; //---------------------------------------- // // Threads, mutexs, thread utils, and // thread safe wrappers // var eventLock: PSDL_Mutex = nil; eventWait: PSDL_Cond = nil; eventTimer: PSDL_TimerID = nil; //---------------------------------------- // // Timer callback // function timerCallback(interval: Uint32; param: pointer): Uint32; {$IFNDEF __GPC__} cdecl; {$ENDIF} begin SDL_CondBroadcast(eventWait); result := interval; end; //---------------------------------------- // Initialization and // cleanup routines // function FE_Init: integer; begin result := -1; if (SDL_INIT_TIMER and SDL_WasInit(SDL_INIT_TIMER)) = 0 then SDL_InitSubSystem(SDL_INIT_TIMER); eventLock := SDL_CreateMutex(); if eventLock = nil then begin setError('FE: can''t create a mutex'); Exit; end; eventWait := SDL_CreateCond(); if eventWait = nil then begin setError('FE: can''t create a condition variable'); Exit; end; eventTimer := SDL_AddTimer(10, timerCallback, nil); if eventTimer = nil then begin setError('FE: can''t add a timer'); Exit; end; result := 0; end; procedure FE_Quit; begin SDL_DestroyMutex(eventLock); eventLock := nil; SDL_DestroyCond(eventWait); eventWait := nil; SDL_RemoveTimer(eventTimer); eventTimer := nil; end; //---------------------------------------- // // replacement for SDL_PushEvent(); // // This was originally an int function; I changed it to a // procedure because it only had one possible return value: 1. // This seemed a bit pointless. -- Mason Wheeler // procedure FE_PushEvent(event: PSDL_Event); begin SDL_LockMutex(eventLock); while SDL_PushEvent(event) = -1 do SDL_CondWait(eventWait, eventLock); SDL_UnlockMutex(eventLock); SDL_CondSignal(eventWait); end; //---------------------------------------- // // replacement for SDL_PumpEvents(); // procedure FE_PumpEvents; begin SDL_LockMutex(eventLock); SDL_PumpEvents(); SDL_UnlockMutex(eventLock); end; //---------------------------------------- // // replacement for SDL_PollEvent(); // function FE_PollEvent(event: PSDL_Event): integer; var val: integer; begin SDL_LockMutex(eventLock); val := SDL_PollEvent(event); SDL_UnlockMutex(eventLock); if val > 0 then SDL_CondSignal(eventWait); result := val; end; //---------------------------------------- // // Replacement for SDL_WaitEvent(); // // This was originally an int function; I changed it to a // procedure because it only had one possible return value: 1. // This seemed a bit pointless. -- Mason Wheeler // procedure FE_WaitEvent(event: PSDL_Event); begin SDL_LockMutex(eventLock); while SDL_PollEvent(event) <= 0 do SDL_CondWait(eventWait, eventLock); SDL_UnlockMutex(eventLock); SDL_CondSignal(eventWait); end; end.
//============================================================================= // sgTileMap.pas //============================================================================= // // Responsible for loading and processing a "Mappy" data file exported using // the Lua script specifically written for SwinGame to create map files. // // Change History: // // Version 3.0: // - 2009-07-13: Clinton: Renamed Event to Tag - see types for more details // - 2009-07-10: Andrew : Added missing const modifier for struct parameters // - 2009-07-09: Clinton: Optimized IsPointInTile slightly (isometric) // Optimized GetTileFromPoint (isometric) // - 2009-07-08: Clinton: Code comments, TODO notes and some tweaks/optimization // - 2009-06-22: Clinton: Comment format, cleanup and new additions. // - 2009-06-17: Andrew : added meta tags, renamed from "mappy" to tilemap // // Version 2: // - 2008-12-17: Andrew : Moved all integers to LongInt // // Version 1.1.5: // - 2008-04-18: Andrew : Fix extensions to work with Delphi. // // Version 1.1: // - 2008-04-02: Stephen: Added MapWidth(), MapHeight(), BlockWidth(), // BlockHeight(), GapX(), GapY(), StaggerX(), StaggerY(), // LoadIsometricInformation(), LoadMapv2(), // : various bug fixes // - 2008-04-02: Andrew : Removed gap loading as mappy support has not been // updated on the web, and this version is unable to // read the old files. // - 2008-03-29: Stephen: MapData record now contains GapX, GapY, StaggerX, // StaggerY, Isometric // : LoadMapInformation, now loads the new isometric related data // : DrawMap now draws isometric tiles with their correct offsets // - 2008-01-30: Andrew : Added const to vector param, increased search for collision tests // - 2008-01-25: Andrew : Fixed compiler hints // - 2008-01-22: Andrew : Re-added CollidedWithMap to allow compatibility with 1.0 // - 2008-01-21: Stephen: CollidedWithMap replaced with 3 Routines, // - HasSpriteCollidedWithTile, // - MoveSpriteOutOfTile, // - WillCollideOnSide // - 2008-01-17: Aki + Andrew: Refactor // // Version 1.0: // - Various //============================================================================= ///@module TileMap ///@static unit sgTileMap; //============================================================================= interface //============================================================================= uses sgTypes; /// @lib /// @class Map /// @method Draw procedure DrawMap(m: Map); /// @lib /// @class Map /// @method HasSpriteCollidedWithTile function SpriteHasCollidedWithTile(m: Map; s: Sprite): Boolean; overload; /// @lib SpriteHasCollidedWithTileOutXY /// @class Map /// @overload HasSpriteCollidedWithTile HasSpriteCollidedWithTileOutXY function SpriteHasCollidedWithTile(m: Map; s: Sprite; out collidedX, collidedY: LongInt): Boolean; overload; /// @lib /// @class Map /// @method WillCollideOnSide function WillCollideOnSide(m: Map; s: Sprite): CollisionSide; /// @lib /// @class Map /// @method MoveSpriteOutOfTile procedure MoveSpriteOutOfTile(m: Map; s: Sprite; x, y: LongInt); /// @lib /// @class Map /// @method MapTagCount function MapTagCount(m: Map; tagType: MapTag): LongInt; /// @lib /// @class Map /// @method MapTagPositionX function MapTagPositionX(m: Map; tagType: MapTag; tagnumber: LongInt): LongInt; /// @lib /// @class Map /// @method MapTagPositionY function MapTagPositionY(m: Map; tagType: MapTag; tagnumber: LongInt): LongInt; /// @lib /// @class Sprite /// @self 2 /// @method CollisionWithMap function CollisionWithMap(m: Map; s: Sprite; const vec: Vector): CollisionSide; //TODO: reorder map/sprite - make the sprite first param. vec is what? /// @lib /// @class Map /// @getter Width function MapWidth(m: Map): LongInt; /// @lib /// @class Map /// @getter Height function MapHeight(m: Map): LongInt; /// @lib /// @class Map /// @getter BlockWidth function BlockWidth(m: Map): LongInt; /// @lib /// @class Map /// @getter BlockHeight function BlockHeight(m: Map): LongInt; // TODO: Do Gap/Stagger need to be public? Concept need to be documented? // GapX and GapY = The distance between each tile (rectangular), can be // different to the normal width and height of the block // StaggerX and StaggerY = The isometric Offset /// The x distance between each tile. See StaggerX for the isometric offset. /// @lib /// @class Map /// @getter GapX function GapX(m: Map): LongInt; /// The y distance between each tile. See StaggerY for the isometric offset. /// @lib /// @class Map /// @getter GapY function GapY(m: Map): LongInt; /// The isometric x offset value. /// @lib /// @class Map /// @getter StaggerX function StaggerX(m: Map): LongInt; /// The isometric y offset value. /// @lib /// @class Map /// @getter StaggerY function StaggerY(m: Map): LongInt; /// Return the tile that is under a given Point2D. Isometric maps are taken /// into consideration. A MapTile knows its x,y index in the map structure, /// the top-right corner of the tile and the 4 points that construct the tile. /// For Isometric tiles, the 4 points will form a diamond. /// @lib /// @class Map /// @self 2 /// @method GetTileFromPoint function GetTileFromPoint(const point: Point2D; m: Map): MapTile; //TODO: Why is the map the second parameter? Inconsistent... /// Returns the MapTag of the tile at the given (x,y) map index. /// Note that if the tile does not have an tag, will return MapTag(-1) /// @lib /// @class Map /// @method GetTagAtTile function GetTagAtTile(m: Map; xIndex, yIndex: LongInt): MapTag; //============================================================================= implementation //============================================================================= uses SysUtils, Classes, //System, sgGraphics, sgCamera, sgCore, sgPhysics, sgGeometry, sgResources, sgSprites, sgShared; //Swingame procedure DrawMap(m: Map); var l, y ,x: LongInt; XStart, YStart, XEnd, YEnd: LongInt; f: LongInt; begin if m = nil then begin RaiseException('No Map supplied (nil)'); exit; end; //WriteLn('GX, GY: ', ToWorldX(0), ',' , ToWorldY(0)); //WriteLn('bw, bh: ', m^.MapInfo.BlockWidth, ', ', m^.MapInfo.BlockHeight); //TODO: Optimize - the x/yStart (no need to keep re-calculating) //Screen Drawing Starting Point XStart := round((ToWorldX(0) / m^.MapInfo.BlockWidth) - (m^.MapInfo.BlockWidth * 1)); YStart := round((ToWorldY(0) / m^.MapInfo.BlockHeight) - (m^.MapInfo.BlockHeight * 1)); //Screen Drawing Ending point XEnd := round(XStart + (sgCore.ScreenWidth() / m^.MapInfo.BlockWidth) + (m^.MapInfo.BlockWidth * 1)); YEnd := round(YStart + (sgCore.ScreenHeight() / m^.MapInfo.BlockHeight) + (m^.MapInfo.BlockHeight * 1)); //WriteLn('DrawMap ', XStart, ',', YStart, ' - ', XEnd, ',', YEnd); if YStart < 0 then YStart := 0; if YStart >= m^.MapInfo.MapHeight then exit; if YEnd < 0 then exit; if YEnd >= m^.MapInfo.MapHeight then YEnd := m^.MapInfo.MapHeight - 1; if XStart < 0 then XStart := 0; if XStart >= m^.MapInfo.MapWidth then exit; if XEnd < 0 then exit; if XEnd >= m^.MapInfo.MapWidth then XEnd := m^.MapInfo.MapWidth - 1; for y := YStart to YEnd do begin //TODO: Optimize - no need to re-test "isometric" - separate and do it ONCE! //Isometric Offset for Y if m^.MapInfo.Isometric then m^.Tiles^.position.y := y * m^.MapInfo.StaggerY else m^.Tiles^.position.y := y * m^.MapInfo.BlockHeight; for x := XStart to XEnd do begin //Isometric Offset for X if (m^.MapInfo.Isometric = true) then begin m^.Tiles^.position.x := x * m^.MapInfo.GapX; if ((y MOD 2) = 1) then m^.Tiles^.position.x := m^.Tiles^.position.x + m^.MapInfo.StaggerX; end else m^.Tiles^.position.x := x * m^.MapInfo.BlockWidth; for l := 0 to m^.MapInfo.NumberOfLayers - m^.MapInfo.CollisionLayer - m^.MapInfo.TagLayer - 1 do begin if (m^.LayerInfo[l].Animation[y][x] = 0) and (m^.LayerInfo[l].Value[y][x] > 0) then begin m^.Tiles^.currentCell := m^.LayerInfo[l].Value[y][x] - 1; //DrawSprite(m^.Tiles, CameraX, CameraY, sgCore.ScreenWidth(), sgCore.ScreenHeight()); DrawSprite(m^.Tiles); end else if (m^.LayerInfo[l].Animation[y][x] = 1) then begin f := round(m^.Frame/10) mod (m^.AnimationInfo[m^.LayerInfo[l].Value[y][x]].NumberOfFrames); m^.Tiles^.currentCell := m^.AnimationInfo[m^.LayerInfo[l].Value[y][x]].Frame[f] - 1; DrawSprite(m^.Tiles); end; end; end; end; m^.Frame := (m^.Frame + 1) mod 1000; end; //Gets the number of MapTag of the specified type function MapTagCount(m: Map; tagType: MapTag): LongInt; begin if m = nil then begin RaiseException('No Map supplied (nil)'); exit; end; if (tagType < MapTag1) or (tagType > High(MapTag)) then begin RaiseException('TagType is out of range'); exit; end; result := Length(m^.TagInfo[LongInt(tagType)]); //TODO: WHY do we keep converting tagType to LongInt - just store as LongINT!!! {count := 0; for y := 0 to m^.MapInfo.MapWidth - 1 do begin for x := 0 to m^.MapInfo.MapHeight - 1 do begin if tag = m^.TagInfo.Tag[y][x] then count := count + 1; end; end; result := count;} end; // Gets the Top Left X Coordinate of the MapTag function MapTagPositionX(m: Map; tagType: MapTag; tagnumber: LongInt): LongInt; begin if (tagnumber < 0) or (tagnumber > MapTagCount(m, tagType) - 1) then begin RaiseException('Tag number is out of range'); exit; end; if (m^.MapInfo.Isometric = true) then begin result := m^.TagInfo[LongInt(tagType)][tagnumber].x * m^.MapInfo.GapX; if ((m^.TagInfo[LongInt(tagType)][tagnumber].y MOD 2) = 1) then result := result + m^.MapInfo.StaggerX; end else result := m^.TagInfo[LongInt(tagType)][tagnumber].x * m^.MapInfo.BlockWidth; end; // Gets the Top Left Y Coordinate of the MapTag function MapTagPositionY(m: Map; tagType: MapTag; tagnumber: LongInt): LongInt; begin if (tagnumber < 0) or (tagnumber > MapTagCount(m, tagType) - 1) then begin RaiseException('Tag number is out of range'); exit; end; if (m^.MapInfo.Isometric = true) then begin result := m^.TagInfo[LongInt(tagType)][tagnumber].y * m^.MapInfo.StaggerY; end else begin result := m^.TagInfo[LongInt(tagType)][tagnumber].y * m^.MapInfo.BlockHeight; end; end; function BruteForceDetection(m: Map; s: Sprite): Boolean; const SEARCH_RANGE = 0; var XStart, XEnd, YStart, YEnd: LongInt; y, x, yCache: LongInt; begin result := false; with m^.MapInfo do begin XStart := round((s^.position.x / BlockWidth) - ((s^.width / BlockWidth) - SEARCH_RANGE)); XEnd := round((s^.position.x / BlockWidth) + ((s^.width / BlockWidth) + SEARCH_RANGE)); YStart := round((s^.position.y / BlockHeight) - ((s^.height / BlockHeight) - SEARCH_RANGE)); YEnd := round((s^.position.y / BlockHeight) + ((s^.height / BlockHeight) + SEARCH_RANGE)); if YStart < 0 then YStart := 0; if YStart >= MapHeight then exit; if YEnd < 0 then exit; if YEnd >= MapHeight then YEnd := MapHeight - 1; if XStart < 0 then XStart := 0; if XStart >= MapWidth then exit; if XEnd < 0 then exit; if XEnd >= MapWidth then XEnd := MapWidth - 1; for y := YStart to YEnd do begin yCache := y * BlockHeight; for x := XStart to XEnd do if m^.CollisionInfo.Collidable[y][x] then if SpriteRectCollision(s, x * BlockWidth, yCache, BlockWidth, BlockHeight) then begin result := true; exit; end; end; end; // with end; function BruteForceDetectionComponent(m: Map; var s: Sprite; xOffset, yOffset: LongInt): Boolean; begin s^.position.x := s^.position.x + xOffset; s^.position.y := s^.position.y + yOffset; result := BruteForceDetection(m, s); { if BruteForceDetection(m, s) then begin result := true; end else result := false;} s^.position.x := s^.position.x - xOffset; s^.position.y := s^.position.y - yOffset; end; procedure MoveOut(s: Sprite; velocity: Vector; x, y, width, height: LongInt); var kickVector: Vector; sprRect, tgtRect: Rectangle; begin sprRect := RectangleFrom(s); tgtRect := RectangleFrom(x, y, width, height); kickVector := VectorOutOfRectFromRect(sprRect, tgtRect, velocity); MoveSprite(s, kickVector); end; function GetPotentialCollisions(m: Map; s: Sprite): Rectangle; function GetBoundingRectangle(): Rectangle; var startPoint, endPoint: Rectangle; startX, startY, endX, endY: LongInt; begin with m^.MapInfo do begin startPoint := RectangleFrom( round( ((s^.position.x - s^.velocity.x) / BlockWidth) - 1) * BlockWidth, round( ((s^.position.y - s^.velocity.y) / BlockHeight) - 1) * BlockHeight, (round( s^.width / BlockWidth) + 2) * BlockWidth, (round( s^.height / BlockHeight) + 2) * BlockHeight ); endPoint := RectangleFrom( round(((s^.position.x + s^.width) / BlockWidth) - 1) * BlockWidth, round(((s^.position.y + s^.height) / BlockHeight) - 1) * BlockHeight, (round(s^.width / BlockWidth) + 2) * BlockWidth, (round(s^.height / BlockHeight) + 2) * BlockHeight ); end; // with //Encompassing Rectangle if startPoint.x < endPoint.x then begin startX := round(startPoint.x); endX := round(endPoint.x + endPoint.width); end else begin startX := round(endPoint.x); endX := round(startPoint.x + startPoint.width); end; if startPoint.y < endPoint.y then begin startY := round(startPoint.y); endY := round(endPoint.y + endPoint.height); end else begin startY := round(endPoint.y); endY := round(startPoint.y + startPoint.height); end; result := RectangleFrom(startX, startY, endX - startX, endY - startY); //Debug Info //DrawRectangle(ColorYellow, startPoint.x, startPoint.y, startPoint.width, startPoint.height); //DrawRectangle(ColorWhite, endPoint.x, endPoint.y, endPoint.width, endPoint.height); //DrawRectangle(ColorGreen, result.x, result.y, result.width, result.height); end; begin //Respresents the Rectangle that encompases both the Current and Previous positions of the Sprite. //Gets the Bounding Collision Rectangle result := GetBoundingRectangle(); //TODO: Why is this an inner function with it does ALL the work?? end; function WillCollideOnSide(m: Map; s: Sprite): CollisionSide; type Collisions = record Top, Bottom, Left, Right: Boolean; end; var col: Collisions; begin col.Right := (s^.velocity.x > 0) and BruteForceDetectionComponent(m, s, s^.width, 0); col.Left := (s^.velocity.x < 0) and BruteForceDetectionComponent(m, s, -s^.width, 0); col.Top := (s^.velocity.y < 0) and BruteForceDetectionComponent(m, s, 0, -s^.height); col.Bottom := (s^.velocity.y > 0) and BruteForceDetectionComponent(m, s, 0, s^.height); if col.Right and col.Bottom then result := BottomRight else if col.Left and col.Bottom then result := BottomLeft else if col.Right and col.Top then result := TopRight else if col.Left and col.Top then result := TopLeft else if col.Left then result := Left else if col.Right then result := Right else if col.Top then result := Top else if col.Bottom then result := Bottom else result := None; end; procedure MoveSpriteOutOfTile(m: Map; s: Sprite; x, y: LongInt); begin //TODO: Avoid these exception tests (at least the first 2) - do them earlier during loading if m = nil then begin RaiseException('No Map supplied (nil)'); exit; end; if s = nil then begin RaiseException('No Sprite suppled (nil)'); exit; end; if (x < 0 ) or (x >= m^.mapInfo.mapWidth) then begin RaiseException('x is outside the bounds of the map'); exit; end; if (y < 0 ) or (y >= m^.mapInfo.mapWidth) then begin RaiseException('y is outside the bounds of the map'); exit; end; with m^.MapInfo do MoveOut(s, s^.velocity, x * BlockWidth, y * BlockHeight, BlockWidth, BlockHeight); end; function SpriteHasCollidedWithTile(m: Map; s: Sprite): Boolean; overload; var x, y: LongInt; begin result := SpriteHasCollidedWithTile(m, s, x, y); end; function SpriteHasCollidedWithTile(m: Map; s: Sprite; out collidedX, collidedY: LongInt): Boolean; overload; var y, x, yCache, dy, dx, i, j, initY, initX: LongInt; xStart, yStart, xEnd, yEnd: LongInt; rectSearch: Rectangle; side: CollisionSide; begin result := false; if m = nil then begin RaiseException('No Map supplied (nil)'); exit; end; if s = nil then begin RaiseException('No Sprite suppled (nil)'); exit; end; rectSearch := GetPotentialCollisions(m, s); side := GetSideForCollisionTest(s^.velocity); with m^.MapInfo do begin yStart := round(rectSearch.y / BlockHeight); yEnd := round((rectSearch.y + rectSearch.height) / BlockHeight); xStart := round(rectSearch.x / BlockWidth); xEnd := round((rectSearch.x + rectSearch.width) / BlockWidth); if yStart < 0 then yStart := 0; if yStart >= MapHeight then exit; if yEnd < 0 then exit; if yEnd >= MapHeight then yEnd := MapHeight - 1; if xStart < 0 then xStart := 0; if xStart >= MapWidth then exit; if xEnd < 0 then exit; if xEnd >= MapWidth then xEnd := MapWidth - 1; end; //with // result := false; case side of TopLeft: begin dy := 1; dx := 1; initY := yStart; initX := xStart; end; TopRight: begin dy := 1; dx := -1; initY := yStart; initX := xEnd; end; BottomLeft: begin dy := -1; dx := 1; initY := yEnd; initX := xStart; end; BottomRight: begin dy := -1; dx := -1; initY := yEnd; initX := xEnd; end; Top: begin dy := 1; dx := 1; initY := yStart; initX := xStart; end; Bottom: begin dy := -1; dx := 1; initY := yEnd; initX := xStart; end; Left: begin dy := 1; dx := 1; initY := yStart; initX := xStart; end; Right: begin dy := 1; dx := -1; initY := yStart; initX := xEnd; end; else begin dy := 1; dx := 1; initY := yStart; initX := xStart; end; end; with m^.MapInfo do begin for i := yStart to yEnd do begin y := initY + (i - yStart) * dy; yCache := y * BlockHeight; for j := xStart to xEnd do begin x := initX + (j - xStart) * dx; //TODO: Optimize - j start at 0 instead... if m^.CollisionInfo.Collidable[y][x] = true then begin if SpriteRectCollision(s, x * BlockWidth, yCache, BlockWidth, BlockHeight) then begin result := true; collidedX := x; collidedY := y; exit; end; end; end; end; end; // with collidedX := -1; collidedY := -1; end; function CollisionWithMap(m: Map; s: Sprite; const vec: Vector): CollisionSide; var x, y: LongInt; temp: Vector; begin result := None; temp := s^.velocity; s^.velocity := vec; if sgTileMap.SpriteHasCollidedWithTile(m, s, x, y) then begin MoveSpriteOutOfTile(m, s, x, y); result := WillCollideOnSide(m, s); end; s^.velocity := temp; end; function MapWidth(m: Map): LongInt; begin result := m^.MapInfo.MapWidth; end; function MapHeight(m: Map): LongInt; begin result := m^.MapInfo.MapHeight; end; function BlockWidth(m: Map): LongInt; begin result := m^.MapInfo.BlockWidth; end; function BlockHeight(m: Map): LongInt; begin result := m^.MapInfo.BlockHeight; end; function GapX(m: Map): LongInt; begin result := m^.MapInfo.GapX; end; function GapY(m: Map): LongInt; begin result := m^.MapInfo.GapY; end; function StaggerX(m: Map): LongInt; begin result := m^.MapInfo.StaggerX; end; function StaggerY(m: Map): LongInt; begin result := m^.MapInfo.StaggerY; end; //Determines whether the specified point is within the tile provided function IsPointInTile(point: Point2D; x, y: LongInt; m: Map): Boolean; var tri: Triangle; begin with m^.MapInfo do begin if Isometric then begin // Create Triangle tri := TriangleFrom(x, y + BlockHeight / 2, x + BlockWidth / 2, y, x + BlockWidth / 2, y + BlockHeight); // Test first triangle and leave early? if PointInTriangle(point, tri) then begin result := True; exit; end // Need to test the second triangle too... else begin tri := TriangleFrom(x + BlockWidth, y + BlockHeight / 2, x + BlockWidth / 2, y, x + BlockWidth / 2, y + BlockHeight); // store result and done result := PointInTriangle(point, tri); end; end else result := PointInRect(point, x, y, BlockWidth, BlockHeight); end; end; function GetTileFromPoint(const point: Point2D; m: Map): MapTile; var x, y, tx, ty: LongInt; begin //Returns (-1,-1) if no tile has this point result.xIndex := -1; result.yIndex := -1; result.topCorner := PointAt(0,0); result.PointA := PointAt(0,0); result.PointB := PointAt(0,0); result.PointC := PointAt(0,0); result.PointD := PointAt(0,0); with m^.MapInfo do begin if Isometric then for y := 0 to MapHeight - 1 do begin // tile y pos? ty := y * StaggerY; for x := 0 to MapWidth - 1 do begin // tile x pos? tx := x * GapX; if ((y MOD 2) = 1) then tx := tx + StaggerX; // test and leave? if IsPointInTile(point, tx, ty, m) then begin result.xIndex := x; result.yIndex := y; result.topCorner := PointAt(tx,ty); result.PointA := PointAt(tx, ty + BlockHeight / 2); result.PointB := PointAt(tx + BlockWidth / 2, ty); result.PointC := PointAt(tx + BlockWidth / 2, ty + BlockHeight); result.PointD := PointAt(tx + BlockWidth, ty + BlockHeight / 2); exit; end; end; end else // Simple square-map (not isometric diamonds) for y := 0 to MapHeight - 1 do begin ty := y * BlockHeight; for x := 0 to MapWidth - 1 do begin tx := x * BlockWidth; if IsPointInTile(point, tx, ty, m) then begin result.xIndex := x; result.yIndex := y; result.topCorner := PointAt(tx,ty); //TODO: Optimize - recalc of PointsA/B/C/D - store and keep. result.PointA := PointAt(tx, ty); result.PointB := PointAt(tx + BlockWidth, ty); result.PointC := PointAt(tx, ty + BlockHeight); result.PointD := PointAt(tx + BlockWidth, ty + BlockHeight); exit; end; end; end; { // Old code - shorter, but takes longer for y := 0 to MapHeight - 1 do begin //TODO: Optimize - to isometric test ONCE not multiple times... //Isometric Offset for Y if Isometric then ty := y * StaggerY else ty := y * BlockHeight; for x := 0 to MapWidth - 1 do begin //Isometric Offset for X if Isometric then begin tx := x * GapX; if ((y MOD 2) = 1) then tx := tx + StaggerX; end else tx := x * BlockWidth; if IsPointInTile(point, tx, ty, m) then begin result.xIndex := x; result.yIndex := y; result.topCorner := PointAt(tx,ty); if Isometric then begin result.PointA := PointAt(tx, ty + BlockHeight / 2); result.PointB := PointAt(tx + BlockWidth / 2, ty); result.PointC := PointAt(tx + BlockWidth / 2, ty + BlockHeight); result.PointD := PointAt(tx + BlockWidth, ty + BlockHeight / 2); exit; end else begin result.PointA := PointAt(tx, ty); result.PointB := PointAt(tx + BlockWidth, ty); result.PointC := PointAt(tx, ty + BlockHeight); result.PointD := PointAt(tx + BlockWidth, ty + BlockHeight); exit; // ARGH! end; end; end; end; } end; // with end; function GetTagAtTile(m: Map; xIndex, yIndex: LongInt): MapTag; var i, j: LongInt; begin for i := LongInt(Low(MapTag)) to LongInt(High(MapTag)) do if (Length(m^.TagInfo[i]) > 0) then for j := 0 to High(m^.TagInfo[i]) do if (m^.TagInfo[i][j].x = xIndex) and (m^.TagInfo[i][j].y = yIndex) then begin result := MapTag(i); exit; end; // default result result := MapTag(-1); end; //============================================================================= initialization begin InitialiseSwinGame(); end; end.
unit MFichas.Model.Configuracao.Metodos.Buscar.Model; interface uses System.SysUtils, System.Generics.Collections, MFichas.Model.Entidade.CONFIGURACOES, MFichas.Model.Configuracao.Interfaces; type TModelConfiguracaoMetodosBuscarModel = class(TInterfacedObject, iModelConfiguracaoMetodosBuscarModel) private [weak] FListaConfiguracao: TObjectList<TCONFIGURACOES>; FParent: iModelConfiguracao; constructor Create(AParent: iModelConfiguracao); public destructor Destroy; override; class function New(AParent: iModelConfiguracao): iModelConfiguracaoMetodosBuscarModel; function Impressora: String; function &End : iModelConfiguracaoMetodos; end; implementation { TModelConfiguracaoMetodosBuscarModel } function TModelConfiguracaoMetodosBuscarModel.&End: iModelConfiguracaoMetodos; begin Result := FParent.Metodos; end; constructor TModelConfiguracaoMetodosBuscarModel.Create(AParent: iModelConfiguracao); begin FParent := AParent; end; destructor TModelConfiguracaoMetodosBuscarModel.Destroy; begin {$IFDEF MSWINDOWS} if Assigned(FListaConfiguracao) then FreeAndNil(FListaConfiguracao); {$ELSE} if Assigned(FListaConfiguracao) then begin FListaConfiguracao.Free; FListaConfiguracao.DisposeOf; end; {$ENDIF} inherited; end; class function TModelConfiguracaoMetodosBuscarModel.New(AParent: iModelConfiguracao): iModelConfiguracaoMetodosBuscarModel; begin Result := Self.Create(AParent); end; function TModelConfiguracaoMetodosBuscarModel.Impressora: String; begin FListaConfiguracao := FParent.DAO.Find; Result := FListaConfiguracao.Items[0].IMPRESSORA; end; end.
unit GX_PeInfoPrint; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GX_BaseForm; type TPeInfoTabs = (pitMsDos, pitPeHeader, pitPeOptHeader, pitImports, pitExports, pitVersionInfo, pitPackageInfo); TPeInfoTabSet = set of TPeInfoTabs; type Tf_PeInfoPrint = class(TfmBaseForm) chk_MsDosHeader: TCheckBox; chk_PeHeader: TCheckBox; chk_PeOptional: TCheckBox; chk_Exports: TCheckBox; chk_Imports: TCheckBox; chk_VersionInfo: TCheckBox; chk_PackageInfo: TCheckBox; b_CheckAll: TButton; b_CheckNone: TButton; b_Print: TButton; b_Cancel: TButton; procedure b_CheckAllClick(Sender: TObject); procedure b_CheckNoneClick(Sender: TObject); private procedure SetData(_Tabs: TPeInfoTabSet); procedure GetData(out _Tabs: TPeInfoTabSet); public class function Execute(_Owner: TComponent; var _Tabs: TPeInfoTabSet): Boolean; end; implementation uses GX_dzVclUtils; {$R *.dfm} { Tf_PeInfoPrint } class function Tf_PeInfoPrint.Execute(_Owner: TComponent; var _Tabs: TPeInfoTabSet): Boolean; var frm: Tf_PeInfoPrint; r: TRect; begin frm := Tf_PeInfoPrint.Create(_Owner); try r := frm.BoundsRect; TMonitor_MakeFullyVisible(frm.Monitor, r); frm.BoundsRect := r; frm.SetData(_Tabs); Result := (frm.ShowModal = mrOk); if Result then frm.GetData(_Tabs); finally FreeAndNil(frm); end; end; procedure Tf_PeInfoPrint.b_CheckAllClick(Sender: TObject); begin chk_MsDosHeader.Checked := True; chk_PeHeader.Checked := True; chk_PeOptional.Checked := True; chk_Imports.Checked := True; chk_Exports.Checked := True; chk_VersionInfo.Checked := True; chk_PackageInfo.Checked := True; end; procedure Tf_PeInfoPrint.b_CheckNoneClick(Sender: TObject); begin chk_MsDosHeader.Checked := False; chk_PeHeader.Checked := False; chk_PeOptional.Checked := False; chk_Imports.Checked := False; chk_Exports.Checked := False; chk_VersionInfo.Checked := False; chk_PackageInfo.Checked := False; end; procedure Tf_PeInfoPrint.GetData(out _Tabs: TPeInfoTabSet); begin _Tabs := []; if chk_MsDosHeader.Checked then Include(_Tabs, pitMsDos); if chk_PeHeader.Checked then Include(_Tabs, pitPeHeader); if chk_PeOptional.Checked then Include(_Tabs, pitPeOptHeader); if chk_Imports.Checked then Include(_Tabs, pitImports); if chk_Exports.Checked then Include(_Tabs, pitExports); if chk_VersionInfo.Checked then Include(_Tabs, pitVersionInfo); if chk_PackageInfo.Checked then Include(_Tabs, pitPackageInfo); end; procedure Tf_PeInfoPrint.SetData(_Tabs: TPeInfoTabSet); begin chk_MsDosHeader.Checked := pitMsDos in _Tabs; chk_PeHeader.Checked := pitPeHeader in _Tabs; chk_PeOptional.Checked := pitPeOptHeader in _Tabs; chk_Imports.Checked := pitImports in _Tabs; chk_Exports.Checked := pitExports in _Tabs; chk_VersionInfo.Checked := pitVersionInfo in _Tabs; chk_PackageInfo.Checked := pitPackageInfo in _Tabs; end; end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, math; const N = 25; sn = 5; h = 0.01; type TForm1 = class(TForm) Image1: TImage; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Edit1: TEdit; Label1: TLabel; procedure Button4Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; THilo = class(TThread) public procedure repintar; procedure actualizara; procedure calcularxf; procedure actualizarx; procedure actualizarv; function minabs(x1, x2: extended): extended; private salir: boolean; protected procedure Execute; override; procedure terminar; end; particula = record x, y: extended; //las coordenadas actuales de la particula xi, yi: extended; //las coordenadas anteriores de la particula xf, yf: extended; //las coordenadas posteriores de la particula vx, vy: extended; //las componentes de la velocidad de la particula ax, ay: extended; //las componentes de la aceleracion de la particula end; var Form1: TForm1; corriendo: boolean; hilo1: THilo; p: array[1..N] of particula; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var posicion: array[0..sn,0..sn] of boolean; x, y, i, j, cont: integer; begin for i := 0 to sn do begin for j := 0 to sn do begin posicion[i,j] := false; end; end; cont := 1; while cont <= N do begin x := random(sn); y := random(sn); if posicion[x,y] = false then begin p[cont].x := (10/sn * x + 5/sn) + ((2*random()-1) * (5/sn - 0.5)); p[cont].y := (10/sn * y + 5/sn) + ((2*random()-1) * (5/sn - 0.5)); cont := cont + 1; posicion[x,y] := true; end; end; for i := 1 to N do begin p[i].vx := 2*random()-1; p[i].vy := (2*random()-1) * sqrt(1 - p[i].vx * p[i].vx); end; {p[1].x := 5.5; p[2].x := 8.5; p[1].y := 5.2; p[2].y := 5; p[1].vx := -5; p[2].vx := 1; p[1].vy := 0; p[2].vy := 0;} hilo1.actualizara; for i := 1 to N do begin p[i].xi := p[i].x - p[i].vx*h + p[i].ax*h*h/2; p[i].yi := p[i].y - p[i].vy*h + p[i].ay*h*h/2; end; hilo1.repintar; end; procedure TForm1.Button2Click(Sender: TObject); begin if corriendo = false then begin corriendo := true; hilo1 := Thilo.Create(false); button2.Caption := 'Parar' end else begin corriendo := false; hilo1.terminar; hilo1.Free; button2.Caption := 'Correr'; end; end; procedure TForm1.Button4Click(Sender: TObject); begin close; end; procedure THilo.Execute; begin salir := false; while not salir do begin synchronize(actualizara); synchronize(calcularxf); synchronize(actualizarv); synchronize(repintar); synchronize(actualizarx); //sleep(1); end; end; procedure THilo.repintar; var I, x, y: Integer; begin Form1.Image1.Canvas.brush.color := clwhite; form1.Image1.canvas.FillRect(rect(0,0,400,400)); for I := 1 to N do begin x := round(p[i].x*40); y := round(p[i].y*40); form1.Image1.Canvas.Brush.Color := clblue; form1.Image1.Canvas.Ellipse(rect(x - 20, y - 20, x + 20, y + 20)); form1.Image1.Canvas.MoveTo(x,y); form1.Image1.Canvas.LineTo(x + round(p[i].vx*40), y + round(p[i].vy*40)); end; end; procedure THilo.actualizara; var I, j: Integer; dx1, dy1, dx2, dy2, dx, dy, r, rf: extended; begin for I := 1 to N do begin p[i].ax := 0; p[i].ay := 0; for j := 1 to N do begin if j<>i then begin dx1 := p[i].x - p[j].x; dy1 := p[i].y - p[j].y; if dx1 <> 0 then begin dx2 := (-1*dx1/abs(dx1)) * (10 - abs(dx1)); end else begin dx2 := 0; end; if dy1 <> 0 then begin dy2 := (-1*dy1/abs(dy1)) * (10 - abs(dy1)); end else begin dy2 := 0; end; dx := minabs(dx1, dx2); dy := minabs(dy1, dy2); r := sqrt(dx*dx + dy*dy); rf := 24 * (2/power(r,13) - 1/power(r,7)); p[i].ax := p[i].ax + rf*dx/r; p[i].ay := p[i].ay + rf*dy/r; end; end; end; end; procedure THilo.calcularxf; var I: Integer; begin for I := 1 to N do begin p[i].xf := 2*p[i].x - p[i].xi + p[i].ax*h*h; p[i].yf := 2*p[i].y - p[i].yi + p[i].ay*h*h; end; end; procedure THilo.actualizarx; var I: Integer; begin for I := 1 to N do begin if p[i].xf > 10 then begin p[i].xi := p[i].x - 10; p[i].x := p[i].xf - 10; end else if p[i].xf < 0 then begin p[i].xi := p[i].x + 10; p[i].x := p[i].xf + 10; end else begin p[i].xi := p[i].x; p[i].x := p[i].xf; end; if p[i].yf > 10 then begin p[i].yi := p[i].y - 10; p[i].y := p[i].yf - 10; end else if p[i].yf < 0 then begin p[i].yi := p[i].y + 10; p[i].y := p[i].yf + 10; end else begin p[i].yi := p[i].y; p[i].y := p[i].yf; end; end; end; procedure THilo.actualizarv; var I: Integer; sum: extended; begin sum := 0; for I := 1 to N do begin p[i].vx := (p[i].xf - p[i].xi)/(2*h); p[i].vy := (p[i].yf - p[i].yi)/(2*h); sum := sum + sqrt(p[i].vx*p[i].vx + p[i].vy*p[i].vy); end; form1.Edit1.Text := floattostr(sum); end; function THilo.minabs(x1: Extended; x2: Extended): extended; begin if abs(x1) < abs(x2) then begin minabs := x1; end else begin minabs := x2; end; end; procedure THilo.terminar; begin salir := true; end; end.
unit uMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, IniFiles, uFrameLogin, ExtCtrls; type TfMain = class(TForm) MainMenu1: TMainMenu; StatusBar1: TStatusBar; Cadastro1: TMenuItem; Fornecedores1: TMenuItem; Sair1: TMenuItem; Deslogar1: TMenuItem; Panel1: TPanel; fFrameLogin1: TfFrameLogin; procedure FormCreate(Sender: TObject); procedure Sair1Click(Sender: TObject); procedure Deslogar1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure Fornecedores1Click(Sender: TObject); procedure fFrameLogin1OKClick(Sender: TObject); private { Private declarations } procedure Conectar; procedure HabilitarMenus(sim: Boolean = false); public { Public declarations } end; var fMain: TfMain; implementation uses uDmPgf, uFornecedor; {$R *.dfm} procedure TfMain.Conectar; var BancoIni: TIniFile; path: string; begin try path := ExtractFilePath(Application.ExeName) + 'banco.ini'; BancoIni := TIniFile.Create(path); try dmPgf.pgfConnection.ConnectionString := 'Provider=MSDASQL.1;' + 'Persist Security Info=False;' + 'User ID=SYSDBA;' + 'Data Source=Firebird DNS'; dmPgf.pgfConnection.DefaultDatabase := BancoIni.ReadString('ConfiguracaoBancoDeDado', 'connectionString', 'error');//'localhost:C:\BD\PGF.FDB'; dmPgf.pgfConnection.LoginPrompt := False; dmPgf.pgfConnection.Connected := True; StatusBar1.Panels[0].Text := 'Base de Dados: ' + BancoIni.ReadString('ConfiguracaoBancoDeDado', 'name', 'error'); except on E: Exception do showMessage(e.Message); end; finally FreeAndNil(BancoIni); end; end; procedure TfMain.FormCreate(Sender: TObject); begin Conectar; HabilitarMenus; end; procedure TfMain.HabilitarMenus(sim: Boolean = false); var i: integer; begin for i := 0 to MainMenu1.Items.Count - 1 do begin MainMenu1.Items[i].Enabled := sim; end; end; procedure TfMain.Sair1Click(Sender: TObject); begin Application.Terminate; end; procedure TfMain.Deslogar1Click(Sender: TObject); begin HabilitarMenus(); fFrameLogin1.edtLogin.Clear; fFrameLogin1.edtPassWord.Clear; fFrameLogin1.Visible := true; end; procedure TfMain.FormShow(Sender: TObject); begin fFrameLogin1.Left := (Self.Width - fFrameLogin1.Width) div 2; fFrameLogin1.Top := (Self.Height - fFrameLogin1.Height) div 2; end; procedure TfMain.Fornecedores1Click(Sender: TObject); begin Application.CreateForm(TfFornecedor, fFornecedor); fFornecedor.Show; end; procedure TfMain.fFrameLogin1OKClick(Sender: TObject); begin fFrameLogin1.OKClick(Sender); HabilitarMenus(fFrameLogin1.LoginOk); end; end.
program hamt_tests; {$mode objfpc}{$H+}{$ModeSwitch typehelpers} uses {$IFDEF UNIX} cthreads, {$ENDIF} Classes, hamt.internals, commontestutils, sysutils, bbutils, contnrs, hamt.maps, hamt.sets { you can add units after this }; type THAMTTestTypeInfo = object(THAMTTypeInfo) class function hash(const s: string): THAMTHash; end; type TMutableMap_Test = class(specialize TMutableMap<string, string, THAMTTestTypeInfo>) procedure testInsert(const k, v: string; override: boolean = false); procedure testGet(const k, v: string); procedure testRemove(const k: string; notthere: boolean = false); procedure testEnumeration(expectedCount: integer); end; const MISSING = 'MISSING'; type TTestThread = class(TThread) id: string; map: TMutableMapStringString; constructor Create(aid: string; amap: TMutableMapStringString); procedure Execute; override; end; {$PUSH} {$RangeChecks OFF} {$OverflowChecks OFF} class function THAMTTestTypeInfo.hash(const s: string): THAMTHash; var p, last: PByte; begin if s = '' then exit(1); p := pbyte(pointer(s)); last := p + length(s); result := 0; //testing cases if p^ = ord('_') then begin inc(p); while p < last do begin result := (result shl BITS_PER_LEVEL) or THAMTHash((p^ - ord('0')) * 10 + (((p+1)^ - ord('0') ))); inc(p, 3); end; exit; end; if p^ = ord('$') then exit(StrToInt(s)); case s of 'test', 'collision+1', 'collision+2', 'collision+3': exit(hash('collision')); end; //actual hash while p < last do begin result := result + p^; result := result + (result shl 10); result := result xor (result shr 6); inc(p); end; result := result + (result shl 3); result := result xor (result shr 11); result := result + (result shl 15); end; {$POP} procedure TMutableMap_Test.testInsert(const k, v: string; override: boolean); var c: integer; begin c := count; test(include(k, v) xor override, 'insert failed (override marker?)'); test(contains(k), 'insert failed: ' + k); test(get(k, 'xx'), v); if not override then inc(c); test(count, c); test((c = 0) = isEmpty); end; procedure TMutableMap_Test.testGet(const k, v: string); begin test(get(k, MISSING), v, 'get ' + k); end; procedure TMutableMap_Test.testRemove(const k: string; notthere: boolean); var c: integer; begin c := count; if notthere then test(exclude(k) <> notthere, 'remove failed: ' + k) else remove(k); // test( <> notthere, 'remove failed: ' + k); test(get(k, MISSING), MISSING); if not notthere then dec(c); test(count, c); end; procedure TMutableMap_Test.testEnumeration(expectedCount: integer); var pair: TMutableMap_Test.PPair; visitedKeys: TFPStringHashTable; acount: integer; begin acount := 0; visitedKeys := TFPStringHashTable.Create; for pair in self do begin test(visitedKeys.Find(pair^.key) = nil, 'duplicated key'); inc(acount); test(get(pair^.key, MISSING), pair^.value); visitedKeys.Add(pair^.key, pair^.value); end; test(acount, expectedCount); visitedKeys.Free; end; function testInsert(m: TImmutableMapStringString; const k, v: string; override: boolean = false): TImmutableMapStringString; var c: integer; begin c := m.count; if override then result := m.include(k, v) else result := m.insert(k, v); // test( xor override, 'insert failed (override marker?)'); test(result.contains(k), 'insert failed: ' + k); test(result.get(k, 'xx'), v); test(result[k], v); test(m.count, c); if not override then inc(c); test(result.count, c); end; procedure testEnumeration(m: TImmutableMapStringString; expectedCount: integer); var pair: TMutableMap_Test.PPair; visitedKeys: TFPStringHashTable; acount: integer; begin acount := 0; visitedKeys := TFPStringHashTable.Create; for pair in m do begin test(visitedKeys.Find(pair^.key) = nil, 'duplicated key'); inc(acount); test(m.get(pair^.key, MISSING), pair^.value); visitedKeys.Add(pair^.key, pair^.value); end; test(acount, expectedCount); visitedKeys.Free; end; constructor TTestThread.Create(aid: string; amap: TMutableMapStringString); begin id := aid; map := amap; inherited Create(false); end; var runningThreads: integer; procedure TTestThread.Execute; var i: Integer; begin for i := 1 to 50000 do map.insert(id + IntToStr(i), IntToStr(i) + id); for i := 1 to 50000 do test(map.get(id + IntToStr(i)), IntToStr(i) + id); for i := 1 to 50000 do test(map.get(IntToStr(i)), 'init' + IntToStr(i)); for i := 1 to 50000 do map.remove(IntToStr(i)); for i := 1 to 50000 do test(map.get(id + IntToStr(i)), IntToStr(i) + id); for i := 1 to 50000 do test(map.contains(IntToStr(i)) = false); map.free; InterLockedDecrement(runningThreads); end; procedure setTestsMutable; var stringSet: TMutableSetString; p: TMutableSetString.PItem; begin stringSet := TMutableSetString.create; stringSet.Insert('hello'); stringSet.insert('foo'); test(stringSet['hello']); test(stringSet.contains('foo')); test(not stringSet.contains('abc')); stringSet.include('foo'); stringSet.include('foobar'); test(stringSet.contains('foo')); test(stringSet.contains('foobar')); stringSet.remove('foo'); stringSet.remove('foobar'); //stringSet.remove('foobar'); stringSet.exclude('foo'); stringSet.exclude('foobar'); stringSet.exclude('foobar'); test(not stringSet.contains('foo')); test(not stringSet.contains('foobar')); stringSet['foo'] := true; test(stringSet.contains('foo')); stringSet['foo'] := false; test(not stringSet.contains('foo')); stringSet['foo'] := true; test(stringSet.contains('foo')); //enumerate all for p in stringSet do test((p^ = 'hello') or (p^ = 'foo')); stringSet.free; end; procedure setTestsImmutable; var set1, set2, set3, set4, set5: TImmutableSetString; p: TImmutableSetString.PItem; begin set1 := TImmutableSetString.create; set2 := set1.Insert('hello'); set3 := set2.insert('foo'); test(not set1.contains('hello')); test(not set1['foo']); test(set2.contains('hello')); test(not set2['foo']); test(set3.contains('hello')); test(set3['foo']); set4 := set3.remove('hello'); set5 := set4.exclude('hello'); test(not set4.contains('hello')); test(set4['foo']); test(not set5.contains('hello')); test(set5['foo']); //enumerate all for p in set3 do test((p^ = 'hello') or (p^ = 'foo')); set1.free; set2.free; set3.free; set4.free; set5.free; end; var hamt, hamt2: TMutableMap_Test; imap, imap2, imap3, imap4: TImmutableMapStringString; mss: TMutableMapStringString; i: Integer; threads: array[1..8] of TThread; begin hamt := TMutableMap_Test.create; hamt.testInsert('hello', 'world'); test(not hamt.contains('xyz')); hamt.testInsert('foo', 'bar'); hamt.testGet('hello', 'world'); hamt.testGet('foo', 'bar'); hamt.testInsert('hello', 'override', true); hamt.testGet('foo', 'bar'); hamt.testEnumeration(2); hamt.remove('hello'); hamt['abc'] := 'def'; hamt.testGet('abc', 'def'); hamt.free; Assert(THAMTTestTypeInfo.hash('test') = THAMTTestTypeInfo.hash('collision')); Assert(THAMTTestTypeInfo.hash('_00') = 0); Assert(THAMTTestTypeInfo.hash('_01_02') = 2 or 32); Assert(THAMTTestTypeInfo.hash('$123') = $123); //test collisions hamt := TMutableMap_Test.create; hamt.testInsert('test', 'A'); hamt.testInsert('collision', 'B'); hamt.testInsert('collision+1', 'C'); hamt.testInsert('collision+2', 'D'); hamt.testGet('test', 'A'); hamt.testGet('collision', 'B'); hamt.testGet('collision+1', 'C'); hamt.testGet('collision+2', 'D'); hamt.testEnumeration(4); hamt.testRemove('test'); hamt.testRemove('test', true); hamt.testRemove('test!', true); hamt.free; hamt := TMutableMap_Test.create; hamt.testInsert('_00_01_02', 'x1'); hamt.testInsert('_00_01_02', 'x2', true); hamt.testInsert('_00_02_03', 'x3'); hamt.testGet('_00_01_02', 'x2'); hamt.testGet('_00_02_03', 'x3'); hamt.testEnumeration(2); hamt.testRemove('_01_02-03', true); hamt.free; hamt := TMutableMap_Test.create; hamt.testInsert('_00_01_02', 'x1'); hamt.testInsert('_00_01-02', 'x1b'); hamt.testInsert('_00_01-03', 'y'); hamt.testGet('_00_01_02', 'x1'); hamt.testGet('_00_01-02', 'x1b'); hamt.testGet('_00_01-03', 'y'); hamt.testEnumeration(3); hamt.testRemove('_01_01-02', true); hamt.testRemove('_01_02-02', true); hamt.free; //test prefix collisions hamt := TMutableMap_Test.create; hamt.testInsert('_02_01_00', 'x1'); hamt.testInsert('_02_01_00', 'x2', true); hamt.testInsert('_03_02_00', 'x3'); hamt.testGet('_02_01_00', 'x2'); hamt.testGet('_03_02_00', 'x3'); hamt.testEnumeration(2); hamt.free; hamt := TMutableMap_Test.create; hamt.testInsert('_02_01_00', 'x1'); hamt.testInsert('_02x01_00', 'x2'); hamt.testInsert('_03_02_00', 'x3'); hamt.testGet('_02_01_00', 'x1'); hamt.testGet('_02x01_00', 'x2'); hamt.testGet('_03_02_00', 'x3'); hamt.testEnumeration(3); hamt.free; //test some keys hamt := TMutableMap_Test.create; hamt.testInsert('$0', '0x0'); hamt.testInsert('$1', '0x1'); hamt.testInsert('$2', '0x2'); hamt.testInsert('$3', '0x3'); hamt.testInsert('$FFFFFFFF', '0xFFFFFFFF'); hamt.testInsert('$FFFFFFFE', '0xFFFFFFFE'); hamt.testInsert('$EFFFFFFF', '0xEFFFFFFF'); hamt.testInsert('$EFFFFFFE', '0xEFFFFFFE'); hamt.testInsert('$7FFFFFFE', '0x7FFFFFFE'); hamt.testInsert('$7FFFFFFF', '0x7FFFFFFF'); hamt.testInsert('$FFFFFFF0', '0xFFFFFFF0'); hamt.testInsert('$FFFFFFF1', '0xFFFFFFF1'); hamt.testInsert('$FFFFFFF2', '0xFFFFFFF2'); hamt.testInsert('$FFFFFFF3', '0xFFFFFFF3'); hamt.testInsert('$eFFFFFF0', '0xeFFFFFF0'); hamt.testInsert('$eFFFFFF1', '0xeFFFFFF1'); hamt.testInsert('$eFFFFFF2', '0xeFFFFFF2'); hamt.testInsert('$eFFFFFF3', '0xeFFFFFF3'); hamt.testInsert('$eFFFFFF7', '0xeFFFFFF7'); hamt.testInsert('$eFFFFFF8', '0xeFFFFFF8'); hamt.testEnumeration(20); hamt.free; //test snapshots hamt := TMutableMap_Test.create; hamt.testInsert('hello', 'world'); hamt.testInsert('foo', 'bar'); hamt2 := TMutableMap_Test(hamt.clone); hamt.testInsert('hello', 'override', true); hamt.testGet('hello', 'override'); hamt.testGet('foo', 'bar'); hamt2.testGet('hello', 'world'); hamt2.testGet('foo', 'bar'); hamt.testEnumeration(2); hamt2.testEnumeration(2); hamt.free; hamt2.Free; hamt := TMutableMap_Test.create; hamt.testInsert('hello', 'world'); hamt.testInsert('foo', 'bar'); hamt2 := TMutableMap_Test(hamt.clone); hamt.testInsert('new', 'N'); hamt.testGet('hello', 'world'); hamt.testGet('foo', 'bar'); hamt.testGet('new', 'N'); hamt2.testGet('hello', 'world'); hamt2.testGet('foo', 'bar'); hamt2.testGet('new', MISSING); hamt.testEnumeration(3); hamt2.testEnumeration(2); hamt.testRemove('new'); hamt2.testRemove('hello'); hamt.testEnumeration(2); hamt2.testEnumeration(1); hamt.free; hamt2.free; hamt := TMutableMap_Test.create; hamt.testInsert('_02_01_00', 'x1'); hamt.testInsert('_02_01_00', 'x2', true); hamt2 := TMutableMap_Test(hamt.clone); hamt.testInsert('_03_02_00', 'x3'); hamt.testGet('_02_01_00', 'x2'); hamt.testGet('_03_02_00', 'x3'); hamt2.testGet('_02_01_00', 'x2'); hamt2.testGet('_03_02_00', MISSING); hamt.testInsert('_03_03_00', 'x4'); hamt2.free; hamt2 := TMutableMap_Test(hamt.clone); hamt.testInsert('_03_03_00', 'x5', true); hamt.testGet('_02_01_00', 'x2'); hamt.testGet('_03_02_00', 'x3'); hamt.testGet('_03_03_00', 'x5'); hamt2.testGet('_02_01_00', 'x2'); hamt2.testGet('_03_02_00', 'x3'); hamt2.testGet('_03_03_00', 'x4'); hamt.testEnumeration(3); hamt2.testEnumeration(3); hamt.free; hamt2.free; hamt := TMutableMap_Test.create; hamt.testInsert('_02_01_00', 'x1'); hamt.testInsert('_02-01_00', 'x2'); hamt2 := TMutableMap_Test(hamt.clone); hamt.testInsert('_03_02_00', 'x3'); hamt.testGet('_02_01_00', 'x1'); hamt.testGet('_02-01_00', 'x2'); hamt.testGet('_03_02_00', 'x3'); hamt2.testGet('_02_01_00', 'x1'); hamt2.testGet('_02-01_00', 'x2'); hamt2.testGet('_03_02_00', MISSING); hamt.testEnumeration(3); hamt2.testEnumeration(2); hamt.testRemove('_02_01_00'); hamt.testEnumeration(2); hamt2.testEnumeration(2); hamt.testRemove('_02-01_00'); hamt.testEnumeration(1); hamt2.testEnumeration(2); hamt.free; hamt2.free; hamt := TMutableMap_Test.create; hamt.testInsert('_02_01_00', 'x1'); hamt.testInsert('_02-01_00', 'x2'); hamt2 := TMutableMap_Test(hamt.clone); hamt.testInsert('_02x01_00', 'x3'); hamt.testGet('_02_01_00', 'x1'); hamt.testGet('_02-01_00', 'x2'); hamt.testGet('_02x01_00', 'x3'); hamt2.testGet('_02_01_00', 'x1'); hamt2.testGet('_02-01_00', 'x2'); hamt2.testGet('_02x01_00', MISSING); hamt.testEnumeration(3); hamt2.testEnumeration(2); hamt.remove('_02_01_00'); hamt.remove('_02-01_00'); hamt.insert('_31_31_00', 'xy'); hamt.remove('_02x01_00'); hamt.remove('_31_31_00'); hamt.free; hamt2.free; hamt := TMutableMap_Test.create; hamt.testInsert('_02_01_00', 'x1'); hamt.testInsert('_02-01_00', 'x2'); hamt2 := TMutableMap_Test(hamt.clone); hamt.testInsert('_02-01_00', 'x3', true); hamt.testGet('_02_01_00', 'x1'); hamt.testGet('_02-01_00', 'x3'); hamt2.testGet('_02_01_00', 'x1'); hamt2.testGet('_02-01_00', 'x2'); hamt.testEnumeration(2); hamt2.testEnumeration(2); hamt.testRemove('_02_01_00'); hamt.testRemove('_02-01_00'); hamt2.testRemove('_02-01_00'); hamt.testEnumeration(0); hamt2.testEnumeration(1); hamt.free; hamt2.free; //more remove tests hamt := TMutableMap_Test.create; hamt.testInsert('_02_00_31', 'x1'); hamt.testInsert('_03-00_31', 'x2'); hamt2 := TMutableMap_Test(hamt.clone); hamt.testRemove('_03_00_31', true); hamt.testRemove('_03-00_31'); hamt2.testEnumeration(2); hamt.testRemove('_02_00_31'); hamt.testEnumeration(0); hamt2.testEnumeration(2); hamt.free; hamt2.free; hamt := TMutableMap_Test.create; hamt.testInsert('_00_00_00', 'x1'); hamt.testInsert('_31-31_31', 'x2'); hamt.testInsert('_30-31_31', 'x3'); hamt.testEnumeration(3); hamt.testRemove('_31-31_31'); hamt.testEnumeration(2); hamt.testRemove('_30-31_31'); hamt.testEnumeration(1); hamt.free; hamt := TMutableMap_Test.create; hamt.testInsert('_31-31_31', 'x1'); hamt.testInsert('_31x31_31', 'x2'); hamt.testInsert('_00x00_01', 'x3'); hamt.testRemove('_31-31_31'); //makes _31x31_31 into an array hamt2 := TMutableMap_Test(hamt.clone); hamt.testRemove('_31x31_31'); hamt.free; hamt2.free; //immutable interface imap := TImmutableMapStringString.Create; imap2 := testInsert(imap, 'a', 'x'); imap3 := testInsert(imap, 'b', 'y'); testEnumeration(imap2, 1); testEnumeration(imap3, 1); imap4 := testInsert(imap3, 'b', 'z', true); testEnumeration(imap4, 1); imap4.free; imap4 := testInsert(imap2, 'c', 'z'); testEnumeration(imap4, 2); imap4.free; imap4 := imap2.remove('a'); testEnumeration(imap4, 0); imap4.free; imap.Free; imap2.Free; imap3.Free; //mutable pointer hamt := TMutableMap_Test.create; hamt.testInsert('a', 'b'); hamt2 := TMutableMap_Test(hamt.clone); hamt.mutable['a']^ := 'c'; hamt.testGet('a', 'c'); hamt2.testGet('a', 'b'); hamt.free; hamt2.free; hamt := TMutableMap_Test.create; hamt.testInsert('_00_00_00', 'x1'); hamt.testInsert('_00_00_01', 'x2'); hamt.testInsert('_00_00_02', 'x3'); hamt2 := TMutableMap_Test(hamt.clone); hamt.mutable['_00_00_00']^ := 'u'; hamt.mutable['_00_00_01']^ := 'v'; hamt.mutable['_00_00_02']^ := 'w'; hamt.testGet('_00_00_00', 'u'); hamt.testGet('_00_00_01', 'v'); hamt.testGet('_00_00_02', 'w'); hamt2.testGet('_00_00_00', 'x1'); hamt2.testGet('_00_00_01', 'x2'); hamt2.testGet('_00_00_02', 'x3'); hamt.free; hamt2.free; //sets setTestsMutable; setTestsImmutable; mss := TMutableMapStringString.Create(); for i := 1 to 50000 do mss.insert(IntToStr(i), 'init' + IntToStr(i)); runningThreads := 8; for i := 1 to 8 do threads[i] := TTestThread.Create('_'+IntToStr(i)+'_', mss.clone); mss.free; while runningThreads > 0 do sleep(100); for i := 1 to 8 do threads[i].free; writeln('ok'); end.
unit GX_IdeSearchPathFavoriteEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GX_BaseForm; type Tf_IdeSearchPathFavoriteEdit = class(TfmBaseForm) l_Name: TLabel; ed_Name: TEdit; l_Path: TLabel; m_Path: TMemo; b_OK: TButton; b_Cancel: TButton; b_Select: TButton; procedure b_SelectClick(Sender: TObject); private procedure GetData(out _Name, _Path: string); procedure SetData(const _Name, _Path: string); procedure HandleFilesDropped(_Sender: TObject; _Files: TStrings); public class function Execute(_Owner: TComponent; var _Name, _Path: string): Boolean; constructor Create(_Owner: TComponent); override; end; implementation uses StrUtils, GX_dzVclUtils, GX_dzSelectDirectoryFix; {$R *.dfm} { Tf_IdeSearchPathFavoriteEdit } class function Tf_IdeSearchPathFavoriteEdit.Execute(_Owner: TComponent; var _Name, _Path: string): Boolean; var frm: Tf_IdeSearchPathFavoriteEdit; begin frm := Tf_IdeSearchPathFavoriteEdit.Create(_Owner); try frm.SetData(_Name, _Path); Result := (frm.ShowModal = mrok); if Result then frm.GetData(_Name, _Path); finally FreeAndNil(frm); end; end; procedure Tf_IdeSearchPathFavoriteEdit.b_SelectClick(Sender: TObject); var Dir: string; begin Dir := ''; if not dzSelectDirectory('Select directory to add', '', Dir, Self) then Exit; m_Path.Lines.Add(Dir); end; constructor Tf_IdeSearchPathFavoriteEdit.Create(_Owner: TComponent); begin inherited; TControl_SetMinConstraints(Self); m_Path.Lines.Delimiter := ';'; TWinControl_ActivateDropFiles(m_Path, HandleFilesDropped); end; procedure Tf_IdeSearchPathFavoriteEdit.HandleFilesDropped(_Sender: TObject; _Files: TStrings); begin m_Path.Lines.AddStrings(_Files); end; procedure Tf_IdeSearchPathFavoriteEdit.GetData(out _Name, _Path: string); begin _Name := ed_Name.Text; _Path := AnsiDequotedStr(m_Path.Lines.DelimitedText, '"'); end; procedure Tf_IdeSearchPathFavoriteEdit.SetData(const _Name, _Path: string); begin ed_Name.Text := _Name; m_Path.Lines.DelimitedText := AnsiDequotedStr(_Path, '"'); end; end.
unit RoundingForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Math, StdCtrls; type TForm1 = class(TForm) btnClassic: TButton; ListBox1: TListBox; btnSimpleRound: TButton; btnTroubles: TButton; procedure btnClassicClick(Sender: TObject); procedure btnSimpleRoundClick(Sender: TObject); procedure btnTroublesClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnClassicClick(Sender: TObject); var i: Integer; begin for i := 0 to 10 do ListBox1.Items.Add (FloatToStr (i + 0.5) + ' -> ' + IntToStr (Round (i + 0.5))); end; procedure TForm1.btnSimpleRoundClick(Sender: TObject); var i: Integer; begin for i := 0 to 10 do ListBox1.Items.Add (FloatToStr (i + 0.5) + ' -> ' + FloatToStr (SimpleRoundTo (i + 0.5, 0))); end; procedure TForm1.btnTroublesClick(Sender: TObject); var d: double; i: Integer; begin // this is not as expected... for i := 0 to 10 do begin d := 1 + i/10 + 0.05; ListBox1.Items.Add (FloatToStr (d) + ' -> ' + FloatToStr (SimpleRoundTo (d, -1))); end; // this seems to work... for i := 0 to 10 do begin d := 1 + i/10 + 0.05; ListBox1.Items.Add (FloatToStr (d) + ' -> ' + FloatToStr (SimpleRoundTo (d * 10, 0) / 10)); end; end; end.
{ Copyright (C) 2013 Dimitar Paperov This source 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 code 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. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit angle_form; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TForm2 } TForm2 = class(TForm) Button1: TButton; Button2: TButton; CheckBox1: TCheckBox; Edit1: TEdit; Edit2: TEdit; Label1: TLabel; Label2: TLabel; procedure Edit1KeyPress(Sender: TObject; var Key: char); private { private declarations } public { public declarations } function ShowMe(aAngleCount: integer): boolean; end; var Form2: TForm2; implementation {$R *.lfm} { TForm2 } procedure TForm2.Edit1KeyPress(Sender: TObject; var Key: char); begin if not (Key in ['0'..'9',DefaultFormatSettings.DecimalSeparator,#8]) then Key := #0; end; function TForm2.ShowMe(aAngleCount: integer): boolean; begin if aAngleCount=1 then begin Label2.Visible:=false; Edit2.Visible:=false; end else begin Label2.Visible:=true; Edit2.Visible:=true; end; Result := (ShowModal = mrOk); end; end.
unit TestUAfrican; { 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, UBird, UAfrican; type // Test methods for class TAfrican TestTAfrican = class(TTestCase) strict private FAfrican: TAfrican; public procedure SetUp; override; procedure TearDown; override; published procedure TestgetSpeed; end; implementation procedure TestTAfrican.SetUp; begin FAfrican := TAfrican.Create; end; procedure TestTAfrican.TearDown; begin FAfrican.Free; FAfrican := nil; end; procedure TestTAfrican.TestgetSpeed; var ReturnValue: string; begin ReturnValue := FAfrican.getSpeed; CheckEquals(ReturnValue, 'African', 'сообщение об ошибке'); // TODO: Validate method results end; initialization // Register any test cases with the test runner RegisterTest(TestTAfrican.Suite); end.
unit eInterestSimulator.Model.Calculadora.Factory; interface uses eInterestSimulator.Model.Interfaces.Calculadora; type TModelCalculadoraFactory = class(TInterfacedObject, iCalculadoraFactory) private function PagamentoUnico: iCalculadora; function PagamentoVariavel: iCalculadora; function Americano: iCalculadora; function AmortizacaoConstante: iCalculadora; function Price: iCalculadora; function AmortizacaoMisto: iCalculadora; function Alemao: iCalculadora; public constructor Create; destructor Destroy; override; class function New: iCalculadoraFactory; end; implementation uses eInterestSimulator.Model.Simulador, eInterestSimulator.Model.PagamentoUnico.Calculadora; { TModelCalculadoraFactory } function TModelCalculadoraFactory.Alemao: iCalculadora; begin end; function TModelCalculadoraFactory.Americano: iCalculadora; begin end; function TModelCalculadoraFactory.AmortizacaoConstante: iCalculadora; begin end; function TModelCalculadoraFactory.AmortizacaoMisto: iCalculadora; begin end; constructor TModelCalculadoraFactory.Create; begin end; destructor TModelCalculadoraFactory.Destroy; begin inherited; end; class function TModelCalculadoraFactory.New: iCalculadoraFactory; begin Result := Self.Create; end; function TModelCalculadoraFactory.PagamentoUnico: iCalculadora; begin Result := TModelPagamentoUnicoCalculadora.New; end; function TModelCalculadoraFactory.PagamentoVariavel: iCalculadora; begin end; function TModelCalculadoraFactory.Price: iCalculadora; begin end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 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, see <http://www.gnu.org/licenses/>. } unit OraGrants; interface uses Classes, SysUtils, Ora, OraStorage, DB,DBQuery, Forms, Dialogs, VirtualTable; type Grant = record Grantor, Grantee, TableSchema, TableName, Privilege, Grantable, //yes-no,''->revoke Hierarchy: string; end; TGrant = ^Grant; TGrantList = class(TObject) private FGrantList: TList; FTableSchema, FTableName: string; FOraSession: TOraSession; FObjectType: TDBFormType; FDSGrantList: TVirtualTable; function GetGrant(Index: Integer): TGrant; procedure SetGrant(Index: Integer; Grant: TGrant); function GetGrantCount: Integer; public procedure GrantAdd(Grant: TGrant); procedure GrantDelete(Index: Integer); property GrantCount: Integer read GetGrantCount; property GrantItems[Index: Integer]: TGrant read GetGrant write SetGrant; function FindByGrants(Grantee, Privilege: string): integer; procedure CopyFrom(GrantList: TGrantList); property TableSchema: string read FTableSchema write FTableSchema; property TableName: string read FTableName write FTableName ; property ObjectType: TDBFormType read FObjectType write FObjectType; property DSGrantList: TVirtualTable read FDSGrantList; property OraSession: TOraSession read FOraSession write FOraSession; constructor Create; destructor Destroy; override; procedure SetDDL; function GetDDL: string; function Grant(GrantScript: string) : boolean; end; function GetPrivs: string; const GrantTablePrivilege: array[1..12] of string = ('Select','Delete','Insert','Update','Alter','References','Index','OnCommitRefresh','QueryRewrite','Debug','Flashback','Execute'); implementation uses util,frmSchemaBrowser; {********************** TGrant ***********************************} function GetPrivs: string; begin result := ' Select * from all_tab_privs ' +' where TABLE_SCHEMA = :pOwner ' +' and TABLE_NAME = :pName ' +' order by grantee, grantable '; end; constructor TGrantList.Create; begin FGrantList := TList.Create; FDSGrantList := TVirtualTable.Create(nil); end; destructor TGrantList.Destroy; var i : Integer; FGrant: TGrant; begin try if FGrantList.Count > 0 then begin for i := FGrantList.Count - 1 downto 0 do begin FGrant := FGrantList.Items[i]; Dispose(FGrant); end; end; finally FGrantList.Free; end; FDSGrantList.Free; inherited; end; procedure TGrantList.GrantAdd(Grant: TGrant); begin FGrantList.Add(Grant); end; procedure TGrantList.GrantDelete(Index: Integer); begin TObject(FGrantList.Items[Index]).Free; FGrantList.Delete(Index); end; function TGrantList.GetGrant(Index: Integer): TGrant; begin Result := FGrantList.Items[Index]; end; procedure TGrantList.SetGrant(Index: Integer; Grant: TGrant); begin if Assigned(Grant) then FGrantList.Items[Index] := Grant end; function TGrantList.GetGrantCount: Integer; begin Result := FGrantList.Count; end; function TGrantList.FindByGrants(Grantee, Privilege: string): integer; var i: integer; begin result := -1; for i := 0 to FGrantList.Count -1 do begin if (TGrant(FGrantList[i]).Grantee = Grantee) and (TGrant(FGrantList[i]).Privilege = Privilege) then begin result := i; exit; end; end; end; procedure TGrantList.CopyFrom(GrantList: TGrantList); var i: integer; begin FOraSession := GrantList.OraSession; FTableSchema := GrantList.TableSchema; FTableName := GrantList.TableName; for i := 0 to GrantList.GrantCount -1 do FGrantList.Add(TGrant(GrantList.GrantItems[i])); end; procedure TGrantList.SetDDL; var FGrant: TGrant; q: TOraQuery; begin if FTableName = '' then exit; q := TOraQuery.Create(nil); q.Session := FOraSession; q.SQL.Text := GetPrivs; q.ParamByName('pOwner').AsString := FTableSchema; q.ParamByName('pName').AsString := FTableName; q.Open; CopyDataSet(q, FDSGrantList); while not q.Eof do begin new(FGrant); FGrant^.Grantor := q.FieldByName('Grantor').AsString; FGrant^.Grantee := q.FieldByName('Grantee').AsString; FGrant^.TableSchema := q.FieldByName('Table_Schema').AsString; FGrant^.TableName := q.FieldByName('Table_Name').AsString; FGrant^.Privilege := q.FieldByName('Privilege').AsString; FGrant^.Grantable := q.FieldByName('Grantable').AsString; FGrant^.Hierarchy := q.FieldByName('Hierarchy').AsString; GrantAdd(FGrant); q.Next; end; q.close; end; function TGrantList.GetDDL: string; var strHeader, strGrantebleY, strGrantebleN, strGrantebleR: string; i: integer; FGrantee: string; begin FGrantee := ''; strGrantebleY := ''; strGrantebleN := ''; strGrantebleR := ''; with self do begin if GetGrantCount > 0 then FGrantee := GrantItems[0].Grantee; for i := 0 to GetGrantCount -1 do begin if FGrantee <> GrantItems[i].Grantee then begin if copy(strGrantebleY, length(strGrantebleY),1) =',' then delete(strGrantebleY, length(strGrantebleY),1); if copy(strGrantebleN, length(strGrantebleN),1) =',' then delete(strGrantebleN, length(strGrantebleN),1); if copy(strGrantebleR, length(strGrantebleR),1) =',' then delete(strGrantebleR, length(strGrantebleR),1); if length(strGrantebleY) > 0 then strHeader := strHeader + 'GRANT '+strGrantebleY+' on '+TableSchema+'.'+TableName+' TO '+FGrantee+' WITH GRANT OPTION;'+ln; if length(strGrantebleN) > 0 then strHeader := strHeader + 'GRANT '+strGrantebleN+' on '+TableSchema+'.'+TableName+' TO '+FGrantee+';'+ln; if length(strGrantebleR) > 0 then strHeader := strHeader + 'REVOKE '+strGrantebleR+' on '+TableSchema+'.'+TableName+' FROM '+FGrantee+';'+ln; strGrantebleY := ''; strGrantebleN := ''; strGrantebleR := ''; end; FGrantee := GrantItems[i].Grantee; if GrantItems[i].Grantable = 'YES' then strGrantebleY := strGrantebleY + GrantItems[i].Privilege +',' else if GrantItems[i].Grantable = 'NO' then strGrantebleN := strGrantebleN + GrantItems[i].Privilege +',' else strGrantebleR := strGrantebleR + GrantItems[i].Privilege +','; end; if copy(strGrantebleY, length(strGrantebleY),1) =',' then delete(strGrantebleY, length(strGrantebleY),1); if copy(strGrantebleN, length(strGrantebleN),1) =',' then delete(strGrantebleN, length(strGrantebleN),1); if copy(strGrantebleR, length(strGrantebleR),1) =',' then delete(strGrantebleR, length(strGrantebleR),1); if length(strGrantebleY) > 0 then strHeader := strHeader + 'GRANT '+strGrantebleY+' on '+TableSchema+'.'+TableName+' TO '+FGrantee+' WITH GRANT OPTION;'+ln; if length(strGrantebleN) > 0 then strHeader := strHeader + 'GRANT '+strGrantebleN+' on '+TableSchema+'.'+TableName+' TO '+FGrantee+';'+ln; if length(strGrantebleR) > 0 then strHeader := strHeader + 'REVOKE '+strGrantebleR+' on '+TableSchema+'.'+TableName+' FROM '+FGrantee+';'+ln; end; //with self result := strHeader; end; function TGrantList.Grant(GrantScript: string) : boolean; begin result := ExecSQL(GrantScript, '', FOraSession); end; end.
unit FormHistory; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type TfrmHistory = class(TForm) procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); published procedure FormPaint(Sender: TObject); private { Private declarations } public { Public declarations } procedure AddLine(Xs,Xe,Y: Integer); procedure ClearLines; end; TLineRec=record Xs,Xe,Y: Integer; end; var frmHistory: TfrmHistory; Lines: array of TLineRec; implementation {$R *.dfm} procedure TfrmHistory.AddLine(Xs,Xe,Y: Integer); var l: Integer; begin l:=Length(Lines); SetLength(Lines,l+1); Lines[l].Xs:=Xs; Lines[l].Xe:=Xe; Lines[l].Y:=Y; end; procedure TfrmHistory.ClearLines; begin SetLength(Lines,0); end; procedure TfrmHistory.FormPaint(Sender: TObject); var i,x,y: Integer; begin y:=self.VertScrollBar.Position; x:=self.HorzScrollBar.Position; with Canvas do begin FillRect(self.BoundsRect); pen.Width:=2; pen.Color:=clBlack; pen.Style:=psSolid; for i:=0 to Length(Lines)-1 do begin MoveTo(Lines[i].Xs-x,Lines[i].Y-y); LineTo(Lines[i].Xe-x,Lines[i].Y-y); LineTo(Lines[i].Xe-5-x,Lines[i].Y-5-y); MoveTo(Lines[i].Xe-x,Lines[i].Y-y); LineTo(Lines[i].Xe-5-x,Lines[i].Y+5-y); end; end; end; procedure TfrmHistory.FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin if Shift=[] then with VertScrollBar do Position:=Position-increment else if Shift=[ssShift] then with HorzScrollBar do Position:=Position-increment end; procedure TfrmHistory.FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin if Shift=[] then with VertScrollBar do Position:=Position+increment else if Shift=[ssShift] then with HorzScrollBar do Position:=Position+increment end; end.
unit View.ImportacaoPlanilhaExtravios; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, dxSkinscxPCPainter, cxClasses, dxLayoutContainer, dxLayoutControl, Vcl.Menus, dxLayoutControlAdapters, Vcl.StdCtrls, cxButtons, dxLayoutcxEditAdapters, cxContainer, cxEdit, cxLabel, System.Actions, Vcl.ActnList, Vcl.ComCtrls, dxCore, cxDateUtils, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxButtonEdit, Control.EntregadoresExpressas, FireDAC.Comp.Client, Control.Sistema, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxCurrencyEdit, cxProgressBar, Control.ExtraviosMultas, Control.Entregas, Common.ENum, cxMemo; type Tview_ImportacaoPlanilhaExtravios = class(TForm) dxLayoutControl1Group_Root: TdxLayoutGroup; dxLayoutControl1: TdxLayoutControl; dxLayoutGroup1: TdxLayoutGroup; dxLayoutGroup2: TdxLayoutGroup; dxLayoutGroup3: TdxLayoutGroup; cxButton1: TcxButton; dxLayoutItem1: TdxLayoutItem; cxLabel1: TcxLabel; dxLayoutItem2: TdxLayoutItem; aclImportarExtravio: TActionList; actFechar: TAction; datEvento: TcxDateEdit; dxLayoutItem3: TdxLayoutItem; cboDescricaoExtravio: TcxComboBox; dxLayoutItem4: TdxLayoutItem; edtCodigoEntregador: TcxButtonEdit; dxLayoutItem5: TdxLayoutItem; txtNomeEntregador: TcxTextEdit; dxLayoutItem6: TdxLayoutItem; actImportar: TAction; cxButton2: TcxButton; dxLayoutItem7: TdxLayoutItem; dsImportacao: TDataSource; dxLayoutAutoCreatedGroup4: TdxLayoutAutoCreatedGroup; edtArquivo: TcxButtonEdit; dxLayoutItem8: TdxLayoutItem; dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup; dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup; OpenDialog: TOpenDialog; pbImportacao: TcxProgressBar; dxLayoutItem9: TdxLayoutItem; actAbrirArquivo: TAction; memObs: TcxMemo; dxLayoutItem10: TdxLayoutItem; procedure edtCodigoEntregadorPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure edtCodigoEntregadorPropertiesChange(Sender: TObject); procedure edtCodigoEntregadorPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure actImportarExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actFecharExecute(Sender: TObject); procedure actAbrirArquivoExecute(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } procedure LocalizaEntregadores; procedure LimpaCampos; function NomeEntregador(iCodigo: Integer): String; procedure Modo(iTipo: Integer); procedure Importar; procedure AbrirArquivo; function ValidaImportacao(): Boolean; public { Public declarations } end; var view_ImportacaoPlanilhaExtravios: Tview_ImportacaoPlanilhaExtravios; FEntregadores : TEntregadoresExpressasControl; iBase: Integer; FExtravios : TExtraviosMultasControl; FEntregas : TEntregasControl; implementation {$R *.dfm} uses Data.SisGeF, View.PesquisarPessoas, Common.Utils, Global.Parametros; { Tview_ImportacaoPlanilhaExtravios } procedure Tview_ImportacaoPlanilhaExtravios.AbrirArquivo; begin if OpenDialog.Execute then begin edtArquivo.Text := OpenDialog.FileName; end; end; procedure Tview_ImportacaoPlanilhaExtravios.actAbrirArquivoExecute(Sender: TObject); begin AbrirArquivo; end; procedure Tview_ImportacaoPlanilhaExtravios.actFecharExecute(Sender: TObject); begin Close; end; procedure Tview_ImportacaoPlanilhaExtravios.actImportarExecute(Sender: TObject); begin if not ValidaImportacao() then Exit; if Application.MessageBox('Confirma a importação?', 'Importar', MB_YESNO + MB_ICONQUESTION) = IDNO then begin Exit; end; Modo(1); Importar; end; procedure Tview_ImportacaoPlanilhaExtravios.edtCodigoEntregadorPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin LocalizaEntregadores; end; procedure Tview_ImportacaoPlanilhaExtravios.edtCodigoEntregadorPropertiesChange(Sender: TObject); begin txtNomeEntregador.Clear; end; procedure Tview_ImportacaoPlanilhaExtravios.edtCodigoEntregadorPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin txtNomeEntregador.Text := NomeEntregador(DisplayValue); end; procedure Tview_ImportacaoPlanilhaExtravios.FormClose(Sender: TObject; var Action: TCloseAction); begin if Data_Sisgef.mtbImportacaoExtravios.Active then Data_Sisgef.mtbImportacaoExtravios.Close; Action := caFree; view_ImportacaoPlanilhaExtravios := nil; end; procedure Tview_ImportacaoPlanilhaExtravios.FormShow(Sender: TObject); begin Modo(0); end; procedure Tview_ImportacaoPlanilhaExtravios.Importar; var iTotal : Integer; dPos : Double; iPos : Integer; sValor: String; FDQuery : TFDQuery; aParam : array of variant; sObs: String; i: Integer; begin try FExtravios := TExtraviosMultasControl.Create(); FEntregas := TEntregasControl.Create(); Data_Sisgef.mtbImportacaoExtravios.Open; Data_Sisgef.mtbImportacaoExtravios.Edit; Data_Sisgef.FDBTextReaderExtravios.FileName := edtArquivo.Text; Data_SisGeF.FDBmExtravios.GuessFormat; Data_SisGeF.FDBmExtravios.Mappings.AddAll; Data_Sisgef.FDBmExtravios.Execute; if Data_Sisgef.mtbImportacaoExtravios.Active then begin if not Data_Sisgef.mtbImportacaoExtravios.IsEmpty then begin iTotal := Data_Sisgef.mtbImportacaoExtravios.RecordCount; Data_Sisgef.mtbImportacaoExtravios.First; iPos := 0; dPos := 0; sObs := ''; while not Data_Sisgef.mtbImportacaoExtravios.Eof do begin if Common.Utils.TUtils.ENumero(Data_Sisgef.mtbImportacaoExtravios.Fields[3].AsString) then begin FExtravios.Extravios.ID := 0; FExtravios.Extravios.Descricao := cboDescricaoExtravio.Text; FExtravios.Extravios.NN := Trim(Data_Sisgef.mtbImportacaoExtravios.Fields[3].AsString); FExtravios.Extravios.Agente := iBase; sValor := Common.Utils.TUtils.ReplaceStr(Data_Sisgef.mtbImportacaoExtravios.Fields[16].AsString,'R$ ', ''); sValor := Common.Utils.TUtils.ReplaceStr(sValor, '.', ''); sValor := Common.Utils.TUtils.ReplaceStr(sValor, 'R$', ''); FExtravios.Extravios.ValorProduto := StrToFloatDef(sValor,0); FExtravios.Extravios.Data := datEvento.Date; FExtravios.Extravios.Multa := 0; SetLength(aParam,2); aParam[0] := 'NN'; aParam[1] := FExtravios.Extravios.NN; FDQuery := FEntregas.Localizar(aParam); Finalize(aParam); if not FDQuery.IsEmpty then begin FExtravios.Extravios.Verba := FDQuery.FieldByName('VAL_VERBA_ENTREGADOR').AsFloat; FExtravios.Extravios.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat; end else begin FExtravios.Extravios.Verba := 0; FExtravios.Extravios.VerbaFranquia := 0; end; FExtravios.Extravios.Total := FExtravios.Extravios.Multa + FExtravios.Extravios.ValorProduto; FExtravios.Extravios.Entregador := edtCodigoEntregador.EditValue; FExtravios.Extravios.Tipo := 1; FExtravios.Extravios.ValorFranquia := 0; FExtravios.Extravios.Extrato := '0'; FExtravios.Extravios.DataFranquia := 0; FExtravios.Extravios.EnvioCorrespondencia := 'NÃO SE APLICA'; FExtravios.Extravios.RetornoCorrespondencia := 'NÃO SE APLICA'; if Copy(FExtravios.Extravios.Descricao,1,2) = '98' then begin FExtravios.Extravios.Restricao := 'S'; FExtravios.Extravios.Percentual := 100; end else begin FExtravios.Extravios.Restricao := 'N'; FExtravios.Extravios.Percentual := 0; end; FExtravios.Extravios.IDExtrato := 0; FExtravios.Extravios.Executor := Global.Parametros.pUser_Name; FExtravios.Extravios.Manutencao := Now(); FExtravios.Extravios.Sequencia := 0; SetLength(aParam,3); aParam[0] := 'TIPO'; aParam[1] := FExtravios.Extravios.NN; aParam[2] := FExtravios.Extravios.Tipo; if FDQuery.Active then FDQuery.Close; FDQuery := FExtravios.Localizar(aParam); if not FDQuery.IsEmpty then begin FExtravios.Extravios.ID := FDQuery.FieldByName('COD_EXTRAVIO').AsInteger; sObs := FDQuery.FieldByName('DES_OBSERVACOES').Text; sObs := sObs + #13 + memObs.Text; FExtravios.Extravios.Acao := Common.ENum.tacAlterar; end else begin FExtravios.Extravios.Acao := Common.ENum.tacIncluir; sObs := memObs.Text; end; FExtravios.Extravios.Obs := sObs; if not FExtravios.Gravar then begin Application.MessageBox(PChar('Erro ao tentar gravar o extravio do NN ' + FExtravios.Extravios.NN + '!'), 'Erro', MB_OK + MB_ICONERROR); end; end; Data_Sisgef.mtbImportacaoExtravios.Next; Inc(iPos,1); dPos := (iPos / iTotal) * 100; pbImportacao.Position := dPos; pbImportacao.Refresh; end; Application.MessageBox('Importação Concluída!', 'Atenção', MB_OK + MB_ICONINFORMATION); end; end; finally FDQuery.Free; FEntregas.Free; FExtravios.Free; LimpaCampos; Modo(0); end; end; procedure Tview_ImportacaoPlanilhaExtravios.LimpaCampos; begin edtArquivo.Clear; datEvento.Clear; cboDescricaoExtravio.ItemIndex := -1; edtCodigoEntregador.EditValue := 0; pbImportacao.Position := 0; memObs.Clear; if Data_Sisgef.mtbImportacaoExtravios.Active then Data_Sisgef.mtbImportacaoExtravios.Close; end; procedure Tview_ImportacaoPlanilhaExtravios.LocalizaEntregadores; var aParam: array of Variant; FDQuery : TFDQuery; begin try FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; FEntregadores := TEntregadoresExpressasControl.Create; SetLength(aParam,3); aParam[0] := 'APOIO'; aParam[1] := 'COD_ENTREGADOR as Código, NOM_FANTASIA as Nome, COD_AGENTE as Base'; aparam[2] := ' WHERE COD_CADASTRO <> 0'; FDQuery := FEntregadores.Localizar(aParam); Finalize(aParam); if not Assigned(View_PesquisarPessoas) then begin View_PesquisarPessoas := TView_PesquisarPessoas.Create(Application); end; View_PesquisarPessoas.qryPesquisa.CreateFieldsFromDataSet(FDQuery); View_PesquisarPessoas.qryPesquisa.LoadFromDataSet(FDQuery); if not FDQuery.IsEmpty then View_PesquisarPessoas.qryPesquisa.First; FDQuery.Close; View_PesquisarPessoas.tvPesquisa.ClearItems; View_PesquisarPessoas.tvPesquisa.DataController.CreateAllItems; View_PesquisarPessoas.Caption := View_PesquisarPessoas.Caption + ' de Entregadores'; if View_PesquisarPessoas.ShowModal = mrOk then begin edtCodigoEntregador.EditValue := View_PesquisarPessoas.qryPesquisa.Fields[1].AsInteger; txtNomeEntregador.Text := View_PesquisarPessoas.qryPesquisa.Fields[2].AsString; iBase := View_PesquisarPessoas.qryPesquisa.Fields[3].AsInteger; end; finally FDQuery.Free; FEntregadores.Free; FreeAndNil(View_PesquisarPessoas); end; end; procedure Tview_ImportacaoPlanilhaExtravios.Modo(iTipo: Integer); begin if iTipo = 0 then begin dxLayoutItem9.Visible := False; actImportar.Enabled := True; end else begin dxLayoutItem9.Visible := True; actImportar.Enabled := False; end; end; function Tview_ImportacaoPlanilhaExtravios.ValidaImportacao: Boolean; begin Result := False; if edtArquivo.Text = '' then begin Application.MessageBox('Informe o arquivo da planilha!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if not FileExists(edtArquivo.Text) then begin Application.MessageBox('Arquivo informado não existe!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if datEvento.Date = 0 then begin Application.MessageBox('Informe a data do evento!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if cboDescricaoExtravio.Text = '' then begin Application.MessageBox('Informe a descrição ou motivo do extravio!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if StrToIntDef(edtCodigoEntregador.Text,0) = 0 then begin Application.MessageBox('Informe o código do entregador!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; Result := True; end; function Tview_ImportacaoPlanilhaExtravios.NomeEntregador(iCodigo: Integer): String; var aParam: array of Variant; FDQuery : TFDQuery; begin try Result := 'NONE'; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; FEntregadores := TEntregadoresExpressasControl.Create; SetLength(aParam,3); aParam[0] := 'ENTREGADOR'; aParam[1] := iCodigo; FDQuery := FEntregadores.Localizar(aParam); Finalize(aParam); if not FDQuery.IsEmpty then begin iBase := FDQuery.FieldByName('COD_AGENTE').AsInteger; Result := FDQuery.FieldByName('NOM_FANTASIA').AsString; end; FDQuery.Close; FEntregadores.Free; finally FDQuery.Free; end; end; end.
UNIT GetStringWord; INTERFACE USES ConstAndTypes; PROCEDURE GetWord(VAR Fin: TEXT; VAR SomeWord: WordString; VAR FindWord: BOOLEAN); {Считываем слово} IMPLEMENTATION FUNCTION NewWord(VAR Fin: TEXT): CHAR; VAR Ch: CHAR; BEGIN IF NOT((EOF(Fin))) THEN BEGIN READ(Fin, Ch); WHILE NOT(EOF(Fin)) AND NOT(Ch IN ValidAlphabet) DO READ(Fin, Ch) END; NewWord := Ch END; FUNCTION UpToLower(VAR Ch: CHAR): CHAR; BEGIN {Преобразуем символы верхнего регистра в нижний} IF (Ch IN Uppercase) THEN Ch := CHR(ORD(Ch) + ASCIIStep); {Заменяем Ё и ё на е} IF (Ch = 'Ё') OR (Ch = 'ё') THEN Ch := 'е'; UpToLower := Ch END; PROCEDURE GetWord(VAR Fin: TEXT; VAR SomeWord: WordString; VAR FindWord: BOOLEAN); VAR Ch: CHAR; BEGIN FindWord := FALSE; {Пропускаем все невалидные символы} Ch := NewWord(Fin); SomeWord := UpToLower(Ch); IF (Ch IN ValidAlphabet) THEN FindWord := TRUE; WHILE NOT(EOF(Fin)) AND (Ch IN ValidAlphabet) DO BEGIN {Посимвольно собираем слово, преобразуя символы верхнего регистра в нижний и заменяя Ё и ё на е} READ(Fin, Ch); IF (Ch IN ValidAlphabet) THEN SomeWord := SomeWord + UpToLower(Ch) END END; BEGIN {GetStringWord} END. {GetStringWord}
unit unitTrajectory; interface uses classes; type TTrajectory = class(TObject) private { Private declarations } public { Public declarations } points: TList; caption: string; trigger: String; nexttraj: String; width, height: integer; constructor Create(ncaption: String); end; implementation constructor TTrajectory.Create(ncaption: String); begin inherited Create; caption := ncaption; points := TList.Create; trigger:=''; nexttraj := ''; end; end.
unit GX_PerfectLayout; {$I GX_CondDefine.inc} interface uses Forms, StdCtrls, Controls, ExtCtrls, Classes, GX_BaseForm; type TfmPerfectLayout = class(TfmBaseForm) gbxLayout: TGroupBox; pnlLayout1: TPanel; shpMain1: TShape; shpOI1: TShape; shpEditor1: TShape; shpWatch1: TShape; lblWatch1: TLabel; lblMain1: TLabel; lblOI1: TLabel; lblEditor1: TLabel; pnlLayout2: TPanel; shpMain2: TShape; shpOI2: TShape; shpEditor2: TShape; shpWatch2: TShape; lblWatch2: TLabel; lblMain2: TLabel; lblOI2: TLabel; lblEditor2: TLabel; rbnLayout1: TRadioButton; rbnLayout2: TRadioButton; rbnCustom: TRadioButton; btnCustom: TButton; btnOK: TButton; btnCancel: TButton; btnHelp: TButton; procedure btnCustomClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); end; implementation {$R *.dfm} uses SysUtils, Windows, Menus, Dialogs, GX_Experts, GX_ConfigurationInfo, GX_GenericUtils, GX_IdeUtils, GX_GxUtils; type TLayoutType = (ltLayout1, ltLayout2, ltCustom); TLayoutExpert = class(TGX_Expert) private FLayoutType: TLayoutType; protected procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; class function FormsConfigurationKey: string; public constructor Create; override; function GetDefaultShortCut: TShortCut; override; function GetActionCaption: string; override; class function GetName: string; override; procedure Execute(Sender: TObject); override; procedure Configure; override; function IsDefaultActive: Boolean; override; property LayoutType: TLayoutType read FLayoutType write FLayoutType; end; function IsValidMoveableForm(const Form: TCustomForm; const AllowParented: Boolean): Boolean; begin Result := False; if (Form = nil) then Exit; // The OI can be repositioned when parented to a docking host in D4+ if (not AllowParented) and (Form.Parent <> nil) then Exit; // Don't save the state of the two GExperts configuration dialogs if (Form.Name = 'fmConfiguration') or (Form.Name = 'fmPerfectLayout') then Exit; // Don't save project forms or invisible forms if (Form.Designer <> nil) or (not Form.Visible) then Exit; Result := True; end; procedure TfmPerfectLayout.btnCustomClick(Sender: TObject); procedure SaveWindow(const Form: TForm; const Settings: TGExpertsSettings); begin Assert(Assigned(Form)); Assert(Assigned(Settings)); // Don't save the state of the two GExperts configuration dialogs if (Form.Name = 'fmConfiguration') or (Form.Name = 'fmPerfectLayout') then Exit; // Don't save project forms or invisible forms if (Form.Designer <> nil) or (not Form.Visible) then Exit; Settings.WriteInteger(Form.Name, 'Left', Form.Left); Settings.WriteInteger(Form.Name, 'Top', Form.Top); Settings.WriteInteger(Form.Name, 'Height', Form.Height); Settings.WriteInteger(Form.Name, 'Width', Form.Width); end; var Settings: TGExpertsSettings; i: Integer; AForm: TForm; Key: string; begin // Do not localize any of the items below Settings := TGExpertsSettings.Create; try Settings.DeleteKey(ConfigInfo.GExpertsIdeRootRegistryKey, TLayoutExpert.FormsConfigurationKey); finally FreeAndNil(Settings); end; Key := AddSlash(ConfigInfo.GExpertsIdeRootRegistryKey) + TLayoutExpert.FormsConfigurationKey; Settings := TGExpertsSettings.Create(Key); try for i := 0 to Screen.FormCount - 1 do begin AForm := Screen.Forms[i]; if IsValidMoveableForm(AForm, False) then SaveWindow(AForm, Settings); end; finally FreeAndNil(Settings); end; end; procedure TfmPerfectLayout.btnHelpClick(Sender: TObject); begin GxContextHelp(Self, 25); end; { TPerfectLayoutExpert } constructor TLayoutExpert.Create; begin inherited Create; end; function TLayoutExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Perfect La&yout'; begin Result := SMenuCaption; end; function TLayoutExpert.GetDefaultShortCut: TShortCut; begin Result := Menus.ShortCut(Word('L'), [ssCtrl, ssShift]); end; class function TLayoutExpert.GetName: string; begin Result := 'PerfectLayout'; // Do not localize. end; procedure TLayoutExpert.Execute(Sender: TObject); procedure LoadCustomLayout; procedure LoadWindow(const Form: TForm; const Settings: TGExpertsSettings); begin Assert(Assigned(Form)); Assert(Assigned(Settings)); Form.WindowState := wsNormal; // Do not localize any of the below items. Form.Left := Settings.ReadInteger(Form.Name, 'Left', Form.Left); Form.Top := Settings.ReadInteger(Form.Name, 'Top', Form.Top); Form.Height := Settings.ReadInteger(Form.Name, 'Height', Form.Height); Form.Width := Settings.ReadInteger(Form.Name, 'Width', Form.Width); end; var Settings: TGExpertsSettings; i: Integer; AForm: TForm; Key: string; begin Key := AddSlash(ConfigInfo.GExpertsIdeRootRegistryKey) + FormsConfigurationKey; Settings := TGExpertsSettings.Create(Key); try for i := 0 to Screen.FormCount - 1 do begin AForm := Screen.Forms[i]; if IsValidMoveableForm(AForm, False) then LoadWindow(AForm, Settings); end; finally FreeAndNil(Settings); end; end; function FindForm(const Name: string; AllowParented: Boolean): TForm; var App: TCustomForm; begin Result := Application.FindComponent(Name) as TForm; if Result = nil then begin App := GetIdeMainForm; if App <> nil then Result := App.FindComponent(Name) as TForm; end; if not IsValidMoveableForm(Result, AllowParented) then Result := nil; end; resourcestring SCouldNotFindAppBuilder = 'Could not find IDE AppBuilder window.'; var OI, Watch, Editor: TCustomForm; App: TCustomForm; Left, Width, Top, Bottom: Integer; R: TRect; begin if LayoutType = ltCustom then begin LoadCustomLayout; Exit; end; App := GetIdeMainForm; R := GetScreenWorkArea(App); if App = nil then begin MessageDlg(SCouldNotFindAppBuilder, mtError, [mbOK], 0); Exit; end; App.WindowState := wsNormal; App.SetBounds(R.Left, R.Top, R.Right-R.Left, App.Height); Top := R.Top + App.Height; Bottom := R.Bottom; Left := R.Left; Width := R.Right - R.Left; Watch := FindForm('WatchWindow', False); // Do not localize. if Watch <> nil then begin if Watch.Visible and Watch.Floating then begin Watch.WindowState := wsNormal; Watch.SetBounds(R.Left, R.Bottom - Watch.Height, R.Right - R.Left, Watch.Height); Bottom := Watch.Top; end; end; OI := FindForm('PropertyInspector', True); // Do not localize. if OI <> nil then begin // In case the OI is docked: if GetParentForm(OI) <> nil then OI := GetParentForm(OI); if OI <> App then begin // If the OI isn't docked into the main window OI.Top := Top; OI.Height := Bottom - Top; if LayoutType = ltLayout1 then begin OI.Left := R.Left; Left := OI.Left + OI.Width; end else begin OI.Left := R.Right - R.Left - OI.Width; Left := R.Left; end; Width := R.Right - R.Left - OI.Width; end; end; Editor := FindForm('EditWindow_0', False); // Do not localize. if Editor <> nil then begin Editor.WindowState := wsNormal; Editor.SetBounds(Left, Top, Width, Bottom - Top); end; end; procedure TLayoutExpert.InternalLoadSettings(Settings: TExpertSettings); begin inherited InternalLoadSettings(Settings); // Do not localize any of the below items FLayoutType := TLayoutType(Settings.ReadEnumerated('Layout', TypeInfo(TLayoutType), Ord(ltLayout1))); end; procedure TLayoutExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited InternalSaveSettings(Settings); // Do not localize any of the below items Settings.WriteEnumerated('Layout', TypeInfo(TLayoutType), Ord(FLayoutType)); end; procedure TLayoutExpert.Configure; var Dlg: TfmPerfectLayout; begin Dlg := TfmPerfectLayout.Create(nil); try Dlg.rbnLayout1.Checked := (FLayoutType = ltLayout1); Dlg.rbnLayout2.Checked := (FLayoutType = ltLayout2); Dlg.rbnCustom.Checked := (FLayoutType = ltCustom); if Dlg.ShowModal = mrOk then begin if Dlg.rbnLayout1.Checked then FLayoutType := ltLayout1 else if Dlg.rbnLayout2.Checked then FLayoutType := ltLayout2 else if Dlg.rbnCustom.Checked then FLayoutType := ltCustom; end; finally FreeAndNil(Dlg); end; end; function TLayoutExpert.IsDefaultActive: Boolean; begin Result := False; // Delphi 5+ provide more powerful saved desktops end; class function TLayoutExpert.FormsConfigurationKey: string; begin Result := AddSlash(ConfigurationKey) + 'Forms'; end; initialization RegisterGX_Expert(TLayoutExpert); end.
unit UFourSquareDemo; interface uses FMX.Forms, FMX.Messages, FMX.TMSCloudBase, FMX.TMSCloudFourSquare, FMX.Controls, FMX.TabControl, FMX.Objects, FMX.TMSCloudImage, FMX.Grid, FMX.Layouts, FMX.TMSCloudListView, UITypes, FMX.Edit, FMX.StdCtrls, System.Classes, FMX.Types, FMX.TreeView, FMX.Dialogs, SysUtils, UCategories, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomFourSquare, iOUtils; type TForm1 = class(TForm) StyleBook1: TStyleBook; Panel1: TPanel; btConnect: TButton; btRemove: TButton; Panel2: TPanel; GroupBox3: TGroupBox; Label2: TLabel; Label3: TLabel; Label1: TLabel; lbResult: TLabel; Label8: TLabel; lbCategories: TLabel; edKeyword: TEdit; edSearch: TEdit; btSearch: TButton; btCategories: TButton; btDelCat: TButton; lvResults: TTMSFMXCloudListView; GroupBox2: TGroupBox; lbUserName: TLabel; ciUser: TTMSFMXCloudImage; lbEmail: TLabel; lbCity: TLabel; lbGender: TLabel; lbBio: TLabel; lbPhone: TLabel; Label5: TLabel; Label7: TLabel; lbUserFriends: TLabel; lbUserCheckins: TLabel; btGetCheckIns: TButton; lvCheckIns: TTMSFMXCloudListView; Image1: TImage; GroupBox1: TGroupBox; lbPhotoCount: TLabel; TMSFMXCloudCloudImage1: TTMSFMXCloudImage; ciCategoryIcon: TTMSFMXCloudImage; lbVenueName: TLabel; lbVenueAddress: TLabel; Label4: TLabel; Label9: TLabel; Label10: TLabel; lbUsers: TLabel; lbCheckIns: TLabel; lbHereNow: TLabel; lbRating: TLabel; Label6: TLabel; lbWebsite: TLabel; PageControl1: TTabControl; TabSheet1: TTabItem; lvVenue: TTMSFMXCloudListView; TabSheet2: TTabItem; lvTips: TTMSFMXCloudListView; TabSheet3: TTabItem; lvSpecials: TTMSFMXCloudListView; btPrevImage: TButton; btNextImage: TButton; edCheckIn: TEdit; btSimilar: TButton; btPhotos: TButton; btTips: TButton; btCheckIn: TButton; btCategory: TButton; TMSFMXCloudFourSquare1: TTMSFMXCloudFourSquare; procedure btConnectClick(Sender: TObject); procedure btGetCheckInsClick(Sender: TObject); procedure btSearchClick(Sender: TObject); procedure btCheckInClick(Sender: TObject); procedure TTMSFMXCloudFourSquare1ReceivedAccessToken(Sender: TObject); procedure btTipsClick(Sender: TObject); procedure btPhotosClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btNextImageClick(Sender: TObject); procedure btPrevImageClick(Sender: TObject); procedure btSimilarClick(Sender: TObject); procedure btRemoveClick(Sender: TObject); procedure btCategoryClick(Sender: TObject); procedure btCategoriesClick(Sender: TObject); procedure btDelCatClick(Sender: TObject); procedure lbWebsiteClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lvResultsChange(Sender: TObject); private { Private declarations } public { Public declarations } Connected: boolean; VenueImage: integer; CategoryList: TStringList; CategoryIDList: TStringList; procedure ToggleControls; procedure FillUserProfile(Profile: TFourSquareUserProfile = nil); procedure GetVenues(CategoryID: string = ''); procedure FillTreeView(AtreeView: TTreeView); end; var Form1: TForm1; implementation {$R *.FMX} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // FourSquareAppkey = 'xxxxxxxxx'; // FourSquareAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm1.FillTreeView(ATreeView: TTreeView); procedure AddFolder(ParentNode: TTreeViewItem; Cats: TFourSquareCategories); var tn: TTreeViewItem; i: integer; begin for i := 0 to Cats.Count - 1 do begin tn := TTreeViewItem.Create(ParentNode); tn.TagString := Cats.Items[i].ID; tn.Text := Cats.Items[i].Summary; if Assigned(ParentNode) then ParentNode.AddObject(tn) else ATreeView.AddObject(tn); if Assigned(Cats.Items[i].SubCategories) then if (Cats.Items[i].SubCategories.Count > 0) then AddFolder(tn, Cats.Items[i].SubCategories); end; end; begin if Assigned(ATreeView) then begin ATreeView.Clear; AddFolder(nil, TMSFMXCloudFourSquare1.Categories); if ATreeView.Count > 0 then begin ATreeView.Selected := ATreeView.Items[0]; end; end; end; procedure TForm1.TTMSFMXCloudFourSquare1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudFourSquare1.SaveTokens; Connected := true; ToggleControls; end; procedure TForm1.btConnectClick(Sender: TObject); var acc: boolean; begin TMSFMXCloudFourSquare1.OnReceivedAccessToken := TTMSFMXCloudFourSquare1ReceivedAccessToken; TMSFMXCloudFourSquare1.App.Key := FourSquare_AppKey; TMSFMXCloudFourSquare1.App.Secret := FourSquare_AppSecret; if TMSFMXCloudFourSquare1.App.Key <> '' then begin TMSFMXCloudFourSquare1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'foursquare.ini'; TMSFMXCloudFourSquare1.PersistTokens.Section := 'tokens'; TMSFMXCloudFourSquare1.LoadTokens; acc := TMSFMXCloudFourSquare1.TestTokens; if not acc then begin TMSFMXCloudFourSquare1.RefreshAccess; acc := TMSFMXCloudFourSquare1.TestTokens; if not acc then TMSFMXCloudFourSquare1.DoAuth; end else begin Connected := true; ToggleControls; end; if Connected then FillUserProfile; end else ShowMessage('Please provide a valid application ID for the client component'); end; procedure TForm1.btGetCheckInsClick(Sender: TObject); var I: integer; li: TListItem; begin TMSFMXCloudFourSquare1.GetCheckIns; lvCheckIns.Items.Clear; for I := 0 to TMSFMXCloudFourSquare1.UserProfile.CheckIns.Count - 1 do begin li := lvCheckIns.Items.Add; li.Text := TMSFMXCloudFourSquare1.UserProfile.CheckIns[I].Venue.Summary; li.SubItems.Add(DateToStr(TMSFMXCloudFourSquare1.UserProfile.CheckIns[I].Created)); li.SubItems.Add(TMSFMXCloudFourSquare1.UserProfile.CheckIns[I].Comment); end; end; procedure TForm1.btNextImageClick(Sender: TObject); begin VenueImage := VenueImage + 1; if TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos.Count > VenueImage then begin TMSFMXCloudCloudImage1.URL := TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos[VenueImage].ImageURL; lbPhotoCount.Text := IntToStr(VenueImage+1) + '/' + IntToStr(TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos.Count); end; end; procedure TForm1.FillUserProfile(Profile: TFourSquareUserProfile); begin if Profile = nil then Profile := TMSFMXCloudFourSquare1.UserProfile; TMSFMXCloudFourSquare1.GetUserProfile(Profile); lbUserName.Text := Profile.FirstName + ' ' + Profile.LastName; lbEmail.Text := Profile.Email; lbCity.Text := Profile.HomeCity; lbBio.Text := Profile.Bio; lbPhone.Text := Profile.PhoneNumber; lbUserFriends.Text := IntToStr(Profile.FriendsCount); lbUserCheckins.Text := IntToStr(Profile.CheckInsCount); ciUser.URL := Profile.ImageURL; if Profile.Gender = fgFemale then lbGender.Text := 'Female' else if Profile.Gender = fgMale then lbGender.Text := 'Male' else lbGender.Text := ''; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin CategoryList.Free; CategoryIDList.Free; end; procedure TForm1.FormCreate(Sender: TObject); begin VenueImage := -1; ToggleControls; CategoryList := TStringList.Create; CategoryIDList := TStringList.Create; lvResults.ColumnByIndex(1).Width := 300; end; procedure TForm1.GetVenues(CategoryID: string); var I: integer; err: string; li: TListItem; begin if (edSearch.Text <> EmptyStr) or (edKeyword.Text <> EmptyStr) then begin err := TMSFMXCloudFourSquare1.GetNearbyVenues(0, 0, edSearch.Text, edKeyword.Text, CategoryID, 20); if err <> EmptyStr then ShowMessage(err) else begin lbResult.Text := TMSFMXCloudFourSquare1.Location.Summary + ', ' + TMSFMXCloudFourSquare1.Location.CountryCode; lvResults.Items.Clear; for I := 0 to TMSFMXCloudFourSquare1.Venues.Count - 1 do begin li := lvResults.Items.Add; li.Text := TMSFMXCloudFourSquare1.Venues[I].Summary; li.SubItems.Add(TMSFMXCloudFourSquare1.Venues[I].Address); end; end; end; end; procedure TForm1.lbWebsiteClick(Sender: TObject); begin if (Connected) and (lbwebsite.Text <> EmptyStr) then ShowMessage(lbwebsite.Text); end; procedure TForm1.lvResultsChange(Sender: TObject); var fv: TFourSquareVenue; i: integer; li: TListItem; hours: string; begin lvTips.Items.Clear; if lvResults.ItemIndex >= 0 then begin TMSFMXCloudCloudImage1.URL := ''; lbPhotoCount.Text := '0/0'; fv := TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex]; TMSFMXCloudFourSquare1.GetVenue(fv); lbRating.Text := FloatToStr(fv.Rating); lbVenueName.Text := fv.Summary; lbVenueAddress.Text := fv.Address; hours := fv.Hours.Status; if fv.Hours.IsOpen = fiOpen then hours := hours + ' (Open)' else if fv.Hours.IsOpen = fiClosed then hours := hours + ' (Closed)'; if fv.CrossStreet <> '' then lbVenueAddress.Text := lbVenueAddress.Text + ' (' + fv.CrossStreet + ')'; lbCheckIns.Text := IntToStr(fv.CheckInsCount); lbUsers.Text := IntToStr(fv.UsersCount); lbWebsite.Text := fv.Website; lbHereNow.Text := IntToStr(fv.HereNowCount); lvVenue.Items[0].Text := hours; lvVenue.Items[0].SubItems[0] := fv.City; lvVenue.Items[0].SubItems[1] := fv.PostalCode; lvVenue.Items[0].SubItems[2] := fv.Country; lvVenue.Items[0].SubItems[3] := fv.Phone; PageControl1.Tabs[1].Text := 'Tips (' + IntToStr(fv.TipCount) + ')'; PageControl1.Tabs[2].Text := 'Specials (' + IntToStr(fv.Specials.Count) + ')'; if fv.Categories.Count > 0 then begin ciCategoryIcon.URL := fv.Categories[0].IconURL; lvVenue.Items[0].SubItems[4] := fv.Categories[0].Summary; end; VenueImage := 0; if fv.Photos.Count > 0 then begin TMSFMXCloudCloudImage1.URL := fv.Photos[0].ImageURL; lbPhotoCount.Text := IntToStr(VenueImage+1) + '/' + IntToStr(fv.Photos.Count); end; lvSpecials.Items.Clear; for I := 0 to fv.Specials.Count - 1 do begin li := lvSpecials.Items.Add; li.Text := fv.Specials[I].Title; li.SubItems.Add(fv.Specials[I].Summary); end; end; end; procedure TForm1.btCategoriesClick(Sender: TObject); var F: TForm2; begin if TMSFMXCloudFourSquare1.Categories.Count = 0 then TMSFMXCloudFourSquare1.GetCategories; F := TForm2.Create(Self); FillTreeView(F.TreeView1); if F.ShowModal = mrOk then begin if Assigned(F.TreeView1.Selected) then begin CategoryList.Add(TFourSquareCategoryItem(F.TreeView1.Selected.Data.AsObject).Summary); CategoryIDList.Add(TFourSquareCategoryItem(F.TreeView1.Selected.Data.AsObject).ID); lbCategories.Text := StringReplace(CategoryList.CommaText, '&', '&&', [rfReplaceAll]); end; end; F.Release; end; procedure TForm1.btCategoryClick(Sender: TObject); begin if lvResults.ItemIndex >= 0 then begin GetVenues(TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Categories[0].ID); end; end; procedure TForm1.btCheckInClick(Sender: TObject); begin if lvResults.ItemIndex >= 0 then TMSFMXCloudFourSquare1.CheckIn(TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].ID, edCheckIn.Text); end; procedure TForm1.btDelCatClick(Sender: TObject); begin if CategoryList.Count > 0 then begin CategoryList.Delete(CategoryList.Count - 1); CategoryIDList.Delete(CategoryIDList.Count - 1); lbCategories.Text := StringReplace(CategoryList.CommaText, '&', '&&', [rfReplaceAll]); end; end; procedure TForm1.btPhotosClick(Sender: TObject); begin if (lvResults.ItemIndex >= 0) then begin TMSFMXCloudFourSquare1.GetPhotos(TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex], 50); VenueImage := 0; if TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos.Count > 0 then begin TMSFMXCloudCloudImage1.URL := TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos[0].ImageURL; lbPhotoCount.Text := IntToStr(VenueImage+1) + '/' + IntToStr(TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos.Count); end; end; end; procedure TForm1.btPrevImageClick(Sender: TObject); begin VenueImage := VenueImage - 1; if (TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos.Count > VenueImage) and (VenueImage >= 0) then begin TMSFMXCloudCloudImage1.URL := TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos[VenueImage].ImageURL; lbPhotoCount.Text := IntToStr(VenueImage+1) + '/' + IntToStr(TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].Photos.Count); end; end; procedure TForm1.btRemoveClick(Sender: TObject); begin TMSFMXCloudFourSquare1.ClearTokens; Connected := false; ToggleControls; end; procedure TForm1.btSearchClick(Sender: TObject); begin GetVenues(CategoryIDList.CommaText); end; procedure TForm1.btSimilarClick(Sender: TObject); var I: integer; li: TListItem; begin if lvResults.ItemIndex >= 0 then begin TMSFMXCloudFourSquare1.GetSimilarVenues(TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex].ID); lvResults.Items.Clear; for I := 0 to TMSFMXCloudFourSquare1.Venues.Count - 1 do begin li := lvResults.Items.Add; li.Text := TMSFMXCloudFourSquare1.Venues[I].Summary; li.SubItems.Add(TMSFMXCloudFourSquare1.Venues[I].Address); end; end; end; procedure TForm1.btTipsClick(Sender: TObject); var I: Integer; li: TListItem; item: TFourSquareVenue; begin PageControl1.TabIndex := 1; if (PageControl1.TabIndex = 1) and (lvResults.ItemIndex >= 0) then begin item := TMSFMXCloudFourSquare1.Venues[lvResults.ItemIndex]; if (item.TipCount > 0) and (item.Tips.Count = 0 )then begin TMSFMXCloudFourSquare1.GetTips(item); for I := 0 to item.Tips.Count - 1 do begin li := lvTips.Items.Add; li.Text := item.Tips[I].Summary; li.SubItems.Add(DateToStr(item.Tips[I].Created)); li.SubItems.Add(item.Tips[I].User.FirstName + ' ' + item.Tips[I].User.LastName); li.SubItems.Add(IntToStr(item.Tips[I].LikesCount)); li.SubItems.Add(BoolToStr(item.Tips[I].Liked)); end; end; end; end; procedure TForm1.ToggleControls; begin btConnect.Enabled := not connected; btRemove.Enabled := connected; edKeyword.Enabled := connected; edSearch.Enabled := connected; btSearch.Enabled := connected; btPrevImage.Enabled := connected; btNextImage.Enabled := connected; btSimilar.Enabled := connected; btPhotos.Enabled := connected; btTips.Enabled := connected; btCheckIn.Enabled := connected; edCheckIn.Enabled := connected; PageControl1.Enabled := connected; lvVenue.Enabled := connected; btCategory.Enabled := connected; btCategories.Enabled := connected; btDelCat.Enabled := connected; btGetCheckIns.Enabled := connected; lvResults.Enabled := connected; lbWebsite.Enabled := connected; end; end.
unit ChangesBetweenEditonsKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы ChangesBetweenEditons } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\ChangesBetweenEditons\ChangesBetweenEditonsKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ChangesBetweenEditonsKeywordsPack" MUID: (B796AE5D8508) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses {$If Defined(Nemesis)} , nscEditor {$IfEnd} // Defined(Nemesis) ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , ChangesBetweenEditons_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy {$If Defined(Nemesis)} , nscTextSource {$IfEnd} // Defined(Nemesis) , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_ChangesBetweenEditons = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы ChangesBetweenEditons ---- *Пример использования*: [code] 'aControl' форма::ChangesBetweenEditons TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_ChangesBetweenEditons Tkw_ChangesBetweenEditons_Control_Text = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола Text ---- *Пример использования*: [code] контрол::Text TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChangesBetweenEditons_Control_Text Tkw_ChangesBetweenEditons_Control_Text_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола Text ---- *Пример использования*: [code] контрол::Text:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChangesBetweenEditons_Control_Text_Push Tkw_ChangesBetweenEditons_Component_TextSource = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола TextSource ---- *Пример использования*: [code] компонент::TextSource TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChangesBetweenEditons_Component_TextSource TkwChangesBetweenEditonsFormText = {final} class(TtfwPropertyLike) {* Слово скрипта .TChangesBetweenEditonsForm.Text } private function Text(const aCtx: TtfwContext; aChangesBetweenEditonsForm: TChangesBetweenEditonsForm): TnscEditor; {* Реализация слова скрипта .TChangesBetweenEditonsForm.Text } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwChangesBetweenEditonsFormText function Tkw_Form_ChangesBetweenEditons.GetString: AnsiString; begin Result := 'ChangesBetweenEditonsForm'; end;//Tkw_Form_ChangesBetweenEditons.GetString class function Tkw_Form_ChangesBetweenEditons.GetWordNameForRegister: AnsiString; begin Result := 'форма::ChangesBetweenEditons'; end;//Tkw_Form_ChangesBetweenEditons.GetWordNameForRegister function Tkw_ChangesBetweenEditons_Control_Text.GetString: AnsiString; begin Result := 'Text'; end;//Tkw_ChangesBetweenEditons_Control_Text.GetString class procedure Tkw_ChangesBetweenEditons_Control_Text.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscEditor); end;//Tkw_ChangesBetweenEditons_Control_Text.RegisterInEngine class function Tkw_ChangesBetweenEditons_Control_Text.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Text'; end;//Tkw_ChangesBetweenEditons_Control_Text.GetWordNameForRegister procedure Tkw_ChangesBetweenEditons_Control_Text_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('Text'); inherited; end;//Tkw_ChangesBetweenEditons_Control_Text_Push.DoDoIt class function Tkw_ChangesBetweenEditons_Control_Text_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Text:push'; end;//Tkw_ChangesBetweenEditons_Control_Text_Push.GetWordNameForRegister function Tkw_ChangesBetweenEditons_Component_TextSource.GetString: AnsiString; begin Result := 'TextSource'; end;//Tkw_ChangesBetweenEditons_Component_TextSource.GetString class procedure Tkw_ChangesBetweenEditons_Component_TextSource.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscTextSource); end;//Tkw_ChangesBetweenEditons_Component_TextSource.RegisterInEngine class function Tkw_ChangesBetweenEditons_Component_TextSource.GetWordNameForRegister: AnsiString; begin Result := 'компонент::TextSource'; end;//Tkw_ChangesBetweenEditons_Component_TextSource.GetWordNameForRegister function TkwChangesBetweenEditonsFormText.Text(const aCtx: TtfwContext; aChangesBetweenEditonsForm: TChangesBetweenEditonsForm): TnscEditor; {* Реализация слова скрипта .TChangesBetweenEditonsForm.Text } begin Result := aChangesBetweenEditonsForm.Text; end;//TkwChangesBetweenEditonsFormText.Text class function TkwChangesBetweenEditonsFormText.GetWordNameForRegister: AnsiString; begin Result := '.TChangesBetweenEditonsForm.Text'; end;//TkwChangesBetweenEditonsFormText.GetWordNameForRegister function TkwChangesBetweenEditonsFormText.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscEditor); end;//TkwChangesBetweenEditonsFormText.GetResultTypeInfo function TkwChangesBetweenEditonsFormText.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwChangesBetweenEditonsFormText.GetAllParamsCount function TkwChangesBetweenEditonsFormText.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TChangesBetweenEditonsForm)]); end;//TkwChangesBetweenEditonsFormText.ParamsTypes procedure TkwChangesBetweenEditonsFormText.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Text', aCtx); end;//TkwChangesBetweenEditonsFormText.SetValuePrim procedure TkwChangesBetweenEditonsFormText.DoDoIt(const aCtx: TtfwContext); var l_aChangesBetweenEditonsForm: TChangesBetweenEditonsForm; begin try l_aChangesBetweenEditonsForm := TChangesBetweenEditonsForm(aCtx.rEngine.PopObjAs(TChangesBetweenEditonsForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aChangesBetweenEditonsForm: TChangesBetweenEditonsForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Text(aCtx, l_aChangesBetweenEditonsForm)); end;//TkwChangesBetweenEditonsFormText.DoDoIt initialization Tkw_Form_ChangesBetweenEditons.RegisterInEngine; {* Регистрация Tkw_Form_ChangesBetweenEditons } Tkw_ChangesBetweenEditons_Control_Text.RegisterInEngine; {* Регистрация Tkw_ChangesBetweenEditons_Control_Text } Tkw_ChangesBetweenEditons_Control_Text_Push.RegisterInEngine; {* Регистрация Tkw_ChangesBetweenEditons_Control_Text_Push } Tkw_ChangesBetweenEditons_Component_TextSource.RegisterInEngine; {* Регистрация Tkw_ChangesBetweenEditons_Component_TextSource } TkwChangesBetweenEditonsFormText.RegisterInEngine; {* Регистрация ChangesBetweenEditonsForm_Text } TtfwTypeRegistrator.RegisterType(TypeInfo(TChangesBetweenEditonsForm)); {* Регистрация типа TChangesBetweenEditonsForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscEditor)); {* Регистрация типа TnscEditor } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
unit uCadastros; interface uses uEnun; type TPessoa = class(TObject) private FBairro: string; FUF: string; FCodigo: Integer; FTelefone1: string; FNome: string; FTipo: Integer; FCidade: string; FEndereco: string; FData: TDateTime; FTelefone: string; procedure SetBairro(const Value: string); procedure SetCidade(const Value: string); procedure SetCodigo(const Value: Integer); procedure SetData(const Value: TDateTime); procedure SetEndereco(const Value: string); procedure SetNome(const Value: string); procedure SetTelefone(const Value: string); procedure SetTelefone1(const Value: string); procedure SetTipo(const Value: Integer); procedure SetUF(const Value: string); public property Codigo : Integer read FCodigo write SetCodigo; property Nome : string read FNome write SetNome; property Endereco : string read FEndereco write SetEndereco; property Cidade : string read FCidade write SetCidade; property Bairro : string read FBairro write SetBairro; property UF : string read FUF write SetUF; property Telefone : string read FTelefone write SetTelefone; property Telefone1 : string read FTelefone1 write SetTelefone1; property Data : TDateTime read FData write SetData; property Tipo : Integer read FTipo write SetTipo; constructor Create; destructor Destroy; override; end; TFuncionario = class(TPessoa) private public constructor Create(AOwner: TPessoa); destructor Destroy; override; end; TCliente = class(TPessoa) private FCPF: string; FVeiculo: TVeiculo; procedure SetCPF(const Value: string); procedure SetVeiculo(const Value: TVeiculo); public property CPF : string read FCPF write SetCPF; property Veiculo : TVeiculo read FVeiculo write SetVeiculo; constructor Create(AOwner: TPessoa); destructor Destroy; override; end; TForncedor = class(TPessoa) private FCNPJ: string; FRazaoSocial: string; FNomeFantasia: string; procedure SetCNPJ(const Value: string); procedure SetNomeFantasia(const Value: string); procedure SetRazaoSocial(const Value: string); public property CNPJ : string read FCNPJ write SetCNPJ; property RazaoSocial : string read FRazaoSocial write SetRazaoSocial; property NomeFantasia : string read FNomeFantasia write SetNomeFantasia; constructor Create(AOwner: TPessoa); destructor Destroy; override; end; implementation { TForncedor } { TForncedor } constructor TForncedor.Create(AOwner: TPessoa); begin Self.Create(TPessoa.Create); end; destructor TForncedor.Destroy; begin inherited; end; procedure TForncedor.SetCNPJ(const Value: string); begin FCNPJ := Value; end; procedure TForncedor.SetNomeFantasia(const Value: string); begin FNomeFantasia := Value; end; procedure TForncedor.SetRazaoSocial(const Value: string); begin FRazaoSocial := Value; end; { TCliente } constructor TCliente.Create(AOwner: TPessoa); begin Self.Create(TPessoa.Create); end; destructor TCliente.Destroy; begin inherited; end; procedure TCliente.SetCPF(const Value: string); begin FCPF := Value; end; procedure TCliente.SetVeiculo(const Value: TVeiculo); begin FVeiculo := Value; end; { TFuncionario } constructor TFuncionario.Create(AOwner: TPessoa); begin Self.Create(TPessoa.Create); end; destructor TFuncionario.Destroy; begin inherited; end; { TPessoa } constructor TPessoa.Create; begin Self.Create; end; destructor TPessoa.Destroy; begin inherited; end; procedure TPessoa.SetBairro(const Value: string); begin FBairro := Value; end; procedure TPessoa.SetCidade(const Value: string); begin FCidade := Value; end; procedure TPessoa.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TPessoa.SetData(const Value: TDateTime); begin FData := Value; end; procedure TPessoa.SetEndereco(const Value: string); begin FEndereco := Value; end; procedure TPessoa.SetNome(const Value: string); begin FNome := Value; end; procedure TPessoa.SetTelefone(const Value: string); begin FTelefone := Value; end; procedure TPessoa.SetTelefone1(const Value: string); begin FTelefone1 := Value; end; procedure TPessoa.SetTipo(const Value: Integer); begin FTipo := Value; end; procedure TPessoa.SetUF(const Value: string); begin FUF := Value; end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type DateTimeTest = public class (Test) private Data: DateTime; method AreEqual(Expected, Actual: DateTime); method AssertFormat(Expected: String; Date: DateTime; Locale: String; Format: String); method AssertFormat(Expected: String; Date: DateTime; Format: String); method AssertFormatDef(Expected: String; Locale: String; Format: String); method AssertFormatDef(Expected: String; Format: String); public method Setup; override; method AddDays; method AddHours; method AddMinutes; method AddMonths; method AddSeconds; method AddYears; method CompareTo; method Ticks; //Formats method FormatYears; method FormatMonths; method FormatDays; method FormatHours; method FormatMinutesSeconds; method ToStringFormat; //fields method Fields; end; implementation method DateTimeTest.Setup; begin Data := new DateTime(1961, 4, 12, 6, 7, 0); end; method DateTimeTest.AreEqual(Expected: DateTime; Actual: DateTime); begin Assert.AreEqual(Actual.Year, Expected.Year); Assert.AreEqual(Actual.Month, Expected.Month); Assert.AreEqual(Actual.Day, Expected.Day); Assert.AreEqual(Actual.Hour, Expected.Hour); Assert.AreEqual(Actual.Minute, Expected.Minute); Assert.AreEqual(Actual.Second, Expected.Second); end; method DateTimeTest.AssertFormat(Expected: String; Date: DateTime; Locale: String; Format: String); begin Assert.AreEqual(Date.ToString(Format, Locale), Expected); end; method DateTimeTest.AssertFormat(Expected: String; Date: DateTime; Format: String); begin AssertFormat(Expected, Date, nil, Format); end; method DateTimeTest.AssertFormatDef(Expected: String; Locale: String; Format: String); begin AssertFormat(Expected, Data, Locale, Format); end; method DateTimeTest.AssertFormatDef(Expected: String; Format: String); begin AssertFormat(Expected, Data, Format); end; method DateTimeTest.AddDays; begin var Value := Data.AddDays(1); Assert.AreEqual(Value.Day, 13); Value := Data.AddDays(-1); Assert.AreEqual(Value.Day, 11); Value := Data.AddDays(19); //next month Assert.AreEqual(Value.Day, 1); Assert.AreEqual(Value.Month, 5); end; method DateTimeTest.AddHours; begin var Value := Data.AddHours(1); Assert.AreEqual(Value.Hour, 7); Value := Data.AddHours(-1); Assert.AreEqual(Value.Hour, 5); Value := Data.AddHours(19); //next day Assert.AreEqual(Value.Day, 13); Assert.AreEqual(Value.Hour, 1); end; method DateTimeTest.AddMinutes; begin var Value := Data.AddMinutes(1); Assert.AreEqual(Value.Minute, 8); Value := Data.AddMinutes(-1); Assert.AreEqual(Value.Minute, 6); Value := Data.AddMinutes(53); //next hour Assert.AreEqual(Value.Minute, 0); Assert.AreEqual(Value.Hour, 7); end; method DateTimeTest.AddMonths; begin var Value := Data.AddMonths(1); Assert.AreEqual(Value.Month, 5); Value := Data.AddMonths(-1); Assert.AreEqual(Value.Month, 3); Value := Data.AddMonths(9); //next year Assert.AreEqual(Value.Month, 1); Assert.AreEqual(Value.Year, 1962); end; method DateTimeTest.AddSeconds; begin var Value := Data.AddSeconds(1); Assert.AreEqual(Value.Second, 1); Value := Data.AddSeconds(-1); Assert.AreEqual(Value.Second, 59); Value := Data.AddSeconds(60); //next year Assert.AreEqual(Value.Second, 0); Assert.AreEqual(Value.Minute, 8); end; method DateTimeTest.AddYears; begin var Value := Data.AddYears(1); Assert.AreEqual(Value.Year, 1962); Value := Data.AddYears(-1); Assert.AreEqual(Value.Year, 1960); end; method DateTimeTest.CompareTo; begin Assert.AreEqual(Data.CompareTo(Data), 0); Assert.IsTrue(Data.CompareTo(Data.AddDays(10)) <> 0); Assert.AreEqual(Data.CompareTo(new DateTime(1961, 4, 12, 6, 7, 0)), 0); end; method DateTimeTest.FormatYears; begin //single digit not supported Assert.Throws(->Data.ToString("{y}")); Assert.Throws(->Data.ToString("{yyy}")); AssertFormatDef("61", "{yy}"); AssertFormatDef("1961", "{yyyy}"); AssertFormat("05", new DateTime(5, 1, 1), "{yy}"); AssertFormat("0005", new DateTime(5, 1, 1), "{yyyy}"); AssertFormat("25", new DateTime(25, 1, 1), "{yy}"); AssertFormat("0025", new DateTime(25, 1, 1), "{yyyy}"); AssertFormat("25", new DateTime(325, 1, 1), "{yy}"); AssertFormat("0325", new DateTime(325, 1, 1), "{yyyy}"); AssertFormat("05", new DateTime(2305, 1, 1), "{yy}"); AssertFormat("2305", new DateTime(2305, 1, 1), "{yyyy}"); end; method DateTimeTest.FormatMonths; begin AssertFormatDef("4", "{M}"); AssertFormatDef("04", "{MM}"); AssertFormat("1", new DateTime(1,1,1), "{M}"); AssertFormat("01", new DateTime(1,1,1), "{MM}"); //short AssertFormat("Jan", new DateTime(1, 1, 1), "en-US", "{MMM}"); AssertFormat("Feb", new DateTime(1, 2, 1), "en-US", "{MMM}"); AssertFormat("Mar", new DateTime(1, 3, 1), "en-US", "{MMM}"); AssertFormat("Apr", new DateTime(1, 4, 1), "en-US", "{MMM}"); AssertFormat("May", new DateTime(1, 5, 1), "en-US", "{MMM}"); AssertFormat("Jun", new DateTime(1, 6, 1), "en-US", "{MMM}"); AssertFormat("Jul", new DateTime(1, 7, 1), "en-US", "{MMM}"); AssertFormat("Aug", new DateTime(1, 8, 1), "en-US", "{MMM}"); AssertFormat("Sep", new DateTime(1, 9, 1), "en-US", "{MMM}"); AssertFormat("Oct", new DateTime(1, 10, 1), "en-US", "{MMM}"); AssertFormat("Nov", new DateTime(1, 11, 1), "en-US", "{MMM}"); AssertFormat("Dec", new DateTime(1, 12, 1), "en-US", "{MMM}"); AssertFormat("janv.", new DateTime(1, 1, 1), "fr-FR", "{MMM}"); AssertFormat("févr.", new DateTime(1, 2, 1), "fr-FR", "{MMM}"); AssertFormat("mars", new DateTime(1, 3, 1), "fr-FR", "{MMM}"); AssertFormat("avr.", new DateTime(1, 4, 1), "fr-FR", "{MMM}"); AssertFormat("mai", new DateTime(1, 5, 1), "fr-FR", "{MMM}"); AssertFormat("juin", new DateTime(1, 6, 1), "fr-FR", "{MMM}"); AssertFormat("juil.", new DateTime(1, 7, 1), "fr-FR", "{MMM}"); AssertFormat("août", new DateTime(1, 8, 1), "fr-FR", "{MMM}"); AssertFormat("sept.", new DateTime(1, 9, 1), "fr-FR", "{MMM}"); AssertFormat("oct.", new DateTime(1, 10, 1), "fr-FR", "{MMM}"); AssertFormat("nov.", new DateTime(1, 11, 1), "fr-FR", "{MMM}"); AssertFormat("déc.", new DateTime(1, 12, 1), "fr-FR", "{MMM}"); //long AssertFormat("January", new DateTime(1, 1, 1), "en-US", "{MMMM}"); AssertFormat("February", new DateTime(1, 2, 1), "en-US", "{MMMM}"); AssertFormat("March", new DateTime(1, 3, 1), "en-US", "{MMMM}"); AssertFormat("April", new DateTime(1, 4, 1), "en-US", "{MMMM}"); AssertFormat("May", new DateTime(1, 5, 1), "en-US", "{MMMM}"); AssertFormat("June", new DateTime(1, 6, 1), "en-US", "{MMMM}"); AssertFormat("July", new DateTime(1, 7, 1), "en-US", "{MMMM}"); AssertFormat("August", new DateTime(1, 8, 1), "en-US", "{MMMM}"); AssertFormat("September", new DateTime(1, 9, 1), "en-US", "{MMMM}"); AssertFormat("October", new DateTime(1, 10, 1), "en-US", "{MMMM}"); AssertFormat("November", new DateTime(1, 11, 1), "en-US", "{MMMM}"); AssertFormat("December", new DateTime(1, 12, 1), "en-US", "{MMMM}"); AssertFormat("janvier", new DateTime(1, 1, 1), "fr-FR", "{MMMM}"); AssertFormat("février", new DateTime(1, 2, 1), "fr-FR", "{MMMM}"); AssertFormat("mars", new DateTime(1, 3, 1), "fr-FR", "{MMMM}"); AssertFormat("avril", new DateTime(1, 4, 1), "fr-FR", "{MMMM}"); AssertFormat("mai", new DateTime(1, 5, 1), "fr-FR", "{MMMM}"); AssertFormat("juin", new DateTime(1, 6, 1), "fr-FR", "{MMMM}"); AssertFormat("juillet", new DateTime(1, 7, 1), "fr-FR", "{MMMM}"); AssertFormat("août", new DateTime(1, 8, 1), "fr-FR", "{MMMM}"); AssertFormat("septembre", new DateTime(1, 9, 1), "fr-FR", "{MMMM}"); AssertFormat("octobre", new DateTime(1, 10, 1), "fr-FR", "{MMMM}"); AssertFormat("novembre", new DateTime(1, 11, 1), "fr-FR", "{MMMM}"); AssertFormat("décembre", new DateTime(1, 12, 1), "fr-FR", "{MMMM}"); end; method DateTimeTest.FormatDays; begin AssertFormatDef("12", "{d}"); AssertFormatDef("12", "{dd}"); AssertFormat("5", new DateTime(1, 1, 5), "{d}"); AssertFormat("05", new DateTime(1, 1, 5), "{dd}"); //short AssertFormat("Mon", new DateTime(2013, 7, 1), "en-US", "{ddd}"); AssertFormat("Tue", new DateTime(2013, 7, 2), "en-US", "{ddd}"); AssertFormat("Wed", new DateTime(2013, 7, 3), "en-US", "{ddd}"); AssertFormat("Thu", new DateTime(2013, 7, 4), "en-US", "{ddd}"); AssertFormat("Fri", new DateTime(2013, 7, 5), "en-US", "{ddd}"); AssertFormat("Sat", new DateTime(2013, 7, 6), "en-US", "{ddd}"); AssertFormat("Sun", new DateTime(2013, 7, 7), "en-US", "{ddd}"); AssertFormat("lun.", new DateTime(2013, 7, 1), "fr-FR", "{ddd}"); AssertFormat("mar.", new DateTime(2013, 7, 2), "fr-FR", "{ddd}"); AssertFormat("mer.", new DateTime(2013, 7, 3), "fr-FR", "{ddd}"); AssertFormat("jeu.", new DateTime(2013, 7, 4), "fr-FR", "{ddd}"); AssertFormat("ven.", new DateTime(2013, 7, 5), "fr-FR", "{ddd}"); AssertFormat("sam.", new DateTime(2013, 7, 6), "fr-FR", "{ddd}"); AssertFormat("dim.", new DateTime(2013, 7, 7), "fr-FR", "{ddd}"); //long AssertFormat("Monday", new DateTime(2013, 7, 1), "en-US", "{dddd}"); AssertFormat("Tuesday", new DateTime(2013, 7, 2), "en-US", "{dddd}"); AssertFormat("Wednesday", new DateTime(2013, 7, 3), "en-US", "{dddd}"); AssertFormat("Thursday", new DateTime(2013, 7, 4), "en-US", "{dddd}"); AssertFormat("Friday", new DateTime(2013, 7, 5), "en-US", "{dddd}"); AssertFormat("Saturday", new DateTime(2013, 7, 6), "en-US", "{dddd}"); AssertFormat("Sunday", new DateTime(2013, 7, 7), "en-US", "{dddd}"); AssertFormat("lundi", new DateTime(2013, 7, 1), "fr-FR", "{dddd}"); AssertFormat("mardi", new DateTime(2013, 7, 2), "fr-FR", "{dddd}"); AssertFormat("mercredi", new DateTime(2013, 7, 3), "fr-FR", "{dddd}"); AssertFormat("jeudi", new DateTime(2013, 7, 4), "fr-FR", "{dddd}"); AssertFormat("vendredi", new DateTime(2013, 7, 5), "fr-FR", "{dddd}"); AssertFormat("samedi", new DateTime(2013, 7, 6), "fr-FR", "{dddd}"); AssertFormat("dimanche", new DateTime(2013, 7, 7), "fr-FR", "{dddd}"); end; method DateTimeTest.FormatHours; begin AssertFormatDef("6", "{h}"); AssertFormatDef("6", "{H}"); //1-12 AssertFormat("1", new DateTime(1, 1, 1, 1, 0, 0), "{h}"); AssertFormat("01", new DateTime(1, 1, 1, 1, 0, 0), "{hh}"); AssertFormat("12", new DateTime(1, 1, 1, 12, 0, 0), "{h}"); AssertFormat("1", new DateTime(1, 1, 1, 13, 0, 0), "{h}"); AssertFormat("01", new DateTime(1, 1, 1, 13, 0, 0), "{hh}"); AssertFormat("12", new DateTime(1, 1, 1, 0, 0, 0), "{h}"); AssertFormat("05", new DateTime(1, 1, 1, 5, 0, 0), "{hh}"); //0-23 AssertFormat("1", new DateTime(1, 1, 1, 1, 0, 0), "{H}"); AssertFormat("01", new DateTime(1, 1, 1, 1, 0, 0), "{HH}"); AssertFormat("12", new DateTime(1, 1, 1, 12, 0, 0), "{H}"); AssertFormat("13", new DateTime(1, 1, 1, 13, 0, 0), "{H}"); AssertFormat("13", new DateTime(1, 1, 1, 13, 0, 0), "{HH}"); AssertFormat("0", new DateTime(1, 1, 1, 0, 0, 0), "{H}"); AssertFormat("00", new DateTime(1, 1, 1, 0, 0, 0), "{HH}"); AssertFormat("23", new DateTime(1, 1, 1, 23, 0, 0), "{H}"); //AM/PM sign AssertFormat("AM", new DateTime(1, 1, 1, 1, 0, 0), "en-US", "{a}"); AssertFormat("PM", new DateTime(1, 1, 1, 13, 0, 0), "en-US", "{a}"); end; method DateTimeTest.FormatMinutesSeconds; begin //minutes AssertFormat("0", new DateTime(1, 1, 1, 1, 0, 0), "{m}"); AssertFormat("30", new DateTime(1, 1, 1, 1, 30, 0), "{m}"); AssertFormat("59", new DateTime(1, 1, 1, 1, 59, 0), "{m}"); AssertFormat("00", new DateTime(1, 1, 1, 1, 0, 0), "{mm}"); AssertFormat("07", new DateTime(1, 1, 1, 1, 7, 0), "{mm}"); AssertFormat("59", new DateTime(1, 1, 1, 1, 59, 0), "{mm}"); //seconds AssertFormat("0", new DateTime(1, 1, 1, 1, 0, 0), "{s}"); AssertFormat("30", new DateTime(1, 1, 1, 1, 0, 30), "{s}"); AssertFormat("59", new DateTime(1, 1, 1, 1, 0, 59), "{s}"); AssertFormat("00", new DateTime(1, 1, 1, 1, 0, 0), "{ss}"); AssertFormat("07", new DateTime(1, 1, 1, 1, 0, 7), "{ss}"); AssertFormat("59", new DateTime(1, 1, 1, 1, 0, 59), "{ss}"); end; method DateTimeTest.ToStringFormat; begin AssertFormatDef("1961/04/12 06:07:00", "{yyyy}/{MM}/{dd} {HH}:{mm}:{ss}"); AssertFormatDef("On Wednesday, 12 April, 1961 at 6:07 – the first human traveled into outer space", "en-US", "On {dddd}, {dd} {MMMM}, {yyyy} at {h}:{mm} – the first human traveled into outer space"); AssertFormatDef("Formating year 1961, 61", "Formating year {yyyy}, {yy}"); AssertFormatDef("Time is 6 o'clock", "Time is {h} o\'clock"); Assert.Throws(->Data.ToString(nil)); Assert.Throws(->Data.ToString("Year is {yyyy")); Assert.Throws(->Data.ToString("Year is yyyy}")); Assert.Throws(->Data.ToString("Year is {}")); Assert.Throws(->Data.ToString("Year is {Yyyy}")); Assert.AreEqual(Data.ToString(''), ''); end; method DateTimeTest.Fields; begin Assert.AreEqual(Data.Year, 1961); Assert.AreEqual(Data.Month, 4); Assert.AreEqual(Data.Day, 12); Assert.AreEqual(Data.Hour, 6); Assert.AreEqual(Data.Minute, 7); Assert.AreEqual(Data.Second, 0); var Value := new DateTime(106, 12, 27, 23, 51, 37); Assert.AreEqual(Value.Year, 106); Assert.AreEqual(Value.Month, 12); Assert.AreEqual(Value.Day, 27); Assert.AreEqual(Value.Hour, 23); Assert.AreEqual(Value.Minute, 51); Assert.AreEqual(Value.Second, 37); AreEqual(new DateTime(1961, 4, 12), Data.Date); Assert.AreEqual(Data.Date.Hour, 0); end; method DateTimeTest.Ticks; begin assert.AreEqual(new DateTime(1970, 1, 2, 1, 2, 3).Ticks, 621356869230000000); assert.AreEqual(new DateTime(1820, 1, 2, 1, 2, 3).Ticks, 574020901230000000); assert.AreEqual(new DateTime(621356869230000000).Ticks, 621356869230000000); end; end.
{*******************************************************} { Проект: Repository } { Модуль: uBaseSubscription.pas } { Описание: Базовая реализация ISubscription } { Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) } { } { Распространяется по лицензии GPLv3 } {*******************************************************} unit uBaseSubscription; interface uses uServices; type TMatchEvent = function (Sender: TObject; AEventData: IInterface): Boolean of object; TProcessEvent = procedure (Sender: TObject; AEventData: IInterface) of object; TBaseSubscription = class(TInterfacedObject, ISubscription) private FOnEventMatch: TMatchEvent; FOnProcessEvent: TProcessEvent; protected public procedure DoEvent(Sender: TObject; AEventData: IInterface); virtual; stdcall; function EventIsMatches(Sender: TObject; AEventData: IInterface): Boolean; virtual; stdcall; property OnEventMatch: TMatchEvent read FOnEventMatch write FOnEventMatch; property OnProcessEvent: TProcessEvent read FOnProcessEvent write FOnProcessEvent; end; implementation { ****************************** TBaseSubscription ******************************* } procedure TBaseSubscription.DoEvent(Sender: TObject; AEventData: IInterface); begin if Assigned(FOnProcessEvent) then FOnProcessEvent(Sender, AEventData); end; function TBaseSubscription.EventIsMatches(Sender: TObject; AEventData: IInterface): Boolean; begin if Assigned(FOnEventMatch) then Result := FOnEventMatch(Sender, AEventData) else Result := False; end; end.
{ Wolverine Archive Extensions } {$O+} unit WArch; interface uses Objects,WProcs,WTypes; type TArchiver = record Name : string[8]; Sign : string[20]; PackCmd : FnameStr; UnPackCmd : FnameStr; ShowOutput : boolean; end; const maxArchivers = 5; Archivers : array[1..maxArchivers] of TArchiver = ((Name:'ZIP'; Sign:'504B0304'; PackCmd:'pkzip @a @f'; UnPackCmd:'pkunzip @a @d'; ShowOutput:false), (Name:'ARJ'; Sign:'60EA'; PackCmd:'arj a @a @f'; UnPackCmd:'arj e @a @d'; ShowOutput:false), (Name:'LHA'; Sign:'? ? 2D6C68'; PackCmd:'lha a @a @f'; UnPackCmd:'lha e @a @d'; ShowOutput:false), (Name:'ARC'; Sign:'1A'; PackCmd:'arc a @a @f'; UnPackCmd:'arc e @a @d'; ShowOutput:false), (Name:'RAR'; Sign:'526172211A'; PackCmd:'rar a -std @a @f'; UnPackCmd:'rar e -std @a @d'; ShowOutput:false)); function UnpackArchive(archive,destdir:FnameStr):boolean; function PackArchive(archive,filespec:FnameStr):boolean; procedure InitArchivers; procedure WriteArchivers; implementation uses XIO,XDebug,XStr; function DetectArchive(afile:FnameStr):byte; var T:TDosStream; temp:string[3]; n:byte; b:byte; buffer:array[1..10] of byte; tb:byte; oki:boolean; begin DetectArchive := 0; T.Init(afile,stOpenRead); if T.Status <> stOK then begin T.Done; exit; end; T.Read(buffer,SizeOf(buffer)); if T.Status <> stOK then begin Debug('read error'); T.Done; exit; end; T.Done; for b:=1 to maxArchivers do begin n := 1; oki := true; while n < length(Archivers[b].Sign) do begin temp := copy(Archivers[b].Sign,n,2); if temp[1] <> '?' then begin Insert('$',temp,1); tb := s2l(temp); if tb <> buffer[(n+1) div 2] then begin oki := false; break; end; end; inc(n,2); end; if oki then begin Debug(Archivers[b].Name+' detected'); DetectArchive := b; exit; end; end; end; function UnpackArchive(archive,destdir:FnameStr):boolean; var cmdline:FnameStr; b:byte; mode:word; begin UnpackArchive := false; b := DetectArchive(archive); if b = 0 then exit; cmdline := Archivers[b].UnpackCmd; FastUpper(cmdline); Replace(cmdline,'@A',archive); Replace(cmdline,'@D',destdir); if Archivers[b].ShowOutput then mode := 0 else mode := xfHideOutput; UnpackArchive := XExec('',cmdline,mode); end; function PackArchive(archive,filespec:FnameStr):boolean; var cmdline:FnameStr; mode:word; olddate:longint; b:byte; begin packArchive := false; if XFileExists(archive) then b := DetectArchive(archive) else b:=1; if b = 0 then exit; olddate := XGetFileDate(archive); cmdline := Archivers[b].packCmd; FastUpper(cmdline); Replace(cmdline,'@A',archive); Replace(cmdline,'@F',fileSpec); if Archivers[b].ShowOutput then mode := 0 else mode := xfHideOutput; packArchive := XExec('',cmdline,mode); XSetFileDate(archive,olddate); end; procedure WriteArchivers; var T:TDosStream; begin T.Init(wkdir^+arcFile,stCreate); T.Write(Archivers,SizeOf(Archivers)); T.Done; end; procedure InitArchivers; var T:TDosStream; begin if not XFileExists(wkdir^+arcFile) then Debug(arcFile+' not found - using defaults') else begin T.init(wkdir^+arcFile,stOpenRead); if T.GetSize = SizeOf(Archivers) then begin T.Read(Archivers,SizeOf(Archivers)); if T.Status <> stOK then Debug(arcFile+' read error!'); end else Debug(arcFile+' invalid!'); T.Done; end; end; end.
unit HlpBlake2SConfig; {$I ..\..\Include\HashLib.inc} interface uses HlpIBlake2SConfig, HlpHashSize, HlpHashLibTypes; resourcestring SInvalidHashSize = 'BLAKE2S HashSize must be restricted to one of the following [16, 20, 28, 32]'; type TBlake2SConfig = class sealed(TInterfacedObject, IBlake2SConfig) strict private var FHashSize: Int32; FPersonalisation, FSalt, FKey: THashLibByteArray; function GetPersonalisation: THashLibByteArray; inline; procedure SetPersonalisation(value: THashLibByteArray); inline; function GetSalt: THashLibByteArray; inline; procedure SetSalt(value: THashLibByteArray); inline; function GetKey: THashLibByteArray; inline; procedure SetKey(value: THashLibByteArray); inline; function GetHashSize: Int32; inline; procedure SetHashSize(value: Int32); inline; public constructor Create(AHashSize: THashSize = THashSize.hsHashSize256); property Personalisation: THashLibByteArray read GetPersonalisation write SetPersonalisation; property Salt: THashLibByteArray read GetSalt write SetSalt; property Key: THashLibByteArray read GetKey write SetKey; property HashSize: Int32 read GetHashSize write SetHashSize; end; implementation { TBlake2SConfig } function TBlake2SConfig.GetHashSize: Int32; begin result := FHashSize; end; function TBlake2SConfig.GetKey: THashLibByteArray; begin result := FKey; end; function TBlake2SConfig.GetPersonalisation: THashLibByteArray; begin result := FPersonalisation; end; function TBlake2SConfig.GetSalt: THashLibByteArray; begin result := FSalt; end; procedure TBlake2SConfig.SetHashSize(value: Int32); begin FHashSize := value; end; procedure TBlake2SConfig.SetKey(value: THashLibByteArray); begin FKey := value; end; procedure TBlake2SConfig.SetPersonalisation(value: THashLibByteArray); begin FPersonalisation := value; end; procedure TBlake2SConfig.SetSalt(value: THashLibByteArray); begin FSalt := value; end; constructor TBlake2SConfig.Create(AHashSize: THashSize); begin if not (Int32(AHashSize) in [16, 20, 28, 32]) then begin raise EArgumentHashLibException.CreateRes(@SInvalidHashSize); end; HashSize := Int32(AHashSize); end; end.
unit tmsUXlsNotes; {$INCLUDE ..\FLXCOMPILER.INC} interface uses SysUtils, tmsUXlsBaseRecords, tmsUXlsRowColEntries, tmsUxlsBaseRecordLists, tmsUXlsEscher, tmsUEscherRecords, tmsXlsMessages, tmsUFlxMessages; type TNoteRecord = class (TBaseRowColRecord) private Dwg: TEscherClientDataRecord; function GetText: UTF16String; procedure SetText(const Value: UTF16String); protected function DoCopyTo: TBaseRecord; override; public constructor CreateFromData(const aRow, aCol: integer; const aTxt: UTF16String; const Drawing: TDrawing; Properties: TImageProperties; const sSheet: TObject); destructor Destroy;override; procedure ArrangeCopyRowsAndCols(const RowOffset, ColOffset: integer);override; procedure ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount: integer; const SheetInfo: TSheetInfo); override; procedure FixDwgIds(const Drawing: TDrawing); property Text: UTF16String read GetText write SetText; end; TNoteRecordList = class (TBaseRowColRecordList) {$INCLUDE TNoteRecordListHdr.inc} procedure FixDwgIds(const Drawing: TDrawing); end; TNoteList = class (TBaseRowColList) //records are TNoteRecordList {$INCLUDE TNoteListHdr.inc} constructor Create; procedure FixDwgIds(const Drawing: TDrawing); procedure AddNewComment(const Row, Col: integer; const Txt: UTF16String; const Drawing: TDrawing; const Properties: TImageProperties; const sSheet: TObject); end; implementation uses tmsUXlsClientData, tmsUEscherOtherRecords; {$INCLUDE TNoteRecordListImp.inc} {$INCLUDE TNoteListImp.inc} { TNoteRecord } procedure TNoteRecord.ArrangeCopyRowsAndCols(const RowOffset, ColOffset: integer); begin if Dwg<>nil then begin //We only copy DWG if we are copying rows/columns, when we copy sheets we dont have to Dwg:=Dwg.CopyDwg(RowOffset, ColOffset, nil) as TEscherClientDataRecord; //warning SetWord(Data, 6, Dwg.ObjId); end; inherited; //This must be last, so we dont modify row end; procedure TNoteRecord.ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount: integer; const SheetInfo: TSheetInfo); begin inherited; if (Dwg<>nil) and (Dwg.FindRoot<>nil) then Dwg.FindRoot.ArrangeInsertRowsAndCols(aRowPos, aRowCount, aColPos, aColCount, SheetInfo, true, nil); //warning end; constructor TNoteRecord.CreateFromData(const aRow, aCol: integer; const aTxt: UTF16String; const Drawing: TDrawing; Properties: TImageProperties; const sSheet: TObject); var aData: PArrayOfByte; aDataSize: integer; begin if (aRow<0) or (aRow>Max_Rows) then raise Exception.CreateFmt(ErrXlsIndexOutBounds, [aRow, 'Row', 0, Max_Rows]); if (aCol<0) or (aCol>Max_Columns) then raise Exception.CreateFmt(ErrXlsIndexOutBounds, [aCol, 'Column', 0, Max_Columns]); aDataSize:=12; GetMem(aData, aDataSize); try SetWord(aData, 0, aRow); SetWord(aData, 2, aCol); SetWord(aData, 4, 0); //option flags SetWord(aData, 6, 0); //object id SetWord(aData, 8, 0); //Author Create(xlr_NOTE, aData, aDataSize); except FreeMem(aData); raise; end; //except Dwg:=Drawing.AddNewComment(Properties, sSheet); SetWord(Data, 6, Dwg.ObjId); //object id Text:=aTxt; end; destructor TNoteRecord.Destroy; begin if Dwg<>nil then begin if (Dwg.Patriarch=nil) then raise Exception.Create(ErrLoadingEscher); Dwg.Patriarch.ContainedRecords.Remove(Dwg.FindRoot); end; inherited; end; function TNoteRecord.DoCopyTo: TBaseRecord; begin Result:=inherited DoCopyTo; (Result as TNoteRecord).Dwg:=Dwg; end; procedure TNoteRecord.FixDwgIds(const Drawing: TDrawing); begin Dwg:= Drawing.FindObjId(GetWord(Data, 6)); end; function TNoteRecord.GetText: UTF16String; var R:TEscherRecord; begin if (Dwg=nil) then Result:='' else begin R:=Dwg.FindRoot; if R=nil then Result:='' else begin R:= Dwg.FindRoot.FindRec(TEscherClientTextBoxRecord); if R=nil then Result:='' else Result:= (R as TEscherClientTextBoxRecord).Value; end; end; end; procedure TNoteRecord.SetText(const Value: UTF16String); var R:TEscherRecord; begin if (Dwg=nil) then exit else begin R:=Dwg.FindRoot; if R=nil then exit else begin R:= R.FindRec(TEscherClientTextBoxRecord); if R=nil then exit else (R as TEscherClientTextBoxRecord).Value:=Value; end; end; end; { TNoteRecordList } procedure TNoteRecordList.FixDwgIds(const Drawing: TDrawing); var i: integer; begin for i:=0 to Count-1 do Items[i].FixDwgIds(Drawing); end; { TNoteList } procedure TNoteList.AddNewComment(const Row, Col: integer; const Txt: UTF16String; const Drawing: TDrawing; const Properties: TImageProperties; const sSheet: TObject); var R: TNoteRecord; begin R:=TNoteRecord.CreateFromData(Row, Col, Txt, Drawing, Properties, sSheet); try AddRecord(R, Row); except FreeAndNil(R); raise; end; //Except end; constructor TNoteList.Create; begin inherited Create(TNoteRecordList); end; procedure TNoteList.FixDwgIds(const Drawing: TDrawing); var i: integer; begin for i:=0 to Count-1 do Items[i].FixDwgIds(Drawing); end; end.
unit LargeMatrix; interface uses Persistent, BackupInterfaces, SyncObjs, Matrix, Windows; type any = 0..0; PLargeMatrixIndex = ^TLargeMatrixIndex; TLargeMatrixIndex = array[any] of pointer; type TLargeMatrix = class( TPersistent ) public constructor Create( aRows, aCols : integer; aElementSize, aResolution : integer ); destructor Destroy; override; private fRows : integer; fCols : integer; fElementSize : integer; fResolution : integer; fIndexRows : integer; fIndexCols : integer; public property Rows : integer read fRows; property Cols : integer read fCols; protected function GetElement( i, j : integer ) : pointer; procedure SetElement( i, j : integer; value : pointer ); private fIndex : PLargeMatrixIndex; private function GetIndex( idxI, idxJ : integer ) : pointer; procedure SetIndex( idxI, idxJ : integer; value : pointer ); private property Index[idxI, idxJ : integer] : pointer read GetIndex write SetIndex; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; private fLock : TCriticalSection; public procedure Lock; procedure Unlock; public procedure Fill( C : byte ); end; TSingleLargeMatrix = class( TLargeMatrix ) public constructor Create( aRows, aCols : integer; aResolution : integer ); private function GetSingleElement( i, j : integer ) : single; procedure SetSingleElement( i, j : integer; value : single ); public property Elements[i, j : integer] : single read GetSingleElement write SetSingleElement; default; public procedure IncElement( i, j : integer; delta : single ); end; TByteLargeMatrix = class( TLargeMatrix, IMatrix ) public constructor Create( aRows, aCols : integer; aResolution : integer ); private function GetByteElement( i, j : integer ) : byte; procedure SetByteElement( i, j : integer; value : byte ); public property Elements[i, j : integer] : byte read GetByteElement write SetByteElement; default; public procedure IncElement( i, j : integer; delta : byte ); // IMatrix private function getCols : integer; function getRows : integer; procedure setDimensions( n, m : integer ); function getElement ( i, j : integer ) : single; procedure setElement ( i, j : integer; value : single ); // IUnknown private function QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; function _AddRef : integer; stdcall; function _Release : integer; stdcall; end; TIntegerLargeMatrix = class( TLargeMatrix, IMatrix ) public constructor Create( aRows, aCols : integer; aResolution : integer ); private function GetIntegerElement( i, j : integer ) : integer; procedure SetIntegerElement( i, j : integer; value : integer ); public property Elements[i, j : integer] : Integer read GetIntegerElement write SetIntegerElement; default; public procedure IncElement( i, j : integer; delta : integer ); // IMatrix private function getCols : integer; function getRows : integer; procedure setDimensions( n, m : integer ); function getElement ( i, j : integer ) : single; procedure setElement ( i, j : integer; value : single ); // IUnknown private function QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; function _AddRef : integer; stdcall; function _Release : integer; stdcall; end; // RegisterBackup procedure RegisterBackup; implementation uses SysUtils, Logs; // TLargeMatrix constructor TLargeMatrix.Create( aRows, aCols : integer; aElementSize, aResolution : integer ); begin inherited Create; fRows := aRows; fCols := aCols; fElementSize := aElementSize; fResolution := aResolution; fIndexRows := fRows div fResolution + integer(fRows mod fResolution > 0); fIndexCols := fCols div fResolution + integer(fCols mod fResolution > 0); getmem( fIndex, fIndexRows*fIndexCols*sizeof(fIndex[0]) ); fillchar( fIndex^, fIndexRows*fIndexCols*sizeof(fIndex[0]), 0 ); fLock := TCriticalSection.Create; end; destructor TLargeMatrix.Destroy; var idxI, idxJ : integer; begin try Logs.Log( 'Demolition', DateTimeToStr(Now) + ' - ' + ClassName ); except end; fLock.Free; for idxI := 0 to pred(fIndexRows) do for idxJ := 0 to pred(fIndexCols) do freemem( Index[idxI, idxJ], sqr(fResolution)*fElementSize ); freemem( fIndex, fIndexRows*fIndexCols*sizeof(fIndex[0]) ); inherited; end; function TLargeMatrix.GetElement( i, j : integer ) : pointer; var SubMatrix : pointer; begin SubMatrix := Index[i div fResolution, j div fResolution]; if SubMatrix <> nil then begin i := i mod fResolution; j := j mod fResolution; result := @(TByteArray(SubMatrix^)[i*fResolution*fElementSize + j*fElementSize]); end else result := nil; end; procedure TLargeMatrix.SetElement( i, j : integer; value : pointer ); var idxI, idxJ : integer; SubMatrix : pointer; begin if (i >= 0) and (i < Rows) and (j >= 0) and (j < Cols) then begin idxI := i div fResolution; idxJ := j div fResolution; SubMatrix := Index[idxI, idxJ]; if SubMatrix = nil then begin getmem( SubMatrix, sqr(fResolution)*fElementSize ); //Logs.Log( 'Survival', DateTimeToStr(Now) + Format('GetMem [%d, %d] (%d)', [idxI, idxJ, sqr(fResolution)*fElementSize])); fillchar( SubMatrix^, sqr(fResolution)*fElementSize, 0 ); Index[idxI, idxJ] := SubMatrix; end; if SubMatrix <> nil then begin i := i mod fResolution; j := j mod fResolution; move( value^, TByteArray(SubMatrix^)[i*fResolution*fElementSize + j*fElementSize], fElementSize ); end; end else Logs.Log( 'Survival', DateTimeToStr(Now) + ' Matrix out of bounds: ' + IntToStr(i) + ',' + IntToStr(j) ); end; function TLargeMatrix.GetIndex( idxI, idxJ : integer ) : pointer; begin result := fIndex[idxI*fIndexCols + idxJ]; end; procedure TLargeMatrix.SetIndex( idxI, idxJ : integer; value : pointer ); begin fIndex[idxI*fIndexCols + idxJ] := value; end; procedure TLargeMatrix.LoadFromBackup( Reader : IBackupReader ); var idxI, idxJ : integer; SubMatrix : pointer; begin inherited; fRows := Reader.ReadInteger( 'Rows', fRows ); fCols := Reader.ReadInteger( 'Cols', fCols ); fElementSize := Reader.ReadInteger( 'ElementSize', fElementSize ); fResolution := Reader.ReadInteger( 'Resolution', fResolution ); fIndexRows := fRows div fResolution + integer(fRows mod fResolution > 0); fIndexCols := fCols div fResolution + integer(fCols mod fResolution > 0); getmem( fIndex, fIndexRows*fIndexCols*sizeof(fIndex[0]) ); // Load Index items for idxI := 0 to pred(fIndexRows) do for idxJ := 0 to pred(fIndexCols) do if Reader.ReadBoolean( 'Used', false ) then begin getmem( SubMatrix, sqr(fResolution)*fElementSize ); Reader.ReadBuffer( 'Data', SubMatrix^, nil, sqr(fResolution)*fElementSize ); Index[idxI, idxJ] := SubMatrix; end else Index[idxI, idxJ] := nil; fLock := TCriticalSection.Create; end; procedure TLargeMatrix.StoreToBackup( Writer : IBackupWriter ); var idxI, idxJ : integer; begin inherited; Writer.WriteInteger( 'Rows', fRows ); Writer.WriteInteger( 'Cols', fCols ); Writer.WriteInteger( 'ElementSize', fElementSize ); Writer.WriteInteger( 'Resolution', fResolution ); // Store Index items for idxI := 0 to pred(fIndexRows) do for idxJ := 0 to pred(fIndexCols) do if Index[idxI, idxJ] <> nil then begin Writer.WriteBoolean( 'Used', true ); Writer.WriteBuffer( 'Data', Index[idxI, idxJ]^, sqr(fResolution)*fElementSize ); end else Writer.WriteBoolean( 'Used', false ); end; procedure TLargeMatrix.Lock; begin fLock.Enter; end; procedure TLargeMatrix.Unlock; begin fLock.Leave; end; procedure TLargeMatrix.Fill( C : byte ); var SubMatrix : pointer; i, j : integer; begin for i := 0 to pred(fIndexRows) do for j := 0 to pred(fIndexCols) do begin SubMatrix := Index[i, j]; if SubMatrix <> nil then fillchar( SubMatrix^, sqr(fResolution)*fElementSize, C ); end; end; // TSingleLargeMatrix type psingle = ^single; constructor TSingleLargeMatrix.Create( aRows, aCols : integer; aResolution : integer ); begin inherited Create( aRows, aCols, sizeof(single), aResolution ); end; function TSingleLargeMatrix.GetSingleElement( i, j : integer ) : single; var ptr : pointer; begin if (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then begin ptr := GetElement( i, j ); if ptr <> nil then result := single(ptr^) else result := 0; end else result := 0; end; procedure TSingleLargeMatrix.SetSingleElement( i, j : integer; value : single ); begin if (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then SetElement( i, j, @value ) end; procedure TSingleLargeMatrix.IncElement( i, j : integer; delta : single ); var element : psingle; begin if (delta <> 0) and (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then begin element := GetElement( i, j ); if element <> nil then element^ := element^ + delta else SetSingleElement( i, j, delta ); end; end; // TByteLargeMatrix type pbyte = ^byte; constructor TByteLargeMatrix.Create( aRows, aCols : integer; aResolution : integer ); begin inherited Create( aRows, aCols, sizeof(byte), aResolution ); end; function TByteLargeMatrix.GetByteElement( i, j : integer ) : byte; var ptr : pointer; begin if (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then begin ptr := inherited GetElement( i, j ); if ptr <> nil then result := byte(ptr^) else result := 0; end else result := 0; end; procedure TByteLargeMatrix.SetByteElement( i, j : integer; value : byte ); begin if (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then inherited SetElement( i, j, @value ) end; procedure TByteLargeMatrix.IncElement( i, j : integer; delta : byte ); var element : pbyte; begin if (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then begin element := inherited GetElement( i, j ); if element <> nil then element^ := element^ + delta else SetByteElement( i, j, delta ); end; end; function TByteLargeMatrix.getCols : integer; begin result := fCols; end; function TByteLargeMatrix.getRows : integer; begin result := fRows; end; procedure TByteLargeMatrix.setDimensions( n, m : integer ); begin end; function TByteLargeMatrix.getElement( i, j : integer ) : single; begin result := Elements[i, j]; end; procedure TByteLargeMatrix.setElement( i, j : integer; value : single ); begin end; function TByteLargeMatrix.QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; begin pointer(Obj) := nil; result := E_FAIL; end; function TByteLargeMatrix._AddRef : integer; stdcall; begin result := 1; end; function TByteLargeMatrix._Release : integer; stdcall; begin result := 1; end; // TIntegerLargeMatrix type pInteger = ^Integer; constructor TIntegerLargeMatrix.Create( aRows, aCols : integer; aResolution : integer ); begin inherited Create( aRows, aCols, sizeof(Integer), aResolution ); end; function TIntegerLargeMatrix.GetIntegerElement( i, j : integer ) : Integer; var ptr : pointer; begin if (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then begin ptr := inherited GetElement( i, j ); if ptr <> nil then result := Integer(ptr^) else result := 0; end else result := 0; end; procedure TIntegerLargeMatrix.SetIntegerElement( i, j : integer; value : Integer ); begin if (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then inherited SetElement( i, j, @value ) end; procedure TIntegerLargeMatrix.IncElement( i, j : integer; delta : Integer ); var element : pInteger; begin if (i >= 0) and (j >= 0) and (i < Rows) and (j < Cols) then begin element := inherited GetElement( i, j ); if element <> nil then element^ := element^ + delta else SetIntegerElement( i, j, delta ); end; end; function TIntegerLargeMatrix.getCols : integer; begin result := fCols; end; function TIntegerLargeMatrix.getRows : integer; begin result := fRows; end; procedure TIntegerLargeMatrix.setDimensions( n, m : integer ); begin end; function TIntegerLargeMatrix.getElement( i, j : integer ) : single; begin result := Elements[i, j]; end; procedure TIntegerLargeMatrix.setElement( i, j : integer; value : single ); begin end; function TIntegerLargeMatrix.QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; begin pointer(Obj) := nil; result := E_FAIL; end; function TIntegerLargeMatrix._AddRef : integer; stdcall; begin result := 1; end; function TIntegerLargeMatrix._Release : integer; stdcall; begin result := 1; end; // RegisterBackup procedure RegisterBackup; begin BackupInterfaces.RegisterClass( TSingleLargeMatrix ); BackupInterfaces.RegisterClass( TByteLargeMatrix ); end; end.
unit CommandoSettings; interface uses Classes, Types, SysUtils; type TCommandoSettings = class private FComponents: TStringList; FUpdatefile: string; FInstallPath: string; FPID: Cardinal; function GetCommandoLine: string; function ReadPID(AIndex: Integer): Integer; function ReadFileName(AIndex: Integer): Integer; function ReadComponentVersion(AIndex: Integer): Integer; function ReadInstallPath(AIndex: Integer): Integer; function GetVersion(AName: string): string; public constructor Create(); destructor Destroy(); override; procedure ReadFromCommandLine(); function HasUpdateFile(): Boolean; function NeedToWait(): Boolean; function IsSelfInstall(): Boolean; property UpdateFile: string read FUpdatefile write FUpdateFile; property PID: Cardinal read FPID write FPID; property InstallPath: string read FInstallPath write FInstallPath; property Components: TStringList read FComponents; property Versions[AName: string]: string read GetVersion; property CommandoLine: string read GetCommandoLine; end; implementation uses StrUtils, Forms; { TCommandoSettings } constructor TCommandoSettings.Create; begin FComponents := TStringList.Create(); end; destructor TCommandoSettings.Destroy; begin FComponents.Free(); inherited; end; function TCommandoSettings.GetCommandoLine: string; var i: Integer; begin Result := ''; if IsSelfInstall then begin Result := Result + '-Install "' + FInstallPath + '" '; end; if NeedToWait then begin Result := Result + '-PID ' + IntToStr(FPID) + ' '; end; if HasUpdateFile then begin Result := Result + '-File "' + FUpdatefile + '" '; end; for i := 0 to FComponents.Count - 1 do begin Result := Result + '-Version ' + FComponents.Names[i] + ' ' + FComponents.ValueFromIndex[i] + ' '; end; Result := Trim(Result); end; function TCommandoSettings.GetVersion(AName: string): string; begin Result := '0'; if FComponents.IndexOfName(AName) > -1 then begin Result := FComponents.Values[AName]; end; end; function TCommandoSettings.HasUpdateFile: Boolean; begin Result := Trim(FUpdatefile) <> ''; end; function TCommandoSettings.IsSelfInstall: Boolean; begin Result := FInstallPath <> ''; end; function TCommandoSettings.NeedToWait: Boolean; begin Result := FPID > 0; end; function TCommandoSettings.ReadComponentVersion(AIndex: Integer): Integer; begin Result := 3; FComponents.Add(ParamStr(AIndex + 1) + '=' + ParamStr(AIndex + 2)); end; function TCommandoSettings.ReadFileName(AIndex: Integer): Integer; begin Result := 2; FUpdatefile := ParamStr(AIndex + 1); end; procedure TCommandoSettings.ReadFromCommandLine; var i: Integer; begin if SameText(Application.ExeName, ParamStr(0)) then begin i := 1; end else begin i := 0; end; while(i < ParamCount) do begin case AnsiIndexText(ParamStr(i), ['-PID', '-File', '-Version', '-Install']) of 0: begin i := i + ReadPID(i); end; 1: begin i := i + ReadFileName(i); end; 2: begin i := i + ReadComponentVersion(i); end; 3: begin i := i + ReadInstallPath(i); end else begin raise Exception.Create('Invalid parameter ' + QuotedStr(ParamStr(i)) + ' at Index ' + IntToStr(i)); end; end; end; end; function TCommandoSettings.ReadInstallPath(AIndex: Integer): Integer; begin Result := 2; FInstallPath := ParamStr(AIndex + 1); end; function TCommandoSettings.ReadPID(AIndex: Integer): Integer; begin Result := 2; FPID := StrToIntDef(ParamStr(AIndex + 1), 0); end; end.
unit uOrcamentoNaoAprovadoVO; interface uses System.SysUtils, uKeyField, uTableName, uTipoVO; type [TableName('Orcamento_NaoAprovado')] TOrcamentoNaoAprovadoVO = class private FDescricao: string; FIdTipo: Integer; FId: Integer; FTipo: TTipoVO; FIdOrcamento: Integer; procedure SetDescricao(const Value: string); procedure SetId(const Value: Integer); procedure SetIdTipo(const Value: Integer); procedure SetTipo(const Value: TTipoVO); procedure SetIdOrcamento(const Value: Integer); public [KeyField('OrcNAp_Id')] property Id: Integer read FId write SetId; [FieldName('OrcNAp_Tipo')] property IdTipo: Integer read FIdTipo write SetIdTipo; [FieldName('OrcNAp_Descricao')] property Descricao: string read FDescricao write SetDescricao; [FieldName('OrcNAp_Orcamento')] property IdOrcamento: Integer read FIdOrcamento write SetIdOrcamento; property Tipo: TTipoVO read FTipo write SetTipo; constructor create; destructor destroy; override; end; implementation { TOrcamentoNaoAprovadoVO } constructor TOrcamentoNaoAprovadoVO.create; begin inherited create; FTipo := TTipoVO.Create; end; destructor TOrcamentoNaoAprovadoVO.destroy; begin FreeAndNil(FTipo); inherited; end; procedure TOrcamentoNaoAprovadoVO.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TOrcamentoNaoAprovadoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TOrcamentoNaoAprovadoVO.SetIdOrcamento(const Value: Integer); begin FIdOrcamento := Value; end; procedure TOrcamentoNaoAprovadoVO.SetIdTipo(const Value: Integer); begin FIdTipo := Value; end; procedure TOrcamentoNaoAprovadoVO.SetTipo(const Value: TTipoVO); begin FTipo := Value; end; end.
unit K620241155_Hk0200166; {* [RequestLink:620241155] } // Модуль: "w:\common\components\rtl\Garant\Daily\K620241155_Hk0200166.pas" // Стереотип: "TestCase" // Элемент модели: "K620241155_Hk0200166" MUID: (56F1351602EA) // Имя типа: "TK620241155_Hk0200166" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoBothNSRCWriterTest ; type TK620241155_Hk0200166 = class(TEVDtoBothNSRCWriterTest) {* [RequestLink:620241155] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK620241155_Hk0200166 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *56F1351602EAimpl_uses* //#UC END# *56F1351602EAimpl_uses* ; function TK620241155_Hk0200166.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'CrossSegments'; end;//TK620241155_Hk0200166.GetFolder function TK620241155_Hk0200166.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '56F1351602EA'; end;//TK620241155_Hk0200166.GetModelElementGUID initialization TestFramework.RegisterTest(TK620241155_Hk0200166.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit LoggerThread; interface uses System.Classes, LoggerInterface, System.SyncObjs; type TLoggerThread = class(TThread) private FCancellationEvent: TEvent; FID: Integer; FLoggerI: ILogger; FInterval: Cardinal; class var FCount: Integer; protected procedure Execute; override; public constructor Create(ALoggerI: ILogger; ACancellationEvent: TEvent; AInterval: Cardinal); end; implementation uses System.SysUtils; constructor TLoggerThread.Create(ALoggerI: ILogger; ACancellationEvent: TEvent; AInterval: Cardinal); begin inherited Create; Inc(FCount); FID := FCount; if not Assigned(ALoggerI) then raise Exception.Create('Logger interface is not assigned'); FLoggerI := ALoggerI; FInterval := AInterval; FCancellationEvent := ACancellationEvent; FreeOnTerminate := False; end; procedure TLoggerThread.Execute; var AMessage: string; AMessageStatus: TMessageStatus; AMessageStatusVar: TMessageStatus; i: Integer; AMessageCount: Integer; AWaitResult: TWaitResult; begin AMessageCount := 0; while not Terminated do begin Inc(AMessageCount); AMessage := Format('Message %d in thread %d', [AMessageCount, FID]); AMessageStatusVar := High(TMessageStatus); i := Random(Integer(AMessageStatusVar) + 1); AMessageStatus := TMessageStatus(i); FLoggerI.Add(AMessage, AMessageStatus); // Ждём события об отмене потока AWaitResult := FCancellationEvent.WaitFor(FInterval); if AWaitResult <> wrTimeout then begin Terminate; break end; end; end; end.
unit uRecadoController; interface uses System.SysUtils, uDMRecado, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFuncoesSIDomper, uGenericProperty, uRecadoVO, Data.DBXJSON, Data.DBXJSONReflect, uConverter, uRecadoFiltro, uUsuarioController, uStatusVO, uContaEmailController, uTipoController, uTipoVO, uRecadoQuadroViewModel, System.Generics.Collections; type TRecadoController = class private FModel: TDMRecado; FOperacao: TOperacao; FModoAbrEnc: string; procedure Post; function StatusAbertura(): TStatusVO; procedure BuscarUsuarioLogado(); procedure BuscarStatusAbertura(); procedure TipoUmRegistro(); public procedure Filtrar(AFiltro: TRecadoFiltro; ACampo, ATexto: string; AContem: Boolean = False); procedure LocalizarId(AId: Integer); procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); function Salvar(AIdUsuario: Integer; AOperacao: string): Integer; procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); procedure FiltrarId(AId: Integer); procedure Quadro(AIdUsuario, AIdRevenda: Integer); procedure QuadroJSON(AIdUsuario, AIdRevenda: Integer); function BuscarQuadroJSON(AIdUsuario, AIdRevenda: Integer): TObjectList<TRecadoQuadroViewModel>; function TextoEmail(AId: Integer): string; procedure EnviarEmail(AIdUsuarioOrigem, AIdUsuarioDestino, AId: Integer); function PermissaoAcessar(AIdUsuario: Integer): Boolean; function PermissaoAcessarQuadro(AIdUsuario: Integer): Boolean; property Model: TDMRecado read FModel write FModel; property ModoAbrEnc: string read FModoAbrEnc write FModoAbrEnc; constructor Create(); destructor Destroy; override; end; implementation { TRecadoController } procedure TRecadoController.BuscarStatusAbertura; var StatusVO: TStatusVO; begin try StatusVO := StatusAbertura(); FModel.CDSCadastroRec_Status.AsInteger := StatusVO.Id; FModel.CDSCadastroSta_Codigo.AsInteger := StatusVO.Codigo; FModel.CDSCadastroSta_Nome.AsString := StatusVO.Nome; finally FreeAndNil(StatusVO); end; end; procedure TRecadoController.BuscarUsuarioLogado; var Usuario: TUsuarioController; begin Usuario := TUsuarioController.Create; try Usuario.LocalizarId(dm.IdUsuario); FModel.CDSCadastroRec_UsuarioLcto.AsInteger := Usuario.Model.CDSCadastroUsu_Id.AsInteger; FModel.CDSCadastroUsu_CodigoLcto.AsInteger := Usuario.Model.CDSCadastroUsu_Codigo.AsInteger; FModel.CDSCadastroNomeUsuarioLcto.AsString := Usuario.Model.CDSCadastroUsu_Nome.AsString; finally FreeAndNil(Usuario); end; end; procedure TRecadoController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; constructor TRecadoController.Create; begin inherited Create; FModel := TDMRecado.Create(nil); end; destructor TRecadoController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TRecadoController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerModule2Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CRecadoPrograma, dm.IdUsuario, AId); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.EnviarEmail(AIdUsuarioOrigem, AIdUsuarioDestino, AId: Integer); var objContaEmail: TContaEmailController; Usuario: TUsuarioController; sEmail: string; sAssunto: string; begin if (AId = 0) or (AIdUsuarioOrigem = 0) or (AIdUsuarioDestino = 0) then Exit; sAssunto := 'Domper Recado - ' + FormatFloat('000000', AId); Usuario := TUsuarioController.Create; objContaEmail := TContaEmailController.Create; try Usuario.LocalizarId(AIdUsuarioDestino); sEmail := Usuario.Model.CDSCadastroUsu_Email.AsString; if sEmail.Trim <> '' then objContaEmail.EnviarEmail(AIdUsuarioOrigem, sEmail, '', sAssunto, TextoEmail(AId), ''); finally FreeAndNil(objContaEmail); FreeAndNil(Usuario); end; end; procedure TRecadoController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerModule2Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try Negocio.Excluir(CRecadoPrograma, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.Filtrar(AFiltro: TRecadoFiltro; ACampo, ATexto: string; AContem: Boolean); var Negocio: TServerModule2Client; oJSON: TJSONValue; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try oJSON := TConverte.ObjectToJSON<TRecadoFiltro>(AFiltro); FModel.CDSConsulta.Close; Negocio.RecadoFiltrar(oJSON, ACampo, ATexto, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.FiltrarId(AId: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.RecadoFiltrarId(AId); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.Imprimir(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CRecadoPrograma, AIdUsuario); dm.Desconectar; // FModel.Rel.Print; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.LocalizarId(AId: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(CRecadoPrograma, AId); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.Novo(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CRecadoPrograma, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; BuscarUsuarioLogado(); BuscarStatusAbertura(); TipoUmRegistro(); FModel.CDSCadastroRec_data.AsDateTime := Date; FModel.CDSCadastroRec_Hora.AsDateTime := Time; FOperacao := opIncluir; FModoAbrEnc := 'A'; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TRecadoController.PermissaoAcessar(AIdUsuario: Integer): Boolean; var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Result := Negocio.RecadoPermissaoUsuario(AIdUsuario, 'Acessar'); dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TRecadoController.PermissaoAcessarQuadro(AIdUsuario: Integer): Boolean; var Negocio: TServerMethods1Client; begin dm.Conectar; Negocio := TServerMethods1Client.Create(dm.Conexao.DBXConnection); try Result := Negocio.PermissaoRecadoQuadro(AIdUsuario); dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TRecadoController.BuscarQuadroJSON(AIdUsuario, AIdRevenda: Integer): TObjectList<TRecadoQuadroViewModel>; var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try try Result := TConverte.JSONToObject<TListaRecadoQuadroViewModel>(Negocio.RecadoQuadroJSON(AIdUsuario, AIdRevenda)); dm.Desconectar; except ON E: Exception do begin raise Exception.Create(E.Message + ' TRecadoController.BuscarQuadroJSON'); end; end; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.Quadro(AIdUsuario, AIdRevenda: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try FModel.CDSQuadro.Close; Negocio.RecadoQuadro(AIdUsuario, AIdRevenda); FModel.CDSQuadro.Open; FModel.CDSLcto.First; while not FModel.CDSLcto.Eof do FModel.CDSLcto.Delete; FModel.CDSDestino.First; while not FModel.CDSDestino.Eof do FModel.CDSDestino.Delete; FModel.CDSQuadro.First; while not FModel.CDSQuadro.Eof do begin if FModel.CDSQuadroTipo.AsString = 'L' then begin FModel.CDSLcto.Append; FModel.CDSLctoRec_Id.AsInteger := FModel.CDSQuadroRec_Id.AsInteger; FModel.CDSLctoRec_Data.AsDateTime := FModel.CDSQuadroRec_Data.AsDateTime; FModel.CDSLctoRec_Hora.AsDateTime := FModel.CDSQuadroRec_Hora.AsDateTime; FModel.CDSLctoUsuarioLcto.AsString := FModel.CDSQuadroUsuarioLcto.AsString; FModel.CDSLctoUsuarioDestino.AsString := FModel.CDSQuadroUsuarioDestino.AsString; FModel.CDSLctoRec_Nivel.AsInteger := FModel.CDSQuadroRec_Nivel.AsInteger; FModel.CDSLctoRec_RazaoSocial.AsString := FModel.CDSQuadroRec_RazaoSocial.AsString; FModel.CDSLctoRec_Telefone.AsString := FModel.CDSQuadroRec_Telefone.AsString; FModel.CDSLctoRec_UsuarioLcto.AsInteger := FModel.CDSQuadroRec_UsuarioLcto.AsInteger; FModel.CDSLctoRec_UsuarioDestino.AsInteger := FModel.CDSQuadroRec_UsuarioDestino.AsInteger; FModel.CDSLcto.Post; end else begin FModel.CDSDestino.Append; FModel.CDSDestinoRec_Id.AsInteger := FModel.CDSQuadroRec_Id.AsInteger; FModel.CDSDestinoRec_Data.AsDateTime := FModel.CDSQuadroRec_Data.AsDateTime; FModel.CDSDestinoRec_Hora.AsDateTime := FModel.CDSQuadroRec_Hora.AsDateTime; FModel.CDSDestinoUsuarioLcto.AsString := FModel.CDSQuadroUsuarioLcto.AsString; FModel.CDSDestinoUsuarioDestino.AsString := FModel.CDSQuadroUsuarioDestino.AsString; FModel.CDSDestinoRec_Nivel.AsInteger := FModel.CDSQuadroRec_Nivel.AsInteger; FModel.CDSDestinoRec_RazaoSocial.AsString := FModel.CDSQuadroRec_RazaoSocial.AsString; FModel.CDSDestinoRec_Telefone.AsString := FModel.CDSQuadroRec_Telefone.AsString; FModel.CDSDestino.Post; end; FModel.CDSQuadro.Next; end; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRecadoController.QuadroJSON(AIdUsuario, AIdRevenda: Integer); var Item: TRecadoQuadroViewModel; Lista: TObjectList<TRecadoQuadroViewModel>; begin dm.ConexaoBanco; Lista := BuscarQuadroJSON(AIdUsuario, AIdRevenda); try FModel.CDSLcto.First; while not FModel.CDSLcto.Eof do FModel.CDSLcto.Delete; FModel.CDSDestino.First; while not FModel.CDSDestino.Eof do FModel.CDSDestino.Delete; for Item in Lista do begin if Item.TipoLan = 'L' then begin FModel.CDSLcto.Append; FModel.CDSLctoRec_Id.AsInteger := Item.Id; FModel.CDSLctoRec_Data.AsDateTime := Item.Data; FModel.CDSLctoRec_Hora.AsDateTime := Item.Hora; FModel.CDSLctoUsuarioLcto.AsString := Item.UsuarioLcto; FModel.CDSLctoUsuarioDestino.AsString := Item.UsuarioDestino; FModel.CDSLctoRec_Nivel.AsInteger := Item.Nivel; FModel.CDSLctoRec_RazaoSocial.AsString := Item.RazaoSocial; FModel.CDSLctoRec_Telefone.AsString := Item.Telefone; FModel.CDSLctoRec_UsuarioLcto.AsInteger := Item.Rec_UsuarioLcto; FModel.CDSLctoRec_UsuarioDestino.AsInteger := Item.Rec_UsuarioDestino; FModel.CDSLcto.Post; end else begin FModel.CDSDestino.Append; FModel.CDSDestinoRec_Id.AsInteger := Item.Id; FModel.CDSDestinoRec_Data.AsDateTime := Item.Data; FModel.CDSDestinoRec_Hora.AsDateTime := Item.Hora; FModel.CDSDestinoUsuarioLcto.AsString := Item.UsuarioLcto; FModel.CDSDestinoUsuarioDestino.AsString := Item.UsuarioDestino; FModel.CDSDestinoRec_Nivel.AsInteger := Item.Nivel; FModel.CDSDestinoRec_RazaoSocial.AsString := Item.RazaoSocial; FModel.CDSDestinoRec_Telefone.AsString := Item.Telefone; FModel.CDSDestino.Post; end; end; finally FreeAndNil(Lista); end; end; function TRecadoController.Salvar(AIdUsuario: Integer; AOperacao: string): Integer; var Negocio: TServerModule2Client; ConsultaSQL: string; id: Integer; ObjVO: TRecadoVO; oObjetoJSON : TJSONValue; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try Post(); ObjVO := TRecadoVO.create; ObjVO.Operacao := AOperacao; ObjVO.Id := FModel.CDSCadastroRec_Id.AsInteger; ObjVO.Data := FModel.CDSCadastroRec_data.AsDateTime; ObjVO.Hora := FModel.CDSCadastroRec_Hora.AsDateTime; ObjVO.IdUsuarioLcto := FModel.CDSCadastroRec_UsuarioLcto.AsInteger; ObjVO.Nivel := FModel.CDSCadastroRec_Nivel.AsInteger; ObjVO.IdCliente := FModel.CDSCadastroRec_Cliente.AsInteger; ObjVO.RazaoSocial := FModel.CDSCadastroRec_RazaoSocial.AsString; ObjVO.Fantasia := FModel.CDSCadastroRec_Fantasia.AsString; ObjVO.Endereco := FModel.CDSCadastroRec_Endereco.AsString; ObjVO.Telefone := FModel.CDSCadastroRec_Telefone.AsString; ObjVO.Contato := FModel.CDSCadastroRec_Contato.AsString; ObjVO.IdUsuarioDestino := FModel.CDSCadastroRec_UsuarioDestino.AsInteger; ObjVO.IdTipo := FModel.CDSCadastroRec_Tipo.AsInteger; ObjVO.IdStatus := FModel.CDSCadastroRec_Status.AsInteger; ObjVO.DescricaoInicial := FModel.CDSCadastroRec_DescricaoInicial.AsString; ObjVO.DataFinal := FModel.CDSCadastroRec_DataFinal.AsDateTime; ObjVO.HoraFinal := FModel.CDSCadastroRec_HoraFinal.AsDateTime; ObjVO.DescricaoFinal := FModel.CDSCadastroRec_DescricaoFinal.AsString; // TGenericProperty.SetProperty<TRecadoVO>(ObjVO, FModel.CDSCadastro); oObjetoJSON := TConverte.ObjectToJSON<TRecadoVO>(ObjVO); Result := StrToIntDef(Negocio.RecadoSalvar(oObjetoJSON).ToString(), 0); FOperacao := opNavegar; dm.Desconectar; except on E: Exception do begin TFuncoes.MensagemErroBanco(E.Message); Abort; end; end; finally FreeAndNil(Negocio); FreeAndNil(ObjVO); end; end; function TRecadoController.StatusAbertura: TStatusVO; var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try Result := TConverte.JSONToObject<TStatusVO>(Negocio.StatusAberturaRecados); finally FreeAndNil(Negocio); dm.Desconectar; end; end; function TRecadoController.TextoEmail(AId: Integer): string; var sTexto: string; sStatus: string; begin if AId = 0 then begin Result := ''; Exit; end; LocalizarId(AId); if Self.ModoAbrEnc = '' then begin if Trim(FModel.CDSCadastroRec_DescricaoFinal.AsString) = '' then Self.ModoAbrEnc := 'A' else Self.ModoAbrEnc := 'E'; end; sStatus := '(Encerrado)'; if Self.ModoAbrEnc = 'A' then sStatus := '(Aberto)'; sTexto := 'Recado Sistema Domper: ' + sStatus +'<br><br>'; sTexto := sTexto + 'Id: ' + FormatFloat('000000', FModel.CDSCadastroRec_Id.AsFloat) + '<br>'; sTexto := sTexto + 'Data: ' + FModel.CDSCadastroRec_data.AsString + ' Hora: ' + FModel.CDSCadastroRec_Hora.AsString + '<br>'; sTexto := sTexto + 'Usuário Lcto: ' + FModel.CDSCadastroNomeUsuarioLcto.AsString + '<br>'; sTexto := sTexto + 'Nivel: ' + FModel.CDSCadastroRec_Nivel.AsString + '<br>'; sTexto := sTexto + 'Razão Social: ' + FModel.CDSCadastroRec_RazaoSocial.AsString + '<br>'; sTexto := sTexto + 'Endereço: ' + FModel.CDSCadastroRec_Endereco.AsString + '<br>'; sTexto := sTexto + 'Telefone: ' + FModel.CDSCadastroRec_Telefone.AsString + '<br>'; sTexto := sTexto + 'Contato: ' + FModel.CDSCadastroRec_Contato.AsString + '<br>'; sTexto := sTexto + 'Usuário Destino: ' + FModel.CDSCadastroNomeUsuarioDest.AsString + '<br>'; sTexto := sTexto + 'Tipo: ' + FModel.CDSCadastroTip_Nome.AsString + '<br>'; sTexto := sTexto + 'Status: ' + FModel.CDSCadastroSta_Nome.AsString + '<br>'; sTexto := sTexto + 'Descrição: <br>' + FModel.CDSCadastroRec_DescricaoInicial.AsString; if Self.ModoAbrEnc = 'E' then // em Encerrado sTexto := sTexto + '<br><br> Descrição Encerramento: <br>' + FModel.CDSCadastroRec_DescricaoFinal.AsString; Result := sTexto; end; procedure TRecadoController.TipoUmRegistro; var obj: TTipoController; Model: TTipoVO; begin obj := TTipoController.Create; try Model := obj.RetornoUmRegistro(prRecado); if Model.Id > 0 then begin FModel.CDSCadastroRec_Tipo.AsInteger := Model.Id; FModel.CDSCadastroTip_Codigo.AsInteger := Model.Codigo; FModel.CDSCadastroTip_Nome.AsString := Model.Nome; end; finally FreeAndNil(obj); FreeAndNil(Model); end; end; end.
unit G2Mobile.Model.Parametro; interface uses FMX.ListView, uDmDados, System.SysUtils, IdSSLOpenSSLHeaders, FireDAC.Comp.Client, FMX.Dialogs, FMX.ListView.Appearances, FMX.ListView.Types, System.Classes, Datasnap.DBClient, FireDAC.Comp.DataSet, Data.DB, G2Mobile.Controller.Parametro, FMX.Objects, uFrmUtilFormate, Form_Mensagem, uRESTDWPoolerDB; const CONST_DELETEPARAMETRO = 'DELETE FROM PARAMETROS'; CONST_PARAMETROSERVIDOR = 'SELECT TOP 1 BLOQ_CLIENTES, DOC_AVISTA, REG_DESCTO, LOGO, ' + ' ISNULL((SELECT ID_TABLET FROM T_TABLETS WHERE DEVICEID = :deviceID' + ' AND STATUS = 1),0) AS ID_TABLET, getdate() AS DT_SINC, BLOQ_VLR_MIN, UNID_MED FROM T_CONFIG'; CONST_INSERTPARAMETROS = ' INSERT INTO PARAMETROS ( BLOQ_CLIENTES, DOC_AVISTA, REG_DESCTO, LOGO, ID_TABLET, BLOQ_VLR_MIN, DT_SINC, UNID_MED) VALUES ' + '( :BLOQ_CLIENTES, :DOC_AVISTA, :REG_DESCTO, :LOGO, :ID_TABLET, :BLOQ_VLR_MIN, :DT_SINC, :UNID_MED)'; CONST_LOGOEMPRESA = 'SELECT LOGO FROM PARAMETROS'; CONST_PARAMETRO = 'SELECT * FROM PARAMETROS'; CONST_VALIDATABLET = 'select id_tablet from parametros'; type TModelParametros = class(TInterfacedObject, iModelParametros) private FQry: TFDQuery; FRdwSQLTemp: TRESTDWClientSQL; public constructor create; destructor destroy; override; class function new: iModelParametros; function BuscaParametrosServidor(DeviceId: String; ADataSet: TFDMemTable): iModelParametros; function PopulaParametrosSqLite(ADataSet: TFDMemTable): iModelParametros; function LimpaTabelaParametros: iModelParametros; function RetornaLogo(AImage: TImage): iModelParametros; function VerificaTablet: Boolean; function Parametro(value: String): Variant; end; implementation { TModelParametros } class function TModelParametros.new: iModelParametros; begin result := self.create; end; constructor TModelParametros.create; begin FQry := TFDQuery.create(nil); FQry.Connection := DmDados.ConexaoInterna; FQry.FetchOptions.RowsetSize := 50000; FQry.Active := false; FQry.SQL.Clear; FRdwSQLTemp := TRESTDWClientSQL.create(nil); FRdwSQLTemp.DataBase := DmDados.RESTDWDataBase1; FRdwSQLTemp.BinaryRequest := True; FRdwSQLTemp.FormatOptions.MaxStringSize := 10000; FRdwSQLTemp.Active := false; FRdwSQLTemp.SQL.Clear; end; destructor TModelParametros.destroy; begin FreeAndNil(FQry); FreeAndNil(FRdwSQLTemp); inherited; end; function TModelParametros.LimpaTabelaParametros: iModelParametros; begin result := self; FQry.ExecSQL(CONST_DELETEPARAMETRO); end; function TModelParametros.BuscaParametrosServidor(DeviceId: String; ADataSet: TFDMemTable): iModelParametros; begin result := self; FRdwSQLTemp.SQL.Text := CONST_PARAMETROSERVIDOR; FRdwSQLTemp.ParamByName('deviceID').AsString := DeviceId; FRdwSQLTemp.Active := True; FRdwSQLTemp.RecordCount; ADataSet.CopyDataSet(FRdwSQLTemp, [coStructure, coRestart, coAppend]); end; function TModelParametros.PopulaParametrosSqLite(ADataSet: TFDMemTable): iModelParametros; var i: Integer; foto: TStream; img_foto: TImage; begin result := self; img_foto := TImage.create(nil); ADataSet.First; try FQry.SQL.Text := CONST_INSERTPARAMETROS; foto := TStream.create; foto := ADataSet.CreateBlobStream(ADataSet.FieldByName('LOGO'), TBlobStreamMode.bmRead); img_foto.Bitmap.LoadFromStream(foto); FQry.ParamByName('BLOQ_CLIENTES').AsInteger := ADataSet.FieldByName('BLOQ_CLIENTES').AsInteger; FQry.ParamByName('DOC_AVISTA').AsInteger := ADataSet.FieldByName('DOC_AVISTA').AsInteger; FQry.ParamByName('REG_DESCTO').AsInteger := ADataSet.FieldByName('REG_DESCTO').AsInteger; FQry.ParamByName('LOGO').Assign(img_foto.Bitmap); FQry.ParamByName('ID_TABLET').AsInteger := ADataSet.FieldByName('ID_TABLET').AsInteger; FQry.ParamByName('BLOQ_VLR_MIN').AsInteger := ADataSet.FieldByName('BLOQ_VLR_MIN').AsInteger; FQry.ParamByName('DT_SINC').AsDateTime := ADataSet.FieldByName('DT_SINC').AsDateTime; FQry.ParamByName('UNID_MED').AsInteger := ADataSet.FieldByName('UNID_MED').AsInteger; FQry.ExecSQL; finally FreeAndNil(img_foto); end; end; function TModelParametros.RetornaLogo(AImage: TImage): iModelParametros; var vStream: TMemoryStream; begin result := self; FQry.Open(CONST_LOGOEMPRESA); vStream := TMemoryStream.create; TBlobField(FQry.FieldByName('logo')).SaveToStream(vStream); vStream.Position := 0; AImage.MultiResBitmap.LoadItemFromStream(vStream, 1); vStream.Free; end; function TModelParametros.Parametro(value: String): Variant; begin FQry.Open(CONST_PARAMETRO); result := FQry.FieldByName(value).AsVariant; end; function TModelParametros.VerificaTablet: Boolean; begin FQry.Open(CONST_VALIDATABLET); {$IF DEFINED (ANDROID)} if (FQry.FieldByName('id_tablet').AsInteger <> 0) then result := True else result := false; {$ENDIF} {$IFDEF MSWINDOWS} result := True {$ENDIF} end; end.
unit MFichas.Model.GrupoProduto; interface uses System.SysUtils, MFichas.Model.GrupoProduto.Interfaces, MFichas.Model.GrupoProduto.Metodos.Buscar, MFichas.Model.GrupoProduto.Metodos.Cadastrar, MFichas.Model.Entidade.GRUPOPRODUTO, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, ORMBR.Container.ObjectSet, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.FDMemTable, ORMBR.Container.DataSet.Interfaces, FireDAC.Comp.Client, MFichas.Model.GrupoProduto.Metodos.Editar; type TModelGrupoProduto = class(TInterfacedObject, iModelGrupoProduto, iModelGrupoProdutoMetodos) private FEntidade : TGRUPOPRODUTO; FConn : iModelConexaoSQL; FDAOObjectSet: iContainerObjectSet<TGRUPOPRODUTO>; FDAODataSet : iContainerDataSet<TGRUPOPRODUTO>; FFDMemTable : TFDMemTable; constructor Create; public destructor Destroy; override; class function New: iModelGrupoProduto; function Metodos : iModelGrupoProdutoMetodos; function Entidade : TGRUPOPRODUTO; overload; function Entidade(AEntidade: TGRUPOPRODUTO): iModelGrupoProduto; overload; function DAO : iContainerObjectSet<TGRUPOPRODUTO>; function DAODataSet : iContainerDataSet<TGRUPOPRODUTO>; //METODOS function Cadastrar: iModelGrupoProdutoMetodosCadastrar; function Editar : iModelGrupoProdutoMetodosEditar; function Buscar : iModelGrupoProdutoMetodosBuscar; function &End : iModelGrupoProduto; end; implementation { TModelGrupoProduto } function TModelGrupoProduto.Buscar: iModelGrupoProdutoMetodosBuscar; begin Result := TModelGrupoProdutoMetodosBuscar.New(Self); end; function TModelGrupoProduto.Cadastrar: iModelGrupoProdutoMetodosCadastrar; begin Result := TModelGrupoProdutoMetodosCadastrar.New(Self); end; function TModelGrupoProduto.Editar: iModelGrupoProdutoMetodosEditar; begin Result := TModelGrupoProdutoMetodosEditar.New(Self); end; function TModelGrupoProduto.&End: iModelGrupoProduto; begin Result := Self; end; function TModelGrupoProduto.Entidade: TGRUPOPRODUTO; begin Result := FEntidade; end; function TModelGrupoProduto.Entidade( AEntidade: TGRUPOPRODUTO): iModelGrupoProduto; begin Result := Self; FEntidade := AEntidade; end; constructor TModelGrupoProduto.Create; begin FEntidade := TGRUPOPRODUTO.Create; FConn := TModelConexaoFactory.New.ConexaoSQL; FDAOObjectSet := TContainerObjectSet<TGRUPOPRODUTO>.Create(FConn.Conn, 10); FFDMemTable := TFDMemTable.Create(nil); FDAODataSet := TContainerFDMemTable<TGRUPOPRODUTO>.Create(FConn.Conn, FFDMemTable); end; function TModelGrupoProduto.DAO: iContainerObjectSet<TGRUPOPRODUTO>; begin Result := FDAOObjectSet; end; function TModelGrupoProduto.DAODataSet: iContainerDataSet<TGRUPOPRODUTO>; begin Result := FDAODataSet; end; destructor TModelGrupoProduto.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); FreeAndNil(FFDMemTable); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; FFDMemTable.Free; FFDMemTable.DisposeOf; {$ENDIF} inherited; end; function TModelGrupoProduto.Metodos: iModelGrupoProdutoMetodos; begin Result := Self; end; class function TModelGrupoProduto.New: iModelGrupoProduto; begin Result := Self.Create; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2013 Embarcadero Technologies, Inc. } { } { Copyright and license exceptions noted in source } { } {*******************************************************} unit Posix.StrOpts platform; {$WEAKPACKAGEUNIT} interface uses Posix.Base, Posix.SysTypes; {$IFDEF MACOS} {$I osx/StrOptsTypes.inc} {$ENDIF MACOS} {$IFDEF LINUX} {$I linux/StrOptsTypes.inc} {$ENDIF LINUX} {$I StrOptsAPI.inc} implementation {$IFDEF MACOS} function IOCPARM_LEN(x: UInt32): UInt32; begin Result := (x shr 16) and IOCPARM_MASK; end; function IOCBASECMD(x: UInt32): UInt32; begin Result := x and not(IOCPARM_MASK shl 16); end; function IOCGROUP(x: UInt32): UInt32; begin Result := (x shr 8) and $FF; end; function _IOC(inout, group, num, len: UInt32): UInt32; begin Result := inout or ((len and IOCPARM_MASK) shl 16) or (group shl 8) or num; end; function _IO(g, n: UInt32): UInt32; begin Result := _IOC(IOC_VOID, g, n, 0); end; function __IOR(g, n, t: UInt32): UInt32; begin Result := _IOC(IOC_OUT, g, n, t); { t is SizeOf(type) instead type} end; function __IOW(g, n, t: UInt32): UInt32; begin Result := _IOC(IOC_IN, g, n, t); { t is SizeOf(type) instead type} end; function __IOWR(g, n, t: UInt32): UInt32; begin Result := _IOC(IOC_INOUT, g, n, t); { t is SizeOf(type) instead type} end; {$ENDIF MACOS} end.
{ rxcustomchartpanel unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit rxcustomchartpanel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls; type TRxCustomChart = class; TRxChartSeriesItem = class; { TRxChartValuesItem } TRxChartValuesItem = class(TCollectionItem) private FCaption: string; FColor: TColor; FVisible: boolean; FLabel:double; procedure SetCaption(const AValue: string); procedure SetColor(const AValue: TColor); procedure SetVisible(const AValue: boolean); protected function GetDisplayName: string; override; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; published property Caption:string read FCaption write SetCaption; property Color:TColor read FColor write SetColor; property Visible:boolean read FVisible write SetVisible; property LabelAsFloat:double read FLabel write FLabel; property LabelAsDateTime:TDateTime read FLabel write FLabel; end; { TRxChartValues } TRxChartValues = class(TCollection) private FRxChartSeriesItem:TRxChartSeriesItem; public constructor Create(ARxChartSeriesItem:TRxChartSeriesItem); end; { TRxChartSeriesItem } TRxChartSeriesItem = class(TCollectionItem) private FCaption: string; FColor: TColor; FVisible: boolean; FChartValues:TRxChartValues; function GetItems: TRxChartValues; procedure SetCaption(const AValue: string); procedure SetColor(const AValue: TColor); procedure SetItems(const AValue: TRxChartValues); procedure SetVisible(const AValue: boolean); protected function GetDisplayName: string; override; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; published property Values:TRxChartValues read GetItems write SetItems; property Caption:string read FCaption write SetCaption; property Color:TColor read FColor write SetColor; property Visible:boolean read FVisible write SetVisible; end; { TRxChartSeries } TRxChartSeries = class(TCollection) private FChart:TRxCustomChart; function GetToolbarItem(Index: Integer): TRxChartSeriesItem; procedure SetToolbarItem(Index: Integer; const AValue: TRxChartSeriesItem); public constructor Create(AChart:TRxCustomChart); property Items[Index: Integer]: TRxChartSeriesItem read GetToolbarItem write SetToolbarItem; default; published end; { TRxCustomChart } TRxCustomChart = class(TCustomPanel) private FChartSeries:TRxChartSeries; function GetItems: TRxChartSeries; procedure SetItems(const AValue: TRxChartSeries); { Private declarations } protected property ChartSeries:TRxChartSeries read GetItems write SetItems; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } end; TRxChart = class(TRxCustomChart) published property ChartSeries; property Align; property Alignment; property Anchors; property AutoSize; property BorderSpacing; property BevelInner; property BevelOuter; property BevelWidth; property BorderWidth; property BorderStyle; property Caption; property Constraints; property DragMode; property Enabled; property Font; property FullRepaint; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; end; implementation { TRxChartSeriesItem } procedure TRxChartSeriesItem.SetCaption(const AValue: string); begin if FCaption=AValue then exit; FCaption:=AValue; end; function TRxChartSeriesItem.GetItems: TRxChartValues; begin Result:=FChartValues; end; procedure TRxChartSeriesItem.SetColor(const AValue: TColor); begin if FColor=AValue then exit; FColor:=AValue; end; procedure TRxChartSeriesItem.SetItems(const AValue: TRxChartValues); begin FChartValues.Assign(AValue); end; procedure TRxChartSeriesItem.SetVisible(const AValue: boolean); begin if FVisible=AValue then exit; FVisible:=AValue; end; function TRxChartSeriesItem.GetDisplayName: string; begin if FCaption<>'' then Result:=FCaption else Result:=inherited GetDisplayName; end; constructor TRxChartSeriesItem.Create(ACollection: TCollection); begin inherited Create(ACollection); FChartValues:=TRxChartValues.Create(Self); end; destructor TRxChartSeriesItem.Destroy; begin FreeAndNil(FChartValues); inherited Destroy; end; { TRxChartSeries } function TRxChartSeries.GetToolbarItem(Index: Integer): TRxChartSeriesItem; begin result := TRxChartSeriesItem( inherited Items[Index] ); end; procedure TRxChartSeries.SetToolbarItem(Index: Integer; const AValue: TRxChartSeriesItem); begin Items[Index].Assign( AValue ); end; constructor TRxChartSeries.Create(AChart: TRxCustomChart); begin inherited Create(TRxChartSeriesItem); FChart:=AChart; end; { TRxCustomChart } function TRxCustomChart.GetItems: TRxChartSeries; begin Result:=FChartSeries; end; procedure TRxCustomChart.SetItems(const AValue: TRxChartSeries); begin FChartSeries.Assign(AValue); end; constructor TRxCustomChart.Create(AOwner: TComponent); begin inherited Create(AOwner); FChartSeries:=TRxChartSeries.Create(Self); end; destructor TRxCustomChart.Destroy; begin FreeAndNil(FChartSeries); inherited Destroy; end; { TRxChartValues } constructor TRxChartValues.Create(ARxChartSeriesItem: TRxChartSeriesItem); begin inherited Create(TRxChartValuesItem); FRxChartSeriesItem := ARxChartSeriesItem; end; { TRxChartValuesItem } procedure TRxChartValuesItem.SetCaption(const AValue: string); begin if FCaption=AValue then exit; FCaption:=AValue; end; procedure TRxChartValuesItem.SetColor(const AValue: TColor); begin if FColor=AValue then exit; FColor:=AValue; end; procedure TRxChartValuesItem.SetVisible(const AValue: boolean); begin if FVisible=AValue then exit; FVisible:=AValue; end; function TRxChartValuesItem.GetDisplayName: string; begin if FCaption<>'' then Result:=FCaption else Result:=inherited GetDisplayName; end; constructor TRxChartValuesItem.Create(ACollection: TCollection); begin inherited Create(ACollection); end; destructor TRxChartValuesItem.Destroy; begin inherited Destroy; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Xml, RemObjects.Elements.EUnit; type ElementTest = public class (Test) private Doc: XmlDocument; Data: XmlElement; public method Setup; override; method AddChild; method RemoveChild; method ReplaceChild; method GetAttribute; method GetAttributeNode; method SetAttribute; method SetAttirubteNS; method SetAttributeNode; method SetAttributeNodeNS; method RemoveAttribute; method RemoveAttributeNode; method HasAttribute; method Attributes; method NodeType; method GetElementsByTagName; method Inserting; end; implementation method ElementTest.Setup; begin Doc := XmlDocument.FromString(XmlTestData.PIXml); Assert.IsNotNil(Doc); Data := Doc["Root"]; Assert.IsNotNil(Doc); end; method ElementTest.AddChild; begin var Node := Data.FirstChild as XmlElement; Assert.IsNotNil(Node); Assert.AreEqual(Node.ChildCount, 3); var lValue := Doc.CreateElement("User"); Node.AddChild(lValue); Assert.AreEqual(Node.ChildCount, 4); Assert.AreEqual(Data.LastChild.ChildCount, 1); lValue := Data.LastChild.FirstChild as XmlElement; Node.AddChild(lValue); Assert.AreEqual(Node.ChildCount, 5); Assert.AreEqual(Data.LastChild.ChildCount, 0); Assert.Throws(->Node.AddChild(nil)); end; method ElementTest.RemoveChild; begin var Node := Data.FirstChild as XmlElement; Assert.IsNotNil(Node); Assert.AreEqual(Node.ChildCount, 3); var lValue := Node.FirstChild; Node.RemoveChild(lValue); Assert.AreEqual(Node.ChildCount, 2); Node.AddChild(lValue); Assert.AreEqual(Node.ChildCount, 3); Assert.Throws(->Node.RemoveChild(nil)); end; method ElementTest.ReplaceChild; begin var Node := Data.FirstChild as XmlElement; Assert.IsNotNil(Node); Assert.AreEqual(Node.ChildCount, 3); var lValue := Doc.CreateElement("Test"); var lExisting := Node.FirstChild; Node.ReplaceChild(lExisting, lValue); Assert.AreEqual(Node.ChildCount, 3); Assert.AreEqual(Node.FirstChild.LocalName, "Test"); Assert.Throws(->Node.ReplaceChild(nil, lValue)); Assert.Throws(->Node.ReplaceChild(lValue, nil)); Assert.Throws(->Node.ReplaceChild(lExisting, lValue)); //not exists lExisting := Node.FirstChild; lValue := Data.LastChild.FirstChild as XmlElement; Node.ReplaceChild(lExisting, lValue); Assert.AreEqual(XmlElement(Node.FirstChild).GetAttribute("Name"), "Admin"); Assert.AreEqual(Data.LastChild.ChildCount, 0); end; method ElementTest.GetAttribute; begin var Node := Data.FirstChild.FirstChild as XmlElement; Assert.IsNotNil(Node); Assert.AreEqual(Node.GetAttribute("Name"), "First"); Assert.AreEqual(Node.GetAttribute("Id"), "1"); Assert.IsNil(Node.GetAttribute(nil)); Assert.IsNil(Node.GetAttribute("NotExisting")); Node := Node.FirstChild.FirstChild as XmlElement; Assert.AreEqual(Node.GetAttribute("verified", "http://example.com/config/"), "true"); Assert.IsNil(Node.GetAttribute("verified", "http://example.com/cfg/")); Assert.IsNil(Node.GetAttribute("x", "http://example.com/config/")); Assert.Throws(->Node.GetAttribute("verified", nil)); Assert.Throws(->Node.GetAttribute(nil, "http://example.com/config/")); end; method ElementTest.GetAttributeNode; begin var Node := Data.FirstChild.FirstChild as XmlElement; Assert.IsNotNil(Node); Assert.AreEqual(Node.GetAttributeNode("Name"):Value, "First"); Assert.AreEqual(Node.GetAttributeNode("Id"):Value, "1"); Assert.IsNil(Node.GetAttributeNode(nil)); Assert.IsNil(Node.GetAttributeNode("NotExisting")); Node := Node.FirstChild.FirstChild as XmlElement; Assert.AreEqual(Node.GetAttributeNode("verified", "http://example.com/config/"):Value, "true"); Assert.IsNil(Node.GetAttributeNode("verified", "http://example.com/cfg/")); Assert.IsNil(Node.GetAttributeNode("x", "http://example.com/config/")); Assert.Throws(->Node.GetAttributeNode("verified", nil)); Assert.Throws(->Node.GetAttributeNode(nil, "http://example.com/config/")); end; method ElementTest.SetAttribute; begin var Node := Data.FirstChild.FirstChild as XmlElement; Assert.IsNotNil(Node); Assert.AreEqual(length(Node.GetAttributes), 2); Node.SetAttribute("Logged", "YES"); Assert.AreEqual(length(Node.GetAttributes), 3); Assert.AreEqual(Node.GetAttribute("Logged"), "YES"); //replace existing Node.SetAttribute("Logged", "NO"); Assert.AreEqual(length(Node.GetAttributes), 3); Assert.AreEqual(Node.GetAttribute("Logged"), "NO"); Node.SetAttribute("Logged", ""); Assert.AreEqual(length(Node.GetAttributes), 3); Assert.AreEqual(Node.GetAttribute("Logged"), ""); //Remove Node.SetAttribute("Logged", nil); Assert.AreEqual(length(Node.GetAttributes), 2); Assert.Throws(->Node.SetAttribute(nil, "true")); end; method ElementTest.SetAttirubteNS; begin var Node := Data.FirstChild.FirstChild.FirstChild.FirstChild as XmlElement; Assert.IsNotNil(Node); Assert.AreEqual(length(Node.GetAttributes), 1); Node.SetAttribute("Logged", "http://example.com/config/","YES"); Assert.AreEqual(length(Node.GetAttributes), 2); Assert.AreEqual(Node.GetAttribute("Logged", "http://example.com/config/"), "YES"); //replace existing Node.SetAttribute("Logged", "http://example.com/config/" ,"NO"); Assert.AreEqual(length(Node.GetAttributes), 2); Assert.AreEqual(Node.GetAttribute("Logged", "http://example.com/config/"), "NO"); Node.SetAttribute("Logged", "http://example.com/config/", ""); Assert.AreEqual(length(Node.GetAttributes), 2); Assert.AreEqual(Node.GetAttribute("Logged", "http://example.com/config/"), ""); //Remove Node.SetAttribute("Logged", "http://example.com/config/", nil); Assert.AreEqual(length(Node.GetAttributes), 1); Assert.Throws(->Node.SetAttribute(nil, "http://example.com/config/", "true")); Assert.Throws(->Node.SetAttribute("Logged", nil, "true")); end; method ElementTest.SetAttributeNode; begin var Node := Data.FirstChild.FirstChild as XmlElement; var Attr := Doc.CreateAttribute("Logged"); Attr.Value := "YES"; Assert.IsNotNil(Attr); Assert.AreEqual(length(Node.GetAttributes), 2); Node.SetAttributeNode(Attr); Assert.AreEqual(length(Node.GetAttributes), 3); Assert.AreEqual(Node.GetAttribute("Logged"), "YES"); Attr.Value := "TEST"; // changing value Assert.AreEqual(Node.GetAttribute("Logged"), "TEST"); //replace existing Attr := Doc.CreateAttribute("Logged"); Attr.Value := "NO"; Node.SetAttributeNode(Attr); Assert.AreEqual(length(Node.GetAttributes), 3); Assert.AreEqual(Node.GetAttribute("Logged"), "NO"); Assert.Throws(->Node.SetAttributeNode(nil)); end; method ElementTest.SetAttributeNodeNS; begin var Node := Data.FirstChild.FirstChild.FirstChild.FirstChild as XmlElement; var Attr := Doc.CreateAttribute("cfg:Logged", "http://example.com/config/"); Attr.Value := "YES"; Assert.IsNotNil(Node); Assert.AreEqual(length(Node.GetAttributes), 1); Node.SetAttributeNode(Attr); Assert.AreEqual(length(Node.GetAttributes), 2); Assert.AreEqual(Node.GetAttribute("Logged", "http://example.com/config/"), "YES"); Attr.Value := "TEST"; Assert.AreEqual(Node.GetAttribute("Logged", "http://example.com/config/"), "TEST"); //replace existing Attr := Doc.CreateAttribute("cfg:Logged", "http://example.com/config/"); Attr.Value := "NO"; Node.SetAttributeNode(Attr); Assert.AreEqual(length(Node.GetAttributes), 2); Assert.AreEqual(Node.GetAttribute("Logged", "http://example.com/config/"), "NO"); end; method ElementTest.RemoveAttribute; begin var Node := Data.FirstChild.FirstChild as XmlElement; Assert.AreEqual(length(Node.GetAttributes), 2); Node.RemoveAttribute("Id"); Assert.AreEqual(length(Node.GetAttributes), 1); Assert.IsNil(Node.GetAttribute("Id")); Node.RemoveAttribute(nil); Assert.AreEqual(length(Node.GetAttributes), 1); Node.RemoveAttribute("NotExisting"); Assert.AreEqual(length(Node.GetAttributes), 1); Node := Node.FirstChild.FirstChild as XmlElement; Assert.AreEqual(length(Node.GetAttributes), 1); Node.RemoveAttribute("verified", "http://example.com/config/"); Assert.AreEqual(length(Node.GetAttributes), 0); Assert.Throws(->Node.RemoveAttribute(nil, "http://example.com/config/")); Assert.Throws(->Node.RemoveAttribute("verified", nil)); end; method ElementTest.RemoveAttributeNode; begin var Node := Data.FirstChild.FirstChild as XmlElement; Assert.AreEqual(length(Node.GetAttributes), 2); Node.RemoveAttributeNode(Node.GetAttributeNode("Id")); Assert.AreEqual(length(Node.GetAttributes), 1); Assert.IsNil(Node.GetAttribute("Id")); Assert.Throws(->Node.RemoveAttributeNode(nil)); Assert.Throws(->Node.RemoveAttributeNode(Doc.CreateAttribute("NotExists"))); Node := Node.FirstChild.FirstChild as XmlElement; Assert.AreEqual(length(Node.GetAttributes), 1); Node.RemoveAttributeNode(Node.GetAttributeNode("verified", "http://example.com/config/")); Assert.AreEqual(length(Node.GetAttributes), 0); end; method ElementTest.HasAttribute; begin var Node := Data.FirstChild.FirstChild as XmlElement; Assert.IsTrue(Node.HasAttribute("Name")); Assert.IsTrue(Node.HasAttribute("Id")); Assert.IsFalse(Node.HasAttribute("NameX")); Assert.IsFalse(Node.HasAttribute(nil)); Node := Node.FirstChild.FirstChild as XmlElement; Assert.IsTrue(Node.HasAttribute("verified", "http://example.com/config/")); Assert.IsFalse(Node.HasAttribute("verified", "")); Assert.IsFalse(Node.HasAttribute("verifiedX", "http://example.com/config/")); Assert.Throws(->Node.HasAttribute("verifiedX", nil)); Assert.Throws(->Node.HasAttribute(nil, "http://example.com/config/")); end; method ElementTest.Attributes; begin var Node := Data.FirstChild.FirstChild as XmlElement; var Expected := new Sugar.Collections.List<String>; Expected.Add("Name"); Expected.Add("Id"); Assert.AreEqual(length(Node.GetAttributes), 2); for i: Integer := 0 to length(Node.GetAttributes) - 1 do Assert.IsTrue(Expected.Contains(Node.GetAttributes[i].Name)); Node := Doc.CreateElement("Sample"); Assert.AreEqual(length(Node.GetAttributes), 0); end; method ElementTest.NodeType; begin Assert.IsTrue(Data.NodeType = XmlNodeType.Element); end; method ElementTest.GetElementsByTagName; begin //Must retrieve elements with specified tag name from all descendants var Actual := Data.GetElementsByTagName("User"); var Expected := new Sugar.Collections.List<String>; Expected.Add("First"); Expected.Add("Second"); Expected.Add("Third"); Expected.Add("Admin"); Assert.AreEqual(length(Actual), 4); for i: Integer := 0 to length(Actual) - 1 do begin Assert.AreEqual(Actual[i].NodeType, XmlNodeType.Element); var Element := Actual[i] as XmlElement; Assert.IsTrue(Expected.Contains(Element.GetAttribute("Name"))); end; Actual := Data.GetElementsByTagName("mail", "http://example.com/config/"); Assert.AreEqual(length(Actual), 1); Assert.IsTrue(Actual[0].NodeType = XmlNodeType.Element); Assert.AreEqual(Actual[0].Value, "first@example.com"); end; method ElementTest.Inserting; begin var Root := Doc.CreateElement("Test"); Assert.IsNotNil(Root); //Attribute var Element: XmlNode := Doc.CreateAttribute("Id"); Assert.IsNotNil(Element); Root.AddChild(Element); Assert.AreEqual(Root.ChildCount, 0); Assert.AreEqual(length(Root.GetAttributes), 1); //Element Element := Doc.CreateElement("SubNode"); Assert.IsNotNil(Element); Root.AddChild(Element); Assert.AreEqual(Root.ChildCount, 1); //cdata XmlElement(Element).AddChild(Doc.CreateCDataSection("String")); Assert.AreEqual(Element.ChildCount, 1); Assert.AreEqual(Element.ChildNodes[0].NodeType, XmlNodeType.CDATA); //text Element := Doc.CreateElement("SubNode"); Root.AddChild(Element); Assert.AreEqual(Root.ChildCount, 2); XmlElement(Element).AddChild(Doc.CreateTextNode("String")); Assert.AreEqual(Element.ChildCount, 1); Assert.AreEqual(Element.ChildNodes[0].NodeType, XmlNodeType.Text); //comment Element := Doc.CreateComment("Comment"); Assert.IsNotNil(Element); Root.AddChild(Element); Assert.AreEqual(Root.ChildCount, 3); //PI Element := Doc.CreateProcessingInstruction("custom", ""); Assert.IsNotNil(Element); Root.AddChild(Element); Assert.AreEqual(Root.ChildCount, 4); end; end.