text
stringlengths
14
6.51M
unit DamLanguage; {$IFDEF FPC}{$mode delphi}{$ENDIF} interface uses DamUnit; {$R Dam_Resource.res} type TDamLanguageDefinition = record OK, Yes, No, Info, Quest, Warn, Error, Msg: string; end; procedure SetDamLangBySysLang(var DamLang: TDamLanguage); function LoadLanguage(Language: TDamLanguage): TDamLanguageDefinition; implementation uses {$IFDEF FPC} Classes, SysUtils, IniFiles, Windows {$ELSE} System.Classes, System.SysUtils, System.IniFiles, Winapi.Windows {$ENDIF}; type TLanguageParams = record Name: string; DamLang: TDamLanguage; SysLang: ShortInt; end; const LANGUAGES_PARAMS: array[0..12] of TLanguageParams = ( (Name: 'English' ; DamLang: dgEnglish ; SysLang: LANG_ENGLISH ), (Name: 'Portuguese'; DamLang: dgPortuguese; SysLang: LANG_PORTUGUESE), (Name: 'Spanish' ; DamLang: dgSpanish ; SysLang: LANG_SPANISH ), (Name: 'German' ; DamLang: dgGerman ; SysLang: LANG_GERMAN ), (Name: 'Italian' ; DamLang: dgItalian ; SysLang: LANG_ITALIAN ), (Name: 'Chinese' ; DamLang: dgChinese ; SysLang: LANG_CHINESE ), (Name: 'Japanese' ; DamLang: dgJapanese ; SysLang: LANG_JAPANESE ), (Name: 'Greek' ; DamLang: dgGreek ; SysLang: LANG_GREEK ), (Name: 'Russian' ; DamLang: dgRussian ; SysLang: LANG_RUSSIAN ), (Name: 'French' ; DamLang: dgFrench ; SysLang: LANG_FRENCH ), (Name: 'Polish' ; DamLang: dgPolish ; SysLang: LANG_POLISH ), (Name: 'Dutch' ; DamLang: dgDutch ; SysLang: LANG_DUTCH ), (Name: 'Turkish' ; DamLang: dgTurkish ; SysLang: LANG_TURKISH ) ); procedure SetDamLangBySysLang(var DamLang: TDamLanguage); var P: TLanguageParams; begin for P in LANGUAGES_PARAMS do if P.SysLang = SysLocale.PriLangID then begin DamLang := P.DamLang; Break; end; //if not found, it's another unsupported language - leave initial language end; function GetLangNameByDamLang(DamLang: TDamLanguage): string; var P: TLanguageParams; begin for P in LANGUAGES_PARAMS do if P.DamLang = DamLang then Exit(P.Name); raise Exception.Create('Invalid language'); end; function LoadLanguage(Language: TDamLanguage): TDamLanguageDefinition; var aLang: string; R: TResourceStream; S: TStringList; Ini: TMemIniFile; begin aLang := GetLangNameByDamLang(Language); S := TStringList.Create; try R := TResourceStream.Create({$IFDEF FPC}HInstance{$ELSE}FindClassHInstance(TDam){$ENDIF}, 'DAM_LANG', RT_RCDATA); try S.LoadFromStream(R, TEncoding.UTF8); finally R.Free; end; Ini := TMemIniFile.Create(EmptyStr); try Ini.SetStrings(S); S.Clear; Ini.ReadSectionValues(aLang, S); finally Ini.Free; end; if S.Count=0 then raise Exception.CreateFmt('Language "%s" not found in resource', [aLang]); with Result do begin OK := S.Values['OK']; Yes := S.Values['Yes']; No := S.Values['No']; Info := S.Values['Info']; Quest := S.Values['Quest']; Warn := S.Values['Warn']; Error := S.Values['Error']; Msg := S.Values['Msg']; end; finally S.Free; end; end; end.
unit RESTRequest4D.Request.Body; interface uses RESTRequest4D.Request.Body.Intf, REST.Client, System.JSON, REST.Types; type TRequestBody = class(TInterfacedObject, IRequestBody) private FRESTRequest: TRESTRequest; function Clear: IRequestBody; function Add(const AContent: string; const AContentType: TRESTContentType = ctNone): IRequestBody; overload; function Add(const AContent: TJSONObject; const AOwns: Boolean = True): IRequestBody; overload; function Add(const AContent: TJSONArray; const AOwns: Boolean = True): IRequestBody; overload; function Add(const AContent: TObject; const AOwns: Boolean = True): IRequestBody; overload; public constructor Create(const ARESTRequest: TRESTRequest); end; implementation uses System.SysUtils; const NO_CONTENT_SHOULD_BE_ADDED = 'No content should be added to the request body when the method is GET.'; { TRequestBody } function TRequestBody.Add(const AContent: string; const AContentType: TRESTContentType): IRequestBody; begin Result := Self; if FRESTRequest.Method = TRESTRequestMethod.rmGET then raise Exception.Create(NO_CONTENT_SHOULD_BE_ADDED); if not AContent.Trim.IsEmpty then FRESTRequest.Body.Add(AContent, AContentType); end; function TRequestBody.Add(const AContent: TJSONObject; const AOwns: Boolean): IRequestBody; begin Result := Self; if Assigned(AContent) then begin FRESTRequest.Body.Add(AContent); if AOwns then AContent.Free; end; end; function TRequestBody.Add(const AContent: TObject; const AOwns: Boolean): IRequestBody; begin Result := Self; if FRESTRequest.Method = TRESTRequestMethod.rmGET then raise Exception.Create(NO_CONTENT_SHOULD_BE_ADDED); if Assigned(AContent) then begin FRESTRequest.Body.Add(AContent); if AOwns then AContent.Free; end; end; function TRequestBody.Add(const AContent: TJSONArray; const AOwns: Boolean): IRequestBody; begin Result := Self; if FRESTRequest.Method = TRESTRequestMethod.rmGET then raise Exception.Create(NO_CONTENT_SHOULD_BE_ADDED); if Assigned(AContent) then begin Self.Add(AContent.ToString, ctAPPLICATION_JSON); if AOwns then AContent.Free; end; end; function TRequestBody.Clear: IRequestBody; begin Result := Self; FRESTRequest.ClearBody; end; constructor TRequestBody.Create(const ARESTRequest: TRESTRequest); begin FRESTRequest := ARESTRequest; end; end.
unit GX_BaseExpert; interface uses Classes, Graphics, GX_ConfigurationInfo; type TGX_BaseExpert = class(TObject) private FBitmap: TBitmap; protected FActive: Boolean; function GetShortCut: TShortCut; virtual; abstract; procedure SetActive(New: Boolean); virtual; procedure SetShortCut(Value: TShortCut); virtual; abstract; // Subkey used to store configuration details in the registry // defaults to GetName class function ConfigurationKey: string; virtual; // Return the file name of an icon associated with // the expert. Do not specify a path. // This bitmap must be included in the // GXIcons.rc file which in turn can be created // from all .bmp files located in the Images // directory by calling the _CreateGXIconsRc.bat // script located in that directory. // It is possible to return an empty string. This // signals that no icon file is available. function GetBitmapFileName: string; virtual; // Overrride to load any configuration settings procedure InternalLoadSettings(Settings: TExpertSettings); virtual; // Overrride to save any configuration settings procedure InternalSaveSettings(Settings: TExpertSettings); virtual; // do nothing, overridden by TGX_Expert and TEditorExpert because // theses settings are "traditionally" stored differently. procedure LoadActiveAndShortCut(Settings: TGExpertsSettings); virtual; // do nothing, overridden by TGX_Expert and TEditorExpert because // theses settings are "traditionally" stored differently. procedure SaveActiveAndShortCut(Settings: TGExpertsSettings); virtual; public // Internal name of expert for expert identification. class function GetName: string; virtual; destructor Destroy; override; function CanHaveShortCut: boolean; virtual; abstract; // displays a dialog saying there are no configuration options // see also HasConfigOptions procedure Configure; virtual; procedure Execute(Sender: TObject); virtual; abstract; // Get a reference to the bitmap for menu items, buttons, etc. // Note that this bitmap is loaded and unloaded on demand; // you will have to .Assign the bitmap to get a permanent copy. function GetBitmap: Graphics.TBitmap; virtual; // Name to be displayed for the expert in the GExperts // *configuration* dialog; this might be different from // the action caption (GetActionCaption) but is the default // for that as well. function GetDisplayName: string; virtual; // Describes the purpose of the expert. Displayed // as hint if the user points the mouse on the expert's icon // in the configuration dialog. function GetHelpString: string; virtual; // Returns 0, meaning: No default shortcut function GetDefaultShortCut: TShortCut; virtual; // Returns true, see also Configure function HasConfigOptions: Boolean; virtual; // Creates a Settings object and passes it to // the virtual methods // LoadActiveAndShortCut and InternalLoadSettings // override InternalLoadSettings to actually load the settings. procedure LoadSettings; // Creates a Settings object and passes it to // the virtual methods // SaveActiveAndShortCut and InternalSaveSettings // override InternalSaveSettings to actually save the settings. procedure SaveSettings; // Returns an empty string, overridden by TGX_Expert and TEditorExpert // to return the correct values. function GetOptionsBaseRegistryKey: string; virtual; // Defaults to True function IsDefaultActive: Boolean; virtual; property Active: Boolean read FActive write SetActive; property ShortCut: TShortCut read GetShortCut write SetShortCut; end; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, Dialogs, GX_GxUtils, GX_MessageBox, GX_IconMessageBox; { TGX_BaseExpert } destructor TGX_BaseExpert.Destroy; begin FreeAndNil(FBitmap); inherited; end; class function TGX_BaseExpert.ConfigurationKey: string; begin Result := GetName; end; procedure TGX_BaseExpert.Configure; resourcestring SNoConfigurationOptions = 'There are no configuration options for this expert.'; begin MessageDlg(SNoConfigurationOptions, mtInformation, [mbOK], 0); end; function TGX_BaseExpert.GetBitmap: Graphics.TBitmap; var BitmapFile: string; begin if not Assigned(FBitmap) then begin // Locate and load the bitmap for the expert if it exists. BitmapFile := GetBitmapFileName; if BitmapFile <> '' then begin if not GxLoadBitmapForExpert(BitmapFile, FBitmap) then begin {$IFOPT D+} SendDebugError('Missing bitmap ' + BitmapFile + ' for ' + Self.ClassName); {$ENDIF} ShowGxMessageBox(TShowMissingIconMessage, ChangeFileExt(BitmapFile, '.bmp')); end; end else begin {$IFOPT D+} SendDebugError('Bitmap missing for expert ' + Self.ClassName); {$ENDIF D+} end; end; Result := FBitmap; end; function TGX_BaseExpert.GetBitmapFileName: string; begin Result := GetName; end; function TGX_BaseExpert.GetDefaultShortCut: TShortCut; begin Result := 0; end; function TGX_BaseExpert.GetDisplayName: string; begin {$IFOPT D+} SendDebugError('The expert ' + Self.ClassName + ' does not provide a human-readable name'); {$ENDIF D+} Result := Self.ClassName; end; function TGX_BaseExpert.GetHelpString: string; begin Result := ''; end; class function TGX_BaseExpert.GetName: string; begin {$IFOPT D+} SendDebugError('The expert ' + Self.ClassName + ' does not provide a Name'); {$ENDIF D+} Result := Self.ClassName; end; function TGX_BaseExpert.GetOptionsBaseRegistryKey: string; begin Result := ''; end; function TGX_BaseExpert.HasConfigOptions: Boolean; begin Result := True; end; procedure TGX_BaseExpert.InternalLoadSettings(Settings: TExpertSettings); begin // do nothing end; procedure TGX_BaseExpert.InternalSaveSettings(Settings: TExpertSettings); begin // do nothing end; function TGX_BaseExpert.IsDefaultActive: Boolean; begin Result := True; end; procedure TGX_BaseExpert.LoadActiveAndShortCut(Settings: TGExpertsSettings); begin // do nothing here, overridden by TGX_Expert and TEditorExpert because // theses settings are "traditionally" stored differently. end; procedure TGX_BaseExpert.LoadSettings; var Settings: TGExpertsSettings; ExpSettings: TExpertSettings; begin Settings := TGExpertsSettings.Create(GetOptionsBaseRegistryKey); try LoadActiveAndShortCut(Settings); ExpSettings := Settings.CreateExpertSettings(ConfigurationKey); try InternalLoadSettings(ExpSettings); finally FreeAndNil(ExpSettings); end; finally FreeAndNil(Settings); end; end; procedure TGX_BaseExpert.SaveActiveAndShortCut(Settings: TGExpertsSettings); begin // do nothing here, overridden by TGX_Expert and TEditorExpert because // theses settings are "traditionally" stored differently. end; procedure TGX_BaseExpert.SaveSettings; var Settings: TGExpertsSettings; ExpSettings: TExpertSettings; begin Settings := TGExpertsSettings.Create(GetOptionsBaseRegistryKey); try SaveActiveAndShortCut(Settings); ExpSettings := Settings.CreateExpertSettings(ConfigurationKey); try InternalSaveSettings(ExpSettings); finally FreeAndNil(ExpSettings); end; finally FreeAndNil(Settings); end; end; procedure TGX_BaseExpert.SetActive(New: Boolean); begin FActive := New; end; end.
unit GX_IdeDock; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, Forms, Controls, MenuBar, Menus, Messages, // You must link to the DesignIde package to compile this unit DockForm; type {$IFDEF EnableIdeDockingSupport} TDummyPopupMenu = class(TPopupMenu) private OwnerMenu: TMenu; public function IsShortCut(var Message: TWMKey): Boolean; override; end; {$ENDIF EnableIdeDockingSupport} {$UNDEF TrickTheIdeAncestorForm} // this must always be undefined, so that {$IFDEF TrickTheIdeAncestorForm} // <--- this define is always false TfmIdeDockForm = class(TDummyIdeDockForm); {$ELSE} TfmIdeDockForm = class(TDockableForm) {$ENDIF TrickTheIdeAncestorForm} protected FMenuBar: TMenuBar; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {$IFDEF EnableIdeDockingSupport} {$ENDIF EnableIdeDockingSupport} end; type TIdeDockFormClass = class of TfmIdeDockForm; type EIdeDockError = class(Exception); IIdeDockManager = interface(IUnknown) ['{408FC1B1-BD7A-4401-93C2-B41E1D19580B}'] // Note: IdeDockFormName must be IDE-unique procedure RegisterDockableForm(IdeDockFormClass: TIdeDockFormClass; var IdeDockFormVar; const IdeDockFormName: string); procedure UnRegisterDockableForm( var IdeDockFormVar; const IdeDockFormName: string); procedure ShowForm(Form: TForm); end; function IdeDockManager: IIdeDockManager; implementation uses Windows, DeskForm, DeskUtil, GX_GenericClasses, GX_GxUtils; {$R *.dfm} type TIdeDockManager = class(TSingletonInterfacedObject, IIdeDockManager) public // Note: IdeDockFormName must be IDE-unique procedure RegisterDockableForm(IdeDockFormClass: TIdeDockFormClass; var IdeDockFormVar; const IdeDockFormName: string); procedure UnRegisterDockableForm( var IdeDockFormVar; const IdeDockFormName: string); procedure ShowForm(Form: TForm); end; { TIdeDockManager } procedure TIdeDockManager.ShowForm(Form: TForm); begin {$IFDEF EnableIdeDockingSupport} with Form as TDockableForm do begin if not Floating then begin ForceShow; FocusWindow(Form); end else Show; end; {$ELSE} Form.Show; {$ENDIF EnableIdeDockingSupport} end; procedure TIdeDockManager.RegisterDockableForm(IdeDockFormClass: TIdeDockFormClass; var IdeDockFormVar; const IdeDockFormName: string); begin {$IFDEF EnableIdeDockingSupport} if @RegisterFieldAddress <> nil then RegisterFieldAddress(IdeDockFormName, @IdeDockFormVar); RegisterDesktopFormClass(IdeDockFormClass, IdeDockFormName, IdeDockFormName); {$ENDIF EnableIdeDockingSupport} end; procedure TIdeDockManager.UnRegisterDockableForm(var IdeDockFormVar; const IdeDockFormName: string); {$IFDEF EnableIdeDockingSupport} {$ENDIF EnableIdeDockingSupport} begin {$IFDEF EnableIdeDockingSupport} if @UnregisterFieldAddress <> nil then UnregisterFieldAddress(@IdeDockFormVar); {$ENDIF EnableIdeDockingSupport} end; var PrivateIdeDockManager: TIdeDockManager = nil; function IdeDockManager: IIdeDockManager; begin Result := PrivateIdeDockManager as IIdeDockManager; end; { TfmIdeDockForm } constructor TfmIdeDockForm.Create(AOwner: TComponent); begin inherited; GxSetDefaultFont(Self); {$IFDEF EnableIdeDockingSupport} if Menu <> nil then begin FMenuBar := TMenuBar.Create(Self); FMenuBar.Parent := Self; FMenuBar.Menu := Menu; FMenuBar.Height := GetSystemMetrics(SM_CYMENU) + 2; Menu := nil; end; if (PopupMenu = nil) and (FMenuBar <> nil) then begin PopupMenu := TDummyPopupMenu.Create(Self); TDummyPopupMenu(PopupMenu).OwnerMenu := FMenuBar.Menu; end; DeskSection := Name; AutoSave := True; SaveStateNecessary := True; {$ENDIF EnableIdeDockingSupport} end; destructor TfmIdeDockForm.Destroy; begin {$IFDEF EnableIdeDockingSupport} SaveStateNecessary := True; {$ENDIF EnableIdeDockingSupport} inherited Destroy; end; {$IFDEF EnableIdeDockingSupport} { TDummyPopupMenu } function TDummyPopupMenu.IsShortCut(var Message: TWMKey): Boolean; begin // Call the form's IsShortCut so docked forms can use main menu shortcuts Result := (OwnerMenu <> nil) and OwnerMenu.IsShortCut(Message); end; {$ENDIF EnableIdeDockingSupport} initialization PrivateIdeDockManager := TIdeDockManager.Create; finalization FreeAndNil(PrivateIdeDockManager); end.
program Maximum (input,output); { bestimmt das Maximum einer Folge von einzulesenden Integer-Zahlen } const ANZ = 4; { Anzahl der einzulesenden Zahlen } type tIndex = 1..ANZ; var i : tIndex; { Laufvariable } Zahl, Max : integer; begin writeln('Geben Sie', ANZ, ' ganze Zahlen ein, deren Maximum bestimmt werden soll.'); write ('1. Wert: '); readln (Zahl); Max := Zahl; { Initialisierung von Max mit ersten Wert der eingegeben wurde } for i := 2 to ANZ do begin write (i, '. Wert: '); readln (Zahl); if Zahl > Max then { Wenn nächster Wert groeßer initialisiertes Max dann wird nächster Wert zum neuen Max } Max := Zahl end; { for-Schleife } writeln ('Das Maxmimum ist: ', Max,'.'); end. { Maximum }
unit UFormViewOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TFormViewOptions = class(TForm) btnOk: TButton; btnCancel: TButton; boxExt: TGroupBox; edText: TEdit; Label1: TLabel; edImages: TEdit; Label2: TLabel; edMedia: TEdit; Label3: TLabel; edInternet: TEdit; Label4: TLabel; boxText: TGroupBox; boxMedia: TGroupBox; chkMediaMCI: TRadioButton; chkMediaWMP64: TRadioButton; btnTextColor: TButton; btnTextFont: TButton; FontDialog1: TFontDialog; ColorDialog1: TColorDialog; labTextFont: TLabel; edTextWidth: TEdit; Label5: TLabel; edTextIndent: TEdit; Label6: TLabel; btnTextOptions: TButton; chkTextWidthFit: TCheckBox; procedure btnTextFontClick(Sender: TObject); procedure btnTextColorClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnTextOptionsClick(Sender: TObject); procedure chkTextWidthFitClick(Sender: TObject); private { Private declarations } public { Public declarations } fTextFontName: string; fTextFontSize: integer; fTextFontColor: integer; fTextFontStyle: TFontStyles; fTextBackColor: integer; fTextDetect: boolean; fTextDetectSize: DWORD; fTextDetectLimit: DWORD; end; //var // FormViewOptions: TFormViewOptions; implementation uses UFormViewOptions2; {$R *.DFM} procedure TFormViewOptions.btnTextFontClick(Sender: TObject); begin with FontDialog1 do begin Font.Name:= fTextFontName; Font.Size:= fTextFontSize; Font.Color:= fTextFontColor; Font.Style:= fTextFontStyle; if Execute then begin fTextFontName:= Font.Name; fTextFontSize:= Font.Size; fTextFontColor:= Font.Color; fTextFontStyle:= Font.Style; labTextFont.Caption:= fTextFontName+', '+IntToStr(fTextFontSize); end; end; end; procedure TFormViewOptions.btnTextColorClick(Sender: TObject); begin with ColorDialog1 do begin Color:= fTextBackColor; if Execute then fTextBackColor:= Color; end; end; procedure TFormViewOptions.FormShow(Sender: TObject); begin labTextFont.Caption:= fTextFontName+', '+IntToStr(fTextFontSize); chkTextWidthFitClick(Self); end; procedure TFormViewOptions.btnTextOptionsClick(Sender: TObject); begin with TFormViewOptions2.Create(Self) do try chkDetect.Checked:= fTextDetect; edDetectSize.Text:= IntToStr(fTextDetectSize); edDetectLimit.Text:= IntToStr(fTextDetectLimit); if ShowModal=mrOk then begin fTextDetect:= chkDetect.Checked; fTextDetectSize:= StrToIntDef(edDetectSize.Text, fTextDetectSize); fTextDetectLimit:= StrToIntDef(edDetectLimit.Text, fTextDetectLimit); end; finally Free; end; end; procedure TFormViewOptions.chkTextWidthFitClick(Sender: TObject); begin edTextWidth.Enabled:= not chkTextWidthFit.Checked; end; end.
unit ColumnAlign; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, UMyStringGrid,FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.Objects, FMX.Edit, FMX.StdCtrls; type TTextColumn = class(TMyStringColumn) private FTextAlign : TTextAlign; protected procedure UpdateColumn; override; published property TextAlign : TTextAlign read FTextAlign write FTextAlign; end; implementation procedure TTextColumn.UpdateColumn; var i, C: Integer; LGrid:TMyCustomGrid; begin inherited; LGrid := Grid; FUpdateColumn := True; try { Create controls } // if Length(FCellControls) < LGrid.VisibleRows then // begin C := High(FCellControls); SetLength(FCellControls, LGrid.VisibleRows); for i := 0 to LGrid.VisibleRows - 1 do begin (FCellControls[i] as TEdit).TextAlign := FTextAlign; end; //end; finally FUpdateColumn := False; end; end; end.
unit CType; interface {$ifdef DELPHI} uses Character; {$else} function IsUpper(c: Char): Boolean; function IsLower(c: Char): Boolean; function IsLetter(c: Char): Boolean; function IsNumber(c: Char): Boolean; function IsWhitespace(c: Char): Boolean; {$endif} function IsPrintable(c: AnsiChar): Boolean; function IsPrintableAnsi(c: Char): Boolean; function IsDecimal(c: Char): Boolean; // allows '.', '+', '-' // Returns the character, if it's in the printable ANSI range (32..127); // otherwise, returns #0. function PrintableAnsi(c: Char): AnsiChar; { like the character counterparts, but the string must be nonempty and all characters in it must fit the criterion. } function IsStringUpper(s: String): Boolean; function IsStringLower(s: String): Boolean; function IsStringAlpha(s: String): Boolean; function IsStringNum(s: String): Boolean; function IsStringDecimal(s: String): Boolean; // allows '.', '+', '-' function IsStringWhitespace(s: String): Boolean; implementation uses System.SysUtils; type TCharPredicate = function(c: Char): Boolean; {$ifndef DELPHI} function IsUpper(c: Char): Boolean; begin Result := (c >= 'A') and (c <= 'Z'); end; function IsLower(c: Char): Boolean; begin Result := (c >= 'a') and (c <= 'z'); end; function IsLetter(c: Char): Boolean; begin IsLetter := IsUpper(c) or IsLower(c); end; function IsNumber(c: Char): Boolean; begin Result := (c >= '0') and (c <= '9'); end; function IsWhitespace(c: Char): Boolean; begin Result := CharInSet(C, [' ', #10, #13, #9]); end; {$endif} function IsPrintable(c: AnsiChar): Boolean; begin Result := (c >= ' ') and (c <= '~'); end; function IsPrintableAnsi(c: Char): Boolean; begin Result := (c >= ' ') and (c <= '~'); end; function PrintableAnsi(c: Char): AnsiChar; begin if IsPrintableAnsi(c) then Result := AnsiChar(c) else Result := #0 end; function IsDecimal(c: Char): Boolean; begin Result := IsNumber(c) or (c = '.') or (c = '+') or (c = '-') end; function StringMatches(s: String; Predicate: TCharPredicate): Boolean; var i: Integer; begin if Length(s) = 0 then Result := false else begin Result := true; for i := 1 to Length(s) do if not Predicate(s[i]) then begin Result := false; Break; end; end; end; function IsStringUpper(s: String): Boolean; begin Result := StringMatches(s, @IsUpper) end; function IsStringLower(s: String): Boolean; begin Result := StringMatches(s, @IsLower) end; function IsStringAlpha(s: String): Boolean; begin Result := StringMatches(s, @IsLetter) end; function IsStringNum(s: String): Boolean; begin Result := StringMatches(s, @IsNumber) end; function IsStringDecimal(s: String): Boolean; begin Result := StringMatches(s, @IsDecimal) end; function IsStringWhitespace(s: String): Boolean; begin Result := StringMatches(s, @IsWhitespace) end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.RTTI.Utils Description : Files functions Author : Kike Pérez Version : 1.4 Created : 09/03/2018 Modified : 05/11/2020 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.RTTI.Utils; {$i QuickLib.inc} interface uses SysUtils, Quick.Commons, TypInfo, Rtti; type TRttiPropertyOrder = (roFirstBase, roFirstInherited); TRTTI = class private class var fCtx : TRttiContext; public {$IFNDEF FPC} class constructor Create; class destructor Destroy; class function GetField(aInstance : TObject; const aFieldName : string) : TRttiField; overload; class function GetField(aTypeInfo : Pointer; const aFieldName : string) : TRttiField; overload; class function FieldExists(aTypeInfo : Pointer; const aFieldName : string) : Boolean; class function GetFieldValue(aInstance : TObject; const aFieldName : string) : TValue; overload; class function GetFieldValue(aTypeInfo : Pointer; const aFieldName: string) : TValue; overload; {$ENDIF} class function GetProperties(aType : TRttiType; aOrder : TRttiPropertyOrder = roFirstBase) : TArray<TRttiProperty>; class function GetType(aTypeInfo : Pointer) : TRttiType; class function GetProperty(aInstance : TObject; const aPropertyName : string) : TRttiProperty; overload; class function GetProperty(aTypeInfo : Pointer; const aPropertyName : string) : TRttiProperty; overload; class function GetPropertyPath(aInstance : TObject; const aPropertyPath : string) : TRttiProperty; {$IFNDEF FPC} class function GetMemberPath(aInstance: TObject; const aPropertyPath: string): TRttiMember; {$ENDIF} class function PathExists(aInstance: TObject; const aPropertyPath: string) : Boolean; class function GetPathValue(aInstance : TObject; const aPropertyPath : string) : TValue; class procedure SetPathValue(aInstance: TObject; const aPropertyPath: string; aValue : TValue); class procedure SetPropertyValue(aInstance : TObject; const aPropertyName : string; aValue : TValue); class function PropertyExists(aTypeInfo : Pointer; const aPropertyName : string) : Boolean; class function GetPropertyValue(aInstance : TObject; const aPropertyName : string) : TValue; overload; class function GetPropertyValue(aTypeInfo : Pointer; const aPropertyName : string) : TValue; overload; class function GetPropertyValueEx(aInstance: TObject; const aPropertyName: string): TValue; {$IFNDEF FPC} class function FindClass(const aClassName: string): TClass; class function CreateInstance<T>: T; overload; class function CreateInstance<T>(const Args: array of TValue): T; overload; class function CreateInstance(aBaseClass : TClass): TObject; overload; class function CallMethod(aObject : TObject; const aMethodName : string; aParams : array of TValue) : TValue; {$ENDIF} end; ERTTIError = class(Exception); TArrayHelper<T> = class public class function Concat(const Args: array of TArray<T>): TArray<T>; static; end; implementation { TRTTIUtils } {$IFNDEF FPC} class constructor TRTTI.Create; begin fCtx := TRttiContext.Create; end; class function TRTTI.CreateInstance<T>: T; begin Result := CreateInstance<T>([]); end; class function TRTTI.CreateInstance<T>(const Args: array of TValue): T; var value: TValue; rtype: TRttiType; rmethod: TRttiMethod; rinstype: TRttiInstanceType; begin rtype := fCtx.GetType(TypeInfo(T)); for rmethod in rtype.GetMethods do begin if (rmethod.IsConstructor) and (Length(rmethod.GetParameters) = Length(Args) ) then begin rinstype := rtype.AsInstance; value := rmethod.Invoke(rinstype.MetaclassType,Args); Result := value.AsType<T>; Exit; end; end; end; class function TRTTI.CreateInstance(aBaseClass : TClass): TObject; var value: TValue; rtype: TRttiType; rmethod: TRttiMethod; rinstype: TRttiInstanceType; begin Result := nil; rtype := fCtx.GetType(aBaseClass); for rmethod in rtype.GetMethods do begin if (rmethod.IsConstructor) and (Length(rmethod.GetParameters) = 0) then begin rinstype := rtype.AsInstance; value := rmethod.Invoke(rinstype.MetaclassType,[]); Result := value.AsType<TObject>; Exit; end; end; end; class function TRTTI.CallMethod(aObject : TObject; const aMethodName : string; aParams : array of TValue) : TValue; var rtype : TRttiType; rmethod : TRttiMethod; rinstype: TRttiInstanceType; begin rtype := fCtx.GetType(aObject.ClassInfo); for rmethod in rtype.GetMethods do begin if CompareText(rmethod.Name,aMethodName) = 0 then begin rinstype := rtype.AsInstance; Result := rmethod.Invoke(rinstype.MetaclassType,aParams); end; end; end; class destructor TRTTI.Destroy; begin fCtx.Free; end; class function TRTTI.FieldExists(aTypeInfo: Pointer; const aFieldName: string): Boolean; var rtype : TRttiType; begin rtype := fCtx.GetType(aTypeInfo); Result := rtype.GetField(aFieldName) <> nil; end; class function TRTTI.GetField(aInstance: TObject; const aFieldName: string): TRttiField; var rtype : TRttiType; begin Result := nil; rtype := fCtx.GetType(aInstance.ClassInfo); if rtype <> nil then begin Result := rtype.GetField(aFieldName); end; end; class function TRTTI.GetField(aTypeInfo: Pointer; const aFieldName: string): TRttiField; var rtype : TRttiType; begin Result := nil; rtype := fCtx.GetType(aTypeInfo); if rtype <> nil then begin Result := rtype.GetField(aFieldName); end; end; class function TRTTI.GetFieldValue(aInstance : TObject; const aFieldName: string): TValue; var rfield: TRttiField; begin rfield := GetField(aInstance,aFieldName); if rfield <> nil then Result := rfield.GetValue(aInstance); end; class function TRTTI.GetFieldValue(aTypeInfo : Pointer; const aFieldName: string): TValue; var rfield: TRttiField; begin rfield := GetField(aTypeInfo,aFieldName); if rfield <> nil then rfield.GetValue(aTypeInfo); end; {$ENDIF} class function TRTTI.GetProperty(aInstance: TObject; const aPropertyName: string): TRttiProperty; var rtype : TRttiType; begin Result := nil; rtype := fCtx.GetType(aInstance.ClassInfo); if rtype <> nil then Result := rtype.GetProperty(aPropertyName); end; class function TArrayHelper<T>.Concat(const Args: array of TArray<T>): TArray<T>; var i, j, out, len: Integer; begin len := 0; for i := 0 to High(Args) do len := len + Length(Args[i]); SetLength(Result, len); out := 0; for i := 0 to High(Args) do for j := 0 to High(Args[i]) do begin Result[out] := Args[i][j]; Inc(out); end; end; class function TRTTI.GetProperties(aType: TRttiType; aOrder: TRttiPropertyOrder = roFirstBase): TArray<TRttiProperty>; var flat: TArray<TArray<TRttiProperty>>; t: TRttiType; depth: Integer; begin if aOrder = TRttiPropertyOrder.roFirstBase then begin t := aType; depth := 0; while t <> nil do begin Inc(depth); t := t.BaseType; end; SetLength(flat, depth); t := aType; while t <> nil do begin Dec(depth); {$IFNDEF FPC} flat[depth] := t.GetDeclaredProperties; {$ELSE} flat[depth] := t.GetProperties; {$ENDIF} t := t.BaseType; end; end else begin t := aType; depth := 0; while t <> nil do begin Inc(depth); t := t.BaseType; end; SetLength(flat, depth); t := aType; depth := 0; while t <> nil do begin {$IFNDEF FPC} flat[depth] := t.GetDeclaredProperties; {$ELSE} flat[depth] := t.GetProperties; {$ENDIF} Inc(depth); t := t.BaseType; end; end; Result := TArrayHelper<TRttiProperty>.Concat(flat); end; class function TRTTI.GetProperty(aTypeInfo: Pointer; const aPropertyName: string): TRttiProperty; var rtype : TRttiType; begin Result := nil; rtype := fCtx.GetType(aTypeInfo); if rtype <> nil then Result := rtype.GetProperty(aPropertyName); end; class function TRTTI.GetPropertyPath(aInstance: TObject; const aPropertyPath: string): TRttiProperty; var prop : TRttiProperty; proppath : string; propname : string; i : Integer; value : TValue; rtype : TRttiType; {$IFNDEF FPC} rfield : TRttiField; {$ENDIF} lastsegment : Boolean; begin Result := nil; proppath := aPropertyPath; lastsegment := False; rtype := fCtx.GetType(aInstance.ClassType); repeat i := proppath.IndexOf('.'); if i > -1 then begin propname := Copy(proppath,1,i); Delete(proppath,1,i+1); end else begin propname := proppath; lastsegment := True; end; if rtype.TypeKind = TTypeKind.tkRecord then begin {$IFNDEF FPC} rfield := rtype.GetField(propname); if rfield <> nil then value := rfield.GetValue(aInstance); {$ELSE} raise ERTTIError.Create('FPC not supports record fields in RTTI'); {$ENDIF} end else begin prop := rtype.GetProperty(propname); if prop = nil then Exit; if lastsegment then Exit(prop) else value := prop.GetValue(aInstance); end; if not lastsegment then begin if value.Kind = TTypeKind.tkClass then rType := fCtx.GetType(value.AsObject.ClassType) else if value.Kind = TTypeKind.tkRecord then rtype := fCtx.GetType(value.TypeInfo); end; until lastsegment; Result := nil; end; {$IFNDEF FPC} class function TRTTI.GetMemberPath(aInstance: TObject; const aPropertyPath: string): TRttiMember; var prop : TRttiProperty; proppath : string; propname : string; i : Integer; value : TValue; rtype : TRttiType; {$IFNDEF FPC} rfield : TRttiField; {$ENDIF} lastsegment : Boolean; begin Result := nil; proppath := aPropertyPath; lastsegment := False; rtype := fCtx.GetType(aInstance.ClassType); repeat i := proppath.IndexOf('.'); if i > -1 then begin propname := Copy(proppath,1,i); Delete(proppath,1,i+1); end else begin propname := proppath; lastsegment := True; end; if rtype.TypeKind = TTypeKind.tkRecord then begin {$IFNDEF FPC} rfield := rtype.GetField(propname); if rfield <> nil then begin if lastsegment then Exit(rfield) else value := rfield.GetValue(value.GetReferenceToRawData); end; {$ELSE} raise ERTTIError.Create('FPC not supports record fields in RTTI'); {$ENDIF} end else begin prop := rtype.GetProperty(propname); if prop = nil then Exit; if lastsegment then Exit(prop) else value := prop.GetValue(aInstance); end; if not lastsegment then begin if value.Kind = TTypeKind.tkClass then rType := fCtx.GetType(value.AsObject.ClassType) else if value.Kind = TTypeKind.tkRecord then rtype := fCtx.GetType(value.TypeInfo); end; until lastsegment; end; {$ENDIF} class function TRTTI.PathExists(aInstance: TObject; const aPropertyPath: string) : Boolean; var proppath : string; propname : string; i : Integer; value : TValue; rtype : TRttiType; rprop : TRttiProperty; {$IFNDEF FPC} rfield : TRttiField; {$ENDIF} lastsegment : Boolean; begin if not Assigned(aInstance) then Exit(False); lastsegment := False; proppath := aPropertyPath; rtype := fCtx.GetType(aInstance.ClassType); repeat Result := False; i := proppath.IndexOf('.'); if i > -1 then begin propname := Copy(proppath,1,i); Delete(proppath,1,i+1); end else begin propname := proppath; lastsegment := True; end; if rtype.TypeKind = TTypeKind.tkRecord then begin {$IFNDEF FPC} rfield := rtype.GetField(propname); if rfield = nil then Exit else begin value := rfield.GetValue(value.GetReferenceToRawData); Result := True; end; {$ELSE} raise ERTTIError.Create('FPC not supports record fields in RTTI'); {$ENDIF} end else begin rprop := rtype.GetProperty(propname); if rprop = nil then Exit else begin value := rprop.GetValue(aInstance); Result := True; end; end; if not lastsegment then begin if value.Kind = TTypeKind.tkClass then rType := fCtx.GetType(value.AsObject.ClassType) else if value.Kind = TTypeKind.tkRecord then rtype := fCtx.GetType(value.TypeInfo); end; until lastsegment; end; class function TRTTI.GetPathValue(aInstance: TObject; const aPropertyPath: string): TValue; var proppath : string; propname : string; i : Integer; value : TValue; rtype : TRttiType; rprop : TRttiProperty; {$IFNDEF FPC} rfield : TRttiField; {$ENDIF} lastsegment : Boolean; begin Result := nil; if not Assigned(aInstance) then Exit; lastsegment := False; proppath := aPropertyPath; rtype := fCtx.GetType(aInstance.ClassType); {$IFDEF FPC} value := aInstance; {$ENDIF} repeat i := proppath.IndexOf('.'); if i > -1 then begin propname := Copy(proppath,1,i); Delete(proppath,1,i+1); end else begin propname := proppath; lastsegment := True; end; if rtype.TypeKind = TTypeKind.tkRecord then begin {$IFNDEF FPC} rfield := rtype.GetField(propname); if rfield = nil then raise ERTTIError.CreateFmt('Field "%s" not found in record',[propname]) else value := rfield.GetValue(value.GetReferenceToRawData); {$ELSE} raise ERTTIError.Create('FPC not supports record fields in RTTI'); {$ENDIF} end else begin rprop := rtype.GetProperty(propname); if rprop = nil then raise ERTTIError.CreateFmt('Property "%s" not found in object',[propname]) {$IFNDEF FPC} else value := rprop.GetValue(aInstance); {$ELSE} else begin if rprop.PropertyType.IsInstance then value := GetObjectProp(value.AsObject,propname) else value := rprop.GetValue(value.AsObject); end; {$ENDIF} end; if not lastsegment then begin if value.Kind = TTypeKind.tkClass then rType := fCtx.GetType(value.AsObject.ClassType) else if value.Kind = TTypeKind.tkRecord then rtype := fCtx.GetType(value.TypeInfo); end; until lastsegment; Result := value; end; class procedure TRTTI.SetPathValue(aInstance: TObject; const aPropertyPath: string; aValue : TValue); var proppath : string; propname : string; i : Integer; value : TValue; rtype : TRttiType; rprop : TRttiProperty; {$IFNDEF FPC} rfield : TRttiField; {$ENDIF} lastsegment : Boolean; begin if not Assigned(aInstance) then Exit; lastsegment := False; proppath := aPropertyPath; rtype := fCtx.GetType(aInstance.ClassType); repeat i := proppath.IndexOf('.'); if i > -1 then begin propname := Copy(proppath,1,i); Delete(proppath,1,i+1); end else begin propname := proppath; lastsegment := True; end; if rtype.TypeKind = TTypeKind.tkRecord then begin {$IFNDEF FPC} rfield := rtype.GetField(propname); if rfield = nil then raise ERTTIError.CreateFmt('Field "%s" not found in record',[propname]) else begin if lastsegment then rfield.SetValue(value.GetReferenceToRawData,aValue) else value := rfield.GetValue(value.GetReferenceToRawData); end; {$ELSE} raise ERTTIError.Create('FPC not supports record fields in RTTI'); {$ENDIF} end else begin rprop := rtype.GetProperty(propname); if rprop = nil then raise ERTTIError.CreateFmt('Property "%s" not found in object',[propname]) else begin if lastsegment then rprop.SetValue(aInstance,aValue) else value := rprop.GetValue(aInstance); end; end; if not lastsegment then begin if value.Kind = TTypeKind.tkClass then rType := fCtx.GetType(value.AsObject.ClassType) else if value.Kind = TTypeKind.tkRecord then rtype := fCtx.GetType(value.TypeInfo); end; until lastsegment; end; class function TRTTI.GetPropertyValue(aInstance: TObject; const aPropertyName: string): TValue; var rprop : TRttiProperty; begin rprop := GetProperty(aInstance,aPropertyName); if rprop <> nil then begin {$IFNDEF FPC} Result := rprop.GetValue(aInstance); {$ELSE} if rprop.PropertyType.IsInstance then Result := GetObjectProp(aInstance,aPropertyName) else Result := rprop.GetValue(aInstance); {$ENDIF} end; end; class function TRTTI.GetPropertyValue(aTypeInfo: Pointer; const aPropertyName: string): TValue; var rprop : TRttiProperty; begin rprop := GetProperty(aTypeInfo,aPropertyName); if rprop <> nil then begin {$IFNDEF FPC} Result := rprop.GetValue(aTypeInfo); {$ELSE} if rprop.PropertyType.IsInstance then Result := GetObjectProp(aTypeInfo,aPropertyName) else Result := rprop.GetValue(aTypeInfo); {$ENDIF} end; end; class function TRTTI.GetPropertyValueEx(aInstance: TObject; const aPropertyName: string): TValue; var pinfo : PPropInfo; begin Result := nil; pinfo := GetPropInfo(aInstance,aPropertyName); if pinfo = nil then begin //if not found can be a public property Result := GetPropertyValue(aInstance,aPropertyName); Exit; end; case pinfo.PropType^.Kind of tkInteger : Result := GetOrdProp(aInstance,pinfo); tkInt64 : Result := GetInt64Prop(aInstance,aPropertyName); tkFloat : Result := GetFloatProp(aInstance,aPropertyName); tkChar : Result := Char(GetOrdProp(aInstance,aPropertyName)); {$IFDEF FPC} tkWString : Result := GetWideStrProp(aInstance,aPropertyName); tkSString, tkAString, {$ELSE} tkUString, tkWString, {$ENDIF} tkLString : Result := GetStrProp(aInstance,pinfo); {$IFDEF FPC} tkEnumeration :Result := GetOrdProp(aInstance,aPropertyName); {$ELSE} tkEnumeration : Result := GetOrdProp(aInstance,aPropertyName); {$ENDIF} tkSet : Result := GetSetProp(aInstance,pinfo,True); {$IFNDEF FPC} tkClass : {$ELSE} tkBool : Result := Boolean(GetOrdProp(aInstance,pinfo)); tkObject : {$ENDIF} Result := GetObjectProp(aInstance,pinfo); tkDynArray : Result := GetDynArrayProp(aInstance,pinfo); end; end; class function TRTTI.GetType(aTypeInfo: Pointer): TRttiType; begin Result := fCtx.GetType(aTypeInfo); end; class function TRTTI.PropertyExists(aTypeInfo: Pointer; const aPropertyName: string) : Boolean; var rtype : TRttiType; begin Result := False; rtype := fCtx.GetType(aTypeInfo); if rtype <> nil then Result := rtype.GetProperty(aPropertyName) <> nil; end; class procedure TRTTI.SetPropertyValue(aInstance: TObject; const aPropertyName: string; aValue: TValue); var rprop : TRttiProperty; begin rprop := GetProperty(aInstance,aPropertyName); if rprop <> nil then rprop.SetValue(aInstance,aValue); end; {$IFNDEF FPC} class function TRTTI.FindClass(const aClassName: string): TClass; var rType : TRttiType; rList : TArray<TRttiType>; begin Result := nil; rList := fCtx.GetTypes; for rType in rList do begin if (rType.IsInstance) and (aClassName.EndsWith(rType.Name)) then begin Result := rType.AsInstance.MetaClassType; Break; end; end; end; {$ENDIF} end.
unit ScheduledServiceModule; interface uses System.SysUtils, System.Classes, System.Android.Service, Androidapi.JNI.App, AndroidApi.JNI.GraphicsContentViewText, Androidapi.JNI.Os; type TServiceModule = class(TAndroidService) function AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags, StartId: Integer): Integer; private FAlarmIntent: JPendingIntent; FInterval: Int64; procedure CreateAlarmIntent(const AAction: string); procedure SetAlarm(const AAction: string; AStartAt: Int64 = 0; AInterval: Int64 = 0); procedure SetDailyAlarm(const AAction: string; const AStartAt: Int64); procedure StopAlarm; public { Public declarations } end; var ServiceModule: TServiceModule; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses System.DateUtils, Androidapi.Helpers, Androidapi.JNI.JavaTypes, DW.OSLog; const cServiceName = 'com.embarcadero.services.ScheduledService'; // Defining these constants here just saves having to import it from Java code cReceiverName = 'com.delphiworlds.kastri.DWMultiBroadcastReceiver'; cActionServiceAlarm = cReceiverName + '.ACTION_SERVICE_ALARM'; function SecondsUntilMidnight: Int64; begin Result := SecondsBetween(Now, Trunc(Now + 1)); end; function GetTimeFromNowInMillis(const ASeconds: Integer): Int64; var LCalendar: JCalendar; begin LCalendar := TJCalendar.JavaClass.getInstance; if ASeconds > 0 then LCalendar.add(TJCalendar.JavaClass.SECOND, ASeconds); Result := LCalendar.getTimeInMillis; end; function GetMidnightInMillis: Int64; begin Result := GetTimeFromNowInMillis(SecondsUntilMidnight); end; procedure TServiceModule.CreateAlarmIntent(const AAction: string); var LActionIntent: JIntent; begin LActionIntent := TJIntent.JavaClass.init(StringToJString(AAction)); LActionIntent.setClassName(TAndroidHelper.Context.getPackageName, StringToJString(cReceiverName)); LActionIntent.putExtra(StringToJString('ServiceName'), StringToJString(cServiceName)); FAlarmIntent := TJPendingIntent.JavaClass.getBroadcast(TAndroidHelper.Context, 0, LActionIntent, TJPendingIntent.JavaClass.FLAG_CANCEL_CURRENT); end; procedure TServiceModule.SetAlarm(const AAction: string; AStartAt: Int64 = 0; AInterval: Int64 = 0); begin if AStartAt = 0 then AStartAt := GetTimeFromNowInMillis(0); StopAlarm; FInterval := AInterval; CreateAlarmIntent(AAction); if FInterval > 0 then begin // Allow for alarms while in "doze" mode if TOSVersion.Check(6) then TAndroidHelper.AlarmManager.setExactAndAllowWhileIdle(TJAlarmManager.JavaClass.RTC_WAKEUP, GetTimeFromNowInMillis(AInterval), FAlarmIntent) else TAndroidHelper.AlarmManager.setRepeating(TJAlarmManager.JavaClass.RTC_WAKEUP, AStartAt, AInterval, FAlarmIntent); end else TAndroidHelper.AlarmManager.&set(TJAlarmManager.JavaClass.RTC_WAKEUP, AStartAt, FAlarmIntent); end; procedure TServiceModule.SetDailyAlarm(const AAction: string; const AStartAt: Int64); begin SetAlarm(AAction, AStartAt, TJAlarmManager.JavaClass.INTERVAL_DAY); end; procedure TServiceModule.StopAlarm; begin if FAlarmIntent <> nil then TAndroidHelper.AlarmManager.cancel(FAlarmIntent); FAlarmIntent := nil; end; function TServiceModule.AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags, StartId: Integer): Integer; begin TOSLog.d('Service started'); if (Intent <> nil) and JStringToString(Intent.getAction).Equals(cActionServiceAlarm) then begin TOSLog.d('Alarm was triggered'); // Do whatever should happen as a result of the alarm // Reset the alarm if on Android 6 or greater, to allow for alarms while in "doze" mode if TOSVersion.Check(6) and (FInterval > 0) then SetAlarm(cActionServiceAlarm, 0, FInterval); end // Set an alarm - a result of True means one was set (i.e. one had not been set before), so you might want to take some action in that case // if SetDailyAlarm(cActionServiceAlarm, MillisecondsUntilMidnight) then // <----- Daily at midnight example else SetAlarm(cActionServiceAlarm, GetTimeFromNowInMillis(60)); // <----- One off, in 1 minutes time Result := TJService.JavaClass.START_STICKY; end; end.
unit PT4Data; { Модуль работы с данными } {$mode objfpc}{$H+} interface uses Classes, SysUtils, PT4Common; type ElemType = (TBool, TInt, TChar, TReal, TPChar, TPoint); PDElem = ^DElem; DElem = record Cmt : string; Next : PDElem; case T : ElemType of TBool : (B : boolean); TInt : (I : integer); TChar : (C : char); TReal : (R : real); TPChar : (PC : PChar); TPoint : (P : PNode); end; procedure DataInit; procedure DataFini; procedure AddToData(var X; T : ElemType); procedure AddToCheck(var X; T : ElemType); procedure AddToResult(var X; T : ElemType); function GetData : PDElem; procedure DumpData; procedure DumpResult; procedure DumpCheck; function CompareData : boolean; implementation var Data, // Исходные данные программы Resuld, // Необходимый результат Check // Полученный результат : PDElem; function CompareData : boolean; var Res : boolean; R, C : PDElem; begin Res := true; R := Resuld; C := Check; while (R <> nil) and (C <> nil) and Res do begin // FIXME if (R^.T <> C^.T) then Res := false else case R^.T of TInt : Res := R^.I = C^.I; TBool : Res := R^.B = C^.B; TChar : Res := R^.C = C^.C; TReal : Res := R^.R = C^.R; TPChar : Res := CompareStr(R^.PC, C^.PC) = 0; end; R := R^.Next; C := C^.Next; end; CompareData := Res and (R = C); end; procedure DumpList(X : PDElem); begin // FIXME if (X <> nil) then begin case X^.T of TInt : write(X^.I); TBool : write(X^.B); TChar : write(X^.C); TReal : write(X^.R); TPChar : write(AnsiToUTF8(X^.PC)); end; write(' '); DumpList(X^.next); end; end; procedure DumpData; begin DumpList(Data); writeln; end; procedure DumpCheck; begin DumpList(Check); writeln; end; procedure DumpResult; begin DumpList(Resuld); writeln; end; function GetData : PDElem; var Q : PDElem; begin // FIXME Q := Data; Data := Data^.Next; GetData := Q; end; procedure DataInit; begin Data := nil; Check := nil; Resuld := nil; end; procedure DestroyList(P : PDElem); begin if (P <> nil) then begin DestroyList(P^.Next); if (P^.T = TPChar) then StrDispose(P^.PC); Dispose(P); end; end; procedure DataFini; begin DestroyList(Data); DestroyList(Check); DestroyList(Resuld); end; procedure AddToList(var X; T : ElemType; var P : PDElem); var Q : PDElem; X_I : integer absolute X; X_B : boolean absolute X; X_C : char absolute X; X_PC : PChar absolute X; X_R : real absolute X; begin if (P = nil) then begin New(Q); Q^.T := T; Q^.Next := nil; // FIXME case T of TInt : Q^.I := X_I; TBool : Q^.B := X_B; TChar : Q^.C := X_C; TReal : Q^.R := X_R; TPChar : Q^.PC := StrNew(X_PC); end; P := Q; end else AddToList(X, T, P^.Next); end; procedure AddToData(var X; T : ElemType); begin AddToList(X, T, Data); end; procedure AddToCheck(var X; T : ElemType); begin AddToList(X, T, Check); end; procedure AddToResult(var X; T : ElemType); begin AddToList(X, T, Resuld); end; end.
unit Synchro; interface uses CabUtils, URL2File, Windows, Classes; type TSyncErrorCode = integer; TSyncEventId = integer; const SYNC_NOERROR = 0; SYNC_ERROR_Unknown = 1; SYNC_ERROR_InvalidDestFile = 2; SYNC_ERROR_InvalidSourceFile = 3; SYNC_ERROR_DecompressionFailed = 4; SYNC_ERROR_BadIndexFile = 5; SYNC_ERROR_DownloadFailed = 6; const syncEvnDone = 1; syncEvnDownloading = 2; syncEvnDecompresing = 3; syncEvnFileDone = 4; type TSyncTask = class; TOnSyncNotify = procedure( SyncTask : TSyncTask; EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean ) of object; TSyncTask = class private fSource : string; fDest : string; fBusy : boolean; fErrorCode : TSyncErrorCode; fErrorInfo : string; fNotify : TOnSyncNotify; fPriority : integer; fMaxSize : integer; fCurrSize : integer; fFileSize : integer; fStartTime : TDateTime; fEstHours : integer; fEstMins : integer; private procedure SetPriority( aPriority : integer ); public property Busy : boolean read fBusy; property ErrorCode : TSyncErrorCode read fErrorCode; property ErrorInfo : string read fErrorInfo; property Priority : integer read fPriority write SetPriority; property MaxSize : integer read fMaxSize; property CurrSize : integer read fCurrSize; property EstHours : integer read fEstHours; property EstMins : integer read fEstMins; private procedure Act; virtual; procedure Synchronize; procedure Notify( EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean ); virtual; function Terminated : boolean; virtual; private procedure DownloadNotify( Progress, ProgressMax : integer; Status : TDownloadStatus; StatusText: string; out Cancel : boolean ); function DecompressNotify( command : TDescompressNotifyCommand; text : string; value : integer ) : boolean; end; TSyncThread = class( TThread ) private fTask : TSyncTask; protected procedure Execute; override; end; TThreadedTask = class( TSyncTask ) private constructor Create; destructor Destroy; override; private fThread : TSyncThread; public property Thread : TSyncThread read fThread; private procedure Act; override; private vclEventId : TSyncEventId; vclTaskDesc : string; vclProgress : integer; vclOverallProgress : integer; procedure Notify( EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean ); override; procedure vclNotify; function Terminated : boolean; override; end; procedure InitSynchro( MaxParallelRequests : integer ); procedure DoneSynchro; function Synchronize ( Source, Dest : string; OnNotify : TOnSyncNotify ) : TSyncErrorCode; function AsyncSynchronize( Source, Dest : string; OnNotify : TOnSyncNotify; Priority : integer ) : TThreadedTask; procedure RegisterException( filename : string ); const syncMasterFile = 'index.midx'; syncIndexFile = 'index.sync'; implementation uses Collection, SyncObjs, UrlMon, SysUtils, StrUtils, ShellAPI, SyncIndex, FileCtrl; type TPendingTasks = class( TSortedCollection ) private function CompareTasks( Task1, Task2 : TObject ) : integer; end; function TPendingTasks.CompareTasks( Task1, Task2 : TObject ) : integer; begin if TSyncTask(Task1).fPriority > TSyncTask(Task2).fPriority then result := 1 else if TSyncTask(Task1).fPriority < TSyncTask(Task2).fPriority then result := -1 else result := 0; end; var Current : TCollection = nil; Pending : TPendingTasks = nil; MaxParallelReq : integer = 0; SyncLock : TCriticalSection = nil; Exceptions : TStringList = nil; procedure Lock; forward; procedure Unlock; forward; procedure ExecuteTask( Task : TSyncTask ); forward; procedure SyncDone ( Task : TSyncTask ); forward; function RemoveFullPath(const Path : string) : boolean; var FileOp : TSHFileOpStruct; tmp : array[0..MAX_PATH] of char; begin fillchar(tmp, sizeof(tmp), 0); strpcopy(tmp, Path); // If Path is a folder the last '\' must be removed. if Path[length(Path)] = '\' then tmp[length(Path)-1] := #0; with FileOp do begin wFunc := FO_DELETE; Wnd := 0; pFrom := tmp; pTo := nil; fFlags := FOF_NOCONFIRMATION or FOF_SILENT; hNameMappings := nil; end; result := SHFileOperation( FileOp ) = 0; end; function ExtractCacheFileName( Cache, filename : string ) : string; begin if system.pos( Cache, filename ) > 0 then begin delete( filename, 1, length(Cache) ); result := filename end else result := filename; end; // TSyncTask procedure TSyncTask.SetPriority( aPriority : integer ); begin Lock; try fPriority := aPriority; Pending.Sort( Pending.CompareTasks ); finally Unlock; end; end; procedure TSyncTask.Act; begin Synchronize; end; procedure TSyncTask.Synchronize; function SynchronizeFiles( source, dest : string ) : TSyncErrorCode; begin if DownloadURLToFile( fSource, fDest, DownloadNotify ) = DWNL_NOERROR then result := SYNC_NOERROR else result := SYNC_ERROR_DownloadFailed; end; function SynchronizeFolders( source, dest : string ) : TSyncErrorCode; function DeleteFiles( names : TStringList ) : boolean; var i : integer; begin try for i := 0 to pred(names.count) do if Exceptions.IndexOf( uppercase(names[i]) ) = NoIndex then DeleteFile( dest + names[i] ); result := true; except result := false; end; end; function DeleteDirs( names : TStringList ) : boolean; var i : integer; begin try for i := 0 to pred(names.count) do RemoveFullPath( dest + names[i] ); result := true; except result := false; end; end; function GetIndexFile : TSyncErrorCode; begin if DownloadURLToFile( source + syncMasterFile, dest + syncMasterFile, DownloadNotify ) = DWNL_NOERROR then result := SYNC_NOERROR else if DownloadURLToFile( source + syncIndexFile, dest + syncIndexFile, DownloadNotify ) = DWNL_NOERROR then result := SYNC_NOERROR else result := SYNC_ERROR_DownloadFailed end; procedure DeleteIndexFile; begin DeleteFile( dest + syncIndexFile ); DeleteFile( dest + syncMasterFile ); end; function FileIsCompressed( filename : string ) : boolean; begin result := uppercase(ExtractFileExt( filename )) = '.CAB'; end; function GetFile( filename : string; out ErrorInfo : string ) : TSyncErrorCode; const MaxAttempts = 3; var attempt : integer; RelPath : string; cancel : boolean; begin attempt := 0; RelPath := ExtractFilePath( filename ); repeat fFileSize := 0; if DownloadURLToFile( source + ChangePath( filename, '\', '/' ), dest + filename, DownloadNotify ) = DWNL_NOERROR then if FileIsCompressed( dest + filename ) then if DecompressFile( dest + filename, dest + RelPath, DecompressNotify ) then begin DeleteFile( dest + filename ); result := SYNC_NOERROR; end else begin result := SYNC_ERROR_DecompressionFailed; ErrorInfo := dest + filename; end else result := SYNC_NOERROR else begin result := SYNC_ERROR_DownloadFailed; ErrorInfo := source + ChangePath( filename, '\', '/' ); end; inc( attempt ); if result <> SYNC_NOERROR then dec( fCurrSize, fFileSize ); until (result = SYNC_NOERROR) or (attempt = MaxAttempts) or Terminated; if result = SYNC_NOERROR then begin cancel := false; Notify( syncEvnFileDone, dest + filename, 0, 0, cancel ); ErrorInfo := ''; end; end; function GetFiles( names : TStringList; out ErrorInfo : string ) : TSyncErrorCode; var i : integer; begin i := 0; result := SYNC_NOERROR; while (i < names.Count) and (result = SYNC_NOERROR) and not Terminated do begin result := GetFile( names[i], ErrorInfo ); inc( i ); end; end; function GetDirs( names : TStringList ) : TSyncErrorCode; var i : integer; begin i := 0; result := SYNC_NOERROR; while (i < names.Count) and (result = SYNC_NOERROR) and not Terminated do begin result := SynchronizeFolders( source + names[i] + '/', dest + names[i] + '\' ); inc( i ); end; end; procedure CreateDirs( names : TStringList ); var i : integer; begin try for i := 0 to pred(names.Count) do CreateDir( dest + names[i] ); except end; end; var NewFiles : TStringList; OldFiles : TStringList; SyncDirs : TStringList; NewDirs : TStringList; OldDirs : TStringList; MasterSync : boolean; procedure CreateLists; begin NewFiles := TStringList.Create; //NewFiles.Sorted := true; NewFiles.Duplicates := dupIgnore; OldFiles := TStringList.Create; OldFiles.Sorted := true; OldFiles.Duplicates := dupIgnore; SyncDirs := TStringList.Create; SyncDirs.Sorted := true; SyncDirs.Duplicates := dupIgnore; OldDirs := TStringList.Create; OldDirs.Sorted := true; OldDirs.Duplicates := dupIgnore; NewDirs := TStringList.Create; NewDirs.Sorted := true; NewDirs.Duplicates := dupIgnore; end; procedure FreeLists; begin NewFiles.Free; OldFiles.Free; SyncDirs.Free; OldDirs.Free; NewDirs.Free; end; begin //CreateDir( dest ); ForceDirectories( dest ); result := GetIndexFile; if result = SYNC_NOERROR then begin CreateLists; try MasterSync := CompareFolder( syncMasterFile, dest, NewFiles, OldFiles, NewDirs, SyncDirs, OldDirs, fMaxSize ); if MasterSync or CompareFolder( syncIndexFile, dest, NewFiles, OldFiles, NewDirs, SyncDirs, OldDirs, fMaxSize ) then begin DeleteFiles( OldFiles ); DeleteDirs( OldDirs ); CreateDirs( NewDirs ); fCurrSize := 0; fFileSize := 0; fStartTime := Now; result := GetFiles( NewFiles, fErrorInfo ); if not MasterSync and (result = SYNC_NOERROR) then result := GetDirs( SyncDirs ); DeleteIndexFile; end else result := SYNC_ERROR_Unknown; finally FreeLists; end; end; end; function IsFolder( dest : string ) : boolean; begin result := uppercase( ExtractFilePath( dest )) = uppercase( dest ); end; var cancel : boolean; begin fBusy := true; if IsFolder( fDest ) then fErrorCode := SynchronizeFolders( fSource, fDest ) else fErrorCode := SynchronizeFiles( fSource, fDest ); fBusy := false; SyncDone( self ); Notify( syncEvnDone, 'Done', 0, 100, cancel ); end; procedure TSyncTask.Notify( EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean ); begin Cancel := false; if assigned(fNotify) then fNotify( self, EventId, TaskDesc, Progress, OverallProgress, Cancel ); end; function TSyncTask.Terminated : boolean; begin result := false; end; procedure TSyncTask.DownloadNotify( Progress, ProgressMax : integer; Status : TDownloadStatus; StatusText: string; out Cancel : boolean ); var Desc : string; Perc : integer; OverallPerc : integer; h, m, s, ms : word; secs, esecs : integer; delta : integer; FileName : string; UseCanceled : boolean; begin FileName := system.Copy( StatusText, BackPos( '/', StatusText, length(StatusText) ) + 1, length(StatusText) ); case Status of dlstConnecting : Desc := 'Finding Resource: ' + FileName; dlstDownloading : Desc := 'Downloading: ' + FileName; else Desc := 'Please wait...'; end; delta := Progress - fFileSize; fFileSize := Progress; fCurrSize := fCurrSize + delta; DecodeTime( Now - fStartTime, h, m, s, ms ); secs := 60*60*h + 60*m + s; if fCurrSize > 0 then begin esecs := ((fMaxSize - fCurrSize)*secs) div fCurrSize; if esecs >= 60*60 then begin fEstHours := esecs div (60*60); fEstMins := (esecs mod (60*60)) div 60; end else begin fEstHours := 0; fEstMins := esecs div 60; end; end; if ProgressMax > 0 then Perc := 100*Progress div ProgressMax else Perc := 0; if fMaxSize > 0 then OverallPerc := 100*fCurrSize div fMaxSize else OverallPerc := 0; Notify( syncEvnDownloading, Desc, Perc, OverallPerc, UseCanceled ); Cancel := Terminated or UseCanceled; end; function TSyncTask.DecompressNotify( command : TDescompressNotifyCommand; text : string; value : integer ) : boolean; var cancel : boolean; begin Notify( syncEvnDecompresing, text, value, -1, cancel ); result := not Terminated and not cancel; end; // TSyncThread procedure TSyncThread.Execute; begin fTask.Synchronize; end; // TThreadedTask constructor TThreadedTask.Create; begin inherited; fThread := TSyncThread.Create( true ); fThread.fTask := self; fThread.Priority := tpLower; end; destructor TThreadedTask.Destroy; begin if not fThread.Terminated then begin fThread.Terminate; WaitForSingleObject( fThread.Handle, INFINITE ); end; //fThread.Terminate; inherited; end; procedure TThreadedTask.Act; begin fThread.Resume; end; procedure TThreadedTask.Notify( EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean ); begin if not Terminated then begin vclEventId := EventId; vclTaskDesc := TaskDesc; vclProgress := Progress; if OverallProgress <> -1 then vclOverallProgress := OverallProgress; Thread.Synchronize( vclNotify ); cancel := false; end; end; procedure TThreadedTask.vclNotify; var cancel : boolean; begin inherited Notify( vclEventId, vclTaskDesc, vclProgress, vclOverallProgress, cancel ); end; function TThreadedTask.Terminated : boolean; begin result := fThread.Terminated; end; // Main functs procedure InitSynchro( MaxParallelRequests : integer ); begin SyncLock := TCriticalSection.Create; Current := TCollection.Create( 0, rkUse ); Pending := TPendingTasks.Create( 0, rkUse, Pending.CompareTasks ); MaxParallelReq := MaxParallelRequests; Exceptions := TStringList.Create; InitDownloader( nil ); end; procedure DoneSynchro; begin DoneDownloader; Exceptions.Free; Current.Free; Pending.Free; SyncLock.Free; end; function Synchronize( Source, Dest : string; OnNotify : TOnSyncNotify ) : TSyncErrorCode; var Task : TSyncTask; begin Task := TSyncTask.Create; Task.fSource := Source; Task.fDest := Dest; Task.fNotify := OnNotify; Task.Synchronize; result := Task.ErrorCode; end; function AsyncSynchronize( Source, Dest : string; OnNotify : TOnSyncNotify; Priority : integer ) : TThreadedTask; begin Lock; try result := TThreadedTask.Create; result.fSource := Source; result.fDest := Dest; result.fPriority := Priority; result.fNotify := OnNotify; result.fBusy := true; if Current.Count < MaxParallelReq then ExecuteTask( result ) else Pending.Insert( result ); finally Unlock; end; end; procedure RegisterException( filename : string ); begin Exceptions.Add( uppercase(filename) ); end; procedure Lock; begin SyncLock.Enter; end; procedure Unlock; begin SyncLock.Leave; end; procedure ExecuteTask( Task : TSyncTask ); begin Lock; try Current.Insert( Task ); Task.Act; finally Unlock; end; end; procedure SyncDone( Task : TSyncTask ); var NewTask : TSyncTask; begin Lock; try Current.Delete( Task ); while (Current.Count < MaxParallelReq) and (Pending.Count > 0) do begin NewTask := TSyncTask(Pending[0]); Pending.AtExtract( 0 ); ExecuteTask( NewTask ); end; finally Unlock; end; end; end.
unit TabbedPages; interface uses Windows, Classes, Graphics, Forms, Controls, Messages, Buttons; type TScrollBtn = (sbLeft, sbRight); type TScroller = class(TCustomControl) private { property usage } FMin: longint; FMax: longint; FPosition: longint; FOnClick: TNotifyEvent; FChange: integer; { private usage } sbLeft: TSpeedButton; sbRight: TSpeedButton; { property access methods } procedure SetMin(Value: longint); procedure SetMax(Value: longint); procedure SetPosition(Value: longint); { private methods } procedure sbMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); function CreateSpeedButton: TSpeedButton; function CanScrollLeft: boolean; function CanScrollRight: boolean; procedure WMSize(var Message: TWMSize); message WM_SIZE; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnClick: TNotifyEvent read FOnClick write FOnClick; property Min: longint read FMin write SetMin default 0; property Max: longint read FMax write SetMax default 0; property Position: longint read FPosition write SetPosition default 0; property Change: integer read FChange write FChange default 1; end; TTabbedPages = class; TMerchPage = class; TTab = class(TCustomControl) private FText: string; FCaption: string; FTabWidth: integer; FTabLeft: integer; TabbedPages: TTabbedPages; Page: TMerchPage; FSelected: boolean; FWMin: boolean; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure SetSelected(Value: boolean); procedure SetText(Value: string); procedure SetTabWidth(const Value: integer); procedure SetTabLeft(const Value: integer); procedure SetCaption(const Value: string); procedure SetTabBounds; function IdealWidth: integer; function MinWidth: integer; protected procedure Paint; override; constructor Create(AOwner: TComponent); override; published property TabWidth: integer read FTabWidth write SetTabWidth; property TabLeft: integer read FTabLeft write SetTabLeft; property Selected: boolean read FSelected write SetSelected; property Text: string read FText write SetText; property Caption: string read FCaption write SetCaption; end; TMerchPage = class(TCustomControl) private FGlyph: TPicture; procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST; procedure CreateTab; procedure SetGlyph(Value: TPicture); protected procedure ReadState(Reader: TReader); override; public constructor Create(AOwner: TComponent); override; published Tab: TTab; property Caption; property Height stored False; property TabOrder stored False; property Visible stored False; property Width stored False; property Glyph: TPicture read FGlyph write SetGlyph; end; TGlyphs = class; TTabChangingEvent = procedure(Sender: TObject; var AllowChange: boolean) of object; TKind = (kdDown, kdUp); TTabbedPages = class(TCustomControl) private FPageList: TList; FAccess: TStrings; FGlyphs: TGlyphs; FPageIndex: integer; FOnChange: TNotifyEvent; FOnChanging: TTabChangingEvent; FOnPageChanged: TNotifyEvent; FKind: TKind; FMargin: integer; FVisibleTabs: integer; FTabHeight: integer; FFirstIndex: integer; FAutoScroll: boolean; Scroller: TScroller; FDoFix: boolean; FGlyphW: integer; FGlyphH: integer; FInserting: boolean; procedure SetKind(Value: TKind); procedure SetPages(Value: TStrings); procedure SetActivePage(const Value: string); procedure UpdateActivePage; function GetActivePage: string; procedure SetPageIndex(Value: integer); procedure SetGlyphList(GlyphList: TGlyphs); procedure PutGlyph(index: integer; Glyph: TPicture); procedure SetFirstIndex(Value: integer); function GetGlyph(index: integer): TPicture; procedure SetMargin(const Value: integer); procedure SetAutoScroll(Value: boolean); procedure AdjustSize; procedure FixTabWidth; procedure SetTabPositions; function CalcNumTabs(Start, Stop: integer; First: integer): integer; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure FontChange(Sender: TObject); procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY; procedure WMDestroy(var Message: TWMDestroy); message WM_DESTROY; procedure CMTabStopChanged(var Message: TMessage); message CM_TABSTOPCHANGED; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CreateScroller; procedure ScrollClick(Sender: TObject); property GlyphW: integer read FGlyphW; property GlyphH: integer read FGlyphH; protected procedure CreateParams(var Params: TCreateParams); override; function GetChildOwner: TComponent; override; procedure GetChildren(Proc: TGetChildProc); override; procedure ReadState(Reader: TReader); override; procedure ShowControl(AControl: TControl); override; function CanChange: boolean; dynamic; procedure Change; dynamic; procedure Paint; override; public procedure SelectNextPage(GoForward: boolean); constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Glyph[index: integer]: TPicture read GetGlyph write PutGlyph stored False; property FirstIndex: integer read FFirstIndex write SetFirstIndex default 0; property AutoScroll: boolean read FAutoScroll write SetAutoScroll default True; published property ActivePage: string read GetActivePage write SetActivePage stored False; property Align; property DragCursor; property DragMode; property Enabled; property Font; property Glyphs: TGlyphs read FGlyphs write SetGlyphList stored False; property Margin: integer read FMargin write SetMargin default 4; property PageIndex: integer read FPageIndex write SetPageIndex default 0; property Pages: TStrings read FAccess write SetPages stored False; property ParentFont; property ParentShowHint; property PopupMenu; property Kind: TKind read FKind write SetKind default kdDown; 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 OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChanging: TTabChangingEvent read FOnChanging write FOnChanging; property OnPageChanged: TNotifyEvent read FOnPageChanged write FOnPageChanged; property OnStartDrag; end; TGlyphs = class(TStrings) private PageList: TList; protected function GetCount: integer; override; function Get(Index: integer): string; override; procedure Put(Index: integer; const S: string); override; function GetObject(Index: integer): TObject; override; procedure PutObject(Index: integer; AObject: TObject); override; procedure SetUpdateState(Updating: boolean); override; public constructor Create(APageList: TList); procedure Clear; override; procedure Delete(Index: integer); override; procedure Insert(Index: integer; const S: string); override; procedure Move(CurIndex, NewIndex: integer); override; end; implementation {$R TABBEDPAGES.RES} uses Consts, SysUtils, Dialogs; const LeftMargin = 2; EndMargin = 2; EdgeWidth = 12; TabMargin = 4; ImplicitTabWidth = 50; ImplicitTabHeight = 21; { TGlyphs } function TGlyphs.GetCount: integer; begin Result := PageList.Count; end; function TGlyphs.Get(Index: integer): string; begin Result := TMerchPage(PageList[Index]).Caption; end; procedure TGlyphs.Put(Index: integer; const S: string); begin end; function TGlyphs.GetObject(Index: integer): TObject; begin Result := TMerchPage(PageList[Index]).Glyph; end; procedure TGlyphs.PutObject(Index: integer; AObject: TObject); begin TMerchPage(PageList[Index]).Glyph := TPicture(AObject); end; procedure TGlyphs.SetUpdateState(Updating: boolean); begin end; constructor TGlyphs.Create(APageList: TList); begin inherited Create; PageList := APageList; end; procedure TGlyphs.Clear; var I: integer; begin for I := 0 to PageList.Count - 1 do TPicture(TMerchPage(PageList[I]).Glyph).Free; end; procedure TGlyphs.Delete(Index: integer); begin TPicture(TMerchPage(PageList[Index]).Glyph).Free; end; procedure TGlyphs.Insert(Index: integer; const S: string); begin end; procedure TGlyphs.Move(CurIndex, NewIndex: integer); begin end; { TScroller } constructor TScroller.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csOpaque]; sbRight := CreateSpeedButton; sbLeft := CreateSpeedButton; sbLeft.Left := 0; sbRight.Left := (Width div 2) - 1; sbRight.Glyph.Handle := LoadBitMap(HInstance, 'RIGHTARROW'); sbLeft.Glyph.Handle := LoadBitMap(HInstance, 'LEFTARROW'); FMin := 0; FMax := 0; FPosition := 0; FChange := 1; end; destructor TScroller.Destroy; begin sbLeft.Free; sbRight.Free; inherited Destroy; end; function TScroller.CreateSpeedButton: TSpeedButton; begin Result := TSpeedButton.Create(Self); Result.Parent := Self; Result.OnMouseUp := sbMouseUp; Result.Top := 0; Result.Height := Height; Result.NumGlyphs := 1; Result.Width := (Width div 2) - 1; end; procedure TScroller.sbMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); var NewPos: longint; begin NewPos := Position; if Sender = sbLeft then Dec(NewPos, Change) else Inc(NewPos, Change); Position := NewPos; end; procedure TScroller.WMSize(var Message: TWMSize); begin inherited; sbRight.Left := (Width div 2) - 1; sbRight.Height := Height; sbRight.Width := (Width div 2) - 1; sbLeft.Height := Height; sbLeft.Width := (Width div 2) - 1; end; procedure TScroller.SetMin(Value: longint); begin if Value < FMax then FMin := Value; end; procedure TScroller.SetMax(Value: longint); begin if Value > FMin then FMax := Value; end; procedure TScroller.SetPosition(Value: longint); begin if Value <> FPosition then begin if Value < Min then Value := Min; if Value > Max then Value := Max; FPosition := Value; Invalidate; if Assigned(FOnClick) then FOnClick(Self); end; end; function TScroller.CanScrollLeft: boolean; begin Result := Position > Min; end; function TScroller.CanScrollRight: boolean; begin Result := Position < Max; end; { TTab } constructor TTab.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; ShowHint := true; visible := false; end; procedure TTab.SetText(Value: string); begin if Value <> FText then begin FText := Value; Caption := Value; Hint := Value; Invalidate; end; end; procedure TTab.SetTabLeft(const Value: integer); begin if Value <> FTabLeft then begin FTabLeft := Value; SetTabBounds; end; end; procedure TTab.SetTabBounds; begin if Selected = true then begin BringToFront; Height := TabbedPages.FTabHeight; Left := TabLeft - 2; Width := TabWidth + 4; if TabbedPages.Kind = kdUp then Top := 0; end else begin Height := TabbedPages.FTabHeight - 2; Left := TabLeft; Width := TabWidth; if TabbedPages.Kind = kdUp then Top := 2; end; Invalidate; end; procedure TTab.SetSelected(Value: boolean); begin if Value <> FSelected then begin FSelected := Value; SetTabBounds; Invalidate; end; end; procedure TTab.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Index: integer; begin inherited; Index := TabbedPages.Pages.IndexOfObject(Page); TabbedPages.PageIndex := Index; end; procedure TTab.SetCaption(const Value: string); var W, I: integer; S: string; begin with Canvas do begin if Page.Glyph.Graphic <> nil then with TabbedPages do W := FGlyphW + Margin else W := 0; inc(W, TabbedPages.Margin); inc(W, TabbedPages.Margin); if W + TextWidth(Value) < TabWidth then FCaption := Value else begin I := 0; S := ''; inc(W, TextWidth('O...')); while (W < TabWidth) and (I <= length(Value)) do begin inc(I); inc(W,TextWidth(Value[I])); S := S + Value[I]; end; if S <> '' then S := S + '...'; FCaption := S; end; end; end; procedure TTab.SetTabWidth(const Value: integer); begin if Value <> FTabWidth then begin if Value > MinWidth then FTabWidth := Value else FTabWidth := MinWidth; SetTabBounds; SetCaption(Text); invalidate; end; end; function TTab.IdealWidth: integer; begin Result := Canvas.TextWidth(Text); if Page.Glyph.Graphic <> nil then inc(Result, TabbedPages.FGlyphW + TabbedPages.Margin); { if Result < ImplicitTabWidth then Result := ImplicitTabWidth; } inc(Result, EdgeWidth); end; function TTab.MinWidth: integer; begin if Page.Glyph.Graphic <> nil then Result := TabbedPages.FGlyphW else Result := Canvas.TextWidth('O...'); inc(Result, EdgeWidth); end; procedure TTab.Paint; var R: TRect; begin R := GetClientRect; with Canvas do begin Brush.Color := clBtnFace; FillRect(Rect(0, 0, Width, Height)); Brush.Color := clBtnFace; CopyMode := cmSrcCopy; if Page.Glyph.Graphic <> nil then begin StretchDraw(Rect(R.Left + TabbedPages.Margin, R.Top + 2, R.Left + TabbedPages.FGlyphW + TabbedPages.Margin, R.Top + 2 + TabbedPages.FGlyphH), Page.Glyph.Graphic); Inc(R.Left, TabbedPages.FGlyphW + TabbedPages.Margin); end; DrawText(Handle, PChar(Caption), Length(Caption), R, DT_VCENTER + DT_CENTER + DT_SINGLELINE); if TabbedPages.Kind = kdDown then if Selected then begin Pen.Color := clWindowFrame; PolyLine([Point(2, Height - 2), Point(Width - 3, Height - 2), Point(Width - 1, Height - 4), Point(Width - 1, 0)]); Pen.Color := clBtnShadow; PolyLine([Point(1, Height - 4), Point(1, Height - 3), Point(Width - 3, Height - 3), Point(Width - 3, Height - 4), Point(Width - 2, Height - 4), Point(Width - 2, -1)]); MoveTo(Width -2, 0); LineTo(Width, 0); Pen.Color := clBtnHighlight; MoveTo(0, Height - 4); LineTo(0, -1); end else begin Pen.Color := clWindowFrame; PolyLine([Point(2, Height - 2), Point(Width - 3, Height - 2), Point(Width - 1, Height - 4), Point(Width - 1, 1), Point(-1, 1)]); Pen.Color := clBtnShadow; PolyLine([Point(1, Height - 4), Point(1, Height - 3), Point(Width - 3, Height - 3), Point(Width - 3, Height - 4), Point(Width - 2, Height - 4), Point(Width - 2, 1)]); MoveTo(Width - 1, 0); LineTo(-1, 0); Pen.Color := clBtnHighlight; MoveTo(0, Height - 4); LineTo(0, 1); end else if Selected then begin Pen.Color := clBtnHighlight; PolyLine([Point(0, Height - 1), Point(0, 4), Point(2, 2), Point(Width - 2, 2)]); Pen.Color := clBtnShadow; MoveTo(Width - 2, 4); LineTo(Width - 2, Height); Pen.Color := clWindowFrame; PolyLine([Point(Width - 2, 3), Point(Width - 1, 4), Point(Width - 1, Height)]); end else begin Pen.Color := clBtnHighlight; PolyLine([Point(Width - 1,Height - 1), Point(0, Height - 1), Point(0, 4), Point(2, 2), Point(Width - 2, 2)]); Pen.Color := clBtnShadow; MoveTo(Width - 2, 4); LineTo(Width - 2, Height - 1); Pen.Color := clWindowFrame; PolyLine([Point(Width - 2, 3), Point(Width - 1, 4), Point(Width - 1, Height - 1)]); end; end; end; { TPageAccess } type TPageAccess = class(TStrings) private PageList: TList; Notebook: TTabbedPages; protected function GetCount: integer; override; function Get(Index: integer): string; override; procedure Put(Index: integer; const S: string); override; function GetObject(Index: integer): TObject; override; procedure SetUpdateState(Updating: boolean); override; public constructor Create(APageList: TList; ANotebook: TTabbedPages); procedure Clear; override; procedure Delete(Index: integer); override; procedure Insert(Index: integer; const S: string); override; procedure Move(CurIndex, NewIndex: integer); override; end; constructor TPageAccess.Create(APageList: TList; ANotebook: TTabbedPages); begin inherited Create; PageList := APageList; Notebook := ANotebook; end; function TPageAccess.GetCount: integer; begin Result := PageList.Count; end; function TPageAccess.Get(Index: integer): string; begin Result := TMerchPage(PageList[Index]).Caption; end; procedure TPageAccess.Put(Index: integer; const S: string); begin TMerchPage(PageList[Index]).Caption := S; TMerchPage(PageList[Index]).Tab.Text := S; end; function TPageAccess.GetObject(Index: integer): TObject; begin Result := TMerchPage(PageList[Index]); end; procedure TPageAccess.SetUpdateState(Updating: boolean); begin { do nothing } end; procedure TPageAccess.Clear; var I: integer; begin for I := 0 to PageList.Count - 1 do TMerchPage(PageList[I]).Free; PageList.Clear; end; procedure TPageAccess.Delete(Index: integer); var Form: TForm; begin TMerchPage(PageList[Index]).Free; PageList.Delete(Index); NoteBook.PageIndex := 0; NoteBook.FixTabWidth; if csDesigning in NoteBook.ComponentState then begin Form := GetParentForm(NoteBook); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; end; procedure TPageAccess.Insert(Index: integer; const S: string); var Page: TMerchPage; Form: TForm; begin Page := TMerchPage.Create(Notebook); with Page do begin Parent := Notebook; Caption := S; end; PageList.Insert(Index, Page); Page.CreateTab; with NoteBook do begin PageIndex := Index; FInserting := True; Click; Invalidate; end; if csDesigning in NoteBook.ComponentState then begin Form := GetParentForm(NoteBook); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; NoteBook.FixTabWidth; end; procedure TPageAccess.Move(CurIndex, NewIndex: integer); var AObject: TObject; begin if CurIndex <> NewIndex then begin AObject := PageList[CurIndex]; PageList[CurIndex] := PageList[NewIndex]; PageList[NewIndex] := AObject; end; end; { TMerchPage } constructor TMerchPage.Create(AOwner: TComponent); begin inherited Create(AOwner); Visible := False; ControlStyle := ControlStyle + [csAcceptsControls]; FGlyph := TPicture.Create; Tab := TTab.Create(Self); end; procedure TMerchPage.ReadState(Reader: TReader); begin if Reader.Parent is TTabbedPages then TTabbedPages(Reader.Parent).FPageList.Add(Self); inherited; CreateTab; end; procedure TMerchPage.CreateTab; begin with Tab do begin TabbedPages := TTabbedPages(Self.Owner); Parent := TabbedPages; Page := Self; FTabWidth := ImplicitTabWidth; Height := TabbedPages.FTabHeight; Text := Self.Caption; end; with TTabbedPages(Owner) do if Kind = kdDown then Tab.Top := Height - FTabHeight; end; procedure TMerchPage.SetGlyph(Value: TPicture); begin FGlyph.Assign(Value); TTabbedPages(Owner).FixTabWidth; end; procedure TMerchPage.WMNCHitTest(var Message: TWMNCHitTest); begin if not (csDesigning in ComponentState) then Message.Result := HTTRANSPARENT else inherited; end; { TTabbedPages } var Registered: boolean = False; constructor TTabbedPages.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 150; Height := 100; ControlStyle := [csDoubleClicks]; FTabHeight := ImplicitTabHeight; ParentFont := False; Font.Name := 'MS Sans Serif'; Font.Size := 8; Font.Style := []; FKind := kdDown; Font.OnChange := FontChange; FPageList := TList.Create; FAccess := TPageAccess.Create(FPageList, Self); FGlyphs := TGlyphs.Create(FPageList); FPageIndex := 0; FFirstIndex := 0; FVisibleTabs := 0; FGlyphW := GetSystemMetrics(SM_CXSMICON); FGlyphH := GetSystemMetrics(SM_CYSMICON); FAutoScroll := True; FMargin := 4; ShowHint := true; CreateScroller; Exclude(FComponentStyle, csInheritable); if not Registered then begin Classes.RegisterClasses([TMerchPage, TTab]); Registered := True; end; end; destructor TTabbedPages.Destroy; begin FAccess.Free; FPageList.Free; inherited Destroy; end; procedure TTabbedPages.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do Style := Style or WS_CLIPCHILDREN; end; function TTabbedPages.GetChildOwner: TComponent; begin Result := Self; end; procedure TTabbedPages.GetChildren(Proc: TGetChildProc); var I: integer; begin for I := 0 to FPageList.Count - 1 do Proc(TControl(FPageList[I])); end; procedure TTabbedPages.SetKind(Value: TKind); begin if Value <> FKind then begin FKind := Value; AdjustSize; Invalidate; end; end; procedure TTabbedPages.SetGlyphList(GlyphList: TGlyphs); begin FGlyphs.Assign(GlyphList); Invalidate; end; procedure TTabbedPages.PutGlyph(index: integer; Glyph: TPicture); begin FGlyphs.Objects[index] := Glyph; FixTabWidth; Invalidate; end; function TTabbedPages.GetGlyph(index: integer): TPicture; begin Result := FGlyphs.Objects[index] as TPicture; end; procedure TTabbedPages.ReadState(Reader: TReader); begin Pages.Clear; inherited ReadState(Reader); if (FPageIndex <> -1) and (FPageIndex >= 0) and (FPageIndex < FPageList.Count) then with TMerchPage(FPageList[FPageIndex]) do begin BringToFront; Visible := True; Tab.Selected := True; end else FPageIndex := -1; AdjustSize; FixTabWidth; end; procedure TTabbedPages.ShowControl(AControl: TControl); var I: integer; begin for I := 0 to FPageList.Count - 1 do if FPageList[I] = AControl then begin SetPageIndex(I); Exit; end; inherited ShowControl(AControl); end; procedure TTabbedPages.SetPages(Value: TStrings); begin FAccess.Assign(Value); Invalidate; end; procedure TTabbedPages.SetPageIndex(Value: integer); var ParentForm: TForm; begin if csLoading in ComponentState then FPageIndex := Value else if (Value >= 0) and (Value < FPageList.Count) then if Value = FPageIndex then TMerchPage(FPageList[Value]).Tab.Selected := true else begin ParentForm := GetParentForm(Self); if ParentForm <> nil then if ContainsControl(ParentForm.ActiveControl) then ParentForm.ActiveControl := Self; with TMerchPage(FPageList[Value]) do begin BringToFront; Visible := True; Tab.Selected := true; end; if (FPageIndex >= 0) and (FPageIndex < FPageList.Count) then begin TMerchPage(FPageList[FPageIndex]).Visible := False; TMerchPage(FPageList[FPageIndex]).Tab.Selected := False; end; FPageIndex := Value; if ParentForm <> nil then if ParentForm.ActiveControl = Self then SelectFirst; if Assigned(FOnPageChanged) then FOnPageChanged(Self); end; end; procedure TTabbedPages.AdjustSize; var I: integer; begin if Kind = kdDown then for I := 0 to FPageList.Count - 1 do begin TMerchPage(FPageList[I]).SetBounds(4, 4, Width - 8, Height - FTabHeight - 6); TMerchPage(FPageList[I]).Tab.Top := Height - FTabHeight; TMerchPage(FPageList[I]).Tab.SetTabBounds; end else for I := 0 to FPageList.Count - 1 do begin TMerchPage(FPageList[I]).SetBounds(4, FTabHeight + 3, Width - 8, Height - FTabHeight - 7); TMerchPage(FPageList[I]).Tab.Top := 0; TMerchPage(FPageList[I]).Tab.SetTabBounds; end; end; procedure TTabbedPages.WMSize(var Message: TWMSize); begin inherited; FixTabWidth; AdjustSize; Invalidate; Message.Result := 0; end; procedure TTabbedPages.SetActivePage(const Value: string); begin SetPageIndex(FAccess.IndexOf(Value)); Invalidate; end; function TTabbedPages.GetActivePage: string; begin Result := FAccess[FPageIndex]; end; procedure TTabbedPages.FontChange(Sender: TObject); begin AdjustSize; FixTabWidth; Refresh; end; procedure TTabbedPages.CMDialogKey(var Message: TCMDialogKey); begin if (Message.CharCode = VK_TAB) and (GetKeyState(VK_CONTROL) < 0) then begin SelectNextPage(GetKeyState(VK_SHIFT) >= 0); Message.Result := 1; end else inherited; end; procedure TTabbedPages.SelectNextPage(GoForward: boolean); var NewIndex: integer; begin if Pages.Count > 1 then begin NewIndex := PageIndex; if GoForward then Inc(NewIndex) else Dec(NewIndex); if NewIndex = Pages.Count then NewIndex := 0 else if NewIndex < 0 then NewIndex := Pages.Count - 1; SetPageIndex(NewIndex); end; end; procedure TTabbedPages.Change; var Form: TForm; begin UpdateActivePage; if csDesigning in ComponentState then begin Form := GetParentForm(Self); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; if Assigned(FOnChange) then FOnChange(Self); end; procedure TTabbedPages.UpdateActivePage; begin if PageIndex >= 0 then SetActivePage(FAccess[PageIndex]); end; function TTabbedPages.CanChange: boolean; begin Result := True; if Assigned(FOnChanging) then FOnChanging(Self, Result); end; procedure TTabbedPages.SetMargin(const Value: integer); begin if Value <> FMargin then begin FMargin := Value; Invalidate; end; end; procedure TTabbedPages.WMDestroy(var Message: TWMDestroy); var FocusHandle: HWnd; begin FocusHandle := GetFocus; if (FocusHandle <> 0) and ((FocusHandle = Handle) or IsChild(Handle, FocusHandle)) then Windows.SetFocus(0); inherited; end; procedure TTabbedPages.CMTabStopChanged(var Message: TMessage); begin if not (csDesigning in ComponentState) then RecreateWnd; end; procedure TTabbedPages.FixTabWidth; var i, AskedWidth, MinWidth: integer; TabSetWidth, Slice: integer; begin TabSetWidth := Width - LeftMargin; AskedWidth := 0; for i := 0 to pred(Pages.Count) do AskedWidth := AskedWidth + TMerchPage(Pages.Objects[i]).Tab.IdealWidth; if AskedWidth > TabSetWidth then begin MinWidth := 0; for i := 0 to pred(Pages.Count) do MinWidth := MinWidth + TMerchPage(Pages.Objects[i]).Tab.MinWidth; if MinWidth > TabSetWidth then // Scroller begin { Scroller.Visible := True; ShowWindow(Scroller.Handle, SW_SHOW); Scroller.Min := 0; Scroller.Max := Pages.Count - FVisibleTabs; Scroller.Position := FirstIndex; } { Beep; MessageDlg('Ya es hora de sacar el Scroller', mtInformation, [mbOk], 0); } Slice := (TabSetWidth - MinWidth) div Pages.Count - 1; for i := 0 to pred(Pages.Count) do with TMerchPage(Pages.Objects[i]).Tab do TabWidth := MinWidth + Slice; end else begin Slice := (TabSetWidth - MinWidth) div Pages.Count - 1; for i := 0 to pred(Pages.Count) do with TMerchPage(Pages.Objects[i]).Tab do TabWidth := MinWidth + Slice; end; end else for i := 0 to pred(Pages.Count) do with TMerchPage(Pages.Objects[i]).Tab do TabWidth := IdealWidth; end; procedure TTabbedPages.SetFirstIndex(Value: integer); begin if (Value >= 0) and (Value < Pages.Count) then begin FFirstIndex := Value; Invalidate; end; end; procedure TTabbedPages.SetTabPositions; var I, TabPos: integer; begin TabPos := LeftMargin; for I := 0 to Pred(Pages.Count) do if (I >= FirstIndex) and (I < FirstIndex + FVisibleTabs) then begin TMerchPage(Pages.Objects[I]).Tab.TabLeft := TabPos; inc(TabPos, TMerchPage(Pages.Objects[I]).Tab.TabWidth); TMerchPage(Pages.Objects[I]).Tab.visible := True; end else TMerchPage(Pages.Objects[I]).Tab.visible := False; end; function TTabbedPages.CalcNumTabs(Start, Stop: integer; First: integer): integer; begin Result := First; while (Start < Stop) and (Result < Pages.Count) do begin Inc(Start, TMerchPage(Pages.Objects[Result]).Tab.TabWidth); if Start <= Stop then Inc(Result); end; Result := Result - First; end; procedure TTabbedPages.Paint; var TabStart, LastTabPos: integer; begin TabStart := LeftMargin; LastTabPos := Width - EndMargin; Scroller.Left := Width - Scroller.Width - 2; FVisibleTabs := CalcNumTabs(TabStart, LastTabPos, FirstIndex); if AutoScroll and (FVisibleTabs < Pages.Count) then begin Dec(LastTabPos, Scroller.Width + 4); FVisibleTabs := CalcNumTabs(TabStart, LastTabPos, FirstIndex); if Kind = kdUp then Scroller.Top := 3 else Scroller.Top := Height - FTabHeight + 3; if FInserting then FirstIndex := Pages.Count - FVisibleTabs; Scroller.Visible := True; ShowWindow(Scroller.Handle, SW_SHOW); Scroller.Min := 0; Scroller.Max := Pages.Count - FVisibleTabs; Scroller.Position := FirstIndex; end else if FVisibleTabs >= Pages.Count then begin FFirstIndex := 0; Scroller.Visible := False; ShowWindow(Scroller.Handle, SW_HIDE); end; FInserting := False; SetTabPositions; with Canvas do begin Brush.Color := clBtnFace; FillRect(Rect(0, 0, Width, Height)); if Kind = kdDown then begin Pen.Color := clBtnHighlight; { Left side } MoveTo(0, Height - FTabHeight); LineTo(0, 0); LineTo(Width - 1, 0); { Top } Pen.Color := clBtnShadow; { Right side } MoveTo(Width - 2, 1); LineTo(Width - 2, Height - FTabHeight); LineTo(0, Height - FTabHeight); Pen.Color := clWindowFrame; MoveTo(Width - 1, 0); LineTo(Width - 1, Height - FTabHeight + 1); LineTo(-1, Height - FTabHeight + 1); end else begin Pen.Color := clBtnHighlight; { Left side } MoveTo(0, Height - 1); LineTo(0, FTabHeight - 1); LineTo(Width - 1, FTabHeight - 1); Pen.Color := clBtnShadow; { Right side } MoveTo(Width - 2, FTabHeight); LineTo(Width - 2, Height); MoveTo(Width - 2, Height - 2); { Bottom } LineTo(0, Height - 2); Pen.Color := clWindowFrame; { Right side } MoveTo(Width - 1, FTabHeight - 1); LineTo(Width - 1, Height-1); LineTo(-1, Height - 1); { Bottom } end; end; end; procedure TTabbedPages.SetAutoScroll(Value: boolean); begin if Value <> FAutoScroll then begin FAutoScroll := Value; Scroller.Visible := False; ShowWindow(Scroller.Handle, SW_HIDE); Invalidate; end; end; procedure TTabbedPages.CreateScroller; begin Scroller := TScroller.Create(Self); with Scroller do begin Parent := Self; Min := 0; Max := 0; Height := FTabHeight - 6; Width := 2 * Height; Position := 0; Visible := False; OnClick := ScrollClick; end; if Kind = kdUp then Scroller.Top := 3 else Scroller.Top := Height - FTabHeight + 3; end; procedure TTabbedPages.ScrollClick(Sender: TObject); begin FirstIndex := TScroller(Sender).Position; end; procedure TTabbedPages.CMDialogChar(var Message: TCMDialogChar); var I: integer; begin for I := 0 to pred(Pages.Count) do begin if IsAccel(Message.CharCode, Pages[I]) then begin Message.Result := 1; if FPageIndex <> I then SetPageIndex(I); Exit; end; end; inherited; end; end.
unit xdg_foreign_unstable_v1_protocol; {$mode objfpc} {$H+} {$interfaces corba} interface uses Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol; type Pzxdg_exporter_v1 = Pointer; Pzxdg_importer_v1 = Pointer; Pzxdg_exported_v1 = Pointer; Pzxdg_imported_v1 = Pointer; Pzxdg_exporter_v1_listener = ^Tzxdg_exporter_v1_listener; Tzxdg_exporter_v1_listener = record end; Pzxdg_importer_v1_listener = ^Tzxdg_importer_v1_listener; Tzxdg_importer_v1_listener = record end; Pzxdg_exported_v1_listener = ^Tzxdg_exported_v1_listener; Tzxdg_exported_v1_listener = record handle : procedure(data: Pointer; AZxdgExportedV1: Pzxdg_exported_v1; AHandle: Pchar); cdecl; end; Pzxdg_imported_v1_listener = ^Tzxdg_imported_v1_listener; Tzxdg_imported_v1_listener = record destroyed : procedure(data: Pointer; AZxdgImportedV1: Pzxdg_imported_v1); cdecl; end; TZxdgExporterV1 = class; TZxdgImporterV1 = class; TZxdgExportedV1 = class; TZxdgImportedV1 = class; IZxdgExporterV1Listener = interface ['IZxdgExporterV1Listener'] end; IZxdgImporterV1Listener = interface ['IZxdgImporterV1Listener'] end; IZxdgExportedV1Listener = interface ['IZxdgExportedV1Listener'] procedure zxdg_exported_v1_handle(AZxdgExportedV1: TZxdgExportedV1; AHandle: String); end; IZxdgImportedV1Listener = interface ['IZxdgImportedV1Listener'] procedure zxdg_imported_v1_destroyed(AZxdgImportedV1: TZxdgImportedV1); end; TZxdgExporterV1 = class(TWLProxyObject) private const _DESTROY = 0; const _EXPORT = 1; public destructor Destroy; override; function Export(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TZxdgExportedV1}): TZxdgExportedV1; function AddListener(AIntf: IZxdgExporterV1Listener): LongInt; end; TZxdgImporterV1 = class(TWLProxyObject) private const _DESTROY = 0; const _IMPORT = 1; public destructor Destroy; override; function Import(AHandle: String; AProxyClass: TWLProxyObjectClass = nil {TZxdgImportedV1}): TZxdgImportedV1; function AddListener(AIntf: IZxdgImporterV1Listener): LongInt; end; TZxdgExportedV1 = class(TWLProxyObject) private const _DESTROY = 0; public destructor Destroy; override; function AddListener(AIntf: IZxdgExportedV1Listener): LongInt; end; TZxdgImportedV1 = class(TWLProxyObject) private const _DESTROY = 0; const _SET_PARENT_OF = 1; public destructor Destroy; override; procedure SetParentOf(ASurface: TWlSurface); function AddListener(AIntf: IZxdgImportedV1Listener): LongInt; end; var zxdg_exporter_v1_interface: Twl_interface; zxdg_importer_v1_interface: Twl_interface; zxdg_exported_v1_interface: Twl_interface; zxdg_imported_v1_interface: Twl_interface; implementation var vIntf_zxdg_exporter_v1_Listener: Tzxdg_exporter_v1_listener; vIntf_zxdg_importer_v1_Listener: Tzxdg_importer_v1_listener; vIntf_zxdg_exported_v1_Listener: Tzxdg_exported_v1_listener; vIntf_zxdg_imported_v1_Listener: Tzxdg_imported_v1_listener; destructor TZxdgExporterV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgExporterV1.Export(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TZxdgExportedV1}): TZxdgExportedV1; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _EXPORT, @zxdg_exported_v1_interface, nil, ASurface.Proxy); if AProxyClass = nil then AProxyClass := TZxdgExportedV1; Result := TZxdgExportedV1(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZxdgExportedV1) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZxdgExportedV1]); end; function TZxdgExporterV1.AddListener(AIntf: IZxdgExporterV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_exporter_v1_Listener, @FUserDataRec); end; destructor TZxdgImporterV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgImporterV1.Import(AHandle: String; AProxyClass: TWLProxyObjectClass = nil {TZxdgImportedV1}): TZxdgImportedV1; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _IMPORT, @zxdg_imported_v1_interface, nil, PChar(AHandle)); if AProxyClass = nil then AProxyClass := TZxdgImportedV1; Result := TZxdgImportedV1(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZxdgImportedV1) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZxdgImportedV1]); end; function TZxdgImporterV1.AddListener(AIntf: IZxdgImporterV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_importer_v1_Listener, @FUserDataRec); end; destructor TZxdgExportedV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgExportedV1.AddListener(AIntf: IZxdgExportedV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_exported_v1_Listener, @FUserDataRec); end; destructor TZxdgImportedV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; procedure TZxdgImportedV1.SetParentOf(ASurface: TWlSurface); begin wl_proxy_marshal(FProxy, _SET_PARENT_OF, ASurface.Proxy); end; function TZxdgImportedV1.AddListener(AIntf: IZxdgImportedV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_imported_v1_Listener, @FUserDataRec); end; procedure zxdg_exported_v1_handle_Intf(AData: PWLUserData; Azxdg_exported_v1: Pzxdg_exported_v1; AHandle: Pchar); cdecl; var AIntf: IZxdgExportedV1Listener; begin if AData = nil then Exit; AIntf := IZxdgExportedV1Listener(AData^.ListenerUserData); AIntf.zxdg_exported_v1_handle(TZxdgExportedV1(AData^.PascalObject), AHandle); end; procedure zxdg_imported_v1_destroyed_Intf(AData: PWLUserData; Azxdg_imported_v1: Pzxdg_imported_v1); cdecl; var AIntf: IZxdgImportedV1Listener; begin if AData = nil then Exit; AIntf := IZxdgImportedV1Listener(AData^.ListenerUserData); AIntf.zxdg_imported_v1_destroyed(TZxdgImportedV1(AData^.PascalObject)); end; const pInterfaces: array[0..12] of Pwl_interface = ( (nil), (nil), (nil), (nil), (nil), (nil), (nil), (nil), (@zxdg_exported_v1_interface), (@wl_surface_interface), (@zxdg_imported_v1_interface), (nil), (@wl_surface_interface) ); zxdg_exporter_v1_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'export'; signature: 'no'; types: @pInterfaces[8]) ); zxdg_importer_v1_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'import'; signature: 'ns'; types: @pInterfaces[10]) ); zxdg_exported_v1_requests: array[0..0] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]) ); zxdg_exported_v1_events: array[0..0] of Twl_message = ( (name: 'handle'; signature: 's'; types: @pInterfaces[0]) ); zxdg_imported_v1_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'set_parent_of'; signature: 'o'; types: @pInterfaces[12]) ); zxdg_imported_v1_events: array[0..0] of Twl_message = ( (name: 'destroyed'; signature: ''; types: @pInterfaces[0]) ); initialization Pointer(vIntf_zxdg_exported_v1_Listener.handle) := @zxdg_exported_v1_handle_Intf; Pointer(vIntf_zxdg_imported_v1_Listener.destroyed) := @zxdg_imported_v1_destroyed_Intf; zxdg_exporter_v1_interface.name := 'zxdg_exporter_v1'; zxdg_exporter_v1_interface.version := 1; zxdg_exporter_v1_interface.method_count := 2; zxdg_exporter_v1_interface.methods := @zxdg_exporter_v1_requests; zxdg_exporter_v1_interface.event_count := 0; zxdg_exporter_v1_interface.events := nil; zxdg_importer_v1_interface.name := 'zxdg_importer_v1'; zxdg_importer_v1_interface.version := 1; zxdg_importer_v1_interface.method_count := 2; zxdg_importer_v1_interface.methods := @zxdg_importer_v1_requests; zxdg_importer_v1_interface.event_count := 0; zxdg_importer_v1_interface.events := nil; zxdg_exported_v1_interface.name := 'zxdg_exported_v1'; zxdg_exported_v1_interface.version := 1; zxdg_exported_v1_interface.method_count := 1; zxdg_exported_v1_interface.methods := @zxdg_exported_v1_requests; zxdg_exported_v1_interface.event_count := 1; zxdg_exported_v1_interface.events := @zxdg_exported_v1_events; zxdg_imported_v1_interface.name := 'zxdg_imported_v1'; zxdg_imported_v1_interface.version := 1; zxdg_imported_v1_interface.method_count := 2; zxdg_imported_v1_interface.methods := @zxdg_imported_v1_requests; zxdg_imported_v1_interface.event_count := 1; zxdg_imported_v1_interface.events := @zxdg_imported_v1_events; end.
unit HGM.Controls.PanelCollapsed; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, HGM.Controls.PanelExt, Vcl.Buttons, Vcl.Imaging.pngimage, HGM.Common; type TPanelCollapsed = class(TPanelExt) private FCaptionPanel:TPanel; FCollapsing:Boolean; FHeight:Integer; FCollapseButton:TSpeedButton; // FOnPaint: TNotifyEvent; FShowSimpleBorder: Boolean; FSimpleBorderColor: TColor; FCollapsed: Boolean; FCapHeight: Integer; function GetCaption: string; procedure SetCaption(const Value: string); function GetShowCaption: Boolean; procedure SetShowCaption(const Value: Boolean); function GetFontCaption: TFont; procedure SetFontCaption(const Value: TFont); procedure SetAlignment(const Value: TAlignment); function GetAlignment: TAlignment; function GetCaptionColor: TColor; procedure SetCaptionColor(const Value: TColor); procedure SetShowSimpleBorder(const Value: Boolean); procedure OnCollapseButtonClick(Sender:TObject); function GetHeight: Integer; procedure SetHeight(const Value: Integer); procedure SetCollapsed(const Value: Boolean); procedure WMSize(var Msg:TWMSize); message WM_SIZE; function GetShowCollapseButton: Boolean; procedure SetShowCollapseButton(const Value: Boolean); procedure SetCapHeight(const Value: Integer); public procedure Paint; override; published property ShowCollapseButton:Boolean read GetShowCollapseButton write SetShowCollapseButton; property Collapsed:Boolean read FCollapsed write SetCollapsed; property Height:Integer read GetHeight write SetHeight; property Caption:string read GetCaption write SetCaption; property Alignment: TAlignment read GetAlignment write SetAlignment default taCenter; property Font; property SimpleBorderColor:TColor read FSimpleBorderColor write FSimpleBorderColor; property CaptionColor:TColor read GetCaptionColor write SetCaptionColor; property FontCaption:TFont read GetFontCaption write SetFontCaption; property ShowCaption:Boolean read GetShowCaption write SetShowCaption; property ShowSimpleBorder:Boolean read FShowSimpleBorder write SetShowSimpleBorder; property VerticalAlignment; property CaptionHeight:Integer read FCapHeight write SetCapHeight; constructor Create(AOwner: TComponent); override; end; procedure Register; implementation {$R hCollPanel.res} procedure Register; begin RegisterComponents(PackageName, [TPanelCollapsed]); end; { TPanelCollapsed } constructor TPanelCollapsed.Create(AOwner: TComponent); var PNG:TPngImage; begin inherited; inherited ShowCaption:=False; inherited BorderStyle:=bsNone; inherited BevelInner:=bvNone; inherited BevelKind:=bkNone; inherited BevelOuter:=bvNone; inherited ParentBackground:=False; FCollapsing:=False; Height:=300; FCapHeight:=30; FCaptionPanel:=TPanel.Create(Self); with FCaptionPanel do begin Parent:=Self; Align:=alTop; Height:=FCapHeight; Caption:=' Caption'; ShowCaption:=True; ParentBackground:=False; ParentColor:=False; BorderStyle:=bsNone; BevelInner:=bvNone; BevelKind:=bkNone; BevelOuter:=bvNone; BringToFront; Color:=clGray; Font.Color:=clWhite; Font.Style:=[fsBold]; Font.Size:=10; Alignment:=taLeftJustify; OnClick:=OnCollapseButtonClick; end; FCollapseButton:=TSpeedButton.Create(FCaptionPanel); with FCollapseButton do begin Parent:=FCaptionPanel; Align:=alRight; AlignWithMargins:=True; PNG:=TPngImage.Create; PNG.LoadFromResourceName(HInstance, 'COLPANEL_HIDE'); Glyph.Assign(PNG); PNG.Free; Flat:=True; OnClick:=OnCollapseButtonClick; end; ShowSimpleBorder:=False; SimpleBorderColor:=clSilver; end; function TPanelCollapsed.GetAlignment: TAlignment; begin Result:=FCaptionPanel.Alignment; end; function TPanelCollapsed.GetCaption: string; begin Result:=FCaptionPanel.Caption; end; function TPanelCollapsed.GetCaptionColor: TColor; begin Result:=FCaptionPanel.Color; end; function TPanelCollapsed.GetFontCaption: TFont; begin Result:=FCaptionPanel.Font; end; function TPanelCollapsed.GetHeight: Integer; begin Result:=FHeight; end; function TPanelCollapsed.GetShowCaption: Boolean; begin Result:=FCaptionPanel.ShowCaption; end; function TPanelCollapsed.GetShowCollapseButton: Boolean; begin Result:=FCollapseButton.Visible; end; procedure TPanelCollapsed.OnCollapseButtonClick(Sender: TObject); begin if not FCollapseButton.Visible then Exit; Collapsed:=not Collapsed; end; procedure TPanelCollapsed.Paint; begin inherited; if FShowSimpleBorder then begin with Canvas do begin Pen.Color:=FSimpleBorderColor; Brush.Style:=bsClear; Rectangle(ClientRect); end; end; end; procedure TPanelCollapsed.SetAlignment(const Value: TAlignment); begin FCaptionPanel.Alignment:= Value; end; procedure TPanelCollapsed.SetCapHeight(const Value: Integer); begin FCapHeight := Value; FCaptionPanel.Height:=FCapHeight; end; procedure TPanelCollapsed.SetCaption(const Value: string); begin FCaptionPanel.Caption:=Value; end; procedure TPanelCollapsed.SetCaptionColor(const Value: TColor); begin FCaptionPanel.Color:=Value; end; procedure TPanelCollapsed.SetCollapsed(const Value: Boolean); begin if FCollapsing then Exit; FCollapsing:=True; FCollapsed:= Value; if FCollapsed then begin { while inherited Height > FCaptionPanel.Height+2 do begin inherited Height:=inherited Height - 3; Application.ProcessMessages; Sleep(1); end; } inherited Height:=FCaptionPanel.Height+2; end else begin { while inherited Height < FHeight do begin inherited Height:=inherited Height + 3; Application.ProcessMessages; Sleep(1); end; } inherited Height:=FHeight; end; FCollapsing:=False; end; procedure TPanelCollapsed.SetFontCaption(const Value: TFont); begin FCaptionPanel.Font:=Value; end; procedure TPanelCollapsed.SetHeight(const Value: Integer); begin FHeight:=Value; if not Collapsed then inherited Height:=FHeight; end; procedure TPanelCollapsed.SetShowCaption(const Value: Boolean); begin FCaptionPanel.ShowCaption:=Value; end; procedure TPanelCollapsed.SetShowCollapseButton(const Value: Boolean); begin FCollapseButton.Visible:=Value; end; procedure TPanelCollapsed.SetShowSimpleBorder(const Value: Boolean); begin FShowSimpleBorder := Value; if FShowSimpleBorder then begin FCaptionPanel.AlignWithMargins:=True; FCaptionPanel.Margins.Left:=1; FCaptionPanel.Margins.Top:=1; FCaptionPanel.Margins.Right:=1; FCaptionPanel.Margins.Bottom:=0; end else begin FCaptionPanel.AlignWithMargins:=False; FCaptionPanel.Margins.Left:=1; FCaptionPanel.Margins.Top:=1; FCaptionPanel.Margins.Right:=1; FCaptionPanel.Margins.Bottom:=0; end; Repaint; end; procedure TPanelCollapsed.WMSize(var Msg: TWMSize); begin inherited; //if not FCollapsing then if Collapsed then Collapsed:=False; end; end.
unit uUnit; interface uses glr_math, uObject; type { TArenaUnit } TArenaUnit = class (TArenaObject) protected fControlVector: TglrVec2f; fDirection: TglrVec2f; procedure Control(const dt: Double); virtual; procedure DoUpdate(const dt: Double); override; public HealthMax, DirectSpeed: Single; Health: Single; constructor Create(); virtual; procedure Spawn(Position: TglrVec3f); override; procedure Die(); virtual; end; implementation { TArenaUnit } procedure TArenaUnit.Spawn(Position: TglrVec3f); begin inherited Spawn(Position); Health := HealthMax; DirectSpeed := 0; end; procedure TArenaUnit.Control(const dt: Double); begin end; procedure TArenaUnit.DoUpdate(const dt: Double); begin inherited DoUpdate(dt); Control(dt); Sprite.Position += Vec3f(fControlVector * dt * DirectSpeed, 0); Sprite.Rotation := fDirection.GetRotationAngle(); if (Health <= 0) then Die(); end; constructor TArenaUnit.Create; begin inherited; fControlVector.Reset(); fDirection := Vec2f(0, 1); end; procedure TArenaUnit.Die; begin end; end.
unit LiveHtmlForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, Menus, ClipBrd, // HtmlGlobals, HTMLUn2, HtmlView, SynEditHighlighter, SynHighlighterHtml, SynEdit, SynEditOptionsDialog, HtmlBuffer; type TFormLiveHtml = class(TForm) HtmlViewer: THtmlViewer; Splitter: TSplitter; PopupMenu: TPopupMenu; pmSelectAll: TMenuItem; pmCopy: TMenuItem; pmPaste: TMenuItem; N1: TMenuItem; NameList1: TMenuItem; Memo: TSynEdit; SynHTMLSyn1: TSynHTMLSyn; SynEditOptionsDialog1: TSynEditOptionsDialog; PopupMenu1: TPopupMenu; Options1: TMenuItem; DocumentSource1: TMenuItem; TestAsString1: TMenuItem; procedure MemoChange(Sender: TObject); procedure HtmlViewerObjectClick(Sender, Obj: TObject; OnClick: widestring); procedure pmSelectAllClick(Sender: TObject); procedure pmCopyClick(Sender: TObject); procedure pmPasteClick(Sender: TObject); procedure NameList1Click(Sender: TObject); procedure Options1Click(Sender: TObject); procedure DocumentSource1Click(Sender: TObject); procedure HtmlViewerParseBegin(Sender: TObject; var Source: TBuffer); protected procedure Loaded; override; end; var FormLiveHtml: TFormLiveHtml; implementation {$R *.dfm} procedure TFormLiveHtml.DocumentSource1Click(Sender: TObject); var SourceList: TStringList; begin Memo.Lines.Add(HtmlViewer.DocumentSource); // SourceList := TStringList.Create; // try // SourceList.Text := HtmlViewer.DocumentSource; // SourceList.SaveToFile(ChangeFileExt(Application.ExeName, '.log')); // finally // SourceList.Free; // end; end; procedure TFormLiveHtml.HtmlViewerObjectClick(Sender, Obj: TObject; OnClick: widestring); begin HtmlViewer.Clear; end; var Str: ThtString; procedure TFormLiveHtml.HtmlViewerParseBegin(Sender: TObject; var Source: TBuffer); begin if TestAsString1.Checked then begin Str := Source.AsString; end; end; procedure TFormLiveHtml.Loaded; begin inherited; HtmlViewer.LoadFromString('Type or paste html text into the field below and see the results in this HtmlViewer.'); Memo.Lines.Text := 'Type or paste html text into this field and see the results in the above HtmlViewer.'; Memo.SelectAll; Caption := 'HtmlViewer ' + VersionNo + ' Live'; end; //-- BG ---------------------------------------------------------- 21.10.2012 -- procedure TFormLiveHtml.MemoChange(Sender: TObject); begin HtmlViewer.LoadFromString(Memo.Text); end; //-- BG ---------------------------------------------------------- 12.09.2012 -- procedure TFormLiveHtml.NameList1Click(Sender: TObject); var Infos: TStringList; Names: TIDObjectList; I: Integer; begin // simply get the names //Clipboard.AsText := HtmlViewer.NameList.Text; // get the names and the actual types of the associated TIDObject derivates. Infos := TStringList.Create; try Names := HtmlViewer.SectionList.IDNameList; for I := 0 to Names.Count - 1 do Infos.Add(Names.Strings[I] + ' (' + Names.Objects[I].ClassName + ')'); Clipboard.AsText := Infos.Text; finally Infos.Free; end; end; //-- BG ---------------------------------------------------------- 21.10.2012 -- procedure TFormLiveHtml.Options1Click(Sender: TObject); var Options: TSynEditorOptionsContainer; begin Options := TSynEditorOptionsContainer.Create(Self); try Options.Assign(Memo); if SynEditOptionsDialog1.Execute(Options) then Options.AssignTo(Memo); finally Options.Free; end; end; //-- BG ---------------------------------------------------------- 03.06.2012 -- procedure TFormLiveHtml.pmCopyClick(Sender: TObject); begin HtmlViewer.CopyToClipboard; end; //-- BG ---------------------------------------------------------- 03.06.2012 -- procedure TFormLiveHtml.pmPasteClick(Sender: TObject); begin Memo.PasteFromClipboard; end; //-- BG ---------------------------------------------------------- 03.06.2012 -- procedure TFormLiveHtml.pmSelectAllClick(Sender: TObject); begin HtmlViewer.SelectAll; end; end.
{ some helper functions/procedures written by Sebastian Kraft sebastian_kraft@gmx.de This software is free under the GNU Public License (c)2005-2008 } Unit functions; {$mode objfpc}{$H+} Interface Uses Classes, SysUtils, math, debug, config; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function crc32(path: String): longint; Function crc32_math(path: String): int64; Function DirectoryIsEmpty(Directory: String): Boolean; Function EraseDirectory(Directory: String): Boolean; //delete directory and all subdirectories/files in it Function UTF8toLatin1(utfstring: ansistring): ansistring; Function Latin1toUTF8(latin1string: ansistring): ansistring; Function rmZeroChar(s: ansistring): ansistring; Function FileCopy(Const FromFile, ToFile: String): boolean; Function FreeSpaceOnDAP: int64; Function ByteToFmtString(bytes: int64; d1, d2: byte): string; // converts i.e. 1024 to 1,0 KB // d1, d2 sets amount of digits before and after ',' Function SecondsToFmtStr(seconds: longint): string;//converts integer to mm:ss time format Function MSecondsToFmtStr(MSeconds: longint): string; function MakeValidFilename(Filename: String): string; procedure BubbleSort(var Items: TStrings); function IntTodB(i, ref: longint):integer; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Implementation //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function crc32(path: String): longint; //creates an very, very basic checksum to identify files Var fhandle: THandle; buf: array [0..63] Of word; z: byte; i, eofile: longint; l: longint; Begin {$Q-} fhandle := sysutils.fileopen(path, fmOpenRead); l := 0; i := 0; z := 0; eofile := 0; While (eofile<>-1) And (i<256) Do Begin eofile := FileRead(fhandle, buf, sizeof(buf)); If (eofile<>-1) Then For z:=0 To high(buf) Do begin L := L+buf[z]; end; inc(i); End; FileClose(fhandle); result := l; {$Q+} End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function crc32_math(path: String): int64; //creates an very, very basic checksum to identify files Var fhandle: THandle; buf: array [0..63] Of int64; z: byte; i, eofile: longint; l: int64; Begin fhandle := sysutils.fileopen(path, fmOpenRead); l := 0; i := 0; z := 0; eofile := 0; While (eofile<>-1) And (i<256) Do Begin eofile := FileRead(fhandle, buf, high(buf)); l := l+sumInt(buf); inc(i); End; FileClose(fhandle); result := l; End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function EraseDirectory(Directory: String): Boolean; Var Srec: TSearchRec; Begin result := false; If DirectoryExists(Directory)Then Begin Try FindFirst(IncludeTrailingPathDelimiter(Directory) + '*', faAnyFile, Srec); Repeat Begin If (Srec.Name <> '.') And (Srec.Name <> '..') Then DeleteFile(Directory+DirectorySeparator+Srec.Name); End; Until FindNext(Srec)<>0; FindClose(Srec); result := RemoveDir(Directory); Except result := false; End; End; End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function UTF8toLatin1(utfstring: ansistring): ansistring; Var i: integer; tmps: string; utf16: boolean; Begin i := 0; tmps := ''; utf16 := false; If length(utfstring)>0 Then Begin Repeat Begin inc(i); Case byte(utfstring[i]) Of $ff: If byte(utfstring[i+1])=$fe Then utf16 := true; $c3: Begin Delete(utfstring, i, 1); utfstring[i] := char(byte(utfstring[i])+64); End; $c2: Begin Delete(utfstring, i, 1); dec(i); End; End; End; Until (i>=length(utfstring)-1) Or utf16; //if utf16 detected If utf16 Then Begin i := i+2; DebugOutLn('utf16',0); Repeat Begin inc(i); If byte(utfstring[i])<>0 Then tmps := tmps+utfstring[i]; End; Until (i>=length(utfstring)); End; End; If Not utf16 Then result := utfstring Else Result := tmps; End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function rmZeroChar(s: ansistring): ansistring; Var i: integer; Begin i := 0; If s<>'' Then Begin Repeat Begin inc(i); If byte(s[i])=0 Then Begin Delete(s, i, 1); dec(i); End; End; Until i>=length(s)-1; End; Result := s; End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function Latin1toUTF8(latin1string: ansistring): ansistring; Var i: integer; c: char; tmps: string; utf16: boolean; Begin i := 0; utf16 := false; If length(latin1string)>0 Then Begin Repeat Begin inc(i); Case byte(latin1string[i]) Of $ff: If byte(latin1string[i+1])=$fe Then utf16 := true; $00..$1f: Begin Delete(latin1string, i, 1); dec(i); End; $c0..$fd: Begin //c0..ff ist der gesamte wertebereich!! If (byte(latin1string[i])=$c3) And (byte(latin1string[i+1])<$C0) Then inc(i) Else Begin latin1string[i] := char(byte(latin1string[i])-64); insert(char($c3), latin1string, i); inc(i); End; End; { $a1..$bf: begin c:=latin1string[i]; insert(char($c2), latin1string, i); // utfstring[i]:=char(byte(utfstring[i])+64); inc(i); end;} End; End; Until (i>=length(latin1string)-1) Or utf16; //if utf16 detected If utf16 Then Begin //latin1string:=AnsiToUtf8(latin1string); may also work instead of following own utf16->utf8 routine inc(i); Repeat Begin inc(i); If byte(latin1string[i])>$1f Then If byte(latin1string[i])<$c0 Then tmps := tmps+char(byte(latin1string[i])) Else tmps := tmps+char($c3)+char(byte(latin1string[i])-64); End; Until (i>=length(latin1string)); End; End; If Not utf16 Then result := latin1string Else Result := tmps; End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ { Function to copy a file FromFile -> ToFile , mainly used while upload to player device} Function FileCopy(Const FromFile, ToFile: String): boolean; Var FromF, ToF: file; NumRead, NumWritten: Word; Buf: array[1..4096] Of byte; Begin Try AssignFile(FromF, FromFile); Reset(FromF, 1); { Record size = 1 } AssignFile(ToF, ToFile); { Open output file } Rewrite(ToF, 1); { Record size = 1 } Repeat BlockRead(FromF, Buf, SizeOf(Buf), NumRead); BlockWrite(ToF, Buf, NumRead, NumWritten); Until (NumRead = 0) Or (NumWritten <> NumRead); CloseFile(FromF); CloseFile(ToF); result := true; Except result := false; End; End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function FreeSpaceOnDAP: int64; Var tmps: string; Begin tmps := GetCurrentDir; // get free memory on player, format string SetCurrentDir(CactusConfig.DAPPath); result := DiskFree(0); DebugOutLn('------>',0); DebugOutLn(Format('DiskFree=%d',[DiskFree(0)]),0); SetCurrentDir(tmps); End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function ByteToFmtString(bytes: int64; d1, d2: byte): string; Var r: real; count: byte; comma, prefix, s1, s2: string; subzero:boolean; Begin count := 0; if bytes>=0 then subzero:=false else subzero:=true; r := abs(bytes); While (r>=power(10, d1)) Do Begin r := r / 1024; inc(count); End; Case count Of 0: prefix := 'Byte'; 1: prefix := 'KB'; 2: prefix := 'MB'; 3: prefix := 'GB'; 4: prefix := 'TB'; 5: prefix := 'PB'; End; str(round (r*power(10, d2)) , s2); If r >= 1 Then Begin s1 := copy(s2, 0, length(s2)-d2); s2 := copy(s2, length(s2)-d2+1, d2); End Else s1 := '0'; If d2<>0 Then comma := ',' Else Begin comma := ''; s2 := ''; End; if subzero=false then result := s1+comma+s2+' '+prefix else result := '- ' + s1+comma+s2+' '+prefix End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function SecondsToFmtStr(seconds: longint): string; Var min, sec: longint; s, s2: string; Begin if seconds>0 then begin min := seconds Div 60; sec := seconds Mod 60; str(min, s); str(sec, s2); If min<10 Then s := '0'+s; If sec<10 Then s2 := '0'+s2; result := s+':'+s2; end else Result:='00:00'; End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function MSecondsToFmtStr(MSeconds: longint): string; Begin if MSeconds>1000 then result := SecondsToFmtStr(MSeconds Div 1000) else Result:='00:00'; End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function DirectoryIsEmpty(Directory: String): Boolean; Var SeR: TSearchRec; i: Integer; Begin Result := False; FindFirst(IncludeTrailingPathDelimiter(Directory) + '*', faAnyFile, SeR); For i := 1 To 2 Do If (SeR.Name = '.') Or (SeR.Name = '..') Then Result := FindNext(SeR) <> 0; FindClose(SeR); End; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function MakeValidFilename(Filename: String): string; var I: integer; { for long file names } // FIXME taken from code for win32 - list correct/complete?? LongForbiddenChars : set of Char = ['<', '>', '|', '"', '\', '/', ':', '*', '?']; begin for I := 1 to Length(Filename) do if (Filename[I] in LongForbiddenChars) then Filename[I] := ' '; result := Filename; end; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure BubbleSort(var Items: TStrings); var done: boolean; i, n: integer; Dummy: string; begin n := Items.Count; repeat done := true; for i := 0 to n - 2 do if Items[i] > Items[i + 1] then begin Dummy := Items[i]; Items[i] := Items[i + 1]; Items[i + 1] := Dummy; done := false; end; until done; end; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function IntTodB(i, ref: longint): integer; var dB: Real; begin if i=0 then db:=0.001 else dB:=i; dB:= 20*log10(dB/ref); result:=round(dB); end; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ End.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clMailUserMgr; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clUserMgr; type TclMailUserAccountItem = class(TclUserAccountItem) private FEmail: string; public procedure Assign(Source: TPersistent); override; published property Email: string read FEmail write FEmail; end; TclMailUserAccountList = class(TclUserAccountList) private function GetItem(Index: Integer): TclMailUserAccountItem; procedure SetItem(Index: Integer; const Value: TclMailUserAccountItem); public function Add: TclMailUserAccountItem; function AccountByEmail(const AEmail: string): TclMailUserAccountItem; function AccountByUserName(const AUserName: string): TclMailUserAccountItem; property Items[Index: Integer]: TclMailUserAccountItem read GetItem write SetItem; default; end; implementation { TclMailUserAccountItem } procedure TclMailUserAccountItem.Assign(Source: TPersistent); begin if (Source is TclMailUserAccountItem) then begin FEmail := (Source as TclMailUserAccountItem).Email; end; inherited Assign(Source); end; { TclMailUserAccountList } function TclMailUserAccountList.AccountByEmail(const AEmail: string): TclMailUserAccountItem; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i]; if CaseInsensitive then begin if SameText(Result.Email, AEmail) then Exit; end else begin if (Result.Email = AEmail) then Exit; end; end; Result := nil; end; function TclMailUserAccountList.AccountByUserName(const AUserName: string): TclMailUserAccountItem; begin Result := inherited AccountByUserName(AUserName) as TclMailUserAccountItem; end; function TclMailUserAccountList.Add: TclMailUserAccountItem; begin Result := TclMailUserAccountItem(inherited Add()); end; function TclMailUserAccountList.GetItem(Index: Integer): TclMailUserAccountItem; begin Result := TclMailUserAccountItem(inherited GetItem(Index)); end; procedure TclMailUserAccountList.SetItem(Index: Integer; const Value: TclMailUserAccountItem); begin inherited SetItem(Index, Value); end; end.
unit Cliente.dao; interface uses System.SysUtils, System.Classes, Data.FMTBcd, Data.DB, Datasnap.DBClient, Datasnap.Provider, Data.SqlExpr, Cliente.model; type TDmCliente = class(TDataModule) sqlExcluir: TSQLDataSet; sqlPesquisar: TSQLDataSet; sqlInserir: TSQLDataSet; sqlAlterar: TSQLDataSet; dspPesquisar: TDataSetProvider; cdsPesquisar: TClientDataSet; cdsPesquisarID: TIntegerField; cdsPesquisarNOME: TStringField; cdsPesquisarTELEFONE: TStringField; private { Private declarations } public function GerarId: Integer; procedure Pesquisar(sNome: string); procedure CarregarCliente(oCliente: TCliente; iCodigo: integer); function Inserir(oCliente: TCliente; out sErro: string): Boolean; function Alterar(oCliente: TCliente; out sErro: string): Boolean; function Excluir(iCodigo: Integer; out sErro: string): Boolean; end; var DmCliente: TDmCliente; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses Conexao.dao; {$R *.dfm} { TDataModule1 } function TDmCliente.Alterar(oCliente: TCliente; out sErro: string): Boolean; begin with sqlAlterar, oCliente do begin Params[0].AsString := Nome; Params[1].AsString := Tipo; Params[2].AsString := Documento; Params[3].AsString := Telefone; Params[4].AsInteger := ID; try ExecSQL(); Result := True; except on E: Exception do begin sErro := 'Ocorreu um erro ao alterar o cliente: ' + sLineBreak + E.Message; Result := False; end; end; end; end; procedure TDmCliente.CarregarCliente(oCliente: TCliente; iCodigo: integer); var sqlCliente: TSQLDataSet; begin sqlCliente := TSQLDataSet.Create(nil); try with sqlCliente do begin SQLConnection := DmConexao.sqlConexao; CommandText := 'SELECT * FROM cliente where (id = ' + IntToStr(iCodigo) + ')'; Open; with oCliente do begin ID := FieldByName('id').AsInteger; Nome := FieldByName('nome').AsString; Tipo := FieldByName('tipo').AsString; Documento := FieldByName('documento').AsString; Telefone := FieldByName('telefone').AsString; end; end; finally FreeAndNil(sqlCliente); end; end; function TDmCliente.Excluir(iCodigo: Integer; out sErro: string): Boolean; begin with sqlExcluir do begin Params[0].AsInteger := iCodigo; try ExecSQL(); Result := True; except on E: Exception do Begin sErro := 'Ocorreu um erro ao excluir o cliente: ' + sLineBreak + E.Message; Result := False; End; end; end; end; function TDmCliente.GerarId: Integer; var sqlSequencial: TSQLDataSet; begin sqlSequencial := TSQLDataSet.Create(nil); try with sqlSequencial do begin SQLConnection := DmConexao.sqlConexao; CommandText := 'SELECT Coalesce(max(id), 0) + 1 as seq FROM cliente'; Open; end; Result := sqlSequencial.FieldByName('seq').AsInteger; finally FreeAndNil(sqlSequencial); end; end; function TDmCliente.Inserir(oCliente: TCliente; out sErro: string): Boolean; begin with sqlInserir, oCliente do begin Params[0].AsInteger := GerarId; Params[1].AsString := Nome; params[2].AsString := Tipo; params[3].AsString := Documento; params[4].AsString := Telefone; try ExecSQL(); Result := True; except on E: Exception do begin sErro := 'Ocorreu um erro ao inserir cliente: ' + sLineBreak + E.Message; Result := False; end; end; end; end; procedure TDmCliente.Pesquisar(sNome: string); begin if cdsPesquisar.Active then cdsPesquisar.Close; cdsPesquisar.Params[0].AsString := '%' + sNome + '%'; cdsPesquisar.Open; cdsPesquisar.First; end; end.
unit EncryptedStreams; interface uses SysUtils, Classes, tfCiphers; type TEncryptedStream = class(TStream) protected FStream: TStream; FKeyStream: TStreamCipher; function NonceSize: Integer; virtual; public function Read(var Buffer; Count: Int32): Int32; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Write(const Buffer; Count: Int32): Int32; override; end; TEncryptedFileStream = class(TEncryptedStream) public constructor Create(const AFileName: string; Mode: Word; AStreamCipher: TStreamCipher); destructor Destroy; override; end; implementation { TEncryptedStream } function TEncryptedStream.NonceSize: Integer; begin Result:= SizeOf(UInt64); end; function TEncryptedStream.Read(var Buffer; Count: Int32): Int32; begin Result:= FStream.Read(Buffer, Count); FKeyStream.Apply(Buffer, Count); end; function TEncryptedStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; var // LSkip: Int64; OldPos, NewPos: Int64; begin OldPos:= FStream.Position; if Origin = soBeginning then Result:= FStream.Seek(Offset + NonceSize, soBeginning) else Result:= FStream.Seek(Offset, Origin); if Result < NonceSize then raise EStreamError.Create('Seek Error'); NewPos:= FStream.Position; FKeyStream.Skip(NewPos - OldPos); Result:= Result - NonceSize; end; function TEncryptedStream.Write(const Buffer; Count: Int32): Int32; var Buf: Pointer; begin if Count <= 0 then begin Result:= 0; Exit; end; GetMem(Buf, Count); try Move(Buffer, Buf^, Count); FKeyStream.Apply(Buf^, Count); Result:= FStream.Write(Buf^, Count); finally FillChar(Buf^, Count, 0); FreeMem(Buf); end; end; { TEncryptedFileStream } constructor TEncryptedFileStream.Create(const AFileName: string; Mode: Word; AStreamCipher: TStreamCipher); var LNonceSize: Integer; LNonce: UInt64; begin FStream:= TFileStream.Create(AFileName, Mode); FKeyStream:= AStreamCipher; LNonceSize:= NonceSize; if LNonceSize > SizeOf(UInt64) then raise EStreamError.Create('Invalid Nonce Size'); if (Mode and fmCreate) = fmCreate then begin LNonce:= FKeyStream.Nonce; FStream.WriteBuffer(LNonce, LNonceSize); end else begin LNonce:= 0; FStream.ReadBuffer(LNonce, LNonceSize); FKeyStream.Nonce:= LNonce; end; end; destructor TEncryptedFileStream.Destroy; begin FStream.Free; inherited Destroy; end; end.
unit MemoryUtils; interface uses Windows; type SIZE_T = Cardinal; {$EXTERNALSYM SIZE_T} DWORDLONG = Int64; // ULONGLONG {$EXTERNALSYM DWORDLONG} type PMemoryStatus = ^TMemoryStatus; LPMEMORYSTATUS = PMemoryStatus; {$EXTERNALSYM LPMEMORYSTATUS} _MEMORYSTATUS = packed record dwLength : DWORD; dwMemoryLoad : DWORD; dwTotalPhys : SIZE_T; dwAvailPhys : SIZE_T; dwTotalPageFile: SIZE_T; dwAvailPageFile: SIZE_T; dwTotalVirtual : SIZE_T; dwAvailVirtual : SIZE_T; end; {$EXTERNALSYM _MEMORYSTATUS} TMemoryStatus = _MEMORYSTATUS; MEMORYSTATUS = _MEMORYSTATUS; {$EXTERNALSYM MEMORYSTATUS} type PMemoryStatusEx = ^TMemoryStatusEx; LPMEMORYSTATUSEX = PMemoryStatusEx; {$EXTERNALSYM LPMEMORYSTATUSEX} _MEMORYSTATUSEX = packed record dwLength : DWORD; dwMemoryLoad : DWORD; ullTotalPhys : DWORDLONG; ullAvailPhys : DWORDLONG; ullTotalPageFile: DWORDLONG; ullAvailPageFile: DWORDLONG; ullTotalVirtual : DWORDLONG; ullAvailVirtual : DWORDLONG; ullAvailExtendedVirtual : DWORDLONG; end; {$EXTERNALSYM _MEMORYSTATUSEX} TMemoryStatusEx = _MEMORYSTATUSEX; MEMORYSTATUSEX = _MEMORYSTATUSEX; {$EXTERNALSYM MEMORYSTATUSEX} //--- procedure GlobalMemoryStatus(var lpBuffer: TMemoryStatus); stdcall; external kernel32; {$EXTERNALSYM GlobalMemoryStatus} function GlobalMemoryStatusEx(var lpBuffer: TMemoryStatusEx): BOOL; stdcall; function BytesToMB(const i: DWORDLONG): DWORD; implementation function GlobalMemoryStatusEx(var lpBuffer: TMemoryStatusEx): BOOL; stdcall; type TFNGlobalMemoryStatusEx = function(var msx: TMemoryStatusEx): BOOL; stdcall; var FNGlobalMemoryStatusEx: TFNGlobalMemoryStatusEx; begin FNGlobalMemoryStatusEx := TFNGlobalMemoryStatusEx( GetProcAddress(GetModuleHandle(kernel32), 'GlobalMemoryStatusEx')); if not Assigned(FNGlobalMemoryStatusEx) then begin SetLastError(ERROR_CALL_NOT_IMPLEMENTED); Result := False; end else Result := FNGlobalMemoryStatusEx(lpBuffer); end; // Byte nach MegaBytes umrechnen function BytesToMB(const i: DWORDLONG): DWORD; overload; var x : DWORDLONG; begin x := i shr 20; Result := x; end; end.
unit uExportarDepartamentoAcesso; interface uses System.SysUtils, System.Classes, uArquivoTexto, uDM, uFireDAC, uDepartamentoAcessoVO, System.Generics.Collections, uGenericDAO; type TExportarDepartamentoAcesso = class private FArquivo: string; public procedure Exportar(); // function Importar(): TObjectList<TDepartamentoAcessoVO>; constructor Create(); overload; end; implementation { TExportarDepartamentoAcesso } constructor TExportarDepartamentoAcesso.Create; begin inherited Create; FArquivo := 'D:\DOMPER\SIDomper\Banco\DepartamentoAcesso.txt'; end; procedure TExportarDepartamentoAcesso.Exportar; var obj: TFireDAC; Arq: TArquivoTexto; begin obj := TFireDAC.create; Arq := TArquivoTexto.Create(FArquivo, tpExportar); try obj.OpenSQL('SELECT * FROM Departamento_Acesso WHERE DepAc_Departamento = 7'); while not obj.Model.Eof do begin Arq.ExportarInt(obj.Model.FieldByName('DepAc_Departamento').AsInteger, 001, 005); Arq.ExportarInt(obj.Model.FieldByName('DepAc_Programa').AsInteger, 006, 005); Arq.ExportarBool(obj.Model.FieldByName('DepAc_Acesso').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('DepAc_Incluir').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('DepAc_Editar').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('DepAc_Excluir').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('DepAc_Relatorio').AsBoolean); Arq.NovaLinha(); obj.Model.Next; end; finally FreeAndNil(obj); FreeAndNil(Arq); end; end; //function TExportarDepartamentoAcesso.Importar: TObjectList<TDepartamentoAcessoVO>; //var // model: TDepartamentoAcessoVO; // lista: TObjectList<TDepartamentoAcessoVO>; // Arq: TArquivoTexto; //begin // lista := TObjectList<TDepartamentoAcessoVO>.Create(); // Arq := TArquivoTexto.Create(FArquivo, tpImportar); // try // while not (Arq.FimArquivo()) do // begin // Arq.ProximoRegistro(); // // model := TDepartamentoAcessoVO.Create; // model.Id := 0; // model.IdDepartamento := Arq.ImportarInt(001, 005); // model.Programa := Arq.ImportarInt(006, 005); // model.Acesso := Arq.ImportarBool(011, 001); // model.Incluir := Arq.ImportarBool(012, 001); // model.Editar := Arq.ImportarBool(013, 001); // model.Excluir := Arq.ImportarBool(014, 001); // model.Relatorio := Arq.ImportarBool(015, 001); // // lista.Add(model); // end; // finally // FreeAndNil(Arq); // end; // Result := lista; //end; end.
unit SuffixTreeLib; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Menus, ComCtrls; const MAX_CHAR = 256; Type SuffixTreeNode = record children: array[0..MAX_CHAR-1] of ^SuffixTreeNode; suffixLink: ^SuffixTreeNode; start: integer; stop: ^integer; suffixIndex: integer; end; Node = ^SuffixTreeNode; intPtr = ^integer; var text: string[100]; root, lastNewNode, activeNode: Node; activeEdge, activeLength, remainingSuffixCount, leafEnd, size: integer; rootEnd, splitEnd: intPtr; treeNodeStr: TTreeNode; function BuildSuffixTree(str: string): Node; implementation uses main; procedure Init(); begin root:= nil; lastNewNode:= nil; activeNode:= nil; activeEdge:= -1; activeLength:= 0; remainingSuffixCount:= 0; leafEnd:= -1; rootEnd:= nil; splitEnd:= nil; size:= -1; end; function NewNode(start: integer; stop: intPtr): Node; var N: Node; i: integer; begin New(N); for i:= 0 to MAX_CHAR - 1 do N^.children[i]:= nil; N^.suffixLink:= root; N^.start:= start; N^.stop:= stop; N^.suffixIndex:= -1; Result:= N; end; function EdgeLength(N: Node): integer; begin Result:= (N^.stop)^ - (N^.start) + 1; end; function WalkDown(currNode: Node): boolean; begin if activeLength >= edgeLength(currNode) then begin activeEdge:= activeEdge + EdgeLength(currNode); activeLength:= activeLength - EdgeLength(currNode); activeNode:= currNode; Result:= True; end; Result:= False; end; procedure ExtendSuffixTree(pos: integer); var split, next: Node; begin leafEnd:= pos; Inc(remainingSuffixCount); lastNewNode:= nil; while remainingSuffixCount > 0 do begin if activeLength = 0 then activeEdge:= pos; if activeNode^.children[ord(text[activeEdge])] = nil then begin activeNode^.children[ord(text[activeEdge])]:= NewNode(pos, @leafEnd); if lastNewNode <> nil then begin lastNewNode^.suffixLink:= activeNode; lastNewNode:= nil; end; end else begin next:= activeNode^.children[ord(text[activeEdge])]; if WalkDown(next) then continue; if text[next^.start + activeLength] = text[pos] then begin if (lastNewNode <> nil) and (activeNode <> root) then begin lastNewNode^.suffixLink:= activeNode; lastNewNode:= nil; end; Inc(activeLength); break; end; New(splitEnd); splitEnd^:= next^.start + activeLength - 1; split:= NewNode(next^.start, splitEnd); activeNode^.children[ord(text[activeEdge])]:= split; split^.children[ord(text[pos])]:= NewNode(pos, @leafEnd); next^.start:= next^.start + activeLength; split^.children[ord(text[next^.start])]:= next; if lastNewNode <> nil then lastNewNode^.suffixLink:= split; lastNewNode:= split; end; //end else Dec(remainingSuffixCount); if (activeNode = root) and (activeLength > 0) then begin Dec(activeLength); activeEdge:= pos - remainingSuffixCount + 1; end else if activeNode <> root then activeNode:= activeNode^.suffixLink; end; //end while end; function BuildSuffixTree(str: string): Node; var i: integer; begin Init(); text:= str + '$'; size:= Length(text); New(rootEnd); rootEnd^:= -1; root:= NewNode(-1, rootEnd); activeNode:= root; for i:= 1 to size do ExtendSuffixTree(i); //PrintSuffixTree(root); Result:= root; end; end.
{ Subroutine SST_R_PAS_SMENT_LABEL * * Process LABEL_STATEMENT syntax. } module sst_r_pas_SMENT_LABEL; define sst_r_pas_sment_label; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_sment_label; {process LABEL_STATEMENT syntax} var tag: sys_int_machine_t; {syntax tag from .syn file} str_h: syo_string_t; {handle to string for a tag} sym_p: sst_symbol_p_t; {scratch pointer to symbol table entry} stat: sys_err_t; label loop; begin syo_level_down; {down into LABEL_STATEMENT syntax} loop: {back here each new label in list} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_label_bad', nil, 0); case tag of 1: begin {tag is for name of new label} sst_symbol_new ( {add new symbol to current scope} str_h, syo_charcase_down_k, sym_p, stat); sym_p^.symtype := sst_symtype_label_k; {this symbol is a label} sym_p^.label_opc_p := nil; {label has not appeared yet in the code} end; syo_tag_end_k: begin {normal end of label statement} syo_level_up; {back up to parent syntax level} return; end; otherwise {illegal TAG value} syo_error_tag_unexp (tag, str_h); end; {end of TAG cases} goto loop; {back for next tag in this syntax} end;
unit Unit1; {$I TeeDefs.inc} interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMXTee.Engine, FMXTee.Procs, FMXTee.Chart, FMX.Layouts, FMXTee.Commander, FMX.Edit, FMXTee.Series, System.UIConsts, FMXTee.Tools, {$IFDEF D21PARALLEL} System.Threading, {$ENDIF} FMX.Controls.Presentation, FMX.ComboEdit, FMX.ComboTrackBar; type // Small class just to do an infinite loop: TUpdateThread=class(TThread) private IForm : TForm; public procedure Execute; override; end; TForm1 = class(TForm) TeeCommander1: TTeeCommander; Layout1: TLayout; Chart1: TChart; CheckBox3: TCheckBox; CheckBox4: TCheckBox; Timer1: TTimer; CBParallel: TCheckBox; TrackBar1: TComboTrackBar; Label1: TLabel; Label2: TLabel; ComboFlat1: TComboTrackBar; ChartTool1: TRepaintMonitor; Label3: TLabel; CheckBox1: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Chart1Resize(Sender: TObject); procedure Chart1AfterDraw(Sender: TObject); procedure Chart1Scroll(Sender: TObject); procedure Chart1UndoZoom(Sender: TObject); procedure Chart1Zoom(Sender: TObject); procedure CheckBox3Change(Sender: TObject); procedure CheckBox4Change(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure CBParallelChange(Sender: TObject); procedure TrackBar1Change(Sender: TObject); procedure ComboFlat1Change(Sender: TObject); procedure Label3Click(Sender: TObject); procedure CheckBox1Change(Sender: TObject); private { Private declarations } IThread : TUpdateThread; Started : Boolean; procedure AddSeries; procedure AppIdle(Sender: TObject; var Done:Boolean); procedure DoStuff; procedure RefreshTotal; procedure ReuseXValues(DoReuse:Boolean); procedure UpdateData; procedure UpdateSeries(Index:Integer); public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} // Number of data points per Series: var Num_Points:Integer=10000; // Create several series and add lots of random data: procedure TForm1.AddSeries; var t : Integer; tmp : TChartValue; tmpMin,tmpMax, tt : Integer; begin Chart1.FreeAllSeries; for t:=0 to Round(TrackBar1.Value)-1 do with Chart1.AddSeries(TFastLineSeries) as TFastLineSeries do begin // Much faster to draw "All" points using Polyline, than // drawing each point as a separate line segment: DrawStyle:=flAll; // Applies to "old" GDI canvas only, increases paint speed: FastPen:=True; // Initialize series X and Y values: XValues.Count:=Num_Points; // Optimization: // As we are creating all Series with the same XValues, we can simply // reuse the first series XValues array into all the other series: if t=0 then SetLength(XValues.Value,Num_Points) else XValues.Value:=Chart1[0].XValues.Value; YValues.Count:=Num_Points; SetLength(YValues.Value,Num_Points); // Add Num_Points random data to series arrays: tmp:=t*1000+Random(400); // Use a 1000 range: tmpMin:=t*1000; tmpMax:=(t+1)*1000; for tt:=0 to Num_Points-1 do begin // X value is simply the point index. // Here we optimize filling the array only for the first Series, // as all series share the same X values: if t=0 then XValues.Value[tt]:=tt; tmp:=tmp+Random(60)-29.5; // Check random data is inside the range we want (1000) if tmp>tmpMax then tmp:=tmpMax else if tmp<tmpMin then tmp:=tmpMin; // Set Y value: YValues.Value[tt]:=tmp; end; end; end; procedure TForm1.FormCreate(Sender: TObject); begin // (FastCalc Applies to 32bit only). // Use 32bit assembler to increase speed: Chart1.Axes.FastCalc:=True; Chart1.Legend.Hide; // Enable or disable multi-CPU usage (speeds up FastLine series with "dsAll" DrawStyle) CBParallelChange(Self); {$IFDEF D12} //ListBox1.Items.Add('Direct2D'); {$ENDIF} //ListBox1.ItemIndex:=0; ComboFlat1.Value:={$IFDEF ANDROID}1000{$ELSE}20000{$ENDIF}; TrackBar1.Value:=10; AddSeries; // Hide grid lines: Chart1.Axes.Bottom.Grid.Hide; Chart1.Axes.Left.Grid.Hide; Chart1.Axes.Bottom.Texts.Selected.Hover.Font.Color:=clWhite; Chart1.Axes.Left.Texts.Selected.Hover.Font.Color:=clWhite; (* // Disable OpenGL lighting to increase speed: TeeOpenGL1.Light0.Visible:=False; TeeOpenGL1.ShadeQuality:=False; TeeOpenGL1.AmbientLight:=0; // <-- 0 means Full Light (Ambient = from 0 to 100) *) // Do not paint bevels: Chart1.BevelOuter:=bvNone; //ListBox1Click(Self); // Cosmetic change colors and text font colors: Chart1.Color:=claBlack; // Chart1.Title.Font.Color:=RGBA(200,150,50,0); Chart1.Axes.Left.Texts.Font.Color:=clWhite; Chart1.Axes.Bottom.Texts.Font.Color:=clWhite; // FormQuality not possible to change at runtime: CheckBox1.Visible:=False; end; procedure TForm1.FormShow(Sender: TObject); begin Application.OnIdle:=AppIdle; end; procedure TForm1.Label3Click(Sender: TObject); begin TeeGotoURL(0,'http://www.steema.com'); end; procedure TForm1.AppIdle(Sender: TObject; var Done:Boolean); begin if not Started then begin CheckBox4Change(Self); Started:=True; end; end; type TChartAccess=class(TCustomAxisPanel); // Experimental: // Use all available CPU processors to calculate all Series data in parallel. procedure TForm1.CBParallelChange(Sender: TObject); begin if CBParallel.IsChecked then TChartAccess(Chart1).ParallelThreads:=TTeeCPU.NumberOfProcessors else TChartAccess(Chart1).ParallelThreads:=1; end; procedure TForm1.Chart1AfterDraw(Sender: TObject); begin // Speed optimization: // After chart is displayed, tell all Series to conservate and reuse their // X coordinates, to avoid recalculating them again: ReuseXValues(True); end; procedure TForm1.Chart1Resize(Sender: TObject); begin // When zooming or scrolling, or resizing the chart, force X coordinates // recalculation again: ReuseXValues(False); end; procedure TForm1.Chart1Scroll(Sender: TObject); begin Chart1Resize(Self); end; procedure TForm1.Chart1UndoZoom(Sender: TObject); begin Chart1Resize(Self); end; procedure TForm1.Chart1Zoom(Sender: TObject); begin Chart1Resize(Self); end; procedure TForm1.CheckBox1Change(Sender: TObject); begin if CheckBox1.IsChecked then Quality:=TCanvasQuality.HighQuality else Quality:=TCanvasQuality.HighPerformance; end; procedure TForm1.CheckBox3Change(Sender: TObject); var t : Integer; begin // When DrawAllPoints = False, it means repeated X position points will // not be painted. for t:=0 to Chart1.SeriesCount-1 do TFastLineSeries(Chart1[t]).DrawAllPoints:=CheckBox3.IsChecked; end; procedure TForm1.CheckBox4Change(Sender: TObject); begin // Switch between using a TTimer or a TThread to do the infinite loop: Timer1.Enabled:=not CheckBox4.IsChecked; if CheckBox4.IsChecked then begin IThread:=TUpdateThread.Create(True); IThread.FreeOnTerminate:=True; {$IFNDEF ANDROID} IThread.Priority:=tpNormal; {$ENDIF} IThread.IForm:=Self; {$IFDEF D9} IThread.Start; {$ELSE} IThread.Resume; {$ENDIF} end else if Assigned(IThread) then IThread.Terminate; end; procedure TForm1.ComboFlat1Change(Sender: TObject); begin Num_Points:=10000; //StrToInt(ComboFlat1.Text); RefreshTotal; AddSeries; end; // Modify all series, all points "Y" values: procedure TForm1.UpdateData; var t : Integer; begin if CBParallel.IsChecked then TTeeCPU.ParallelFor(0,Chart1.SeriesCount-1,UpdateSeries) else for t:=0 to Chart1.SeriesCount-1 do UpdateSeries(t); end; procedure TForm1.UpdateSeries(Index:Integer); const BufferSize=100; var tmpMin, tmpMax, t: Integer; tmp0 : Array[0..BufferSize-1] of TChartValue; val : TChartValue; tmp : TChartValues; begin with Chart1[Index] do begin tmp:=YValues.Value; // In "Buffer mode", move data points to simulate data scrolling //if CBMode.IsChecked then begin // Backup the first points: for t := 0 to BufferSize-1 do tmp0[t]:=tmp[t]; // Scroll data from right to left: for t := 0 to Num_Points-1-BufferSize do tmp[t]:=tmp[t+BufferSize]; // Restore the first points to the last: for t := 0 to BufferSize-1 do tmp[Num_Points-1-BufferSize+t]:=tmp0[t]; end (* else begin tmpMin:=Index*1000; tmpMax:=(Index+1)*1000; // Modify all values, increase them with a random quantity: for t:=0 to Num_Points-1 do begin val:=tmp[t]+Random(32)-15.5; if (val<tmpMax) and (val>tmpMin) then tmp[t]:=val; end; end *) end; end; procedure TForm1.RefreshTotal; begin // Text1.Text:= end; type TFastAccess=class(TFastLineSeries); // Speed optimization: // Enable or disable reusing the X coordinates, to avoid recalculating them. procedure TForm1.ReuseXValues(DoReuse:Boolean); var t : Integer; begin for t:=0 to Chart1.SeriesCount-1 do TFastAccess(Chart1[t]).ReuseXValues:=DoReuse; end; procedure TForm1.Timer1Timer(Sender: TObject); begin UpdateData; Chart1.Invalidate; end; procedure TForm1.TrackBar1Change(Sender: TObject); begin RefreshTotal; AddSeries; end; procedure TForm1.DoStuff; begin UpdateData; Chart1.Invalidate; Application.ProcessMessages; end; { TUpdateThread } // Simple infinite loop procedure TUpdateThread.Execute; begin inherited; while not Terminated do begin Synchronize(TForm1(IForm).DoStuff); end; end; end.
unit View.PesquisaEntregadoresExpressas; 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, dxSkinsDefaultPainters, cxContainer, cxEdit, dxLayoutcxEditAdapters, dxLayoutContainer, cxLabel, cxClasses, dxLayoutControl, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, dxLayoutControlAdapters, Vcl.Menus, System.Actions, Vcl.ActnList, Vcl.StdCtrls, cxButtons, Vcl.Buttons, cxCheckBox, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxTextEdit, cxMaskEdit, cxButtonEdit, dxBar; type Tview_PesquisaEntregadoresExpressas = class(TForm) layoutControlGridGroup_Root: TdxLayoutGroup; layoutControlGrid: TdxLayoutControl; gridPesquisaDBTableView1: TcxGridDBTableView; gridPesquisaLevel1: TcxGridLevel; gridPesquisa: TcxGrid; layoutItemGrid: TdxLayoutItem; actionListPesquisa: TActionList; actionExpandirGrid: TAction; actionRetrairGrid: TAction; fdPesquisa: TFDQuery; fdPesquisaid_entregador: TFDAutoIncField; fdPesquisacod_agente: TIntegerField; fdPesquisanom_base: TStringField; fdPesquisacod_entregador: TIntegerField; fdPesquisanom_entregador: TStringField; fdPesquisades_chave: TStringField; fdPesquisacod_cadastro: TIntegerField; fdPesquisanom_cadastro: TStringField; dsPesquisa: TDataSource; gridPesquisaDBTableView1id_entregador: TcxGridDBColumn; gridPesquisaDBTableView1cod_agente: TcxGridDBColumn; gridPesquisaDBTableView1nom_base: TcxGridDBColumn; gridPesquisaDBTableView1cod_entregador: TcxGridDBColumn; gridPesquisaDBTableView1nom_entregador: TcxGridDBColumn; gridPesquisaDBTableView1des_chave: TcxGridDBColumn; gridPesquisaDBTableView1cod_cadastro: TcxGridDBColumn; gridPesquisaDBTableView1nom_cadastro: TcxGridDBColumn; buttonEditTextoPesquisar: TcxButtonEdit; layoutItemtextoPesquisa: TdxLayoutItem; actionPesquisar: TAction; actionLimpar: TAction; actionExportar: TAction; actionFechar: TAction; buttonFechar: TcxButton; layoutItemFechar: TdxLayoutItem; buttonOK: TcxButton; layoutItemOK: TdxLayoutItem; dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup; actionOK: TAction; buttonLocalizar: TcxButton; layoutItemLocalizar: TdxLayoutItem; popupMenu: TPopupMenu; Exportar1: TMenuItem; Expandir1: TMenuItem; Retrair1: TMenuItem; actionPainelGrupo: TAction; Painel1: TMenuItem; procedure FormShow(Sender: TObject); procedure actionRetrairGridExecute(Sender: TObject); procedure buttonEditTextoPesquisarPropertiesChange(Sender: TObject); procedure actionLimparExecute(Sender: TObject); procedure actionPesquisarExecute(Sender: TObject); procedure fdPesquisaAfterClose(DataSet: TDataSet); procedure actionFecharExecute(Sender: TObject); procedure dsPesquisaStateChange(Sender: TObject); procedure actionOKExecute(Sender: TObject); procedure gridPesquisaEnter(Sender: TObject); procedure gridPesquisaDBTableView1DblClick(Sender: TObject); procedure buttonEditTextoPesquisarEnter(Sender: TObject); procedure gridPesquisaDBTableView1CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure gridPesquisaDBTableView1NavigatorButtonsButtonClick(Sender: TObject; AButtonIndex: Integer; var ADone: Boolean); procedure actionExpandirGridExecute(Sender: TObject); procedure actionPainelGrupoExecute(Sender: TObject); private { Private declarations } procedure StartForm; procedure SetGroup(bFlag: Boolean); procedure PesquisaEntregador(sFiltro: String); procedure ExportData; function FormulaFilro(sTexto: String): String; public { Public declarations } iID: Integer; end; var view_PesquisaEntregadoresExpressas: Tview_PesquisaEntregadoresExpressas; implementation {$R *.dfm} uses Data.SisGeF, Common.Utils; { Tview_PesquisaEntregadoresExpressas } procedure Tview_PesquisaEntregadoresExpressas.actionExpandirGridExecute(Sender: TObject); begin gridPesquisaDBTableView1.ViewData.Expand(True); end; procedure Tview_PesquisaEntregadoresExpressas.actionFecharExecute(Sender: TObject); begin iID := 0; fdpesquisa.Filtered := False; ModalResult := mrCancel; end; procedure Tview_PesquisaEntregadoresExpressas.actionLimparExecute(Sender: TObject); begin buttonEditTextoPesquisar.Clear; end; procedure Tview_PesquisaEntregadoresExpressas.actionOKExecute(Sender: TObject); begin iId := fdPesquisaid_entregador.AsInteger; fdpesquisa.Filtered := False; ModalResult := mrOk; end; procedure Tview_PesquisaEntregadoresExpressas.actionPainelGrupoExecute(Sender: TObject); begin SetGroup(gridPesquisaDBTableView1.OptionsView.GroupByBox); end; procedure Tview_PesquisaEntregadoresExpressas.actionPesquisarExecute(Sender: TObject); begin PesquisaEntregador(FormulaFilro(buttonEditTextoPesquisar.Text)); end; procedure Tview_PesquisaEntregadoresExpressas.actionRetrairGridExecute(Sender: TObject); begin gridPesquisaDBTableView1.ViewData.Collapse(True); end; procedure Tview_PesquisaEntregadoresExpressas.buttonEditTextoPesquisarEnter(Sender: TObject); begin buttonOK.Default := False; end; procedure Tview_PesquisaEntregadoresExpressas.buttonEditTextoPesquisarPropertiesChange(Sender: TObject); begin if buttonEditTextoPesquisar.Text = '' then begin actionLimpar.Enabled := False; buttonLocalizar.Enabled := False; end else begin actionLimpar.Enabled := True; buttonLocalizar.Enabled := True; end; end; procedure Tview_PesquisaEntregadoresExpressas.dsPesquisaStateChange(Sender: TObject); begin if TDataSource(Sender).DataSet.State = dsbrowse then //Se tiver em mode de edicao ou isercao begin actionOK.Enabled := True; actionExportar.Enabled := True; end else actionOK.Enabled := False; actionExportar.Enabled := False; begin end; end; procedure Tview_PesquisaEntregadoresExpressas.ExportData; var fnUtil : Common.Utils.TUtils; sMensagem: String; begin try fnUtil := Common.Utils.TUtils.Create; if Data_Sisgef.mtbRoteirosExpressas.IsEmpty then Exit; if Data_Sisgef.SaveDialog.Execute() then begin if FileExists(Data_Sisgef.SaveDialog.FileName) then begin sMensagem := 'Arquivo ' + Data_Sisgef.SaveDialog.FileName + ' já existe! Sobrepor ?'; if Application.MessageBox(PChar(sMensagem), 'Sobrepor', MB_YESNO + MB_ICONQUESTION) = IDNO then Exit end; fnUtil.ExportarDados(gridPesquisa,Data_Sisgef.SaveDialog.FileName); end; finally fnUtil.Free; end; end; procedure Tview_PesquisaEntregadoresExpressas.fdPesquisaAfterClose(DataSet: TDataSet); begin Data_Sisgef.FDConnectionMySQL.Close; end; procedure Tview_PesquisaEntregadoresExpressas.FormShow(Sender: TObject); begin StartForm; end; function Tview_PesquisaEntregadoresExpressas.FormulaFilro(sTexto: String): String; var sMensagem: String; sFiltro: String; fFuncoes : Common.Utils.TUtils; begin Result := ''; sFiltro := ''; fFuncoes := Common.Utils.TUtils.Create; if sTexto = '' then begin sMensagem := 'O campo de texto a pesquisar não foi preenchido!. ' + 'Caso deseje visualizar todos os entregadores clique OK, porém, esse processo pode ser lento.'; if Application.MessageBox(PChar(sMensagem), 'Aten��o!', MB_OKCANCEL + MB_ICONWARNING) = IDCANCEL then begin sFiltro := 'NONE'; end; end else begin sFiltro := 'nom_base like ' + QuotedStr('%' + sTexto + '%') + ' or nom_entregador like ' + QuotedStr('%' + sTexto + '%') + ' ' + 'or des_chave like ' + QuotedStr('%' + sTexto + '%') + ' or nom_cadastro like ' + QuotedStr('%' + sTexto + '%'); if fFuncoes.ENumero(sTexto) then begin if sTexto <> '' then begin sFiltro := sFiltro + ' or '; end; sFiltro := sFiltro + 'id_entregador like ' + sTexto + ' or cod_agente like ' + sTexto + ' or cod_entregador like ' + sTexto + ' or cod_cadastro like ' + sTexto; end; end; fFuncoes.Free; Result := sFiltro; end; procedure Tview_PesquisaEntregadoresExpressas.gridPesquisaDBTableView1CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin actionOKExecute(Sender); end; procedure Tview_PesquisaEntregadoresExpressas.gridPesquisaDBTableView1DblClick(Sender: TObject); begin actionOKExecute(Sender); end; procedure Tview_PesquisaEntregadoresExpressas.gridPesquisaDBTableView1NavigatorButtonsButtonClick(Sender: TObject; AButtonIndex: Integer; var ADone: Boolean); begin case AButtonIndex of 16 : ExportData; 17 : gridPesquisaDBTableView1.ViewData.Expand(True); 18 : gridPesquisaDBTableView1.ViewData.Collapse(True); 19 : SetGroup(gridPesquisaDBTableView1.OptionsView.GroupByBox); end; end; procedure Tview_PesquisaEntregadoresExpressas.gridPesquisaEnter(Sender: TObject); begin if fdPesquisa.IsEmpty then begin buttonOK.Default := False; end else begin buttonOK.Default := True; end; end; procedure Tview_PesquisaEntregadoresExpressas.PesquisaEntregador(sFiltro: String); begin if sFiltro = 'NONE' then begin Exit; end; if not sFiltro.IsEmpty then begin fdpesquisa.Filtered := False; fdpesquisa.Filter := sFiltro; fdpesquisa.Filtered := True; end; fdPesquisa.Open(); if not fdPesquisa.IsEmpty then begin gridPesquisa.SetFocus; end; end; procedure Tview_PesquisaEntregadoresExpressas.SetGroup(bFlag: Boolean); begin gridPesquisaDBTableView1.OptionsView.GroupByBox := (not bFlag); gridPesquisaDBTableView1.OptionsCustomize.ColumnGrouping := (not bFlag); end; procedure Tview_PesquisaEntregadoresExpressas.StartForm; begin iID := 0; end; end.
unit TabbedContainerRes; interface uses SysUtils, Classes, ImgList, vtPngImgList, nsTabbedInterfaceTypes; type TTabbedContainerRes = class(TDataModule) ilTabImages: TvtNonFixedPngImageList; private function pm_GetIconIndex(aIconType: TnsTabIconType): Integer; public property IconIndex[IconType: TnsTabIconType]: Integer read pm_GetIconIndex; end; function nsTabbedContainerRes: TTabbedContainerRes; implementation {$R *.dfm} uses Forms, vtPngImgListUtils; const cTabIconMainIndex = 0; (* - главная иконка приложения *) cTabIconListIndex = 1; (* - список *) cTabIconDocumentNormalIndex = 2; (* - документ *) cTabIconDocumentPreactiveIndex = 3; (* - не вступившая в силу редакция документа *) cTabIconDocumentAbolishedIndex = 4; (* - утратившая силу редакция документа *) cTabIconDocumentNewRedactionIndex = 5; (* - редакция документа *) cTabIconAACIndex = 6; (* - ААК *) cTabIconDrugIndex = 7; (* - лекарственное средство *) cTabIconDrugSpecialIndex = 8; cTabIconDrugAnnuledIndex = 9; (* - ануллированные лекарственные срдества *) cTabIconMedicFirmIndex = 10; (* - медицинские фирмы *) cTabIconMedicDictionaryIndex = 11; (* - словарь инфарм *) cTabIconDictionaryIndex = 12; (* - толковый словарь *) cTabIconAttributeSearchIndex = 13; (* - поиск по реквизитам *) cTabIconSituationSearchIndex = 14; (* - поиск по ситуации *) cTabIconPublishSourceSearchIndex = 15; (* - поиск по источнику опубликования *) cTabIconLegislationReviewSearchIndex = 16; (* - обзор изменений законодательства Прайм *) cTabIconDrugSearchIndex = 17; (* - поиск лекарственного средства *) cTabIconCompareEditionsIndex = 18; (* - сравнение редакций *) cTabIconChangesBetweenEditionsIndex = 19; (* - обзор измений документа *) cTabIconPrimeIndex = 20; (* - документ ленты Прайм *) cTabIconIpharmMainMenuIndex = 21; (* - основное меню Инфарма *) cTabIconConsultationIndex = 24; (* - консультация *) cTabIconComplectInfoIndex = 23; (* - информация о комплекте *) cTabIconLawSupportOnlineIndex = 24; (* - правовая поддержка онлайн *) cTabIconRubricatorIndex = 25; (* - рубрикатор *) cTabIconBaseSearchIndex = 26; (* - базовый поиск *) cTabIconPrintPreviewIndex = 27; (* - Предварительный просмотр *) cTabIconNewsOnlineIndex = 28; (* - Новости онлайн *) cIconTypesArr: array[TnsTabIconType] of Integer = ( cTabIconMainIndex, // titMain cTabIconListIndex, // titList cTabIconDocumentNormalIndex, // titDocumentNormal cTabIconDocumentPreactiveIndex, // titDocumentPreactive cTabIconDocumentAbolishedIndex, // titDocumentAbolished cTabIconDocumentNewRedactionIndex, // titDocumentNewRedaction cTabIconAACIndex, // titAAC cTabIconDrugIndex, // titDrug cTabIconDrugSpecialIndex, // titDrugSpecial cTabIconDrugAnnuledIndex, // titDrugAnnuled cTabIconMedicFirmIndex, // titMedicFirm cTabIconMedicDictionaryIndex, // titMedicDictionary cTabIconDictionaryIndex, // titDictionary cTabIconAttributeSearchIndex, // titAttributeSearch cTabIconPublishSourceSearchIndex, // titPublishSourceSearch cTabIconLegislationReviewSearchIndex, // titLegislationReviewSearch cTabIconDrugSearchIndex, // titDrugSearch cTabIconCompareEditionsIndex, // titCompareEditions cTabIconChangesBetweenEditionsIndex, // titChangesBetweenEditions cTabIconSituationSearchIndex, // titSituationSearch cTabIconPrimeIndex, // titPrime cTabIconIpharmMainMenuIndex, // titInpharmMainMenu cTabIconConsultationIndex, // titConsultation cTabIconComplectInfoIndex, // titComplectInfo cTabIconLawSupportOnlineIndex, // titLawSupportOnline cTabIconRubricatorIndex, // titRubricator cTabIconBaseSearchIndex, // titBaseSearch cTabIconPrintPreviewIndex, // titPrintPreview cTabIconNewsOnlineIndex // titNewsOnline );//cIconTypesArr var g_nsTabbedContainerRes: TTabbedContainerRes; function nsTabbedContainerRes: TTabbedContainerRes; begin if (g_nsTabbedContainerRes = nil) then Application.CreateForm(TTabbedContainerRes, g_nsTabbedContainerRes); Result := g_nsTabbedContainerRes; end; { TTabbedContainerRes } function TTabbedContainerRes.pm_GetIconIndex( aIconType: TnsTabIconType): Integer; begin Result := cIconTypesArr[aIconType]; end; initialization AddImageListCreator(@nsTabbedContainerRes); end.
program concesionaria; type vehiculo = record marca :string; modelo :string; precio :real; end; actuales = record marca :string; acumulador :real; contador :integer; end; procedure leerVehiculo(var v:vehiculo); begin write('Ingrese la marca del vehiculo: '); readln(v.marca); write('Ingrese el modelo del vehiculo: '); readln(v.modelo); write('Ingrese el precio del vehiculo: '); readln(v.precio); end; procedure procesarVehiculo(var m:actuales; precio :real); procedure acumular(var a:real; c :real); begin a := a + c; end; procedure incrementar(var c :integer); begin c := c + 1; end; begin acumular(m.acumulador, precio); incrementar(m.contador); end; procedure imprimirPromedio(m:actuales); var promedio: real; begin promedio := m.acumulador / m.contador; writeln('El costo medio para la marca ', m.marca ,' es: ', promedio:8:2); end; procedure reiniciarMarca(var m:actuales; marca:string); begin m.acumulador := 0; m.contador := 0; m.marca := marca; end; procedure comprobarMaximo(var maximo:vehiculo; v :vehiculo); procedure actualizar(var m:vehiculo; v:vehiculo); begin m.marca := v.marca; m.modelo := v.modelo; m.precio := v.precio; end; begin if (v.precio >= maximo.precio) then actualizar(maximo, v); end; var marcaActual :actuales; vehiculoActual, maximo :vehiculo; begin leerVehiculo(vehiculoActual); reiniciarMarca(marcaActual, vehiculoActual.marca); while(marcaActual.marca <> 'ZZZ') do begin comprobarMaximo(maximo, vehiculoActual); if (vehiculoActual.marca = marcaActual.marca) then procesarVehiculo(marcaActual, vehiculoActual.precio) else begin imprimirPromedio(marcaActual); reiniciarMarca(marcaActual, vehiculoActual.marca); procesarVehiculo(marcaActual, vehiculoActual.precio); end; leerVehiculo(vehiculoActual); end; writeln('La marca y modelo del auto más caro son: ', maximo.marca, ' y ', maximo.modelo); end.
unit WinHelper; interface uses System.Generics.Collections, System.SysUtils, WinApi.TlHelp32, WinApi.Windows; type TProcessRec = record PID: DWORD; Name: string; constructor Create(PID: DWORD; const Name: string); end; TProcessRecList = TList<TProcessRec>; TModuleRec = TModuleEntry32; TModuleRecList = TList<TModuleRec>; // return True to continue enumeration or False to stop it. TEnumProcessesCallback = reference to function(const pe: TProcessEntry32): boolean; TEnumModulesCallback = reference to function(const me: TModuleEntry32): boolean; // Enumerate processes with callback. Result is False if there was error. function EnumProcesses(cb: TEnumProcessesCallback): boolean; // Enumerate processes to list. Result is False if there was error. function EnumProcessesToList(List: TProcessRecList): boolean; type // Used to compare strings. TStringMatchKind = ( MATCH_STRING_WHOLE, // string equals to X MATCH_STRING_START, // string starts with X MATCH_STRING_END, // string ends with X MATCH_STRING_PART // string contains X ); function FindPIDByProcessName( const Name: string; out PID: DWORD; Match: TStringMatchKind = MATCH_STRING_WHOLE): boolean; // Enumerate modules with callback. Result is False if there was error. function EnumModules(PID: DWORD; cb: TEnumModulesCallback): boolean; // Enumerate modules to list. Result is False if there was error. function EnumModulesToList(PID: DWORD; List: TModuleRecList): boolean; type // Used in FindModule to test if this is the module we search. // Return True on match. TFindModuleChecker = reference to function(const me: TModuleEntry32): boolean; // Find module by custom condition. function FindModule(PID: DWORD; out value: TModuleEntry32; Checker: TFindModuleChecker): boolean; // Find module by address that belongs to this module. function FindModuleByAddress(PID: DWORD; Addr: NativeUInt; out me: TModuleEntry32): boolean; // Find module by module name. function FindModuleByName(PID: DWORD; const Name: string): boolean; // Find main process module (exe). function FindMainModule(PID: DWORD; out me: TModuleEntry32): boolean; function SetPrivilegeByName(const Name: string; State: boolean): boolean; function SetDebugPrivilege(State: boolean): boolean; implementation function EnumProcesses(cb: TEnumProcessesCallback): boolean; var hShot, hShotMod: THandle; pe: TProcessEntry32; begin // Create process snapshot. hShot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if hShot = INVALID_HANDLE_VALUE then exit(false); // Traverse it. try ZeroMemory(@pe, SizeOf(pe)); pe.dwSize := SizeOf(pe); if not Process32First(hShot, pe) then exit(false); repeat // Add process only if we can query its module list. hShotMod := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pe.th32ProcessID); if hShotMod <> INVALID_HANDLE_VALUE then begin CloseHandle(hShotMod); if not cb(pe) then break; end; until not Process32Next(hShot, pe); exit(True); finally CloseHandle(hShot); end; end; function EnumProcessesToList(List: TProcessRecList): boolean; begin List.Clear; result := EnumProcesses( function(const pe: TProcessEntry32): boolean begin List.Add(TProcessRec.Create(pe.th32ProcessID, pe.szExeFile)); result := True; end); end; function CompareStringsWithMachKind(const s1, s2: string; kind: TStringMatchKind): boolean; begin case kind of MATCH_STRING_WHOLE: result := s1.Equals(s2); MATCH_STRING_START: result := s1.StartsWith(s2); MATCH_STRING_END: result := s1.EndsWith(s2); MATCH_STRING_PART: result := s1.Contains(s2); else result := false; end; end; function FindPIDByProcessName(const Name: string; out PID: DWORD; Match: TStringMatchKind): boolean; var tmpName: string; foundPID: DWORD; begin tmpName := Name.ToUpper; foundPID := 0; EnumProcesses( function(const pe: TProcessEntry32): boolean begin if CompareStringsWithMachKind(string(pe.szExeFile).ToUpper, tmpName, Match) then begin foundPID := pe.th32ProcessID; exit(false); // don't continue search, already found end; exit(True); // continue search end); PID := foundPID; result := foundPID <> 0; end; function EnumModules(PID: DWORD; cb: TEnumModulesCallback): boolean; var hShot: THandle; me: TModuleEntry32; begin hShot := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PID); if hShot = INVALID_HANDLE_VALUE then exit(false); try ZeroMemory(@me, SizeOf(me)); me.dwSize := SizeOf(me); if not Module32First(hShot, me) then exit(false); repeat if not cb(me) then break; until not Module32Next(hShot, me); exit(True); finally CloseHandle(hShot); end; end; function EnumModulesToList(PID: DWORD; List: TModuleRecList): boolean; begin List.Clear; result := EnumModules(PID, function(const me: TModuleEntry32): boolean begin List.Add(me); exit(True); end); end; function FindModule(PID: DWORD; out value: TModuleEntry32; Checker: TFindModuleChecker): boolean; var found: boolean; tmp: TModuleEntry32; begin found := false; EnumModules(PID, function(const me: TModuleEntry32): boolean begin if Checker(me) then begin tmp := me; found := True; exit(false); end; exit(True); end); if found then value := tmp else fillchar(value, SizeOf(value), 0); exit(found); end; function FindModuleByAddress(PID: DWORD; Addr: NativeUInt; out me: TModuleEntry32): boolean; begin result := FindModule(PID, me, function(const me: TModuleEntry32): boolean begin result := (Addr >= NativeUInt(me.modBaseAddr)) and (Addr < NativeUInt(me.modBaseAddr + me.modBaseSize)); end); end; function FindModuleByName(PID: DWORD; const Name: string): boolean; var tmpName: string; me: TModuleEntry32; begin tmpName := name.ToUpper; result := FindModule(PID, me, function(const me: TModuleEntry32): boolean begin result := string(me.szModule).ToUpper.Equals(tmpName); end); end; function FindMainModule(PID: DWORD; out me: TModuleEntry32): boolean; begin result := FindModule(PID, me, function(const me: TModuleEntry32): boolean begin result := True; // first module is main one end); end; // http://msdn.microsoft.com/en-us/library/windows/desktop/aa446619(v=vs.85).aspx function SetPrivilege( hToken: THandle; // access token handle lpszPrivilege: LPCTSTR; // name of privilege to enable/disable bEnablePrivilege: BOOL // to enable or disable privilege ): boolean; var tp: TOKEN_PRIVILEGES; luid: int64; Status: DWORD; ReturnLength: DWORD; begin if LookupPrivilegeValue( nil, // lookup privilege on local system lpszPrivilege, // privilege to lookup luid) // receives LUID of privilege then begin tp.PrivilegeCount := 1; tp.Privileges[0].luid := luid; if bEnablePrivilege then tp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED else tp.Privileges[0].Attributes := 0; // Enable the privilege or disable all privileges. if AdjustTokenPrivileges(hToken, false, tp, SizeOf(TOKEN_PRIVILEGES), nil, ReturnLength) then begin Status := GetLastError(); if Status = ERROR_SUCCESS then exit(True); end; end; exit(false); end; function SetPrivilegeByName(const Name: string; State: boolean): boolean; var hToken: THandle; begin if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY or TOKEN_ADJUST_PRIVILEGES, hToken) then exit(false); result := SetPrivilege(hToken, LPCTSTR(Name), State); CloseHandle(hToken); end; function SetDebugPrivilege(State: boolean): boolean; begin result := SetPrivilegeByName('SeDebugPrivilege', State); end; { TProcessRec } constructor TProcessRec.Create(PID: DWORD; const Name: string); begin self.PID := PID; self.Name := Name; end; end.
unit HGM.Common.Notify; interface uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.Buttons, System.SysUtils, HGM.Common; type TNotifyControl = class(TWinControl) property Color; end; TNotify = class(TComponent) public type TLastRecord = record Empty:Boolean; Caption:string; Text:string; Image:string; Color:TColor; end; private FBottom:Integer; FButtonClose:TSpeedButton; FColor: TColor; FLabelCaption:TLabel; FLabelText:TLabel; FLastNotify:TLastRecord; FOldSize:TSize; FOwner:TForm; FPanel:TWinControl; FPanelClient:TPanel; FPanelLeft:TPanel; FPanelTop:TPanel; FRight:Integer; FTime:Cardinal; FTimerHide:TTimer; FVisible:Boolean; procedure SetOwner(const Value: TForm); virtual; function GetFontCaption: TFont; virtual; function GetFontText: TFont; virtual; procedure AnimateWait; virtual; procedure BeforeShow; virtual; procedure OnClickClose(Sender:TObject); virtual; procedure OnClickText(Sender:TObject); virtual; procedure SetColor(const Value: TColor); virtual; procedure SetFontCaption(const Value: TFont); virtual; procedure SetFontText(const Value: TFont); virtual; procedure SetPanel(const Value: TWinControl); virtual; procedure SetRight(const Value: Integer); virtual; procedure SetTime(const Value: Cardinal); virtual; procedure OnTimerHide(Sender:TObject); virtual; procedure ShowNotify; virtual; abstract; procedure UpdatePanel; virtual; abstract; public property PanelLeft:TPanel read FPanelLeft; property PanelClient:TPanel read FPanelClient; property Panel:TWinControl read FPanel write SetPanel; property LabelCaption:TLabel read FLabelCaption; property LabelText:TLabel read FLabelText; property LastNotify:TLastRecord read FLastNotify; procedure Close; virtual; procedure HideLastNotify; virtual; procedure HideNotify; virtual; abstract; procedure ShowLastNotify; virtual; procedure ShowTextMessage; virtual; procedure Update; virtual; procedure UpdateGlobalSize; virtual; procedure Error(Caption, Text:string); virtual; procedure Info(Caption, Text:string); virtual; procedure Ok(Caption, Text: string); virtual; procedure Warning(Caption, Text:string); virtual; constructor Create(AOwner: TComponent); override; published property Bottom:Integer read FBottom write FBottom default 20; property Color:TColor read FColor write SetColor default clGray; property FontCaption:TFont read GetFontCaption write SetFontCaption; property FontText:TFont read GetFontText write SetFontText; property OwnerForm:TForm read FOwner write SetOwner; property Right:Integer read FRight write SetRight default 20; property Time:Cardinal read FTime write SetTime default 5; end; TNotifyWindow = class(TNotify) private procedure UpdatePanel; override; procedure SetOwner(const Value: TForm); override; public procedure HideNotify; override; procedure ShowNotify; override; constructor Create(AOwner: TComponent); override; end; TNotifyPanel = class(TNotify) private procedure UpdatePanel; override; public procedure HideNotify; override; procedure ShowNotify; override; constructor Create(AOwner: TComponent); override; end; procedure Register; implementation procedure Register; begin RegisterComponents(PackageName, [TNotifyWindow, TNotifyPanel]); end; { TNotify } constructor TNotify.Create(AOwner: TComponent); begin inherited; FVisible:=False; FRight:=20; FBottom:=20; HideLastNotify; SetPanel(FPanel); Color:=clGray; FPanelLeft:=TPanel.Create(FPanel); with FPanelLeft do begin Parent:=FPanel; Align:=alLeft; BevelOuter:=bvNone; ParentBackground:=False; ParentColor:=False; Color:=clMaroon; Caption:='!'; Font.Size:=45; Width:=FPanel.Height; end; FPanelClient:=TPanel.Create(FPanel); with FPanelClient do begin Parent:=FPanel; Align:=alClient; BevelOuter:=bvNone; ParentBackground:=False; ParentColor:=True; //Color:=FColor; Caption:=''; end; FPanelTop:=TPanel.Create(FPanelClient); with FPanelTop do begin Parent:=FPanelClient; Height:=25; Align:=alTop; BevelOuter:=bvNone; ParentBackground:=True; ParentColor:=True; Caption:=''; end; FLabelCaption:=TLabel.Create(FPanelTop); with FLabelCaption do begin Parent:=FPanelTop; AlignWithMargins:=True; Align:=alClient; WordWrap:=False; OnClick:=OnClickText; Cursor:=crHandPoint; Font.Size:=12; Caption:=''; end; FButtonClose:=TSpeedButton.Create(FPanelTop); with FButtonClose do begin Parent:=FPanelTop; Height:=25; Width:=25; Align:=alRight; Caption:='×'; Font.Color:=clWhite; Font.Size:=14; Font.Style:=[fsBold]; Flat:=True; OnClick:=OnClickClose; end; FLabelText:=TLabel.Create(FPanelClient); with FLabelText do begin Parent:=FPanelClient; AlignWithMargins:=True; Align:=alClient; Margins.Bottom:=10; Margins.Right:=10; Margins.Left:=10; Margins.Top:=3; Font.Size:=9; OnClick:=OnClickText; Cursor:=crHandPoint; Caption:=''; WordWrap:=TRue; end; FTimerHide:=TTimer.Create(nil); FTimerHide.Enabled:=False; FTimerHide.OnTimer:=OnTimerHide; //default Time:=5; end; procedure TNotify.AnimateWait; begin Application.ProcessMessages; Sleep(5); end; procedure TNotify.BeforeShow; begin if FVisible then HideNotify; end; procedure TNotify.Close; begin if FVisible then HideNotify; end; procedure TNotify.HideLastNotify; begin FLastNotify.Empty:=True; end; procedure TNotify.ShowLastNotify; begin if FLastNotify.Empty then Exit; ShowNotify; end; procedure TNotify.ShowTextMessage; begin MessageBox(Application.Handle, PWideChar(FLastNotify.Text), PWideChar(FLastNotify.Caption), MB_ICONQUESTION or MB_OK); end; procedure TNotify.Update; begin if FVisible then ShowNotify; end; procedure TNotify.UpdateGlobalSize; begin FPanel.Left:=FPanel.Left+(FOwner.ClientWidth - FOldSize.Width); FPanel.Top:=FPanel.Top+(FOwner.ClientHeight - FOldSize.Height); FOldSize.Width:=FOwner.ClientWidth; FOldSize.Height:=FOwner.ClientHeight; end; procedure TNotify.Ok(Caption, Text: string); begin BeforeShow; FLastNotify.Empty:=False; FLastNotify.Caption:=Caption; FLastNotify.Text:=Text; FLastNotify.Image:='i'; FLastNotify.Color:=$0000E686; ShowNotify; end; procedure TNotify.OnClickClose(Sender: TObject); begin Close; end; procedure TNotify.OnClickText(Sender: TObject); begin ShowTextMessage; end; procedure TNotify.OnTimerHide(Sender: TObject); begin if TNotifyControl(Panel).MouseInClient or PtInRect(Panel.ClientRect, Panel.ScreenToClient(Mouse.CursorPos)) then Exit; HideNotify; end; procedure TNotify.Error(Caption, Text: string); begin BeforeShow; FLastNotify.Empty:=False; FLastNotify.Caption:=Caption; FLastNotify.Text:=Text; FLastNotify.Image:='!'; FLastNotify.Color:=clMaroon; ShowNotify; end; function TNotify.GetFontCaption: TFont; begin Result:=FLabelCaption.Font; end; function TNotify.GetFontText: TFont; begin Result:=FLabelText.Font; end; procedure TNotify.Info(Caption, Text: string); begin BeforeShow; FLastNotify.Empty:=False; FLastNotify.Caption:=Caption; FLastNotify.Text:=Text; FLastNotify.Image:='i'; FLastNotify.Color:=$00FFCC66; ShowNotify; end; procedure TNotify.Warning(Caption, Text: string); begin BeforeShow; FLastNotify.Empty:=False; FLastNotify.Caption:=Caption; FLastNotify.Text:=Text; FLastNotify.Image:='!'; FLastNotify.Color:=$000066FF; ShowNotify; end; procedure TNotify.SetColor(const Value: TColor); begin FColor:=Value; TNotifyControl(FPanel).Color:=FColor; end; procedure TNotify.SetFontCaption(const Value: TFont); begin FLabelCaption.Font:=Value; FButtonClose.Font.Color:=Value.Color; end; procedure TNotify.SetFontText(const Value: TFont); begin FLabelText.Font:=Value; end; procedure TNotify.SetOwner(const Value: TForm); begin FOwner:=Value; FPanel.Parent:=FOwner; UpdatePanel; end; procedure TNotify.SetPanel(const Value: TWinControl); begin FPanel:=Value; UpdatePanel; end; procedure TNotify.SetRight(const Value: Integer); begin FRight:=Value; end; procedure TNotify.SetTime(const Value: Cardinal); begin FTime:=Value; FTimerHide.Interval:=FTime * 1000; end; { TNotifyWindow } constructor TNotifyWindow.Create(AOwner: TComponent); begin FPanel:=TForm.Create(nil); with TForm(FPanel) do begin FormStyle:=fsStayOnTop; Visible:=False; Caption:='Notify'; DoubleBuffered:=True; BorderStyle:=bsNone; end; inherited; end; procedure TNotifyWindow.HideNotify; var Incr:Integer; begin FTimerHide.Enabled:=False; Incr:=2; while TForm(Panel).Top < Screen.Height do begin Incr:=Incr+2; TForm(Panel).Top:=TForm(Panel).Top + Incr; AnimateWait; end; TForm(Panel).Top:=Screen.Height; TForm(Panel).Visible:=False; FVisible:=False; end; procedure TNotifyWindow.SetOwner(const Value: TForm); begin FOwner:=Value; FOldSize.Height:=FOwner.ClientHeight; FOldSize.Width:=FOwner.ClientWidth; UpdatePanel; end; procedure TNotifyWindow.ShowNotify; var incr, ToPos:Integer; begin FLabelCaption.Caption:=FLastNotify.Caption; FLabelText.Caption:=FLastNotify.Text; FPanelLeft.Color:=FLastNotify.Color; FVisible:=True; FTimerHide.Enabled:=False; TForm(Panel).Visible:=True; TForm(Panel).BringToFront; Incr:=2; TForm(Panel).Left:=Screen.Width - TForm(Panel).Width - FRight; ToPos:=Screen.Height - TForm(Panel).Height - FBottom; while TForm(Panel).Top > ToPos do begin Incr:=Incr+2; TForm(Panel).Top:=TForm(Panel).Top - Incr; AnimateWait; end; TForm(Panel).Top:=ToPos; FTimerHide.Enabled:=True; end; procedure TNotifyWindow.UpdatePanel; begin FPanel.Visible:=False; FPanel.Width:=350; FPanel.Height:=93; TNotifyControl(FPanel).Color:=FColor; FPanel.Left:=Screen.Width - FPanel.Width - FRight; FPanel.Top:=Screen.Height; end; { TNotifyPanel } constructor TNotifyPanel.Create(AOwner: TComponent); begin FPanel:=TPanel.Create(nil); with TPanel(FPanel) do begin Visible:=False; Caption:=''; DoubleBuffered:=True; BorderStyle:=bsNone; BevelInner:=bvNone; BevelKind:=bkNone; BevelOuter:=bvNone; Left:=0; Top:=0; end; if AOwner is TForm then OwnerForm:=TForm(AOwner); inherited Create(AOwner); end; procedure TNotifyPanel.HideNotify; var Incr:Integer; begin FTimerHide.Enabled:=False; Incr:=2; while Panel.Top < FOwner.ClientHeight do begin Incr:=Incr+2; Panel.Top:=Panel.Top + Incr; AnimateWait; end; Panel.Top:=FOwner.ClientHeight; Panel.Visible:=False; FVisible:=False; end; procedure TNotifyPanel.ShowNotify; var incr, ToPos:Integer; begin if not Assigned(FOwner) then raise Exception.Create('Необходимо указать форму владельца (OwnerForm)'); FLabelCaption.Caption:=FLastNotify.Caption; FLabelText.Caption:=FLastNotify.Text; FPanelLeft.Color:=FLastNotify.Color; FPanelLeft.Caption:=FLastNotify.Image; FVisible:=True; FTimerHide.Enabled:=False; Panel.Visible:=True; Panel.BringToFront; Incr:=2; Panel.Left:=FOwner.ClientWidth - Panel.Width - FRight; ToPos:=FOwner.ClientHeight - Panel.Height - FBottom; while Panel.Top > ToPos do begin Incr:=Incr+2; Panel.Top:=Panel.Top - Incr; AnimateWait; end; Panel.Top:=ToPos; FTimerHide.Enabled:=True; end; procedure TNotifyPanel.UpdatePanel; begin FPanel.Visible:=False; FPanel.Width:=350; FPanel.Height:=93; TNotifyControl(FPanel).Color:=FColor; if Assigned(FOwner) then begin FPanel.Left:=(FOwner.ClientWidth - FPanel.Width - FRight); FPanel.Top:=FOwner.ClientHeight; FOldSize.Width:=FOwner.ClientWidth; FOldSize.Height:=FOwner.ClientHeight; end; end; end.
unit clock_control; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, Graphics, LCLType, DateUtils, Types; type { TLazClockControl } TLazClockControl = class(TCustomControl) public BackgroundImage: TPortableNetworkGraphic; constructor Create(AOwner: TComponent); override; procedure EraseBackground(DC: HDC); override; procedure Paint; override; function GetResourcesDir: string; end; implementation {$ifdef Darwin} uses MacOSAll; {$endif} constructor TLazClockControl.Create(AOwner: TComponent); begin inherited Create(AOwner); BackgroundImage := TPortableNetworkGraphic.Create; BackgroundImage.LoadFromFile(GetResourcesDir() + 'skins' + PathDelim + 'wallclock1.PNG'); end; procedure TLazClockControl.EraseBackground(DC: HDC); begin // Uncomment this to enable default background erasing //inherited EraseBackground(DC); end; procedure TLazClockControl.Paint; var lCurTime: TDateTime; lHours, lMinutes, lSeconds, lMilliseconds: word; lPointerAngleMajor, lPointerAngleMinor: Double; Lmajor, Lminor: Integer; // Size of the pointer, bigger and smaller parts, counting from the clock center ClockCenter, MajorPos, MinorPos: TPoint; begin Canvas.Draw(0, 0, BackgroundImage); lCurTime := Now(); SysUtils.DecodeTime(lCurTime, lHours, lMinutes, lSeconds, lMilliseconds); ClockCenter := Types.Point(Width div 2, Height div 2); // Seconds indicator lPointerAngleMajor := - 2 * Pi * (lSeconds / 60); Lmajor := 150; Lminor := 50; MinorPos.X := Round(ClockCenter.X + Lminor * Sin(lPointerAngleMajor)); MinorPos.Y := Round(ClockCenter.Y + Lminor * Cos(lPointerAngleMajor)); MajorPos.X := Round(ClockCenter.X - Lmajor * Sin(lPointerAngleMajor)); MajorPos.Y := Round(ClockCenter.Y - Lmajor * Cos(lPointerAngleMajor)); Canvas.Pen.Color := clRed; Canvas.Pen.Width := 3; Canvas.Line(MinorPos, MajorPos); // Minutes indicator lPointerAngleMajor := - 2 * Pi * (lMinutes / 60); Lmajor := 120; Lminor := 30; MinorPos.X := Round(ClockCenter.X + Lminor * Sin(lPointerAngleMajor)); MinorPos.Y := Round(ClockCenter.Y + Lminor * Cos(lPointerAngleMajor)); MajorPos.X := Round(ClockCenter.X - Lmajor * Sin(lPointerAngleMajor)); MajorPos.Y := Round(ClockCenter.Y - Lmajor * Cos(lPointerAngleMajor)); Canvas.Pen.Color := clBlack; Canvas.Pen.Width := 5; Canvas.Line(MinorPos, MajorPos); // Hours indicator if lHours > 12 then lHours := lHours - 12; lPointerAngleMajor := - 2 * Pi * (lHours / 12); Lmajor := 80; Lminor := 20; MinorPos.X := Round(ClockCenter.X + Lminor * Sin(lPointerAngleMajor)); MinorPos.Y := Round(ClockCenter.Y + Lminor * Cos(lPointerAngleMajor)); MajorPos.X := Round(ClockCenter.X - Lmajor * Sin(lPointerAngleMajor)); MajorPos.Y := Round(ClockCenter.Y - Lmajor * Cos(lPointerAngleMajor)); Canvas.Pen.Color := clBlack; Canvas.Pen.Width := 7; Canvas.Line(MinorPos, MajorPos); end; function TLazClockControl.GetResourcesDir: string; {$ifdef Darwin} var pathRef: CFURLRef; pathCFStr: CFStringRef; pathStr: shortstring; {$endif} begin {$ifdef UNIX} {$ifdef Darwin} pathRef := CFBundleCopyBundleURL(CFBundleGetMainBundle()); pathCFStr := CFURLCopyFileSystemPath(pathRef, kCFURLPOSIXPathStyle); CFStringGetPascalString(pathCFStr, @pathStr, 255, CFStringGetSystemEncoding()); CFRelease(pathRef); CFRelease(pathCFStr); Result := pathStr + '/Contents/Resources/'; {$else} Result := '/usr/share/lazclock/'; {$endif} {$endif} {$ifdef Windows} Result := ExtractFilePath(Application.EXEName); {$endif} end; end.
unit uFuncoesRelatorios; interface Uses SqlExpr, DBGrids, DBClient, Forms, Tlhelp32; procedure Pesquisar(Banco : TSqlConnection; Filtro, Tabela : String); function OrdenaDBGrid(xGrid: DBGrids.TDBGrid; Column: TColumn; CDS: TClientDataSet): boolean; function Alltrim(const Search: string): string; implementation uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs, jpeg, ExtCtrls, Menus, DB, StdCtrls, Mask, DBCtrls, Grids, DateUtils, ImgList, dbTables, IniFiles, Registry, ShlObj, WinInet, WinSock, Math, SysConst, Buttons, IdTCPClient, StrUtils, ShellApi, dbWeb, ComObj, XMLDoc, XMLIntf, TypInfo, uPesquisa; function Alltrim(const Search: string): string; {Remove os espaços em branco de ambos os lados da string} const BlackSpace = [#33..#126]; var Index: byte; begin Index:=1; while (Index <= Length(Search)) and not (Search[Index] in BlackSpace) do begin Index:=Index + 1; end; Result:=Copy(Search, Index, 255); Index := Length(Result); while (Index > 0) and not (Result[Index] in BlackSpace) do begin Index:=Index - 1; end; Result := Copy(Result, 1, Index); end; procedure Pesquisar(Banco : TSqlConnection; Filtro, Tabela : String); var I : Integer; begin if not(Assigned(frmPesquisa)) then begin try Screen.Cursor:=crHourGlass; frmPesquisa:=tfrmpesquisa.create(application); frmpesquisa.Caption:='Pesquisa Registros'; frmPesquisa.sqlPesquisa.SQLConnection:=Banco; frmPesquisa.cdsPesquisa.CommandText:=Filtro; frmPesquisa.cdsPesquisa.FetchParams; frmPesquisa.cdsPesquisa.Active:=true; if frmpesquisa.cdsPesquisa.RecordCount>0 then begin for i := 0 to frmpesquisa.cdsPesquisa.FieldCount-1 do begin case (frmPesquisa.cdsPesquisa.Fields.Fields[i].DataType) of ftBCD, ftFloat : TNumericField(frmpesquisa.cdsPesquisa.Fields.Fields[i]).DisplayFormat:='###,###0.00'; ftInteger : TNumericField(frmpesquisa.cdsPesquisa.Fields.Fields[i]).DisplayFormat:='###,###0'; end; // if (frmpesquisa.cdsPesquisa.Fields.Fields[i].DataType = ftFloat) then // TNumericField(frmpesquisa.cdsPesquisa.Fields.Fields[i]).DisplayFormat:='###,###0.00'; end; frmPesquisa.dbgrdPesquisa.DataSource:=frmPesquisa.dsPesquisa; for i := 0 to frmPesquisa.dbgrdPesquisa.Columns.Count-1 do frmPesquisa.dbgrdPesquisa.Columns[i].Title.Alignment:=taCenter; frmPesquisa.ShowModal; Screen.Cursor:=crDefault; end else begin ShowMessage('Não existem registros para pesquisa'); Screen.Cursor:=crDefault; frmpesquisa.Close; end; finally frmPesquisa.cdsPesquisa.Active:=false; FreeAndNil(frmPesquisa); end; end else application.MessageBox('Já existe pesquisa em andamento','Sistema de Alerta',MB_ICONINFORMATION+MB_OK); end; function OrdenaDBGrid(xGrid: DBGrids.TDBGrid; Column: TColumn; CDS: TClientDataSet): boolean; const idxDefault = 'DEFAULT_ORDER'; var strColumn: string; bolUsed: Boolean; idOptions: TIndexOptions; I: Integer; VDescendField: string; begin Result := false; if not CDS.Active then exit; strColumn := idxDefault; // Se for campo calculado não deve fazer nada if (Column.Field.FieldKind = fkCalculated) then exit; // O índice já está em uso bolUsed := (Column.Field.FieldName = cds.IndexName); // Verifica a existência do índice e propriedades CDS.IndexDefs.Update; idOptions := []; for I := 0 to CDS.IndexDefs.Count - 1 do begin if cds.IndexDefs.Items[I].Name = Column.Field.FieldName then begin strColumn := Column.Field.FieldName; // Determina como deve ser criado o índice, inverte a condição ixDescending case (ixDescending in cds.IndexDefs.Items[I].Options) of True: begin idOptions := []; VDescendField := ''; end; False: begin idOptions := [ixDescending]; vDescendField := strColumn; end; end; end; end; // Se não encontrou o índice, ou o índice já esta em uso... if (strColumn = idxDefault) or bolUsed then begin if bolUsed then CDS.DeleteIndex(Column.Field.FieldName); try CDS.AddIndex(Column.Field.FieldName, Column.Field.FieldName, idOptions, VDescendField, '', 0); strColumn := Column.Field.FieldName; except // O índice esta indeterminado, passo para o padrão if bolUsed then strColumn := idxDefault; end; end; for I := 0 to xGRID.Columns.Count - 1 do begin xGrid.Columns[I].Title.Font.Style := []; xGrid.Columns[I].Title.Font.Color := clWindowText; end; for I := 0 to xGRID.Columns.Count - 1 do begin // if Pos(StrColumn, xGrid.Columns[I].Field.FieldName) <> 0 then if StrColumn=xGrid.Columns[I].Field.FieldName then begin xGrid.Columns[I].Title.Font.Style := [fsBold]; xGrid.Columns[I].Title.Font.Color := clBlue; end else begin xGrid.Columns[I].Title.Font.Style := []; xGrid.Columns[I].Title.Font.Color := clWindowText; end; end; try CDS.IndexName := strColumn; except CDS.IndexName := idxDefault; end; result := true; end; end.
unit prototype_lib; interface uses classes,streaming_class_lib, contnrs; type TPrototypedObject=class(TStreamingClass) private fPrototype: TPrototypedObject; function GetPrototypeName: string; procedure SetPrototypeName(value: string); // procedure SetPrototype(value: TPrototypedObject); protected function HasPrototype: Boolean; function IsPrototype: boolean; published property Prototype: string read GetPrototypeName write SetPrototypeName stored HasPrototype; end; TPrototypeClass=class of TPrototypedObject; procedure LoadPrototypes(dir,FileMask: string); var PrototypeList: TObjectList; implementation uses SysUtils; function TPrototypedObject.GetPrototypeName: string; begin Result:=fPrototype.Name; end; procedure TPrototypedObject.SetPrototypeName(value: string); var i: Integer; buName: string; begin for i:=0 to PrototypeList.Count-1 do if (PrototypeList[i] is ClassType) and ((PrototypeList[i] as TPrototypedObject).name=value) then begin fPrototype:=TPrototypedObject(PrototypeList[i]); buName:=Name; Assign(fPrototype); Name:=buName; Exit; end; fPrototype:=nil; Raise Exception.CreateFmt('SetPrototypeName: couldn''t find prototype %s',[value]); end; function TPrototypedObject.IsPrototype: boolean; begin Result:=(fPrototype=nil); end; function TPrototypedObject.HasPrototype: Boolean; begin Result:=(fPrototype<>nil); end; (* General *) procedure LoadPrototypes(dir,FileMask: string); var sr: TSearchRec; fn: string; p: TPrototypedObject; budir: string; begin budir:=GetCurrentDir; SetCurrentDir(dir); fn:=FileMask; if FindFirst(fn,faAnyFile,sr)=0 then repeat try p:=TPrototypedObject.LoadComponentFromFile(sr.Name) as TPrototypedObject; PrototypeList.Add(p); finally end; until FindNext(sr)<>0; FindClose(sr); SetCurrentDir(budir); end; initialization PrototypeList:=TObjectList.Create; finalization PrototypeList.Free; end.
unit untAdmPaginas; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, HTTPDefs, websession, fpHTTP, fpWeb, //database libs db, sqldb, //custom libs untAdmPage, untDB; type { TuntAdmPaginas } TuntAdmPaginas = class(TuntAdmPage) private { private declarations } procedure tagReplace(Sender: TObject; const TagString:String; TagParams: TStringList; Out ReplaceText: String); override; public { public declarations } function select(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean) : string; function insert(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean) : string; function update(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean) : string; function delete(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean) : string; function doSQL(action:string; sql: string):string; function getListMenu(): string; class function exec(item: integer) : string; class function getPageType( item: integer) : string; class function getPageReference( item: integer) : string; constructor Create; destructor Destroy; override; end; implementation { TuntAdmPaginas } procedure TuntAdmPaginas.tagReplace(Sender: TObject; const TagString: String; TagParams: TStringList; out ReplaceText: String); var straux : string; begin if AnsiCompareText(TagString, 'wiseAdmPath') = 0 then begin ReplaceText:= AppURL; end; if AnsiCompareText(TagString, 'wiseMsg') = 0 then begin ReplaceText:= msg; end; if AnsiCompareText(TagString, 'wiseConfigItem') = 0 then begin ReplaceText:= TuntDB.getConfigItem( TagParams.Values['get'], self.Database); end; if AnsiCompareText(TagString, 'wiseList') = 0 then begin if AnsiCompareText( LowerCase( TagParams.Values['type'] ), 'menu') = 0 then ReplaceText:= getListMenu(); if AnsiCompareText( LowerCase( TagParams.Values['type'] ), 'page') = 0 then ReplaceText:= 'paginas'; //lista paginas if AnsiCompareText( LowerCase( TagParams.Values['type'] ), 'tipo') = 0 then ReplaceText:= '<option>tipos</option>'; //tipos if AnsiCompareText( LowerCase( TagParams.Values['type'] ), 'referencia') = 0 then ReplaceText:= '<option>referencias</option>'; //referencias end; end; function TuntAdmPaginas.getListMenu(): string; var strAux: string; begin TuntDB.Connect( Self.Database ); try with SQLQuery do begin Close; SQL.Add('SELECT id, name, idpage, idcategory, posicao FROM tbsitemenu ORDER BY posicao ;'); Open; if RecordCount > 0 then begin //roda os resultados while not EOF do begin straux := straux + '<tr>'+ '<td>'+ FieldByName('name').AsString +'</td>'+ '<td>'+ getPageType( FieldByName('idpage').AsInteger ) +'</td>'+ '<td>'+ getPageReference( FieldByName('idpage').AsInteger ) +'</td>'+ '<td>'+ FieldByName('posicao').AsString +'º</td>'+ '<td>'+ '<a href="#" onclick="pageMenusEdit( '+ FieldByName('idpage').AsString +','+ QuotedStr( FieldByName('name').AsString ) +','+ QuotedStr( getPageType( FieldByName('idpage').AsInteger ) ) +','+ QuotedStr( getPageReference( FieldByName('idpage').AsInteger ) ) +','+ FieldByName('posicao').AsString + ' );">'+ '<img src="sys.img/edit.png"/>'+ '</a>'+ '</td>'+ '<td>'+ '<a href="#" onclick="pageMenusDelete( '+ FieldByName('idpage').AsString +' );">'+ '<img src="sys.img/delete.png"/>'+ '</a>'+ '</td>'+ '</tr>'; next; end; end else begin //usuário e/ou senha incorretos Result:= 'Sem itens de menu.'; end; end; Result:= strAux; except Result:= 'Erro na base de dados!'; end; TuntDB.Disconnect(); end; function TuntAdmPaginas.select(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean) : string; var max,i : integer; resp: string; begin // end; function TuntAdmPaginas.insert(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean) : string; begin // end; function TuntAdmPaginas.update(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean) : string; begin // end; function TuntAdmPaginas.delete(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean) : string; begin end; function TuntAdmPaginas.doSQL(action:string; sql:string):string; begin end; class function TuntAdmPaginas.exec(item: integer) : string; var straux: string; begin case item of //nova pagina 1 : begin self.Form := self.FormPath + 'frmPaginasNova.html'; //if Request.QueryFields.Values['act'] = '2' then //msg := update(); //atualiza e carrega mensagem Result:= self.getHTML(); end; 2 : begin self.Form := self.FormPath + 'frmPaginasLista.html'; //if Request.QueryFields.Values['act'] = '2' then //msg := update(); //atualiza e carrega mensagem Result:= self.getHTML(); end; //menus 3 : begin self.Form := self.FormPath + 'frmPaginasMenus.html'; if Request.QueryFields.Values['act'] = '1' then msg := 'inserir...' //insert() else if Request.QueryFields.Values['act'] = '2' then msg := 'atualizar...'// update() else if Request.QueryFields.Values['act'] = '3' then msg := 'apagar...';// delete(); Result:= self.getHTML(); end; end; end; class function TuntAdmPaginas.getPageType( item: integer) : string; var qryAux : TSQLQuery; begin //TuntDB.Connect( Self.Database ); try qryAux := TSQLQuery.Create(nil); qryAux.DataBase := SQLite3Con; qryAux.Transaction := SQLTrans; with qryAux do begin Close; SQL.Add('SELECT id, filename, type FROM tbsitepages WHERE id='+ IntToStr(item) +' ;'); Open; if RecordCount > 0 then begin if FieldByName('type').AsString = 'file' then Result:= 'Arquivo'; if FieldByName('type').AsString = 'page' then Result:= 'Interno'; if FieldByName('type').AsString = 'category' then Result:= 'Categoria'; if FieldByName('type').AsString = 'link' then Result:= 'Externo'; end else begin Result:= 'Conteúdo dinâmico'; end; end; qryAux.Destroy; except Result:= 'Erro na base de dados!'; end; //TuntDB.Disconnect();} end; class function TuntAdmPaginas.getPageReference( item: integer) : string; var qryAux : TSQLQuery; begin //TuntDB.Connect( Self.Database ); try qryAux := TSQLQuery.Create(nil); qryAux.DataBase := SQLite3Con; qryAux.Transaction := SQLTrans; with qryAux do begin Close; SQL.Add('SELECT id, filename FROM tbsitepages WHERE id='+ IntToStr(item) +' ;'); Open; if RecordCount > 0 then begin Result:= FieldByName('filename').AsString; end else begin //usuário e/ou senha incorretos Result:= 'Conteúdo dinâmico'; end; end; qryAux.Destroy; except Result:= 'Erro na base de dados!'; end; //TuntDB.Disconnect();} end; constructor TuntAdmPaginas.Create; begin end; destructor TuntAdmPaginas.Destroy; begin inherited Destroy; end; end.
//Exercicio 14: Faça um algoritmo que receba a idade de uma pessoa e exiba mensagem de maioridade. { Solução em Portugol Algoritmo Exercicio14; Var idade: inteiro; Inicio exiba("Programa que determina se uma pessoa é maior de idade."); exiba("Digite uma idade: "); leia(idade); se(idade >= 18) então exiba("Maior de idade."); fimse; se(idade < 18) então exiba("Menor de idade."); fimse; Fim. } // Solução em Pascal Program Exercicio14; Uses crt; Var idade: Integer; Begin Clrscr; Writeln('Programa que determina se uma pessoa é maior de idade.'); WriteLn('Digite uma idade: '); Readln(idade); if(idade >= 18) then writeln('Maior de idade.'); if(idade < 18) then writeln('Menor de idade.'); Repeat Until Keypressed; End.
{ Subroutine SST_DTYPE_NEW (DTYPE_P) * * Allocate memory under the current scope for a new data type descriptor. The * descriptor will be initialized, and DTYPE_P will be returned pointing to it. } module sst_DTYPE_NEW; define sst_dtype_new; %include 'sst2.ins.pas'; procedure sst_dtype_new ( {allocate new data type in current scope} out dtype_p: sst_dtype_p_t); {pnt to new created and initted block} begin sst_mem_alloc_scope (sizeof(dtype_p^), dtype_p); {allocate mem for new data type} with dtype_p^:d do begin {D is new data type descriptor block} d.symbol_p := nil; d.dtype := sst_dtype_undef_k; d.bits_min := 0; d.align_nat := 0; d.align := 0; d.size_used := 0; d.size_align := 0; end; {done with D abbreviation} end;
unit thread_main; interface uses SysUtils, Classes, Windows, ActiveX; type TThreadMain = class(TThread) private { Private declarations } protected procedure Execute; override; end; var ThreadMain: TThreadMain; // {$DEFINE DEBUG} procedure WrapperMain; // обертка для синхронизации и выполнения с другим потоком function GetHeat: bool; function GetChemicalAnalysis(InHeat: string): bool; implementation uses logging, settings, main, sql; procedure TThreadMain.Execute; begin CoInitialize(nil); while not Terminated do begin Synchronize(WrapperMain); sleep(1000); end; CoUninitialize; end; procedure WrapperMain; begin try //reconnect if not OraSqlSettings.configured then ConfigOracleSetting(true); // точка вместо запятой при преобразовании в строку FormatSettings.DecimalSeparator := '.'; GetHeat; except on E: Exception do SaveLog('error'+#9#9+E.ClassName+', с сообщением: '+E.Message); end; end; function GetHeat: bool; begin try PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('select distinct t1.tid, t1.heat FROM temperature_current t1'); PQuery.SQL.Add('where not exists'); PQuery.SQL.Add('(select distinct heat FROM chemical_analysis t2 where t1.heat=t2.heat)'); PQuery.SQL.Add('order by t1.tid desc LIMIT 1'); PQuery.Open; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; if not PQuery.FieldByName('heat').IsNull then GetChemicalAnalysis(PQuery.FieldByName('heat').AsString); end; function GetChemicalAnalysis(InHeat: string): bool; var ChemicalAnalysisArray: array [0 .. 9] of ansistring; begin try OraQuery.Close; OraQuery.SQL.Clear; OraQuery.SQL.Add('select DATE_IN_HIM'); OraQuery.SQL.Add(', NPL, MST, GOST, C, MN, SI, S, CR, B from him_steel'); OraQuery.SQL.Add('where DATE_IN_HIM>=sysdate-300'); //-- 300 = 10 month OraQuery.SQL.Add('and NUMBER_TEST=''0'''); OraQuery.SQL.Add('and NPL in ('''+InHeat+''')'); OraQuery.SQL.Add('order by DATE_IN_HIM desc'); OraQuery.Open; OraQuery.FetchAll; except on E : Exception do begin SaveLog('error'+#9#9+E.ClassName+', с сообщением: '+E.Message); ConfigOracleSetting(false); exit; end; end; //если не находим записываем фeйк if not OraQuery.FieldByName('NPL').IsNull then begin ChemicalAnalysisArray[0] := OraQuery.FieldByName('DATE_IN_HIM').AsString; ChemicalAnalysisArray[1] := UTF8Decode(OraQuery.FieldByName('NPL').AsString); if OraQuery.FieldByName('MST').IsNull then ChemicalAnalysisArray[2] := '0' else ChemicalAnalysisArray[2] := UTF8Decode(OraQuery.FieldByName('MST').AsString); if OraQuery.FieldByName('GOST').IsNull then ChemicalAnalysisArray[3] := '0' else ChemicalAnalysisArray[3] := UTF8Decode(OraQuery.FieldByName('GOST').AsString); if OraQuery.FieldByName('C').IsNull then ChemicalAnalysisArray[4] := '0' else ChemicalAnalysisArray[4] := StringReplace(OraQuery.FieldByName('C').AsString,',','.',[rfReplaceAll]); if OraQuery.FieldByName('MN').IsNull then ChemicalAnalysisArray[5] := '0' else ChemicalAnalysisArray[5] := StringReplace(OraQuery.FieldByName('MN').AsString,',','.',[rfReplaceAll]); if OraQuery.FieldByName('SI').IsNull then ChemicalAnalysisArray[6] := '0' else ChemicalAnalysisArray[6] := StringReplace(OraQuery.FieldByName('SI').AsString,',','.',[rfReplaceAll]); if OraQuery.FieldByName('S').IsNull then ChemicalAnalysisArray[7] := '0' else ChemicalAnalysisArray[7] := StringReplace(OraQuery.FieldByName('S').AsString,',','.',[rfReplaceAll]); if OraQuery.FieldByName('CR').IsNull then ChemicalAnalysisArray[8] := '0' else ChemicalAnalysisArray[8] := StringReplace(OraQuery.FieldByName('CR').AsString,',','.',[rfReplaceAll]); if OraQuery.FieldByName('B').IsNull then ChemicalAnalysisArray[9] := '0' else ChemicalAnalysisArray[9] := StringReplace(OraQuery.FieldByName('B').AsString,',','.',[rfReplaceAll]); end else begin ChemicalAnalysisArray[0] := '01.01.0001'; ChemicalAnalysisArray[1] := InHeat; ChemicalAnalysisArray[2] := '0'; ChemicalAnalysisArray[3] := '0'; ChemicalAnalysisArray[4] := '0'; ChemicalAnalysisArray[5] := '0'; ChemicalAnalysisArray[6] := '0'; ChemicalAnalysisArray[7] := '0'; ChemicalAnalysisArray[8] := '0'; ChemicalAnalysisArray[9] := '0'; end; SaveLog('service'+#9#9+'save'+#9+'chemical analysis -> '+ ChemicalAnalysisArray[0]+#9+ChemicalAnalysisArray[1]+#9+ ChemicalAnalysisArray[2]+#9+ChemicalAnalysisArray[3]+#9+ ChemicalAnalysisArray[4]+#9+ChemicalAnalysisArray[5]+#9+ ChemicalAnalysisArray[6]+#9+ChemicalAnalysisArray[7]+#9+ ChemicalAnalysisArray[8]+#9+ChemicalAnalysisArray[9]); try PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('insert INTO chemical_analysis'); PQuery.SQL.Add('(timestamp, heat, date_external, grade, standard, c, mn, si, s, cr, b)'); PQuery.SQL.Add('values(EXTRACT(EPOCH FROM now()),'); PQuery.SQL.Add(''''+ChemicalAnalysisArray[1]+''', '''+ChemicalAnalysisArray[0]+''','); PQuery.SQL.Add(''''+ChemicalAnalysisArray[2]+''', '''+ChemicalAnalysisArray[3]+''','); PQuery.SQL.Add(''+ChemicalAnalysisArray[4]+', '+ChemicalAnalysisArray[5]+','); PQuery.SQL.Add(''+ChemicalAnalysisArray[6]+', '+ChemicalAnalysisArray[7]+','); PQuery.SQL.Add(''+ChemicalAnalysisArray[8]+', '+ChemicalAnalysisArray[9]+')'); PQuery.ExecSQL; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; end.
unit Soko1; { This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Sokoban, StdCtrls, ShellAPI, IniFiles; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; OpenDlg: TOpenDialog; procedure Label2Click(Sender: TObject); procedure Soko1Win(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Label6Click(Sender: TObject); private Soko1 : TSoko; fLevel:integer; Start:TDateTime; Next :string; procedure LoadFromFile(AFileName:string); end; var Form1: TForm1; implementation {$R *.DFM} Const help='Sokoban (C) 2000 By Paul TOTH <tothpaul@free.fr>'#13#13+ 'The object of the game is quite simple - you must push all the mines into storage rooms,'#13+ 'preferably in the fewest number of moves and pushes.'#13#13+ 'This program is free software; you can redistribute it and/or'+ 'modify it under the terms of the GNU General Public License'+ 'as published by the Free Software Foundation; either version 2'+ 'of the License, or (at your option) any later version.'#13+ '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.'#13+ 'You should have received a copy of the GNU General Public License'+ 'along with this program; if not, write to the Free Software'+ 'Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.'; Levels:array[1..3,0..10] of pchar= // X = Wall // * = Mine // @ = storage room // ! = player (( 'XXXXXXXXXXXXXXXXXXX', 'XXXXX...XXXXXXXXXXX', 'XXXXX*..XXXXXXXXXXX', 'XXXXX..*XXXXXXXXXXX', 'XXX..*.*.XXXXXXXXXX', 'XXX.X.XX.XXXXXXXXXX', 'X...X.XX.XXXXX..@@X', 'X.*..*..........@@X', 'XXXXX.XXX.X!XX..@@X', 'XXXXX.....XXXXXXXXX', 'XXXXXXXXXXXXXXXXXXX' ),( 'XXXXXXXXXXXXXXXXXXX', 'X@@..X.....XXXXXXXX', 'X@@..X.*..*..XXXXXX', 'X@@..X*XXXX..XXXXXX', 'X@@....!.XX..XXXXXX', 'X@@..X.X..*.XXXXXXX', 'XXXXXX.XX*.*.XXXXXX', 'XXX.*..*.*.*.XXXXXX', 'XXX....X.....XXXXXX', 'XXXXXXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXX' ),( 'XXXXXXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXX', 'XXXXXXXXX.....!XXXX', 'XXXXXXXXX.*X*.XXXXX', 'XXXXXXXXX.*..*XXXXX', 'XXXXXXXXXX*.*.XXXXX', 'XXXXXXXXX.*.X.XXXXX', 'X@@@@..XX.*..*..XXX', 'XX@@@....*..*...XXX', 'X@@@@..XXXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXX' )); procedure TForm1.Label2Click(Sender: TObject); begin with TLabel(Sender) do begin Font.color:=clPurple; Application.ProcessMessages; case Tag of 0:ShellExecute(Handle,nil,'mailto:tothpaul@free.fr',nil,nil,0); 1:ShowMessage(Help); 2:ShellExecute(Handle,nil,'http://tothpaul.free.fr',nil,nil,0); 3:Application.Terminate; end; end; end; procedure TForm1.Soko1Win(Sender: TObject); begin if fLevel<>0 then begin ShowMessage('Level complet with '+IntToStr(Soko1.MoveCount)+' moves - '+FormatDateTime('hh:mm:ss',Time-Start)); end; if fLevel<0 then begin LoadFromFile(Next); exit; end; inc(fLevel); if fLevel<=High(Levels) then begin ShowMessage('Entering level '+IntToStr(fLevel)); Soko1.LoadLevel(Levels[fLevel]); Start:=Time; end else begin ShowMessage( 'Congratulations !'#13+ 'Send me your own levels, look at Soko1.pas to see how they are build...' ); end; end; procedure TForm1.FormCreate(Sender: TObject); begin Soko1:=TSoko.Create(Form1); Soko1.Parent:=Form1; Soko1.Top:=15; fLevel:=0; end; procedure TForm1.Label6Click(Sender: TObject); begin if OpenDlg.Execute then LoadFromFile(OpenDlg.FileName); end; procedure TForm1.LoadFromFile(AFileName:string); var s:TStringList; begin s:=TStringList.Create; try try s.LoadFromFile(AFileName); Caption:=s[0]; Next:=s[12]; Soko1.LoadStrings(s); fLevel:=-1; except ShowMessage(AFileName); end; finally; s.Free; end; end; end.
unit Plugin.Tool; interface uses System.SysUtils, System.Classes,Vcl.Imaging.jpeg, Vcl.Graphics,IdURI, IdGlobal,IdCoderMIME,EncdDecd; type TTool = class public function URLDecode(Asrc: string; AByteEncoding: IIdtextEncoding): string; function URLEncode(Asrc: string; AByteEncoding: IIdTextEncoding): string; function Base64Decode(S: string): string; function Base64Encode(S: string): string; function BitmapToString(img:TBitmap):string; function StringToBitmap(imgStr: string): TBitmap; end; implementation function TTool.URLDecode(Asrc: string; AByteEncoding: IIdtextEncoding): string; begin if AByteEncoding <> nil then Result := TIdURI.URLDecode(Asrc, AByteEncoding) else Result := TIdURI.URLDecode(Asrc); end; function TTool.URLEncode(Asrc: string; AByteEncoding: IIdTextEncoding): string; begin if AByteEncoding <> nil then Result := TIdURI.URLEncode(Asrc, AByteEncoding) else Result := TIdURI.URLEncode(Asrc); end; function TTool.Base64Encode(S: string): string; var base64: TIdEncoderMIME; // tmpBytes: TBytes; begin base64 := TIdEncoderMIME.Create(nil); try base64.FillChar := '='; Result := base64.EncodeString(S); // tmpBytes := TEncoding.UTF8.GetBytes(S); // Result := base64.EncodeBytes(TIdBytes(tmpBytes)); finally base64.Free; end; end; ///将base64字符串转化为Bitmap位图 function TTool.StringToBitmap(imgStr:string):TBitmap; var ss:TStringStream; ms:TMemoryStream; bitmap:TBitmap; begin ss := TStringStream.Create(imgStr); ms := TMemoryStream.Create; DecodeStream(ss,ms);//将base64字符流还原为内存流 ms.Position:=0; bitmap := TBitmap.Create; bitmap.LoadFromStream(ms); ss.Free; ms.Free; result :=bitmap; end; ///将Bitmap位图转化为base64字符串 function TTool.BitmapToString(img:TBitmap): string; var ms:TMemoryStream; ss:TStringStream; s:string; begin ms := TMemoryStream.Create; img.SaveToStream(ms); ss := TStringStream.Create(''); ms.Position:=0; EncodeStream(ms,ss);//将内存流编码为base64字符流 s:=ss.DataString; ms.Free; ss.Free; result:=s; end; function TTool.Base64Decode(S: string): string; var base64: TIdDeCoderMIME; // tmpBytes: TBytes; begin Result := S; base64 := TIdDecoderMIME.Create(nil); try base64.FillChar := '='; // tmpBytes := TBytes(base64.DecodeBytes(S)); //Result := TEncoding.UTF8.GetString(tmpBytes); Result := base64.DecodeString(S); finally base64.Free; end; end; end.
unit LUX.GPU.Vulkan.Shader; interface //#################################################################### ■ uses vulkan_core, vulkan_win32; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TVkShader<TVkPipeli_:class> = class; TVkShaderVert<TVkPipeli_:class> = class; TVkShaderFrag<TVkPipeli_:class> = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkShader TVkShader<TVkPipeli_:class> = class private protected _Pipeli :TVkPipeli_; _Module :VkShaderModuleCreateInfo; _Stage :VkPipelineShaderStageCreateInfo; ///// アクセス ///// メソッド procedure CreateModule; virtual; procedure DestroModule; virtual; public constructor Create( const Pipeli_:TVkPipeli_ ); destructor Destroy; override; ///// プロパティ property Pipeli :TVkPipeli_ read _Pipeli; property Module :VkShaderModuleCreateInfo read _Module; property Stage :VkPipelineShaderStageCreateInfo read _Stage ; ///// メソッド procedure LoadFromFile( const FileName_:String ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkShaderVert TVkShaderVert<TVkPipeli_:class> = class( TVkShader<TVkPipeli_> ) private protected public constructor Create( const Pipeli_:TVkPipeli_ ); destructor Destroy; override; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkShaderFrag TVkShaderFrag<TVkPipeli_:class> = class( TVkShader<TVkPipeli_> ) private protected public constructor Create( const Pipeli_:TVkPipeli_ ); destructor Destroy; override; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses System.Classes, LUX.GPU.Vulkan; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkShader //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス /////////////////////////////////////////////////////////////////////// メソッド procedure TVkShader<TVkPipeli_>.CreateModule; begin Assert( vkCreateShaderModule( TVkPipeli( _Pipeli ).Device.Handle, @_Module, nil, @_Stage.module ) = VK_SUCCESS ); end; procedure TVkShader<TVkPipeli_>.DestroModule; begin vkDestroyShaderModule( TVkPipeli( _Pipeli ).Device.Handle, _Stage.module, nil ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkShader<TVkPipeli_>.Create( const Pipeli_:TVkPipeli_ ); begin inherited Create; _Pipeli := Pipeli_; TVkPipeli( _Pipeli ).Shaders.Add( TVkShader( Self ) ); _Module := Default( VkShaderModuleCreateInfo ); _Module.sType := VkStructureType.VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; _Module.pNext := nil; _Module.flags := 0; _Module.codeSize := 0; _Module.pCode := nil; _Stage.sType := VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; _Stage.pNext := nil; _Stage.flags := 0; // _Stage.stage _Stage.pName := 'main'; _Stage.pSpecializationInfo := nil; end; destructor TVkShader<TVkPipeli_>.Destroy; begin if _Stage.module > 0 then DestroModule; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TVkShader<TVkPipeli_>.LoadFromFile( const FileName_:String ); var F :TMemoryStream; begin F := TMemoryStream.Create; try F.LoadFromFile( FileName_ ); _Module.codeSize := F.Size; _Module.pCode := F.Memory; CreateModule; finally F.Free; end; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkShaderVert //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkShaderVert<TVkPipeli_>.Create( const Pipeli_:TVkPipeli_ ); begin inherited; _Stage.stage := VK_SHADER_STAGE_VERTEX_BIT; end; destructor TVkShaderVert<TVkPipeli_>.Destroy; begin inherited; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkShaderFrag //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkShaderFrag<TVkPipeli_>.Create( const Pipeli_:TVkPipeli_ ); begin inherited; _Stage.stage := VK_SHADER_STAGE_FRAGMENT_BIT; end; destructor TVkShaderFrag<TVkPipeli_>.Destroy; begin inherited; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit StockDayData_Parse_Sina_Html2; interface uses win.iobuffer, define_stockday_sina, define_stock_quotes, StockDayDataAccess; function DataParse_DayData_Sina(ADataAccess: TStockDayDataAccess; AResultData: PIOBuffer): Boolean; overload; implementation uses Sysutils, StockDayData_Parse_Sina, UtilsHttp, UtilsLog, DomCore, HtmlParser; type PParseRecord = ^TParseRecord; TParseRecord = record HtmlParser: THtmlParser; HtmlDoc: TDocument; IsInTable: Integer; IsTableHeadReady: Boolean; TableHeader: TRT_DealDayData_HeaderSina; DealDayData: TRT_Quote_M1_Day; end; function GetNodeText(ANode: TNode): WideString; var i: integer; tmpNode: TNode; begin Result := ''; if nil = ANode then exit; if nil = ANode.childNodes then Exit; for i := 0 to ANode.childNodes.length - 1 do begin tmpNode := ANode.childNodes.item(i); if ELEMENT_NODE = tmpNode.nodetype then begin if 1 = ANode.childNodes.length then begin Result := GetNodeText(ANode.childNodes.item(0)); end; end; if TEXT_NODE = tmpNode.nodetype then begin Result := tmpNode.nodeValue; end; end; end; procedure ParseStockDealDataTableRow(ADataAccess: TStockDayDataAccess; AParseRecord: PParseRecord; ANode: TNode); var i: integer; tmpChild: TNode; tmpHeadColName: TDealDayDataHeadName_Sina; tmpStr: string; tmpTDIndex: integer; tmpIsHead: Boolean; begin FillChar(AParseRecord.DealDayData, SizeOf(AParseRecord.DealDayData), 0); tmpTDIndex := -1; tmpIsHead := false; for i := 0 to ANode.childNodes.length - 1 do begin tmpChild := ANode.childNodes.item(i); if SameText(tmpChild.nodeName, 'td') then begin inc (tmpTDIndex); if (not AParseRecord.IsTableHeadReady) then begin // 处理 行数据 tmpStr := trim(tmpChild.nodeValue); if '' = tmpStr then begin tmpStr := GetNodeText(tmpChild); end; if '' <> tmpStr then begin for tmpHeadColName := Low(TDealDayDataHeadName_Sina) to High(TDealDayDataHeadName_Sina) do begin if SameText(tmpStr, DealDayDataHeadNames_Sina[tmpHeadColName]) or (Pos(DealDayDataHeadNames_Sina[tmpHeadColName], tmpStr) > 0) then begin AParseRecord.TableHeader.HeadNameIndex[tmpHeadColName] := tmpTDIndex; tmpIsHead := true; end; end; end; end else begin // 处理 行数据 tmpStr := trim(tmpChild.nodeValue); if '' = tmpStr then begin tmpStr := Trim(GetNodeText(tmpChild)); end; for tmpHeadColName := Low(TDealDayDataHeadName_Sina) to High(TDealDayDataHeadName_Sina) do begin if AParseRecord.TableHeader.HeadNameIndex[tmpHeadColName] = tmpTDIndex then begin ParseCellData(tmpHeadColName, @AParseRecord.DealDayData, tmpStr); end; end; end; end; end; if not AParseRecord.IsTableHeadReady then begin AParseRecord.IsTableHeadReady := tmpIsHead; end else begin AddDealDayData(ADataAccess, @AParseRecord.DealDayData); end; end; function HtmlParse_DayData_Sina_Table(ADataAccess: TStockDayDataAccess; AParseRecord: PParseRecord; ANode: TNode): Boolean; var i, j: integer; tmpNode1: TNode; tmpcnt1: integer; tmpcnt2: integer; tmpRow: integer; tmpTagName: string; var tmpHeadColName: TDealDayDataHeadName_Sina; begin Result := false; AParseRecord.IsTableHeadReady := false; for tmpHeadColName := low(TDealDayDataHeadName_Sina) to high(TDealDayDataHeadName_Sina) do begin AParseRecord.TableHeader.HeadNameIndex[tmpHeadColName] := -1; end; tmpcnt1 := ANode.childNodes.length; tmpRow := 0; for i := 0 to tmpcnt1 - 1 do begin tmpNode1 := ANode.childNodes.item(i); tmpTagName := lowercase(tmpNode1.nodeName); if SameText(tmpTagName, 'tr') then begin ParseStockDealDataTableRow(ADataAccess, AParseRecord, tmpNode1); end; if SameText(tmpTagName, 'tbody') then begin tmpcnt2 := tmpNode1.childNodes.length; for j := 0 to tmpcnt2 - 1 do begin if SameText(tmpNode1.childNodes.item(j).nodeName, 'tr') then begin ParseStockDealDataTableRow(ADataAccess, AParseRecord, ANode.childNodes.item(i)); end; end; continue; end; end; if AParseRecord.IsTableHeadReady then begin Result := true; end; end; function HtmlParse_DayData_Sina(ADataAccess: TStockDayDataAccess; AParseRecord: PParseRecord; ANode: TNode): Boolean; var i, j: integer; tmpcnt: integer; tmpTableId: WideString; tmpNode: TNode; tmpIsHandledNode: Boolean; begin result := false; if nil = ANode then exit; tmpIsHandledNode := false; if SameText(string(lowercase(ANode.nodeName)), 'table') then begin Inc(AParseRecord.IsInTable); tmpcnt := 0; if nil <> ANode.childNodes then tmpcnt := ANode.childNodes.length; tmpTableId := ''; tmpNode := nil; if nil <> ANode.attributes then begin for i := 0 to ANode.attributes.length - 1 do begin tmpNode := ANode.attributes.item(i); if SameText('id', tmpNode.nodeName) then begin tmpTableId := GetNodeText(tmpNode); Break; end; end; end; if tmpTableId <> '' then begin if SameText('FundHoldSharesTable', tmpTableId) then begin tmpIsHandledNode := true; end else begin if Pos('fundholdsharestable', lowercase(tmpTableId)) = 1 then begin tmpIsHandledNode := true; end; end; end; end; if tmpIsHandledNode then begin result := HtmlParse_DayData_Sina_Table(ADataAccess, AParseRecord, ANode); end else begin if nil <> ANode.childNodes then begin tmpcnt := ANode.childNodes.length; for i := 0 to tmpcnt - 1 do begin tmpNode := ANode.childNodes.item(i); if not result then begin result := HtmlParse_DayData_Sina(ADataAccess, AParseRecord, tmpNode); end else begin HtmlParse_DayData_Sina(ADataAccess, AParseRecord, tmpNode); end; end; end; end; if SameText(string(lowercase(ANode.nodeName)), 'table') then begin Dec(AParseRecord.IsInTable); end; end; function DataParse_DayData_Sina(ADataAccess: TStockDayDataAccess; AResultData: PIOBuffer): Boolean; overload; var tmpParseRec: TParseRecord; // 168k 的数据太大 不能这样设置 tmpHttpHeadSession: THttpHeadParseSession; begin Result := False; if nil = AResultData then exit; FillChar(tmpParseRec, SizeOf(tmpParseRec), 0); FIllChar(tmpHttpHeadSession, SizeOf(tmpHttpHeadSession), 0); HttpBufferHeader_Parser(AResultData, @tmpHttpHeadSession); if (199 < tmpHttpHeadSession.RetCode) and (300 > tmpHttpHeadSession.RetCode)then begin SaveHttpResponseToFile(AResultData, @tmpHttpHeadSession, 'e:\test.html'); tmpParseRec.HtmlParser := THtmlParser.Create; try try tmpParseRec.HtmlDoc := tmpParseRec.HtmlParser.parseString( TDomString(AnsiString(PAnsiChar(@AResultData.Data[tmpHttpHeadSession.HeadEndPos + 1])))); if tmpParseRec.HtmlDoc <> nil then begin Result := HtmlParse_DayData_Sina(ADataAccess, @tmpParseRec, tmpParseRec.HtmlDoc.documentElement); end; except Log('ParserSinaDataError:', ADataAccess.StockItem.sCode + 'error html');// + AnsiString(PAnsiChar(@AResultData.Data[tmpHttpHeadSession.HeadEndPos + 1]))); end; finally FreeAndNil(tmpParseRec.HtmlParser); end; end; end; end.
//FPC 2.6.2 program Helloworld; begin writeln('hello,world!'); end.
unit TTSTSUMTAGTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSTSUMTAGRecord = record PSort: String[30]; PID: Integer; PLilSort: String[20]; PUser: String[40]; PCategory: String[40]; PDate: String[10]; PSubNumber: SmallInt; PDescription: String[25]; PReference: String[25]; PExpireDate: String[10]; PLoanNumber: String[20]; End; TTTSTSUMTAGBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSTSUMTAGRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSTSUMTAG = (TTSTSUMTAGPrimaryKey); TTTSTSUMTAGTable = class( TDBISAMTableAU ) private FDFSort: TStringField; FDFID: TAutoIncField; FDFLilSort: TStringField; FDFUser: TStringField; FDFCategory: TStringField; FDFDate: TStringField; FDFSubNumber: TSmallIntField; FDFDescription: TStringField; FDFReference: TStringField; FDFExpireDate: TStringField; FDFLoanNumber: TStringField; procedure SetPSort(const Value: String); function GetPSort:String; procedure SetPLilSort(const Value: String); function GetPLilSort:String; procedure SetPUser(const Value: String); function GetPUser:String; procedure SetPCategory(const Value: String); function GetPCategory:String; procedure SetPDate(const Value: String); function GetPDate:String; procedure SetPSubNumber(const Value: SmallInt); function GetPSubNumber:SmallInt; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPReference(const Value: String); function GetPReference:String; procedure SetPExpireDate(const Value: String); function GetPExpireDate:String; procedure SetPLoanNumber(const Value: String); function GetPLoanNumber:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSTSUMTAG); function GetEnumIndex: TEITTSTSUMTAG; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSTSUMTAGRecord; procedure StoreDataBuffer(ABuffer:TTTSTSUMTAGRecord); property DFSort: TStringField read FDFSort; property DFID: TAutoIncField read FDFID; property DFLilSort: TStringField read FDFLilSort; property DFUser: TStringField read FDFUser; property DFCategory: TStringField read FDFCategory; property DFDate: TStringField read FDFDate; property DFSubNumber: TSmallIntField read FDFSubNumber; property DFDescription: TStringField read FDFDescription; property DFReference: TStringField read FDFReference; property DFExpireDate: TStringField read FDFExpireDate; property DFLoanNumber: TStringField read FDFLoanNumber; property PSort: String read GetPSort write SetPSort; property PLilSort: String read GetPLilSort write SetPLilSort; property PUser: String read GetPUser write SetPUser; property PCategory: String read GetPCategory write SetPCategory; property PDate: String read GetPDate write SetPDate; property PSubNumber: SmallInt read GetPSubNumber write SetPSubNumber; property PDescription: String read GetPDescription write SetPDescription; property PReference: String read GetPReference write SetPReference; property PExpireDate: String read GetPExpireDate write SetPExpireDate; property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber; published property Active write SetActive; property EnumIndex: TEITTSTSUMTAG read GetEnumIndex write SetEnumIndex; end; { TTTSTSUMTAGTable } procedure Register; implementation function TTTSTSUMTAGTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSTSUMTAGTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSTSUMTAGTable.GenerateNewFieldName } function TTTSTSUMTAGTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSTSUMTAGTable.CreateField } procedure TTTSTSUMTAGTable.CreateFields; begin FDFSort := CreateField( 'Sort' ) as TStringField; FDFID := CreateField( 'ID' ) as TAutoIncField; FDFLilSort := CreateField( 'LilSort' ) as TStringField; FDFUser := CreateField( 'User' ) as TStringField; FDFCategory := CreateField( 'Category' ) as TStringField; FDFDate := CreateField( 'Date' ) as TStringField; FDFSubNumber := CreateField( 'SubNumber' ) as TSmallIntField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFReference := CreateField( 'Reference' ) as TStringField; FDFExpireDate := CreateField( 'ExpireDate' ) as TStringField; FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField; end; { TTTSTSUMTAGTable.CreateFields } procedure TTTSTSUMTAGTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSTSUMTAGTable.SetActive } procedure TTTSTSUMTAGTable.SetPSort(const Value: String); begin DFSort.Value := Value; end; function TTTSTSUMTAGTable.GetPSort:String; begin result := DFSort.Value; end; procedure TTTSTSUMTAGTable.SetPLilSort(const Value: String); begin DFLilSort.Value := Value; end; function TTTSTSUMTAGTable.GetPLilSort:String; begin result := DFLilSort.Value; end; procedure TTTSTSUMTAGTable.SetPUser(const Value: String); begin DFUser.Value := Value; end; function TTTSTSUMTAGTable.GetPUser:String; begin result := DFUser.Value; end; procedure TTTSTSUMTAGTable.SetPCategory(const Value: String); begin DFCategory.Value := Value; end; function TTTSTSUMTAGTable.GetPCategory:String; begin result := DFCategory.Value; end; procedure TTTSTSUMTAGTable.SetPDate(const Value: String); begin DFDate.Value := Value; end; function TTTSTSUMTAGTable.GetPDate:String; begin result := DFDate.Value; end; procedure TTTSTSUMTAGTable.SetPSubNumber(const Value: SmallInt); begin DFSubNumber.Value := Value; end; function TTTSTSUMTAGTable.GetPSubNumber:SmallInt; begin result := DFSubNumber.Value; end; procedure TTTSTSUMTAGTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSTSUMTAGTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSTSUMTAGTable.SetPReference(const Value: String); begin DFReference.Value := Value; end; function TTTSTSUMTAGTable.GetPReference:String; begin result := DFReference.Value; end; procedure TTTSTSUMTAGTable.SetPExpireDate(const Value: String); begin DFExpireDate.Value := Value; end; function TTTSTSUMTAGTable.GetPExpireDate:String; begin result := DFExpireDate.Value; end; procedure TTTSTSUMTAGTable.SetPLoanNumber(const Value: String); begin DFLoanNumber.Value := Value; end; function TTTSTSUMTAGTable.GetPLoanNumber:String; begin result := DFLoanNumber.Value; end; procedure TTTSTSUMTAGTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Sort, String, 30, N'); Add('ID, AutoInc, 0, N'); Add('LilSort, String, 20, N'); Add('User, String, 40, N'); Add('Category, String, 40, N'); Add('Date, String, 10, N'); Add('SubNumber, SmallInt, 0, N'); Add('Description, String, 25, N'); Add('Reference, String, 25, N'); Add('ExpireDate, String, 10, N'); Add('LoanNumber, String, 20, N'); end; end; procedure TTTSTSUMTAGTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Sort;ID, Y, Y, Y, N'); end; end; procedure TTTSTSUMTAGTable.SetEnumIndex(Value: TEITTSTSUMTAG); begin case Value of TTSTSUMTAGPrimaryKey : IndexName := ''; end; end; function TTTSTSUMTAGTable.GetDataBuffer:TTTSTSUMTAGRecord; var buf: TTTSTSUMTAGRecord; begin fillchar(buf, sizeof(buf), 0); buf.PSort := DFSort.Value; buf.PID := DFID.Value; buf.PLilSort := DFLilSort.Value; buf.PUser := DFUser.Value; buf.PCategory := DFCategory.Value; buf.PDate := DFDate.Value; buf.PSubNumber := DFSubNumber.Value; buf.PDescription := DFDescription.Value; buf.PReference := DFReference.Value; buf.PExpireDate := DFExpireDate.Value; buf.PLoanNumber := DFLoanNumber.Value; result := buf; end; procedure TTTSTSUMTAGTable.StoreDataBuffer(ABuffer:TTTSTSUMTAGRecord); begin DFSort.Value := ABuffer.PSort; DFLilSort.Value := ABuffer.PLilSort; DFUser.Value := ABuffer.PUser; DFCategory.Value := ABuffer.PCategory; DFDate.Value := ABuffer.PDate; DFSubNumber.Value := ABuffer.PSubNumber; DFDescription.Value := ABuffer.PDescription; DFReference.Value := ABuffer.PReference; DFExpireDate.Value := ABuffer.PExpireDate; DFLoanNumber.Value := ABuffer.PLoanNumber; end; function TTTSTSUMTAGTable.GetEnumIndex: TEITTSTSUMTAG; var iname : string; begin result := TTSTSUMTAGPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSTSUMTAGPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSTSUMTAGTable, TTTSTSUMTAGBuffer ] ); end; { Register } function TTTSTSUMTAGBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..11] of string = ('SORT','ID','LILSORT','USER','CATEGORY','DATE' ,'SUBNUMBER','DESCRIPTION','REFERENCE','EXPIREDATE','LOANNUMBER' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 11) and (flist[x] <> s) do inc(x); if x <= 11 then result := x else result := 0; end; function TTTSTSUMTAGBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftAutoInc; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftSmallInt; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; end; end; function TTTSTSUMTAGBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PSort; 2 : result := @Data.PID; 3 : result := @Data.PLilSort; 4 : result := @Data.PUser; 5 : result := @Data.PCategory; 6 : result := @Data.PDate; 7 : result := @Data.PSubNumber; 8 : result := @Data.PDescription; 9 : result := @Data.PReference; 10 : result := @Data.PExpireDate; 11 : result := @Data.PLoanNumber; end; end; end.
unit LoanMoneyTask; interface uses Tasks, Kernel, Accounts, CacheAgent, BackupInterfaces, MathUtils; type TMetaLoanMoneyTask = class(TMetaTask) private fLoan : TMoney; public property Loan : TMoney read fLoan write fLoan; end; TLoanMoneyTask = class(TAtomicTask) protected class function GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; override; public function Execute : TTaskResult; override; public procedure StoreToCache(Prefix : string; Cache : TObjectCache); override; end; procedure RegisterBackup; implementation // TLoanMoneyTask class function TLoanMoneyTask.GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; var Tycoon : TTycoon; begin result := inherited GetPriority(MetaTask, SuperTask, Context); if result <> tprIgnoreTask then begin Tycoon:= TTycoon(Context.getContext(tcIdx_Tycoon)); if (Tycoon <> nil) and (Tycoon.LoanAmount >= TMetaLoanMoneyTask(MetaTask).Loan) then result := tprAccomplished; end; end; function TLoanMoneyTask.Execute : TTaskResult; var Tycoon : TTycoon; begin Tycoon:= TTycoon(Context.getContext(tcIdx_Tycoon)); if (Tycoon <> nil) and (Tycoon.LoanAmount >= TMetaLoanMoneyTask(MetaTask).Loan) then result := trFinished else result := trContinue; end; procedure TLoanMoneyTask.StoreToCache(Prefix : string; Cache : TObjectCache); begin inherited; Cache.WriteString(Prefix + 'Loan', FormatMoney(TMetaLoanMoneyTask(MetaTask).Loan)); end; procedure RegisterBackup; begin RegisterClass(TLoanMoneyTask); end; end.
PROGRAM increment; VAR i : integer; BEGIN i := 0; REPEAT writeln('i = ', i); i := i + 1; UNTIL i > 5; writeln('Done!'); END.
// Visual C++'s MFC pulped CMapStringToObj class // Copyright (C) 1996 by Merchise Group [PastelCAD] unit MapStringToObject; interface uses {$ifdef PERSISTENTMAP} Persistent, {$endif} Classes; const HashTableSize = 512; {$ifdef PERSISTENTMAP} {$TYPEINFO ON} {$endif} type TMapMode = (mmUse, mmOwn); TMapStringToObject = {$ifdef PERSISTENTMAP} class(TStreamable) {$else} class(TObject) {$endif} public constructor Create(aMode : TMapMode = mmUse); destructor Destroy; override; {$ifdef PERSISTENTMAP} public constructor Read(Storage : TInput); override; procedure Write(Storage : TOutput); override; {$endif} private HashTable : array[0..pred(HashTableSize)] of TStringList; private fMode : TMapMode; function GetCount : integer; function GetIndexes(pos : integer) : string; function GetItems(index : string) : TObject; procedure SetItems(index : string; Item : TObject); function GetValues(index : string) : string; procedure SetValues(index : string; value : string); public property Mode : TMapMode read fMode; property Count : integer read GetCount; property Indexes[pos : integer] : string read GetIndexes; property Items[index : string] : TObject read GetItems write SetItems; default; property Values[index : string] : string read GetValues write SetValues; public procedure Clear; procedure Remove(index : string); procedure RemoveObject(item : TObject); protected procedure FreeObject(anObject : TObject); virtual; public procedure LoadFromFile( filename : string ); procedure SaveToFile( filename : string ); end; implementation uses {$IFDEF USELogs} SysUtils, Logs; {$ELSE} SysUtils; {$ENDIF} function HashValue(const s : string) : cardinal; var i : integer; begin Result := 0; {$Q-} for i := 1 to length(s) do Result := (Result shl 5) + Result + ord(s[i]); end; constructor TMapStringToObject.Create(aMode : TMapMode); begin inherited Create; fMode := aMode; end; destructor TMapStringToObject.Destroy; begin {$IFDEF USELogs} try Logs.Log( 'Demolition', TimeToStr(Now) + ' - ' + ClassName ); except end; {$ENDIF} Clear; inherited; end; {$ifdef PERSISTENTMAP} constructor TMapStringToObject.Read(Storage : TInput); var cnt : integer; i : integer; name : string; begin inherited; with Storage do begin fMode := TMapMode(ReadOrdValue(sizeof(fMode))); cnt := ReadOrdValue(sizeof(cnt)); for i := 0 to pred(cnt) do begin name := ReadString; Items[name] := ReadObject; end; end; end; procedure TMapStringToObject.Write(Storage : TOutput); var cnt : integer; i : integer; name : string; begin inherited; with Storage do begin cnt := Count; WriteOrdValue(longint(fMode), sizeof(fMode)); WriteOrdValue(cnt, sizeof(cnt)); for i := 0 to pred(cnt) do begin name := Indexes[i]; WriteString(name); WriteObject(Items[name]); end; end; end; {$endif} function TMapStringToObject.GetCount : integer; var i : integer; begin Result := 0; for i := low(HashTable) to high(HashTable) do if HashTable[i] <> nil then inc(Result, HashTable[i].Count); end; function TMapStringToObject.GetIndexes(pos : integer) : string; var i : integer; c : integer; Found : boolean; begin c := 0; i := low(HashTable); Found := false; repeat if HashTable[i] <> nil then if pos < c + HashTable[i].count then Found := true else begin inc(c, HashTable[i].count); inc(i); end else inc(i); until Found or (i > high(HashTable)); if Found then Result := HashTable[i][pos - c] else raise Exception.Create('Index out of bounds'); end; function TMapStringToObject.GetItems(index : string) : TObject; var hash : integer; ndx : integer; begin hash := HashValue(index) mod HashTableSize; if HashTable[hash] <> nil then with HashTable[hash] do begin ndx := IndexOf(index); if ndx >= 0 then Result := Objects[ndx] else Result := nil; end else Result := nil; end; procedure TMapStringToObject.SetItems(index : string; Item : TObject); var hash : integer; begin hash := HashValue(index) mod HashTableSize; if HashTable[hash] = nil then begin HashTable[hash] := TStringList.Create; with HashTable[hash] do begin Sorted := true; Duplicates := dupError; end; end; HashTable[hash].AddObject(index, Item); end; function TMapStringToObject.GetValues(index : string) : string; var hash : integer; begin hash := HashValue(index) mod HashTableSize; if HashTable[hash] <> nil then result := HashTable[hash].Values[index] else Result := ''; end; procedure TMapStringToObject.SetValues(index : string; value : string); var hash : integer; begin hash := HashValue(index) mod HashTableSize; if HashTable[hash] = nil then begin HashTable[hash] := TStringList.Create; with HashTable[hash] do begin Sorted := true; Duplicates := dupError; end; end; HashTable[hash].Values[index] := value; end; procedure TMapStringToObject.Clear; procedure FreeList(var aList : TStringList); var i : integer; begin if aList <> nil then begin for i := 0 to pred(aList.Count) do FreeObject(aList.Objects[i]); aList.Free; aList := nil; end; end; var i : integer; begin if fMode = mmUse then for i := low(HashTable) to high(HashTable) do begin HashTable[i].Free; HashTable[i] := nil; end else for i := low(HashTable) to high(HashTable) do FreeList(HashTable[i]); end; procedure TMapStringToObject.Remove(index : string); var hash : integer; ndx : integer; begin hash := HashValue(index) mod HashTableSize; if HashTable[hash] <> nil then with HashTable[hash] do begin ndx := IndexOf(index); if ndx >= 0 then begin if fMode = mmOwn then FreeObject(Objects[ndx]); Delete(ndx); end; end; end; procedure TMapStringToObject.RemoveObject(item : TObject); var ndx : integer; i : integer; begin i := low(HashTable); ndx := -1; repeat if HashTable[i] <> nil then begin ndx := HashTable[i].IndexOfObject(item); if ndx < 0 then inc(i); end else inc(i); until (i > high(HashTable)) or (ndx >=0); if ndx >= 0 then with HashTable[i] do begin if fMode = mmOwn then FreeObject(Objects[ndx]); Delete(ndx); end; end; procedure TMapStringToObject.FreeObject(anObject : TObject); begin anObject.Free; end; procedure TMapStringToObject.LoadFromFile( filename : string ); begin end; { var Lines : TStringList; i : integer; begin Lines := TStringList.Create; try Lines.LoadFromFile( filename ); for i := 0 to pred(Lines.Count) do Lines.V Values[ except Lines.Free; end; end; } procedure TMapStringToObject.SaveToFile( filename : string ); begin end; initialization {$ifdef PERSISTENTMAP} TMapStringToObject.Register; {$endif} end.
unit uCommon; interface uses Classes, AdvObj, BaseGrid, AdvGrid, SysUtils, Forms, fuDim, HTMListB, uMT2Classes; function IsValidInt(StringIn : String) : boolean; function IndexFromValues(StringList : TStrings;ValueIn : String) : integer; function PhoneDataToString(PhoneDataIn : String) : String; procedure ClearGrid(GridIn : TADVStringGrid; RowStartIn, RowCountIN : integer); function GetGUIDName : String; function GetShipMethodsByMember(MemberNbr : String; SiteID : integer) : TStringList; function ExtractRecipNameFromEmailAddress(EmailIn : String) : String; procedure ShowDimForm(CallingForm : TCustomForm); procedure HideDimForm; function GetCharsBeforeTab(StringIn : String) : String; function FindIndexOfPlainTextInHTMList(ListIn : THTMListBox ;PlainText : String) : integer; function IsPossibleItem(ItemIn : String) : boolean; function GetStatusName(StatusID : integer) : String; function GetPriorityName(PriorityID : integer) : String; function GetListIndexFromIntegerAsObject(ListIn : TStringList; IDIn : integer) : integer; function GetCategoryName(CtgyID : integer) : String; function GetCategoryIDFromName(CtgyName : String) : integer; function GetCategoryFromCtgyID(CtgyID : integer) : TCategory; implementation uses duMT2, uMT2GlobalVar; function IndexFromValues(StringList : TStrings; ValueIn : String) : integer; var i : integer; begin Result:= -1; for i:= 0 to Pred(StringList.Count) do if StringList.ValueFromIndex[i] = ValueIn then begin Result:= i; break; end; end; function IsValidInt(StringIn : String) : boolean; var i : integer; begin Result:= True; for i:= 1 to Length(StringIn) do if not (StringIn[i] IN ['0','1','2','3','4','5','6','7','8','9']) then begin Result:= false; break; end; end; function PhoneDataToString(PhoneDataIn : String) : String; begin // this takes a sold string of numbers and returns a formatted display for phones Result:= Copy(PhoneDataIn,1,10); //sometime the string includes an extention which we don't want if length(Result) = 10 then //contains an area cod begin Insert('(',Result,1); Insert(') ',Result,5); Insert(' ',Result,10); end else // no area code so just add the space Insert(' ',Result,4); end; procedure ClearGrid(GridIn : TADVStringGrid; RowStartIn, RowCountIn : integer); var x, y : integer; begin With GridIn do begin for x:= 0 to Pred(ColCOunt) do for y:= RowStartIn to RowCount do Cells[x,y]:= ''; RowCount:= RowCOuntIn; end; end; function GetGUIDName : String; var Guid : TGuid; begin CreateGUID(guid); Result:= GUIDToString(Guid); Result:= StringReplace(Result,'-','',[rfReplaceAll]); Result:= StringReplace(Result,'{','',[rfReplaceAll]); Result:= StringReplace(Result,'}','',[rfReplaceAll]); end; function GetShipMethodsByMember(MemberNbr : String; SiteID : integer) : TStringList; var sShipVia : String; begin WIth dmMT2.fqSelect do try Active:= false; SQL.Text:= 'SELECT a.carrier_id,a.shipvia,b.sequence'; SQL.Add('FROM [ASCTrac].dbo.CARRIERACCT a'); SQL.Add('LEFT OUTER JOIN [ASCTrac].dbo.RTCUSTS b ON(a.shipvia = b.routeid AND b.customerid=:cnbr)'); SQL.Add('WHERE entity_id = :cnbr'); Params[0].AsString:= MemberNbr + '-MAIN'; Active:= true; Result:= TStringList.Create; if RecordCount > 0 then begin sShipVia:= '<font face="segoe ui" size="10" color="clGray">Carrier </font><font face="segoe ui" size="12" color="clBlack">' + Fields[0].AsString + '</font>'; sShipVia:= sShipVia + '<font face="segoe ui" size="10" color="clGray"> Route </font><font face="segoe ui" size="12" color="clBlack">' + Fields[1].AsString + '</font>'; if FIelds[2].AsString <> '' then sShipVia:= sShipVia + '<font face="segoe ui" size="10" color="clGray"> Stop </font><font face="segoe ui" size="12" color="clBlack">' + Fields[2].AsString + '</font>'; Result.Add(sShipVia); end; finally Active:= false; end; end; function ExtractRecipNameFromEmailAddress(EmailIn : String) : String; var iPos : integer; begin iPos:= POS('@',EMailIn); if iPos > 0 then Result:= Copy(EmailIn,1,iPos -1) else Result:= emailin; end; procedure ShowDimForm(CallingForm : TCustomForm); begin frmDim.Width:= CallingForm.Width; frmDim.Height:= CallingForm.Height; frmDim.left:= CallingForm.Left; frmDim.top:= CallingForm.top; frmDim.Show; end; procedure HideDimForm; begin frmDim.Hide; end; function GetCharsBeforeTab(StringIn : String ) : String; var iPos : integer; begin iPOS:= POS(#9,StringIn); if iPos > 0 then Result:= Copy(StringIn,1,iPos-1) else Result:= StringIn; end; function FindIndexOfPlainTextInHTMList(ListIn : THTMListBox ;PlainText : String) : integer; var iInc : integer; begin Result:= -1; for iInc:= 0 to Pred(ListIn.COunt) do if ListIn.TextItems[iInc] = PlainText then begin result:= iInc; break; end; end; function IsPossibleItem(ItemIn : String) : boolean; begin Result:= Length(ItemIn) = 6; if Result then Result:= IsValidInt(ItemIn); end; function GetStatusName(StatusID : integer) : String; begin case StatusID of 0: Result:= 'New'; 1: Result:= 'In Progress'; 2: Result:= 'On Hold'; 3: Result:= 'Wating for Client'; 4: Result:= 'Complete'; end; end; function GetPriorityName(PriorityID : integer) : String; begin case PriorityID of 0: Result:= 'Low'; 1: Result:= 'Medium'; 2: Result:= 'High'; 3: Result:= 'Critical'; end; end; function GetListIndexFromIntegerAsObject(ListIn : TStringList; IDIn : integer) : integer; var iDx : integer; I: Integer; begin Result:= -1; //assumes no match by default With ListIn do for iDx := 0 to Pred(Count) do if IDIn = Integer(ListIn.Objects[iDx]) then begin Result:= iDx; Break; end; end; function GetCategoryName(CtgyID : integer) : String; var iDx : integer; MyCategory : TCategory; begin Result:= ''; With stlGV_AllCtgy do for iDx:= 0 to PRed(Count) do begin MyCategory:= TCategory(Objects[iDx]); if CtgyID = MyCategory.CtgyID then begin Result:= stlGV_AllCtgy[iDx]; Break; end; end; end; function GetCategoryIDFromName(CtgyName : String) : Integer; var iDx : integer; MyCategory : TCategory; begin Result:= 0; With stlGV_AllCtgy do for iDx:= 0 to PRed(Count) do if CtgyNAme = Strings[iDx] then begin MyCategory:= TCategory(stlGV_AllCtgy.Objects[iDx]); Result:= MyCategory.CtgyID; Break; end; end; function GetCategoryFromCtgyID(CtgyID : integer) : TCategory; var iDx : integer; MyCategory : TCategory; begin Result:= nil; With stlGV_AllCtgy do for iDx:= 0 to PRed(Count) do begin MyCategory:= TCategory(Objects[iDx]); if CtgyID = MyCategory.CtgyID then begin Result:= MyCategory; Break; end; end; end; end.
{*********************************************************} {* VPDATA.PAS 1.03 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* *} {* ***** END LICENSE BLOCK ***** *} {$I vp.inc} unit VpData; { Data classes for Visual PlanIt's resources, events, tasks, contacts, etc... } interface uses {$IFDEF LCL} LMessages,LCLProc,LCLType, {$ELSE} Windows, {$ENDIF} SysUtils, Classes, {$IFDEF VERSION6} Types, {$ENDIF} VpBase, VpSR, VpConst, Dialogs; type TVpEventRec = packed record Rec : TRect; IconRect : TRect; Event : Pointer; end; type TVpEventArray = array of TVpEventRec; TVpAlarmAdvType = (atMinutes, atHours, atDays); TVpRepeatType = (rtNone=0, rtDaily, rtWeekly, rtMonthlyByDay, rtMonthlyByDate, rtYearlyByDay, rtYearlyByDate, rtCustom); TVpContactSort = (csLastFirst, csFirstLast); { forward declarations } TVpResource = class; TVpTasks = class; TVpSchedule = class; TVpEvent = class; TVpContacts = class; TVpContact = class; TVpTask = class; TVpResources = class protected{private} FOwner: TObject; FResourceList: TList; function Compare(Descr1, Descr2: string): Integer; function GetItem(Index: Int64): TVpResource; function GetCount: Integer; function NextResourceID: Int64; public constructor Create(Owner: TObject); destructor Destroy; override; function AddResource(ResID: Int64): TVpResource; function FindResourceByName (AName : string) : TVpResource; function GetResource(ID: Integer): TVpResource; procedure ClearResources; procedure RemoveResource(Resource: TVpResource); procedure Sort; property Count: Integer read GetCount; property Items[Index: Int64]: TVpResource read GetItem; property Owner: TObject read FOwner; end; TVpResource = class protected{private} FLoading : Boolean; FOwner: TVpResources; FActive: Boolean; { Internal flag used to determine whether to display } { this resource } FItemIndex: integer; FChanged: Boolean; FDeleted: Boolean; FEventsDirty: Boolean; FContactsDirty: Boolean; FTasksDirty: Boolean; FSchedule: TVpSchedule; FTasks: TVpTasks; FNotes: string; FDescription: string; { reserved for your use } FUserField0: string; FUserField1: string; FUserField2: string; FUserField3: string; FUserField4: string; FUserField5: string; FUserField6: string; FUserField7: string; FUserField8: string; FUserField9: string; FResourceID: Integer; FContacts: TVpContacts; function GetSchedule: TVpSchedule; procedure SetChanged(Value: Boolean); procedure SetDeleted(Value: Boolean); procedure SetDescription(const Value: string); procedure SetResourceID(const Value: Integer); procedure SetSchedule(const Value: TVpSchedule); procedure SetTasks(const Value: TVpTasks); procedure SetNotes(const Value: string); procedure SetContacts(const Value: TVpContacts); public constructor Create(Owner: TVpResources); destructor Destroy; override; property Loading: Boolean read FLoading write FLoading; property Changed: Boolean read FChanged write SetChanged; property Deleted: Boolean read FDeleted write SetDeleted; property EventsDirty: Boolean read FEventsDirty write FEventsDirty; property ContactsDirty: Boolean read FContactsDirty write FContactsDirty; property TasksDirty: Boolean read FTasksDirty write FTasksDirty; property Active: Boolean read FActive write FActive; property Owner: TVpResources read FOwner; property ItemIndex: integer read FItemIndex; property Notes: string read FNotes write SetNotes; property ResourceID: Integer read FResourceID write SetResourceID; property Description: string read FDescription write SetDescription; property Schedule: TVpSchedule read GetSchedule write SetSchedule; property Tasks: TVpTasks read FTasks write SetTasks; property Contacts: TVpContacts read FContacts write SetContacts; { Reserved for your use } property UserField0: string read FUserField0 write FUserField0; property UserField1: string read FUserField1 write FUserField1; property UserField2: string read FUserField2 write FUserField2; property UserField3: string read FUserField3 write FUserField3; property UserField4: string read FUserField4 write FUserField4; property UserField5: string read FUserField5 write FUserField5; property UserField6: string read FUserField6 write FUserField6; property UserField7: string read FUserField7 write FUserField7; property UserField8: string read FUserField8 write FUserField8; property UserField9: string read FUserField9 write FUserField9; end; TVpSchedule = class protected{private} FOwner : TVpResource; FEventList: TList; FBatchUpdate: Integer; function Compare(Time1, Time2: TDateTime): Integer; function FindTimeSlot(StartTime, EndTime: TDateTime): Boolean; function GetCount: Integer; public constructor Create(Owner: TVpResource); destructor Destroy; override; function AddEvent(RecordID: Int64; StartTime, EndTime: TDateTime): TVpEvent; procedure DeleteEvent(Event: TVpEvent); function GetEvent(Index: Int64): TVpEvent; function RepeatsOn(Event: TVpEvent; Day: TDateTime): Boolean; procedure Sort; procedure ClearEvents; procedure BatchUpdate(Value: Boolean); function EventCountByDay(Value: TDateTime): Integer; procedure EventsByDate(Date: TDateTime; EventList: TList); procedure AllDayEventsByDate(Date: TDateTime; EventList: TList); property Owner: TVpResource read FOwner; property EventCount: Integer read GetCount; end; { TVpEvent } TVpEvent = class private FLocation: string; protected{private} FOwner: TVpSchedule; FItemIndex: Integer; FChanged: Boolean; FDeleted: Boolean; FLoading: Boolean; FPrivateEvent: Boolean; FAlarmSet: Boolean; FDingPath: string; FAllDayEvent: Boolean; FCategory: Integer; FAlarmAdv: Integer; FAlertDisplayed: Boolean; FAlarmAdvType: TVpAlarmAdvType; FRecordID: Int64; FNote: string; FDescription: string; FStartTime: TDateTime; FEndTime: TDateTime; FSnoozeTime: TDateTime; FRepeatCode: TVpRepeatType; FRepeatRangeEnd: TDateTime; FCustInterval: Integer; { reserved for your use } FUserField0: string; FUserField1: string; FUserField2: string; FUserField3: string; FUserField4: string; FUserField5: string; FUserField6: string; FUserField7: string; FUserField8: string; FUserField9: string; procedure SetAllDayEvent(Value: Boolean); procedure SetItemIndex(Value: Integer); procedure SetChanged(Value: Boolean); procedure SetDeleted(Value: Boolean); procedure SetDingPath(Value: string); procedure SetAlarmAdv(Value: Integer); procedure SetAlarmAdvType(Value: TVpAlarmAdvType); procedure SetSnoozeTime(Value: TDateTime); procedure SetAlarmSet(Value: Boolean); procedure SetCategory(Value: Integer); procedure SetDescription(const Value: string); procedure SetEndTime(Value: TDateTime); procedure SetNote(const Value: string); procedure SetRecordID(Value: Int64); procedure SetStartTime(Value: TDateTime); procedure SetCustInterval(Value: Integer); procedure SetRepeatCode(Value: TVpRepeatType); procedure SetRepeatRangeEnd(Value: TDateTime); public constructor Create(Owner: TVpSchedule); destructor Destroy; override; property AlarmWavPath: string read FDingPath write SetDingPath; property AlertDisplayed: Boolean read FAlertDisplayed write FAlertDisplayed; property AllDayEvent: Boolean read FAllDayEvent write SetAllDayEvent; property Changed: Boolean read FChanged write SetChanged; property Deleted: Boolean read FDeleted write SetDeleted; property ItemIndex: Integer read FItemIndex; property RecordID : Int64 read FRecordID write SetRecordID; property StartTime : TDateTime read FStartTime write SetStartTime; property EndTime : TDateTime read FEndTime write SetEndTime; property Description : string read FDescription write SetDescription; property Note : string read FNote write SetNote; property Category : Integer read FCategory write SetCategory; property AlarmSet : Boolean read FAlarmSet write SetAlarmSet; property AlarmAdv : Integer read FAlarmAdv write SetAlarmAdv; property Loading : Boolean read FLoading write FLoading; { 0=Minutes, 1=Hours, 2=Days } property AlarmAdvType : TVpAlarmAdvType read FAlarmAdvType write SetAlarmAdvType; property SnoozeTime : TDateTime read FSnoozeTime write SetSnoozeTime; { rtNone, rtDaily, rtWeekly, rtMonthlyByDay, rtMonthlyByDate, } { rtYearlyByDay, rtYearlyByDate, rtCustom } property RepeatCode : TVpRepeatType read FRepeatCode write SetRepeatCode; property RepeatRangeEnd: TDateTime read FRepeatRangeEnd write SetRepeatRangeEnd; { Custom Repeat Interval in seconds } { is Zero if IntervalCode <> 7 } property CustInterval : Integer read FCustInterval write SetCustInterval; property Owner: TVpSchedule read FOwner; property Location: string read FLocation write FLocation; { Reserved for your use } property UserField0: string read FUserField0 write FUserField0; property UserField1: string read FUserField1 write FUserField1; property UserField2: string read FUserField2 write FUserField2; property UserField3: string read FUserField3 write FUserField3; property UserField4: string read FUserField4 write FUserField4; property UserField5: string read FUserField5 write FUserField5; property UserField6: string read FUserField6 write FUserField6; property UserField7: string read FUserField7 write FUserField7; property UserField8: string read FUserField8 write FUserField8; property UserField9: string read FUserField9 write FUserField9; end; TVpTasks = class protected{private} FOwner: TVpResource; FTaskList: TList; FBatchUpdate: Integer; public constructor Create(Owner: TVpResource); destructor Destroy; override; procedure BatchUpdate(value: Boolean); procedure Sort; function Compare(Item1, Item2: TVpTask): Integer; function AddTask(RecordID: Int64): TVpTask; function Count : Integer; function CountByDay(Date: TDateTime): Integer; function Last: TVpTask; function LastByDay(Date: TDateTime): TVpTask; function First: TVpTask; function FirstByDay(Date: TDateTime): TVpTask; procedure DeleteTask(Task: TVpTask); function GetTask(Index: Integer): TVpTask; procedure ClearTasks; property Owner: TVpREsource read FOwner; end; TVpTask = class protected{private} FLoading: Boolean; FOwner: TVpTasks; FChanged: Boolean; FDeleted: Boolean; FItemIndex: Integer; FPriority: Integer; FCategory: Integer; FComplete: Boolean; FDescription: string; FDetails: string; FCreatedOn: TDateTime; FCompletedOn: TDateTIme; FRecordID: Integer; FDueDate: TDateTime; { reserved for your use } FUserField0: string; FUserField1: string; FUserField2: string; FUserField3: string; FUserField4: string; FUserField5: string; FUserField6: string; FUserField7: string; FUserField8: string; FUserField9: string; procedure SetCategory(const Value: Integer); procedure SetChanged(const Value: Boolean); procedure SetComplete(const Value: Boolean); procedure SetCompletedOn(const Value: TDateTime); procedure SetCreatedOn(const Value: TDateTime); procedure SetDescription(const Value: string); procedure SetDetails(const Value: string); procedure SetDueDate(const Value: TDateTime); procedure SetPriority(const Value: Integer); function IsOverdue: Boolean; public constructor Create(Owner: TVpTasks); destructor Destroy; override; property Loading: Boolean read FLoading write FLoading; property Changed: Boolean read FChanged write SetChanged; property Deleted: Boolean read FDeleted write FDeleted; property DueDate: TDateTime read FDueDate write SetDueDate; property Description: string read FDescription write SetDescription; property ItemIndex: Integer read FItemIndex; property Details: string read FDetails write SetDetails; property Complete: Boolean read FComplete write SetComplete; property RecordID: Integer read FRecordID write FRecordID; property CreatedOn: TDateTime read FCreatedOn write SetCreatedOn; property CompletedOn: TDateTIme read FCompletedOn write SetCompletedOn; property Owner: TVpTasks read FOwner; { Not implemented yet } property Priority: Integer read FPriority write SetPriority; property Category: Integer read FCategory write SetCategory; { Reserved for your use } property UserField0: string read FUserField0 write FUserField0; property UserField1: string read FUserField1 write FUserField1; property UserField2: string read FUserField2 write FUserField2; property UserField3: string read FUserField3 write FUserField3; property UserField4: string read FUserField4 write FUserField4; property UserField5: string read FUserField5 write FUserField5; property UserField6: string read FUserField6 write FUserField6; property UserField7: string read FUserField7 write FUserField7; property UserField8: string read FUserField8 write FUserField8; property UserField9: string read FUserField9 write FUserField9; end; TVpContacts = class protected FOwner : TVpResource; FContactsList : TList; FBatchUpdate : Integer; FContactSort : TVpContactSort; function Compare(Item1, Item2: TVpContact): Integer; procedure SetContactSort (const v : TVpContactSort); public constructor Create(Owner: TVpResource); destructor Destroy; override; procedure BatchUpdate(Value: Boolean); function Count: Integer; function Last:TVpContact; function First: TVpContact; procedure Sort; function AddContact(RecordID: Integer): TVpContact; procedure DeleteContact(Contact: TVpContact); function GetContact(Index: Integer): TVpContact; procedure ClearContacts; { new functions introduced to support the new buttonbar component } function FindContactByName(const Name: string; CaseInsensitive: Boolean = True): TVpContact; function FindContactIndexByName(const Name: string; CaseInsensitive: Boolean = True): Integer; property ContactsList: TList read FContactsList; property ContactSort : TVpContactSort read FContactSort write SetContactSort default csLastFirst; end; TVpContact = class protected{private} FLoading : Boolean; FOwner : TVpContacts; FChanged : Boolean; FItemIndex : Integer; FRecordID : Integer; FDeleted : Boolean; FPosition : string; FLastName : string; FFirstName : string; FBirthDate : TDateTime; FAnniversary : TDateTime; FTitle : string; FCompany : string; FEmail : string; FPhone1 : string; FPhone2 : string; FPhone3 : string; FPhone4 : string; FPhone5 : string; FPhoneType1 : integer; FPhoneType2 : integer; FPhoneType3 : integer; FPhoneType4 : integer; FPhoneType5 : integer; FAddress : string; FCity : string; FState : string; FZip : string; FCountry : string; FNote : string; FPrivateRec : boolean; FCategory : integer; FCustom1 : string; FCustom2 : string; FCustom3 : string; FCustom4 : string; { reserved for your use } FUserField0 : string; FUserField1 : string; FUserField2 : string; FUserField3 : string; FUserField4 : string; FUserField5 : string; FUserField6 : string; FUserField7 : string; FUserField8 : string; FUserField9 : string; procedure SetAddress(const Value: string); procedure SetBirthDate(Value: TDateTime); procedure SetAnniversary(Value: TDateTime); procedure SetCategory( Value: integer); procedure SetChanged(Value: Boolean); procedure SetCity(const Value: string); procedure SetCompany(const Value: string); procedure SetCountry(const Value: string); procedure SetCustom1(const Value: string); procedure SetCustom2(const Value: string); procedure SetCustom3(const Value: string); procedure SetCustom4(const Value: string); procedure SetDeleted(Value: Boolean); procedure SetEMail(const Value: string); procedure SetFirstName(const Value: string); procedure SetLastName(const Value: string); procedure SetNote(const Value: string); procedure SetPhone1(const Value: string); procedure SetPhone2(const Value: string); procedure SetPhone3(const Value: string); procedure SetPhone4(const Value: string); procedure SetPhone5(const Value: string); procedure SetPhoneType1(Value: integer); procedure SetPhoneType2(Value: integer); procedure SetPhoneType3(Value: integer); procedure SetPhoneType4(Value: integer); procedure SetPhoneType5(Value: integer); procedure SetPosition(const Value: string); procedure SetRecordID(Value: Integer); procedure SetState(const Value: string); procedure SetTitle(const Value: string); procedure SetZip(const Value: string); public constructor Create(Owner: TVpContacts); destructor Destroy; override; function FullName : string; property Loading : Boolean read FLoading write FLoading; property Changed : Boolean read FChanged write SetChanged; property Deleted : Boolean read FDeleted write SetDeleted; property RecordID : Integer read FRecordID write SetRecordID; property Position : string read FPosition write SetPosition; property FirstName : string read FFirstName write SetFirstName; property LastName : string read FLastName write SetLastName; property BirthDate : TDateTime read FBirthdate write SetBirthdate; property Anniversary : TDateTime read FAnniversary write SetAnniversary; property Title : string read FTitle write SetTitle; property Company : string read FCompany write SetCompany; property EMail : string read FEmail write SetEMail; property Phone1 : string read FPhone1 write SetPhone1; property Phone2 : string read FPhone2 write SetPhone2; property Phone3 : string read FPhone3 write SetPhone3; property Phone4 : string read FPhone4 write SetPhone4; property Phone5 : string read FPhone5 write SetPhone5; property PhoneType1 : integer read FPhoneType1 write SetPhoneType1; property PhoneType2 : integer read FPhoneType2 write SetPhoneType2; property PhoneType3 : integer read FPhoneType3 write SetPhoneType3; property PhoneType4 : integer read FPhoneType4 write SetPhoneType4; property PhoneType5 : integer read FPhoneType5 write SetPhoneType5; property Address : string read FAddress write SetAddress; property City : string read FCity write SetCity; property State : string read FState write SetState; property Zip : string read FZip write SetZip; property Country : string read FCountry write SetCountry; property Note : string read FNote write SetNote; property Category : integer read FCategory write SetCategory; property Custom1 : string read FCustom1 write SetCustom1; property Custom2 : string read FCustom2 write SetCustom2; property Custom3 : string read FCustom3 write SetCustom3; property Custom4 : string read FCustom4 write SetCustom4; property Owner : TVpContacts read FOwner write FOwner; { Reserved for your use } property UserField0 : string read FUserField0 write FUserField0; property UserField1 : string read FUserField1 write FUserField1; property UserField2 : string read FUserField2 write FUserField2; property UserField3 : string read FUserField3 write FUserField3; property UserField4 : string read FUserField4 write FUserField4; property UserField5 : string read FUserField5 write FUserField5; property UserField6 : string read FUserField6 write FUserField6; property UserField7 : string read FUserField7 write FUserField7; property UserField8 : string read FUserField8 write FUserField8; property UserField9 : string read FUserField9 write FUserField9; end; implementation uses VpException, VpMisc; { TVpResources } (*****************************************************************************) constructor TVpResources.Create(Owner: TObject); begin inherited Create; FOwner := Owner; FResourceList := TList.Create; end; {=====} destructor TVpResources.Destroy; begin ClearResources; FResourceList.Free; inherited; end; {=====} function TVpResources.GetItem(Index: Int64): TVpResource; begin result := TVpResource(FResourceList.List^[Index]); end; {=====} function TVpResources.GetCount: Integer; begin result := FResourceList.Count; end; {=====} function TVpResources.NextResourceID: Int64; var I : Integer; ID: Int64; Res: TVpResource; begin ID := 0; for I := 0 to pred(FResourceList.Count) do begin Res := GetResource(I); if (Res <> nil) and (ID <= Res.ResourceID) then Inc(ID); end; result := ID; end; {=====} function TVpResources.AddResource(ResID: Int64): TVpResource; var Resource : TVpResource; begin Resource := TVpResource.Create(Self); try Resource.Loading := true; Resource.FItemIndex := FResourceList.Add(Resource); Resource.ResourceID := ResID; Resource.Active := true; Resource.Loading := false; result := Resource; except Resource.Free; raise EFailToCreateResource.Create; end; end; {=====} function TVpResources.FindResourceByName (AName : string) : TVpResource; var i : Integer; begin Result := nil; AName := LowerCase (AName); for i := 0 to Count - 1 do if LowerCase (Items[i].Description) = AName then begin Result := Items[i]; Break; end; end; {=====} function TVpResources.GetResource(ID: integer): TVpResource; var I: Integer; Res: TVpResource; begin result := nil; for I := 0 to pred(FResourceList.Count) do begin res := FResourceList.Items[I]; if Res.ResourceID = ID then begin result := Res; Exit; end; end; end; {=====} procedure TVpResources.ClearResources; begin while FResourceList.Count > 0 do TVpResource(FResourceList.Last).Free; end; {=====} procedure TVpResources.RemoveResource(Resource: TVpREsource); begin { The resource removes the list entry in its destructor } Resource.Free; end; {=====} procedure TVpResources.Sort; var i, j : integer; IndexOfMin : integer; Temp : pointer; CompResult : integer; {Comparison Result} begin for i := 0 to pred(FResourceList.Count) do begin IndexOfMin := i; for j := i to FResourceList.Count - 1 do begin { compare description item[j] and item[i] } CompResult := Compare(TVpResource(FResourceList.List^[j]).Description, TVpResource(FResourceList.List^[IndexOfMin]).Description); { if the description of j is less than the description of i then flip 'em} if CompResult < 0 then IndexOfMin := j; end; Temp := FResourceList.List^[i]; FResourceList.List^[i] := FResourceList.List^[IndexOfMin]; FResourceList.List^[IndexOfMin] := Temp; end; { Fix object embedded ItemIndexes } for i := 0 to pred(FResourceList.Count) do begin TVpResource(FResourceList.List^[i]).FItemIndex := i; end; end; {=====} { Used in the above sort procedure. Compares the descriptions of the two } { passed in events. } function TVpResources.Compare(Descr1, Descr2: string): Integer; begin { Compares the value of the Item descriptions } if Descr1 < Descr2 then result := -1 else if Descr1 = Descr2 then result := 0 else {Descr2 is less than Descr1} result := 1; end; {=====} { TVpResource } (*****************************************************************************) constructor TVpResource.Create(Owner: TVpResources); begin inherited Create; FOwner := Owner; FSchedule := TVpSchedule.Create(Self); FTasks := TVpTasks.Create(Self); FContacts := TVpContacts.Create(Self); FItemIndex := -1; FActive := false; end; {=====} destructor TVpResource.Destroy; begin { Clear and free the schedule, tasks and contacts } FSchedule.ClearEvents; FSchedule.Free; FTasks.ClearTasks; FTasks.Free; FContacts.ClearContacts; FContacts.Free; { remove self from Resources list } if (FItemIndex > -1) and (FOwner <> nil) then FOwner.FResourceList.Delete(FItemIndex); inherited; end; {=====} procedure TVpResource.SetContacts(const Value: TVpContacts); begin FContacts := Value; end; {=====} procedure TVpResource.SetChanged(Value: Boolean); begin if Loading then Exit; if Value <> FChanged then begin FChanged := Value; end; end; {=====} procedure TVpResource.SetDeleted(Value: Boolean); begin if FDeleted <> Value then begin FDeleted := Value; Changed := true; end; end; {=====} function TVpResource.GetSchedule: TVpSchedule; begin if FSchedule = nil then FSchedule := TVpSchedule.Create(self); result := FSchedule; end; {=====} procedure TVpResource.SetDescription(const Value: string); begin if Value <> FDescription then begin if Assigned (Owner) then begin if Owner.FindResourceByName (Value) <> nil then raise EDuplicateResource.Create; end; FDescription := Value; FChanged := true; end; end; {=====} procedure TVpResource.SetNotes(const Value: string); begin FNotes := Value; FChanged := true; end; procedure TVpResource.SetResourceID(const Value: Integer); begin FResourceID := Value; end; {=====} procedure TVpResource.SetSchedule(const Value: TVpSchedule); begin FSchedule := Value; end; {=====} procedure TVpResource.SetTasks(const Value: TVpTasks); begin FTasks := Value; end; {=====} { TVpEvent } (*****************************************************************************) constructor TVpEvent.Create(Owner: TVpSchedule); begin inherited Create; FAlertDisplayed := false; FOwner := Owner; FChanged := false; FItemIndex := -1; FSnoozeTime := 0.0; end; {=====} destructor TVpEvent.Destroy; begin if (FOwner <> nil) and (FItemIndex <> -1) then begin FOwner.FEventList.Delete(FItemIndex); FOwner.Sort; end; inherited; end; {=====} procedure TVpEvent.SetAlarmAdv(Value: Integer); begin if Value <> FAlarmAdv then begin FAlarmAdv := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetAlarmAdvType(Value: TVpAlarmAdvType); begin if Value <> FAlarmAdvType then begin FAlarmAdvType := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetSnoozeTime(Value: TDateTime); begin if Value <> FSnoozeTime then begin FSnoozeTime := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetAlarmSet(Value: Boolean); begin if Value <> FAlarmSet then begin FAlarmSet := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetCategory(Value: Integer); begin if Value <> FCategory then begin FCategory := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetDescription(const Value: string); begin if Value <> FDescription then begin FDescription := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetEndTime(Value: TDateTime); begin if Value <> FEndTIme then begin FEndTime := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetAllDayEvent(Value: Boolean); begin if Value <> FAllDayEvent then begin FAllDayEvent := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetItemIndex(Value: Integer); begin if Value <> FItemIndex then begin FItemIndex := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetChanged(Value: Boolean); begin if Loading then Exit; if Value <> FChanged then begin FChanged := Value; if FChanged then Owner.FOwner.EventsDirty := true; end; end; {=====} procedure TVpEvent.SetDeleted(Value: Boolean); begin if Value <> FDeleted then begin FDeleted := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetDingPath(Value: string); begin if Value <> FDingPath then begin FDingPath := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetNote(const Value: string); begin if Value <> FNote then begin FNote := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetRecordID(Value: Int64); begin if Value <> FRecordID then begin FRecordID := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetRepeatCode(Value: TVpRepeatType); begin { rtNone, rtDaily, rtWeekly, rtMonthlyByDay, rtMonthlyByDate, } { rtYearlyByDay, rtYearlyByDate, rtCustom } if Value <> FRepeatCode then begin FRepeatCode := Value; if value <> rtCustom then SetCustInterval(0); Changed := true; end; end; {=====} procedure TVpEvent.SetRepeatRangeEnd(Value: TDateTime); begin if Value > StartTime then begin FRepeatRangeEnd := Value; Changed := true; end; end; {=====} procedure TVpEvent.SetCustInterval(Value: Integer); begin if Value <> FCustInterval then begin if RepeatCode = rtCustom then FCustInterval := Value else FCustInterval := 0; Changed := true; end; end; {=====} procedure TVpEvent.SetStartTime(Value: TDateTime); begin if Value <> FStartTIme then begin FStartTime := Value; Changed := true; end; end; {=====} { TVpSchedule } (*****************************************************************************) constructor TVpSchedule.Create(Owner: TVpResource); begin inherited Create; FOwner := Owner; FBatchUpdate := 0; FEventList := TList.Create; end; {=====} destructor TVpSchedule.Destroy; begin ClearEvents; FEventList.Free; inherited; end; {=====} procedure TVpSchedule.Sort; var i, j : integer; IndexOfMin : integer; Temp : pointer; CompResult : integer; {Comparison Result} begin { WARNING!! The DayView component is heavily dependent upon the events } { being properly sorted. If you change the way this procedure works, } { you WILL break the DayView component!!! } { for greater performance, we don't sort while doing batch updates. } if FBatchUpdate > 0 then exit; for i := 0 to pred(FEventList.Count) do begin IndexOfMin := i; for j := i to FEventList.Count - 1 do begin { compare start times of item[j] and item[i] } CompResult := Compare(TVpEvent(FEventList.List^[j]).StartTime, TVpEvent(FEventList.List^[IndexOfMin]).StartTime); { if the starttime of j is less than the starttime of i then flip 'em} if CompResult < 0 then IndexOfMin := j { if the start times match then sort by end time } else if CompResult = 0 then begin { if the endtime of j is less than the end time of i then flip 'em} if (Compare(TVpEvent(FEventList.List^[j]).EndTime, TVpEvent(FEventList.List^[IndexOfMin]).EndTime) < 0) then IndexOfMin := j; end; end; Temp := FEventList.List^[i]; FEventList.List^[i] := FEventList.List^[IndexOfMin]; FEventList.List^[IndexOfMin] := Temp; end; { Fix object embedded ItemIndexes } for i := 0 to pred(FEventList.Count) do begin TVpEvent(FEventList.List^[i]).FItemIndex := i; end; end; {=====} { Used in the above sort procedure. Compares the start times of the two } { passed in events. } function TVpSchedule.Compare(Time1, Time2: TDateTime): Integer; begin { Compares the value of the Item start dates } if Time1 < Time2 then result := -1 else if Time1 = Time2 then result := 0 else {Time2 is earlier than Time1} result := 1; end; {=====} {Adds the event to the eventlist and returns a pointer to it, or nil on failure} function TVpSchedule.AddEvent(RecordID: Int64; StartTime, EndTime: TDateTime): TVpEvent; begin result := nil; if EndTime > StartTime then begin result := TVpEvent.Create(Self); try result.Loading := true; result.FItemIndex := FEventList.Add(result); result.RecordID := RecordID; result.StartTime := StartTime; result.EndTime := EndTime; result.Loading := false; Sort; except result.free; raise EFailToCreateEvent.Create; end; end; end; {=====} procedure TVpSchedule.ClearEvents; begin BatchUpdate(true); try while FEventList.Count > 0 do TVpEvent(FEventList.Last).Free; finally BatchUpdate(false); end; end; {=====} procedure TVpSchedule.BatchUpdate(Value: Boolean); begin if Value then FBatchUpdate := FBatchUpdate + 1 else FBatchUpdate := FBatchUpdate - 1; if FBatchUpdate < 1 then begin FBatchUpdate := 0; Sort; end; end; {=====} { Frees the specified event, which also removes it from the list. } procedure TVpSchedule.DeleteEvent(Event: TVpEvent); begin Event.Deleted := true; Owner.EventsDirty := true; end; {=====} function TVpSchedule.GetEvent(Index: Int64): TVpEvent; begin { Returns an event on success or nil on failure } result := FEventList.Items[Index]; end; {=====} function TVpSchedule.RepeatsOn(Event: TVpEvent; Day: TDateTime): Boolean; var EY, EM, ED: Word; NY, NM, ND: Word; EventWkDay, EventDayCount: Word; ThisWkDay, ThisDayCount: Word; EventJulian, ThisJulian: Word; begin result := false; if (Event.RepeatCode <> rtNone) and (trunc(Event.RepeatRangeEnd + 1) > now) then begin case Event.RepeatCode of rtDaily: if (Day < trunc(Event.RepeatRangeEnd) + 1) and (Day > trunc(Event.StartTime)) then begin result := true; end; rtWeekly: if (Day < trunc(Event.RepeatRangeEnd) + 1) and (Day > trunc(Event.StartTime)) then begin result := (Trunc(Day) - Trunc(Event.StartTime)) mod 7 = 0; end; rtMonthlyByDay: if (Day < trunc(Event.RepeatRangeEnd) + 1) and (Day > trunc(Event.StartTime)) then begin { get the year, month and day of the first event in the series } DecodeDate(Event.StartTime, EY, EM, ED); { get the weekday of the first event in the series } EventWkDay := DayOfWeek(Event.StartTime); { Get the occurence of the first event in the series } { (First Monday, Third Monday, etc...) } EventDayCount := ED div 7 + 1; { get the year, month and day of the "Day" parameter } DecodeDate(Day, NY, NM, ND); { get the weekday of the "Day" parameter } ThisWkDay := DayOfWeek(Day); { Get the weekday occurence of the "Day" parameter } { (First Monday, Third Monday, etc...) } ThisDayCount := ND div 7 + 1; { if (ThisWeekDay is equal to EventWkDay) } { AND (ThisDayCount is equal to EventDayCount) } { then we have a recurrence on this day } result := (ThisWkDay = EventWkDay) and (ThisDayCount = EventDayCount); end; rtMonthlyByDate: if (Day < trunc(Event.RepeatRangeEnd) + 1) and (Day > trunc(Event.StartTime)) then begin { get the year, month and day of the first event in the series } DecodeDate(Event.StartTime, EY, EM, ED); { get the year, month and day of the "Day" parameter } DecodeDate(Day, NY, NM, ND); { if the day values are equal then we have a recurrence on this } { day } result := ED = ND; end; rtYearlyByDay: if (Day < trunc(Event.RepeatRangeEnd) + 1) and (Day > trunc(Event.StartTime)) then begin { get the julian date of the first event in the series } EventJulian := GetJulianDate(Event.StartTime); { get the julian date of the "Day" parameter } ThisJulian := GetJulianDate(Day); { if the julian values are equal then we have a recurrence on } { this day } result := EventJulian = ThisJulian; end; rtYearlyByDate: if (Day < trunc(Event.RepeatRangeEnd) + 1) and (Day > trunc(Event.StartTime)) then begin { get the year, month and day of the first event in the series } DecodeDate(Event.StartTime, EY, EM, ED); { get the year, month and day of the "Day" parameter } DecodeDate(Day, NY, NM, ND); { if the day values and month values are equal then we have a } { recurrence on this day } result := (ED = ND) and (EM = NM); end; rtCustom: if (Day < trunc(Event.RepeatRangeEnd) + 1) and (Day > trunc(Event.StartTime)) then begin { if the number of elapsed days between the "Day" parameter and } { the event start time is evenly divisible by the event's custom } { interval, then we have a recurrence on this day } result := (Trunc(Day) - Trunc(Event.StartTime)) mod Event.CustInterval = 0; end; end; end; end; {=====} function TVpSchedule.EventCountByDay(Value: TDateTime): Integer; var I: Integer; Event: TVpEvent; begin result := 0; for I := 0 to pred(EventCount) do begin Event := GetEvent(I); { if this is a repeating event and it falls on today then inc } { result } if (Event.RepeatCode > rtNone) and (RepeatsOn(Event, Value)) then Inc(Result) { otherwise if it is an event that naturally falls on today, then } { inc result } else if ((trunc(Value) >= trunc(Event.StartTime)) and (trunc(Value) <= trunc(Event.EndTime))) then Inc(Result); end; end; {=====} procedure TVpSchedule.EventsByDate(Date: TDateTime; EventList: TList); var I: Integer; Event: TVpEvent; begin if EventCountByDay(Date) = 0 then EventList.Clear else begin { Add this days events to the Event List. } for I := 0 to pred(EventCount) do begin Event := GetEvent(I); { if this is a repeating event and it falls on "Date" then add it to } { the list. } if (Event.RepeatCode > rtNone) and (RepeatsOn(Event, Date)) then EventList.Add(Event) { otherwise if this event naturally falls on "Date" then add it to } { the list. } else if ((trunc(Date) >= trunc(Event.StartTime)) and (trunc(Date) <= trunc(Event.EndTime))) then EventList.Add(Event); end; end; end; {=====} procedure TVpSchedule.AllDayEventsByDate(Date: TDateTime; EventList: TList); var I: Integer; Event: TVpEvent; begin EventList.Clear; if EventCountByDay(Date) = 0 then Exit else begin { Add this days events to the Event List. } for I := 0 to pred(EventCount) do begin Event := GetEvent(I); if (((trunc(Date) >= trunc(Event.StartTime)) and (trunc(Date) <= trunc(Event.EndTime))) or (RepeatsOn(Event,Date))) and (Event.AllDayEvent) then EventList.Add(Event); end; end; end; {=====} { binary search } function TVpSchedule.FindTimeSlot(StartTime, EndTime: TDateTime): Boolean; var L, R, M: Integer; CStart, CEnd, CompStart, CompEnd: integer; { comparison results } HitStart, HitEnd, HitStraddle: Boolean; begin HitStart := false; HitEnd := false; HItStraddle := false; { Set left and right indexes } L := 0; R := Pred(FEventList.Count); while (L <= R) do begin { Calculate the middle index } M := (L + R) div 2; { Check to see if the middle item straddles our start time } { Compare the the middle item's starttime against the passed in times } CStart := Compare(TVpEvent(FEventList.List^[M]).StartTime, StartTime); CEnd := Compare(TVpEvent(FEventList.List^[M]).EndTime, StartTime); { if the middle item's starttime is less than or equal to the given } { starttime AND the middle item's endtime is greater than or equal to the } { given starttime then we've hit at the start time } if ((CStart <= 0) and (CEnd >= 0)) then HitStart := true; { Check to see if the middle item straddles our end time } { Compare the the middle item's Endtime against the passed in times } CStart := Compare(TVpEvent(FEventList.List^[M]).StartTime, EndTime); CEnd := Compare(TVpEvent(FEventList.List^[M]).EndTime, EndTime); { if the middle item's starttime is less than or equal to the given } { endtime AND the middle item's endtime is greater than or equal to the } { given endtime then we've hit at the end time } if ((CStart <= 0) and (CEnd >= 0)) then HitEnd := true; if (not HitStart) and (not HitEnd) then begin { Check to see if our times fall completely within the middle item } CompStart := Compare(TVpEvent(FEventList.List^[M]).StartTime, StartTime); CompEnd := Compare(TVpEvent(FEventList.List^[M]).EndTime, EndTime); { if the middle item's starttime is less than our starttime AND its } { endtime is greater than our endtime, then teh middle item straddles } { our times } if ((CompStart <= 0) and (CompEnd >= 0)) then HitStraddle := true; if not HItStraddle then { Check to see if the middle item falls completely inside our times } CompStart := Compare(TVpEvent(FEventList.List^[M]).StartTime, StartTime); CompEnd := Compare(TVpEvent(FEventList.List^[M]).EndTime, EndTime); { if the middle item's starttime is less than our starttime AND its } { endtime is greater than our endtime, then teh middle item straddles } { our times } if ((CompStart >= 0) and (CompEnd <= 0)) then HitStraddle := true; end; if (HitStart or HitEnd or HitStraddle) then begin result := true; exit; end else begin { No hit so keep going } CStart := Compare(TVpEvent(FEventList.List^[M]).StartTime, StartTime); { if the middle item's starttime is less than or equal to the given } { starttime AND the middle item's endtime is greater than or equal to the } { given starttime then we've hit at the start time } if (CStart < 0) then L := Succ(M) else R := Pred(M); end; end; { if we got here then we didn't hit an existing item } result := false; end; {=====} function TVpSchedule.GetCount: Integer; begin result := FEventList.Count; end; {=====} { TVpContact } (*****************************************************************************) constructor TVpContact.Create(Owner: TVpContacts); begin inherited Create; FChanged := false; FOwner := Owner; FItemIndex := -1; FPhoneType1 := Ord(ptWork); FPhoneType2 := Ord(ptHome); FPhoneType3 := Ord(ptWorkFax); FPhoneType4 := Ord(ptMobile); FPhoneType5 := Ord(ptAssistant); end; {=====} destructor TVpContact.Destroy; begin { Remove self from owners list } if (FItemIndex > -1) and (FOwner <> nil) then FOwner.FContactsList.Delete(FItemIndex); inherited; end; {=====} function TVpContact.FullName : string; begin if (FFirstName = '') and (FLastName = '') then Result := '' else Result := FFirstName + ' ' + FLastName; end; {=====} procedure TVpContact.SetBirthDate(Value: TDateTIme); begin if Value <> FBirthdate then begin FBirthdate := Value; Changed := true; end; end; {=====} procedure TVpContact.SetAnniversary(Value: TDateTIme); begin if Value <> FAnniversary then begin FAnniversary := Value; Changed := true; end; end; {=====} procedure TVpContact.SetAddress(const Value: string); begin if Value <> FAddress then begin FAddress := Value; Changed := true; end; end; {=====} procedure TVpContact.SetCategory(Value: integer); begin if Value <> FCategory then begin FCategory := Value; Changed := true; end; end; {=====} procedure TVpContact.SetChanged(Value: Boolean); begin if Loading then Exit; if Value <> FChanged then begin FChanged := Value; if FChanged then FOwner.FOwner.ContactsDirty := true; end; end; {=====} procedure TVpContact.SetCity(const Value: string); begin if Value <> FCity then begin FCity := Value; Changed := true; end; end; {=====} procedure TVpContact.SetCompany(const Value: string); begin if Value <> FCompany then begin FCompany := Value; Changed := true; end; end; {=====} procedure TVpContact.SetCountry(const Value: string); begin if Value <> FCountry then begin FCountry := Value; Changed := true; end; end; {=====} procedure TVpContact.SetCustom1(const Value: string); begin if Value <> FCustom1 then begin FCustom1 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetCustom2(const Value: string); begin if Value <> FCustom2 then begin FCustom2 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetCustom3(const Value: string); begin if Value <> FCustom3 then begin FCustom3 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetCustom4(const Value: string); begin if Value <> FCustom4 then begin FCustom4 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetDeleted(Value: Boolean); begin if Value <> FDeleted then begin FDeleted := Value; Changed := true; end; end; {=====} procedure TVpContact.SetEMail(const Value: string); begin if Value <> FEmail then begin FEMail := Value; Changed := true; end; end; {=====} procedure TVpContact.SetFirstName(const Value: string); begin if Value <> FFirstName then begin FFirstName := Value; Changed := true; end; end; {=====} procedure TVpContact.SetLastName(const Value: string); begin if Value <> FLastName then begin FLastName := Value; Changed := true; end; end; {=====} procedure TVpContact.SetNote(const Value: string); begin if Value <> FNote then begin FNote := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhone1(const Value: string); begin if Value <> FPhone1 then begin FPhone1 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhone2(const Value: string); begin if Value <> FPhone2 then begin FPhone2 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhone3(const Value: string); begin if Value <> FPhone3 then begin FPhone3 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhone4(const Value: string); begin if Value <> FPhone4 then begin FPhone4 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhone5(const Value: string); begin if Value <> FPhone5 then begin FPhone5 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhoneType1(Value: Integer); begin if Value <> FPhoneType1 then begin FPhoneType1 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhoneType2(Value: Integer); begin if Value <> FPhoneType2 then begin FPhoneType2 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhoneType3(Value: Integer); begin if Value <> FPhoneType3 then begin FPhoneType3 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhoneType4(Value: Integer); begin if Value <> FPhoneType4 then begin FPhoneType4 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPhoneType5(Value: Integer); begin if Value <> FPhoneType5 then begin FPhoneType5 := Value; Changed := true; end; end; {=====} procedure TVpContact.SetPosition(const Value: string); begin if Value <> FPosition then begin FPosition := Value; Changed := true; end; end; {=====} procedure TVpContact.SetRecordID(Value: Integer); begin if Value <> FRecordID then begin FRecordID := Value; Changed := true; end; end; {=====} procedure TVpContact.SetState(const Value: string); begin if Value <> FState then begin FState := Value; Changed := true; end; end; {=====} procedure TVpContact.SetTitle(const Value: string); begin if Value <> FTitle then begin FTitle := Value; Changed := true; end; end; {=====} procedure TVpContact.SetZip(const Value: string); begin if Value <> FZip then begin FZip := Value; Changed := true; end; end; {=====} { TVpContacts } (*****************************************************************************) constructor TVpContacts.Create(Owner: TVpResource); begin inherited Create; FOwner := Owner; FContactsList := TList.Create; FContactSort := csLastFirst; end; {=====} destructor TVpContacts.Destroy; begin ClearContacts; FContactsList.Free; inherited; end; {=====} procedure TVpContacts.BatchUpdate(Value: Boolean); begin if Value then Inc(FBatchUpdate) else Dec(FBatchUpdate); if FBatchUpdate < 1 then begin FBatchUpdate := 0; Sort; end; end; {=====} procedure TVpContacts.Sort; var i, j : integer; IndexOfMin : integer; Temp : pointer; begin { for greater performance, we don't sort while doing batch updates. } if FBatchUpdate > 0 then exit; for i := 0 to pred(FContactsList.Count) do begin IndexOfMin := i; for j := i to FContactsList.Count - 1 do if (Compare(FContactsList.List^[j], FContactsList.List^[IndexOfMin]) < 0) then IndexOfMin := j; Temp := FContactsList.List^[i]; FContactsList.List^[i] := FContactsList.List^[IndexOfMin]; FContactsList.List^[IndexOfMin] := Temp; end; { Fix object embedded ItemIndexes } for i := 0 to pred(FContactsList.Count) do begin TVpContact(FContactsList.List^[i]).FItemIndex := i; end; end; {=====} { Used by the above sort procedure } function TVpContacts.Compare(Item1, Item2: TVpContact): Integer; begin if ContactSort = csFirstLast then begin { Compares the value of the contact Names } if Item1.FirstName < Item2.FirstName then result := -1 else if Item1.FirstName = Item2.FirstName then begin { if first names are equal then compare last names } if Item1.LastName < Item2.LastName then result := -1 else if Item1.LastName = Item2.LastName then result := 0 else result := 1; end else result := 1; end else begin { Compares the value of the contact Names } if Item1.LastName < Item2.LastName then result := -1 else if Item1.LastName = Item2.LastName then begin { if last names are equal then compare first names } if Item1.FirstName < Item2.FirstName then result := -1 else if Item1.FirstName = Item2.FirstName then result := 0 else result := 1; end else result := 1; end; end; {=====} function TVpContacts.AddContact(RecordID: Integer): TVpContact; var Contact: TVpContact; begin Contact := TVpContact.Create(Self); try Contact.Loading := true; Contact.FItemIndex := FContactsList.Add(Contact); Contact.RecordID := RecordID; Contact.Loading := false; result := Contact; except Contact.Free; raise EFailToCreateContact.Create; end; end; {=====} function TVpContacts.Count: Integer; begin result := FContactsList.Count; end; {=====} function TVpContacts.Last: TVpContact; begin result := FContactsList.Items[FContactsList.Count - 1]; end; {=====} function TVpContacts.First: TVpContact; begin result := FContactsList.Items[0]; end; {=====} procedure TVpContacts.DeleteContact(Contact: TVpContact); begin {Contacts automatically remove themselves from the list in their destructor } Contact.Free; end; {=====} function TVpContacts.GetContact(Index: Integer): TVpContact; begin result := FContactsList.Items[Index]; end; {=====} procedure TVpContacts.ClearContacts; begin BatchUpdate(true); try while FContactsList.Count > 0 do TVpContact(FContactsList.Last).Free; finally BatchUpdate(false); end; end; {=====} { - new} { new function introduced to support the new buttonbar component } function TVpContacts.FindContactByName(const Name: string; CaseInsensitive: Boolean): TVpContact; var I: Integer; SearchStr: String; SearchLength: Integer; begin Result := nil; { to enhance performance, uppercase the input name } { and get its length only once } if CaseInsensitive then SearchStr := uppercase(Name) else SearchStr := Name; SearchLength := Length(SearchStr); { Iterate the contacts looking for a match } for I := 0 to FContactsList.Count - 1 do begin if CaseInsensitive then begin { not case sensitive } if (Copy(uppercase(TVpContact(FContactsList.List^[I]).LastName), 1, SearchLength) = SearchStr) then begin { we found a match, so return it and bail out } Result := FContactsList.Items[I]; Exit; end; end else begin { case sensitive } if (Copy(TVpContact(FContactsList.List^[I]).LastName, 1, SearchLength) = SearchStr ) then begin { we found a match, so return it and bail out } Result := FContactsList.Items[I]; Exit; end; end; end; end; {=====} { - new} { new function introduced to support the new buttonbar component } function TVpContacts.FindContactIndexByName(const Name: string; CaseInsensitive: Boolean): Integer; var Contact: TVpContact; begin result := -1; Contact := FindContactByName(Name, CaseInsensitive); if Contact <> nil then Result := FContactsList.IndexOf(Contact); end; {=====} procedure TVpContacts.SetContactSort (const v : TVpContactSort); begin if v <> FContactSort then begin FContactSort := v; Sort; end; end; {=====} (*****************************************************************************) { TVpTask } constructor TVpTask.Create(Owner: TVpTasks); begin inherited Create; FChanged := false; FOwner := Owner; SetCreatedOn(Now); FDescription := ''; end; {=====} destructor TVpTask.Destroy; begin { Remove self from owners list } if (FItemIndex > -1) and (FOwner <> nil) then begin FOwner.FTaskList.Delete(FItemIndex); FOwner.Sort; end; inherited; end; {=====} function TVpTask.IsOverdue: Boolean; begin result := (Trunc(DueDate) < now + 1); end; {=====} procedure TVpTask.SetCategory(const Value: Integer); begin if Value <> FCategory then begin FCategory := Value; Changed := true; end; end; {=====} procedure TVpTask.SetChanged(const Value: Boolean); begin if Loading then Exit; if Value <> FChanged then begin FChanged := Value; if FChanged then Owner.FOwner.TasksDirty := true; end; end; {=====} procedure TVpTask.SetComplete(const Value: Boolean); begin if Value <> FComplete then begin FComplete := Value; if FComplete then SetCompletedOn(Now) else SetCompletedOn(0.0); end; end; {=====} procedure TVpTask.SetCompletedOn(const Value: TDateTIme); begin if Value <> FCompletedOn then begin FCompletedOn := Value; Changed := true; end; end; {=====} procedure TVpTask.SetCreatedOn(const Value: TDateTime); begin if Value <> FCreatedOn then begin FCreatedOn := Value; Changed := true; end; end; {=====} procedure TVpTask.SetDescription(const Value: string); begin if Value <> FDescription then begin FDescription := Value; Changed := true; end; end; {=====} procedure TVpTask.SetPriority(const Value: Integer); begin if Value <> FPriority then begin FPriority := Value; Changed := true; end; end; {=====} procedure TVpTask.SetDetails(const Value: string); begin if Value <> FDetails then begin FDetails := Value; Changed := true; end; end; {=====} procedure TVpTask.SetDueDate(const Value: TDateTime); begin { Trunc the time element from the DueDate value so that it reflects } { the Date only. } if FDueDate <> Trunc(Value) then begin FDueDate := Trunc(Value); Changed := true; end; end; {=====} (*****************************************************************************) { TVpTaskList } constructor TVpTasks.Create(Owner: TVpResource); begin inherited Create; FOwner := Owner; FTaskList := TList.Create; FTaskList.Clear; {!!!} end; {=====} destructor TVpTasks.Destroy; begin ClearTasks; FTaskList.Free; inherited; end; {=====} function TVpTasks.AddTask(RecordID: Int64): TVpTask; var Task: TVpTask; begin Task := TVpTask.Create(Self); try result := Task; Task.Loading := true; Task.FItemIndex := FTaskList.Add(result); Task.RecordID := RecordID; FOwner.TasksDirty := true; Task.Loading := false; {the data which to sort by has not yet been added to the object} // Sort; except Task.Free; raise EFailToCreateTask.Create; end; end; {=====} function TVpTasks.Count : Integer; begin result := FTaskList.Count; end; {=====} function TVpTasks.Last: TVpTask; begin result := FTaskList.Last; end; {=====} function TVpTasks.First: TVpTask; begin result := FTaskList.First; end; {=====} function TVpTasks.CountByDay(Date: TDateTime): Integer; var i : Integer; ATask : TVpTask; begin Result := 0; for i := 0 to pred (Count) do begin ATask := GetTask (i); if Trunc (ATask.DueDate) = Trunc (Date) then Inc (Result); end; end; {=====} function TVpTasks.LastByDay(Date: TDateTime): TVpTask; var i : Integer; ATask : TVpTask; begin result := nil; for i := 0 to pred (Count) do begin ATask := GetTask (i); if Trunc (ATask.CreatedOn) = Trunc (Date) then begin Result := ATask; end; end; end; {=====} function TVpTasks.FirstByDay(Date: TDateTime): TVpTask; var i : Integer; ATask : TVpTask; begin result := nil; for i := 0 to pred (Count) do begin ATask := GetTask (i); if Trunc (ATask.CreatedOn) = Trunc (Date) then begin Result := ATask; Break; end; end; end; {=====} procedure TVpTasks.ClearTasks; begin BatchUpdate(true); try while FTaskList.Count > 0 do TVpTask(FTaskList.Last).Free; finally BatchUpdate(False); end; end; {=====} procedure TVpTasks.BatchUpdate(value: Boolean); begin if Value then Inc(FBatchUpdate) else Dec(FBatchUpdate); if FBatchUpdate < 1 then begin FBatchUpdate := 0; Sort; end; end; {=====} procedure TVpTasks.Sort; var i, j : integer; IndexOfMin : integer; Temp : pointer; begin { for greater performance, we don't sort while doing batch updates. } if FBatchUpdate > 0 then exit; for i := 0 to pred(FTaskList.Count) do begin IndexOfMin := i; for j := i to FTaskList.Count - 1 do if (Compare(FTaskList.List^[j], FTaskList.List^[IndexOfMin]) < 0) then IndexOfMin := j; Temp := FTaskList.List^[i]; FTaskList.List^[i] := FTaskList.List^[IndexOfMin]; FTaskList.List^[IndexOfMin] := Temp; end; { Fix object embedded ItemIndexes } for i := 0 to pred(FTaskList.Count) do begin TVpTask(FTaskList.List^[i]).FItemIndex := i; end; end; {=====} { Used in the above sort procedure. Compares the start times of the two } { passed in events. } function TVpTasks.Compare(Item1, Item2: TVpTask): Integer; begin { Compares the value of the Items DueDates } if Item1.DueDate < Item2.DueDate then result := -1 { if the start times are equal then sort by description } else if Item1.DueDate = Item2.DueDate then begin if Item1.Description < Item2.Description then result := -1 else if Item1.Description = Item2.Description then result := 0 else result := 1 end else {Item 2 starts earlier than Item 1} result := 1; end; {=====} procedure TVpTasks.DeleteTask(Task: TVpTask); begin {Tasks automatically remove themselves from the list in their destructor } Task.Free; end; {=====} function TVpTasks.GetTask(Index: Integer): TVpTask; begin result := FTaskList.Items[Index]; end; {=====} end.
unit GX_IdeGotoEnhancer; {$I GX_CondDefine.inc} interface uses SysUtils, GX_UnitPositions; type TGxIdeGotoEnhancer = class public class function GetEnabled: Boolean; // static; class procedure SetEnabled(const Value: Boolean); //static; end; implementation uses {$IFOPT D+}GX_DbugIntf, {$ENDIF} GX_OtaUtils, ToolsAPI, Windows, Messages, GX_IdeFormEnhancer, Forms, Controls, StdCtrls, ExtCtrls, Classes; type TWinControlHack = class(TWinControl) end; type TGotoEnhancer = class private FFormCallbackHandle: TFormChangeHandle; lb_UnitPositions: TListBox; FUnitPositions: TUnitPositions; FLineInput: TWinControlHack; ///<summary> /// frm can be nil </summary> procedure HandleFormChanged(_Sender: TObject; _Form: TCustomForm); function IsGotoForm(_Form: TCustomForm): Boolean; procedure lb_UnitPositionsClick(Sender: TObject); procedure LineInputKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); public constructor Create; destructor Destroy; override; end; var TheGotoEnhancer: TGotoEnhancer = nil; { TGxIdeGotoEnhancer } class function TGxIdeGotoEnhancer.GetEnabled: Boolean; begin Result := Assigned(TheGotoEnhancer); end; class procedure TGxIdeGotoEnhancer.SetEnabled(const Value: Boolean); begin if Value then begin if not Assigned(TheGotoEnhancer) then TheGotoEnhancer := TGotoEnhancer.Create end else FreeAndNil(TheGotoEnhancer); end; { TGotoEnhancer } constructor TGotoEnhancer.Create; begin inherited Create; FFormCallbackHandle := TIDEFormEnhancements.RegisterFormChangeCallback(HandleFormChanged) end; destructor TGotoEnhancer.Destroy; begin TIDEFormEnhancements.UnregisterFormChangeCallback(FFormCallbackHandle); inherited; end; function TGotoEnhancer.IsGotoForm(_Form: TCustomForm): Boolean; const GOTO_DIALOG_CLASS = 'TGotoLineDialog'; GOTO_DIALOG_NAME = 'GotoLineDialog'; begin Result := (_Form.ClassName = GOTO_DIALOG_CLASS) and (_Form.Name = GOTO_DIALOG_NAME); end; function TryGetControl(_frm: TForm; _Idx: Integer; const _Name: string; out _ctrl: TControl): Boolean; begin Result := False; if _frm.ControlCount <= _Idx then Exit; _ctrl := _frm.Controls[_Idx]; Result := (_ctrl.Name = _Name); end; function TryGetButton(_frm: TForm; _Idx: Integer; const _Name: string; out _btn: TButton): Boolean; var ctrl: TControl; begin Result := TryGetControl(_frm, _Idx, _Name, ctrl); if Result and (ctrl is TButton) then _btn := TButton(ctrl); end; function TryGetBevel(_frm: TForm; _Idx: Integer; const _Name: string; out _bvl: TBevel): Boolean; var ctrl: TControl; begin Result := TryGetControl(_frm, _Idx, _Name, ctrl); if Result and (ctrl is TBevel) then _bvl := TBevel(ctrl); end; function TryGetWinControl(_frm: TForm; _Idx: Integer; const _Name: string; out _wctrl: TWinControl): Boolean; var ctrl: TControl; begin Result := TryGetControl(_frm, _Idx, _Name, ctrl); if Result and (ctrl is TWinControl) then _wctrl := TWinControl(ctrl); end; procedure TGotoEnhancer.HandleFormChanged(_Sender: TObject; _Form: TCustomForm); const LB_UNIT_POSITIONS = 'GxIdeGotoEnhancerUnitPositionsListbox'; var frm: TForm; Bevel1: TBevel; OkButton: TButton; CancelButton: TButton; HelpButton: TButton; Items: TStrings; i: Integer; begin if not IsGotoForm(_Form) then begin Exit; end; frm := TForm(_Form); if not TryGetBevel(frm, 0, 'Bevel1', Bevel1) then Exit; if not TryGetWinControl(frm, 2, 'LineInput', TWinControl(FLineInput)) then Exit; if not TryGetButton(frm, 3, 'OKButton', OkButton) then Exit; if not TryGetButton(frm, 4, 'CancelButton', CancelButton) then Exit; if not TryGetButton(frm, 5, 'HelpButton', HelpButton) then Exit; if Assigned(frm.FindComponent(LB_UNIT_POSITIONS)) then Exit; frm.Height := 240; OkButton.Top := frm.ClientHeight - OkButton.Height - 8; CancelButton.Top := frm.ClientHeight - CancelButton.Height - 8; HelpButton.Top := frm.ClientHeight - HelpButton.Height - 8; lb_UnitPositions := TListBox.Create(frm); lb_UnitPositions.Name := LB_UNIT_POSITIONS; lb_UnitPositions.Parent := frm; lb_UnitPositions.Top := Bevel1.Top + Bevel1.Height + 8; lb_UnitPositions.Left := Bevel1.Left; lb_UnitPositions.Width := Bevel1.Width; lb_UnitPositions.Height := OkButton.Top - lb_UnitPositions.Top - 8; lb_UnitPositions.OnClick := lb_UnitPositionsClick; lb_UnitPositions.TabOrder := OkButton.TabOrder; Items := lb_UnitPositions.Items; Items.BeginUpdate; try FUnitPositions := TUnitPositions.Create(GxOtaGetCurrentSourceEditor); for i := 0 to FUnitPositions.Count - 1 do begin Items.Add(FUnitPositions.Positions[i].Name); end; finally Items.EndUpdate; end; FLineInput.OnKeyDown := LineInputKeyDown; end; type {$IFDEF GX_VER160_up} TStringType = WideString; PCharType = PWideChar; {$ELSE} TStringType = string; PCharType = PAnsiChar; {$ENDIF} procedure TCombobox_SetText(_cmb: TWinControl; const _Text: TStringType); begin _cmb.Perform(WM_SETTEXT, 0, Longint(PCharType(_Text))); _cmb.Perform(CM_TEXTCHANGED, 0, 0); end; procedure TCombobox_SelectAll(_cmb: TWinControl); begin SendMessage(_cmb.Handle, CB_SETEDITSEL, 0, Integer($FFFF0000)); end; function TCombobox_DroppedDown(_cmb: TWinControl): Boolean; begin Result := LongBool(SendMessage(_cmb.Handle, CB_GETDROPPEDSTATE, 0, 0)); end; procedure TGotoEnhancer.LineInputKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if not TComboBox(FLineInput).DroppedDown then begin if (Key in [VK_UP, VK_DOWN]) and (Shift = []) then begin SendMessage(lb_UnitPositions.Handle, WM_KEYDOWN, Key, 0); Key := 0; end; end; end; procedure TGotoEnhancer.lb_UnitPositionsClick(Sender: TObject); var Idx: Integer; View: IOTAEditView; CharPos: TOTACharPos; CursorPos: TOTAEditPos; begin Idx := lb_UnitPositions.ItemIndex; if Idx = -1 then Exit; View := GxOtaGetTopMostEditView; CharPos := GxOtaGetCharPosFromPos(FUnitPositions.Positions[Idx].Position, View); View.ConvertPos(False, CursorPos, CharPos); TCombobox_SetText(FLineInput, IntToStr(CursorPos.Line)); TCombobox_SelectAll(FLineInput); end; end.
unit TTSACOLTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSACOLRecord = record PCifFlag: String[1]; PLoanNum: String[20]; PActCollNum: Integer; PModCount: Integer; PDescription: String[60]; End; TTTSACOLBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSACOLRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSACOL = (TTSACOLPrimaryKey, TTSACOLbyDescription); TTTSACOLTable = class( TDBISAMTableAU ) private FDFCifFlag: TStringField; FDFLoanNum: TStringField; FDFActCollNum: TIntegerField; FDFModCount: TIntegerField; FDFDescription: TStringField; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPActCollNum(const Value: Integer); function GetPActCollNum:Integer; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetEnumIndex(Value: TEITTSACOL); function GetEnumIndex: TEITTSACOL; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSACOLRecord; procedure StoreDataBuffer(ABuffer:TTTSACOLRecord); property DFCifFlag: TStringField read FDFCifFlag; property DFLoanNum: TStringField read FDFLoanNum; property DFActCollNum: TIntegerField read FDFActCollNum; property DFModCount: TIntegerField read FDFModCount; property DFDescription: TStringField read FDFDescription; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PActCollNum: Integer read GetPActCollNum write SetPActCollNum; property PModCount: Integer read GetPModCount write SetPModCount; property PDescription: String read GetPDescription write SetPDescription; published property Active write SetActive; property EnumIndex: TEITTSACOL read GetEnumIndex write SetEnumIndex; end; { TTTSACOLTable } procedure Register; implementation procedure TTTSACOLTable.CreateFields; begin FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFActCollNum := CreateField( 'ActCollNum' ) as TIntegerField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFDescription := CreateField( 'Description' ) as TStringField; end; { TTTSACOLTable.CreateFields } procedure TTTSACOLTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSACOLTable.SetActive } procedure TTTSACOLTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSACOLTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSACOLTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSACOLTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSACOLTable.SetPActCollNum(const Value: Integer); begin DFActCollNum.Value := Value; end; function TTTSACOLTable.GetPActCollNum:Integer; begin result := DFActCollNum.Value; end; procedure TTTSACOLTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSACOLTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSACOLTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSACOLTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSACOLTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('CifFlag, String, 1, N'); Add('LoanNum, String, 20, N'); Add('ActCollNum, Integer, 0, N'); Add('ModCount, Integer, 0, N'); Add('Description, String, 60, N'); end; end; procedure TTTSACOLTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, CifFlag;LoanNum;ActCollNum, Y, Y, N, N'); Add('byDescription, Description, N, N, Y, N'); end; end; procedure TTTSACOLTable.SetEnumIndex(Value: TEITTSACOL); begin case Value of TTSACOLPrimaryKey : IndexName := ''; TTSACOLbyDescription : IndexName := 'byDescription'; end; end; function TTTSACOLTable.GetDataBuffer:TTTSACOLRecord; var buf: TTTSACOLRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCifFlag := DFCifFlag.Value; buf.PLoanNum := DFLoanNum.Value; buf.PActCollNum := DFActCollNum.Value; buf.PModCount := DFModCount.Value; buf.PDescription := DFDescription.Value; result := buf; end; procedure TTTSACOLTable.StoreDataBuffer(ABuffer:TTTSACOLRecord); begin DFCifFlag.Value := ABuffer.PCifFlag; DFLoanNum.Value := ABuffer.PLoanNum; DFActCollNum.Value := ABuffer.PActCollNum; DFModCount.Value := ABuffer.PModCount; DFDescription.Value := ABuffer.PDescription; end; function TTTSACOLTable.GetEnumIndex: TEITTSACOL; var iname : string; begin result := TTSACOLPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSACOLPrimaryKey; if iname = 'BYDESCRIPTION' then result := TTSACOLbyDescription; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSACOLTable, TTTSACOLBuffer ] ); end; { Register } function TTTSACOLBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('CIFFLAG','LOANNUM','ACTCOLLNUM','MODCOUNT','DESCRIPTION' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TTTSACOLBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftInteger; 5 : result := ftString; end; end; function TTTSACOLBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCifFlag; 2 : result := @Data.PLoanNum; 3 : result := @Data.PActCollNum; 4 : result := @Data.PModCount; 5 : result := @Data.PDescription; end; end; end.
unit l3LogFont; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "L3" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/L3/NOT_FINISHED_l3LogFont.pas" // Начат: 11.10.1999 14:27 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Low Level::L3::l3Canvas::Tl3LogFont // // Описатель шрифта системы. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// {$Include ..\L3\l3Define.inc} interface uses Windows, l3Interfaces, l3PrimString, l3CustomString ; type Tl3LogFont = class(Tl3PrimString{Tl3CustomString}) {* Описатель шрифта системы. } private // property fields f_NameLen : Integer; f_LogFont : TEnumLogFont; f_TextMetric : TTextMetric; protected // property methods function GetAsPCharLen: Tl3PCharLenPrim; override; {-} public // public methods procedure AssignString(P: Tl3PrimString); override; {-} function IsFixed: Boolean; {-} function IsTrueType: Boolean; {-} constructor Create(const lpLogFont : TEnumLogFont; const lpTextMetric : TTextMetric); reintroduce; {-} constructor CreateNamed(const lpLogFont : TEnumLogFont; const lpTextMetric : TTextMetric; const aName : AnsiString); {-} public // public properties property LogFont: TEnumLogFont read f_LogFont; {-} property TextMetric: TTextMetric read f_TextMetric; {-} end;//Tl3LogFont implementation uses SysUtils, l3String, l3FontTools, l3Base ; // start class Tl3LogFont constructor Tl3LogFont.Create(const lpLogFont : TEnumLogFont; const lpTextMetric : TTextMetric); //reintroduce; {-} begin inherited Create; Self.f_LogFont := lpLogFont; Self.f_NameLen := StrLen(Self.f_LogFont.elfLogFont.lfFaceName); Self.f_TextMetric := lpTextMetric; if l3IsDefaultCharset(Self.f_LogFont.elfLogFont.lfCharSet) then Self.f_LogFont.elfLogFont.lfCharSet := CS_Effective; end; constructor Tl3LogFont.CreateNamed(const lpLogFont : TEnumLogFont; const lpTextMetric : TTextMetric; const aName : AnsiString); {-} {$IfDef XE} var l_WS : String; {$EndIf XE} begin Create(lpLogFont, lpTextMetric); {$IfDef XE} l_WS := aName; l3Move(l_WS[1], f_LogFont.elfLogFont.lfFaceName[0], Length(l_WS) * SizeOf(Char)); {$Else XE} l3Move(aName[1], f_LogFont.elfLogFont.lfFaceName[0], Length(aName)); {$EndIf XE} f_NameLen := Length(aName); end; function Tl3LogFont.GetAsPCharLen: Tl3PCharLenPrim; //override; {-} begin Result := l3PCharLen(f_LogFont.elfLogFont.lfFaceName, f_NameLen); end; procedure Tl3LogFont.AssignString(P: Tl3PrimString); {override;} {-} begin inherited; if (P Is Tl3LogFont) then begin Assert(false, 'А нужно ли такое присваивание константных объектов?'); f_LogFont := Tl3LogFont(P).f_LogFont; f_TextMetric := Tl3LogFont(P).f_TextMetric; end;//P Is Tl3LogFont end; function Tl3LogFont.IsFixed: Boolean; {-} begin Result := not // http://mdp.garant.ru/pages/viewpage.action?pageId=296632270&focusedCommentId=296633958#comment-296633958 ((f_TextMetric.tmPitchAndFamily AND TMPF_FIXED_PITCH) <> 0); end; function Tl3LogFont.IsTrueType: Boolean; {-} begin Result := (f_TextMetric.tmPitchAndFamily AND TMPF_TRUETYPE) <> 0; end; end.
unit QuickList_DealClass; interface uses QuickSortList, define_dealclass; type PDealClassListItem = ^TDealClassListItem; TDealClassListItem = record DBId : integer; DealClass : PRT_DefClass; end; TDealClassList = class(TALBaseQuickSortList) public function GetItem(Index: Integer): Integer; procedure SetItem(Index: Integer; const ADbId: Integer); function GetDealClass(Index: Integer): PRT_DefClass; procedure PutDealClass(Index: Integer; ADealClass: PRT_DefClass); public procedure Notify(Ptr: Pointer; Action: TListNotification); override; procedure InsertItem(Index: Integer; const ADBId: integer; ADealClass: PRT_DefClass); function CompareItems(const Index1, Index2: Integer): Integer; override; public function IndexOf(ADBId: Integer): Integer; function IndexOfDealClass(ADealClass: PRT_DefClass): Integer; Function AddDealClass(const ADBId: integer; ADealClass: PRT_DefClass): Integer; function Find(ADBId: Integer; var Index: Integer): Boolean; procedure InsertObject(Index: Integer; const ADbId: integer; ADealClass: PRT_DefClass); //property Items[Index: Integer]: Integer read GetItem write SetItem; default; property StockPackCode[Index: Integer]: Integer read GetItem write SetItem; default; property DealClass[Index: Integer]: PRT_DefClass read GetDealClass write PutDealClass; end; implementation function TDealClassList.AddDealClass(const ADBId: integer; ADealClass: PRT_DefClass): Integer; begin if not Sorted then begin Result := FCount end else if Find(ADBId, Result) then begin case Duplicates of lstDupIgnore: Exit; lstDupError: Error(@SALDuplicateItem, 0); end; end; InsertItem(Result, ADBId, ADealClass); end; {*****************************************************************************************} procedure TDealClassList.InsertItem(Index: Integer; const ADBId: integer; ADealClass: PRT_DefClass); var tmpDealClassListItem: PDealClassListItem; begin New(tmpDealClassListItem); tmpDealClassListItem^.DBId := ADBId; tmpDealClassListItem^.DealClass := ADealClass; try inherited InsertItem(index, tmpDealClassListItem); except Dispose(tmpDealClassListItem); raise; end; end; {***************************************************************************} function TDealClassList.CompareItems(const Index1, Index2: integer): Integer; begin result := PDealClassListItem(Get(Index1))^.DBId - PDealClassListItem(Get(Index2))^.DBId; end; {***********************************************************************} function TDealClassList.Find(ADbId: Integer; var Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := FCount - 1; while L <= H do begin I := (L + H) shr 1; C := GetItem(I) - ADbId; if C < 0 then begin L := I + 1 end else begin H := I - 1; if C = 0 then begin Result := True; if Duplicates <> lstDupAccept then L := I; end; end; end; Index := L; end; {*******************************************************} function TDealClassList.GetItem(Index: Integer): Integer; begin Result := PDealClassListItem(Get(index))^.DbId end; {******************************************************} function TDealClassList.IndexOf(ADbId: Integer): Integer; begin if not Sorted then Begin Result := 0; while (Result < FCount) and (GetItem(result) <> ADbId) do Inc(Result); if Result = FCount then Result := -1; end else if not Find(ADbId, Result) then Result := -1; end; {*******************************************************************************************} procedure TDealClassList.InsertObject(Index: Integer; const ADbId: integer; ADealClass: PRT_DefClass); var tmpDealClassListItem: PDealClassListItem; begin New(tmpDealClassListItem); tmpDealClassListItem^.DbId := ADbId; tmpDealClassListItem^.DealClass := ADealClass; try inherited insert(index, tmpDealClassListItem); except Dispose(tmpDealClassListItem); raise; end; end; {***********************************************************************} procedure TDealClassList.Notify(Ptr: Pointer; Action: TListNotification); begin if Action = lstDeleted then dispose(ptr); inherited Notify(Ptr, Action); end; {********************************************************************} procedure TDealClassList.SetItem(Index: Integer; const ADbId: Integer); Var aPDealClassListItem: PDealClassListItem; begin New(aPDealClassListItem); aPDealClassListItem^.DbId := ADbId; aPDealClassListItem^.DealClass := nil; Try Put(Index, aPDealClassListItem); except Dispose(aPDealClassListItem); raise; end; end; {*********************************************************} function TDealClassList.GetDealClass(Index: Integer): PRT_DefClass; begin if (Index < 0) or (Index >= FCount) then Error(@SALListIndexError, Index); Result := PDealClassListItem(Get(index))^.DealClass; end; {***************************************************************} function TDealClassList.IndexOfDealClass(ADealClass: PRT_DefClass): Integer; begin for Result := 0 to Count - 1 do begin if GetDealClass(Result) = ADealClass then begin Exit; end; end; Result := -1; end; {*******************************************************************} procedure TDealClassList.PutDealClass(Index: Integer; ADealClass: PRT_DefClass); begin if (Index < 0) or (Index >= FCount) then Error(@SALListIndexError, Index); PDealClassListItem(Get(index))^.DealClass := ADealClass; end; end.
unit DAO.LacresDevolucao; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.LacresDevolucao; type TLacresDevolucaoDAO = class private FConexao: TConexao; public constructor Create; function Inserir(ALacre: TLacresDevolucao): Boolean; function Alterar(ALacre: TLacresDevolucao): Boolean; function Excluir(ALacre: TLacresDevolucao): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'tblacres'; implementation { TLacresDevolucaoDAO } function TLacresDevolucaoDAO.Alterar(ALacre: TLacresDevolucao): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('update ' + TABLENAME + ' set COD_STATUS = :COD_STATUS, NOM_USUARIO = :NOM_USUARIO, ' + 'DAT_MANUTENCAO = :DAT_MANUTENCAO ' + 'where COD_BASE = :COD_BASE AND NUM_LACRE = :NUM_LACRE;',[ALacre.Status, ALacre.Usuario, ALacre.Manutencao, Alacre.Base, Alacre.Lacre]); Result := True; finally FDQuery.Free; end; end; constructor TLacresDevolucaoDAO.Create; begin FConexao := TConexao.Create(); end; function TLacresDevolucaoDAO.Excluir(ALacre: TLacresDevolucao): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where COD_BASE = :COD_BASE AND NUM_LACRE = :NUM_LACRE;', [ALacre.Base, ALacre.Lacre]); Result := True; finally FDQuery.Free; end; end; function TLacresDevolucaoDAO.Inserir(ALacre: TLacresDevolucao): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('insert int ' + TABLENAME + ' (COD_BASE, NUM_LACRE, COD_STATUS, NOM_USUARIO, DAT_MANUTENCAO) ' + 'VALUES ' + '(:COD_BASE, :NUM_LACRE, :COD_STATUS, :NOM_USUARIO, :DAT_MANUTENCAO);',[Alacre.Base, Alacre.Lacre, ALacre.Status, ALacre.Usuario, ALacre.Manutencao]); Result := True; finally FDQuery.Free; end; end; function TLacresDevolucaoDAO.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] = 'BASE' then begin FDQuery.SQL.Add('WHERE COD_BASE = :COD_BASE'); FDQuery.ParamByName('COD_BASE').AsInteger := aParam[1]; end; if aParam[0] = 'LACRE' then begin FDQuery.SQL.Add('WHERE COD_BASE = :COD_BASE AND NUM_LACRE = :NUM_LACRE'); FDQuery.ParamByName('COD_BASE').AsInteger := aParam[1]; FDQuery.ParamByName('NUM_LACRE').AsString := aParam[2]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; FDQuery.Open; Result := FDQuery; end; end.
unit Localizer; {$mode objfpc}{$H+} interface function LocalizeString(str:string):string; implementation uses windows; function LocalizeString(str: string): string; var locale:cardinal; const RUS_ID:cardinal=1049; begin result:=str; locale:=GetSystemDefaultLangID(); if str = 'err_caption' then begin if locale = RUS_ID then result:='Ошибка!' else result:='Error!'; end else if str = 'err_bundle_corrupt' then begin if locale = RUS_ID then result:='Установочные файлы мода повреждены!' else result:='The installer is corrupted!'; end else if str = 'btn_next' then begin if locale = RUS_ID then result:='Далее' else result:='Next'; end else if str = 'stage_integrity_check' then begin if locale = RUS_ID then result:='Пожалуйста, подождите...' else result:='Please wait...'; end else if str = 'hint_select_install_dir' then begin if locale = RUS_ID then result:='Укажите путь для установки мода (желательно только из латинских символов)' else result:='Select the installation directory for the mod (please use Latin symbols only)'; end else if str = 'msg_confirm' then begin if locale = RUS_ID then result:='Требуется подтверждение' else result:='Please confirm'; end else if str = 'confirm_dir_nonempty' then begin if locale = RUS_ID then result:='Выбранная Вами директория не пуста. Продолжить установку в нее?' else result:='The selected directory is not empty, continue installation?'; end else if str = 'confirm_dir_unexist' then begin if locale = RUS_ID then result:='Выбранная Вами директория не существует. Создать и продолжить установку в нее?' else result:='The selected directory doesn''t exist. Create it and continue installation?'; end else if str = 'hint_select_game_dir' then begin if locale = RUS_ID then result:='Выберите директорию, в которой установлена оригинальная игра' else result:='Please select the directory where the game is installed'; end else if str = 'msg_no_game_in_dir' then begin if locale = RUS_ID then result:='Похоже, что оригинальная игра НЕ установлена в выбраной Вами директории. Продолжить?' else result:='Looks like the game is NOT installed in the selected directory. Continue anyway?'; end else if str = 'installing' then begin if locale = RUS_ID then result:='Подождите, идет установка мода...' else result:='Installing mod, please wait...'; end else if str = 'err_cant_create_dir' then begin if locale = RUS_ID then result:='Не удалось создать директорию' else result:='Can''t create directory'; end else if str = 'err_cant_read_bundle_content' then begin if locale = RUS_ID then result:='Не удалось прочитать файл с контентом' else result:='Can''t read content file'; end else if str = 'err_writing_file' then begin if locale = RUS_ID then result:='Не удалось записать файл с контентом' else result:='Can''t write content file'; end else if str = 'stage_finalizing' then begin if locale = RUS_ID then result:='Настройка мода...' else result:='Finalizing...'; end else if str = 'err_unk' then begin if locale = RUS_ID then result:='Неизвестная ошибка' else result:='Unknown error'; end else if str = 'exit_installer' then begin if locale = RUS_ID then result:='Выход' else result:='Exit'; end else if str = 'success_install' then begin if locale = RUS_ID then result:='Установка успешно завершена' else result:='The mod has been successfully installed'; end else if str = 'confirm_close' then begin if locale = RUS_ID then result:='Выйти из установщика?' else result:='Exit installer?'; end else if str = 'user_cancelled' then begin if locale = RUS_ID then result:='Отменено пользователем' else result:='Cancelled by user'; end else if str = 'reverting_changes' then begin if locale = RUS_ID then result:='Идет завершение установки и откат изменений, подождите...' else result:='Stopping installation, please wait...'; end else if str = 'stage_packing_select' then begin if locale = RUS_ID then result:='Выберите директорию для упаковки' else result:='Select directory for packing'; end else if str = 'packing_completed' then begin if locale = RUS_ID then result:='Запаковка успешно завершена' else result:='Packing successful'; end else if str = 'run_updater' then begin if locale = RUS_ID then result:='Запустить установку аддонов' else result:='Run addons installer'; end; end; end.
program ch3(input, output); { Chapter 3 Assignment Alberto Villalobos February 12, 2014 Description: A user enters parameters of an area to be mowerd and the program outputs the square footage to be mowed and the estimated time required. Input: lengh and width of house and lawn Output: Area to be mowed and time required } const ftperhour = 50; var area, time, housewidth, houselength, lawnwidth, lawnlength: Integer; begin writeln('Enter lawn width: '); read(lawnwidth); writeln('Enter lawn length: '); read(lawnlength); writeln('Enter house width: '); read(housewidth); writeln('Enter house length: '); read(houselength); area := lawnwidth * lawnlength - housewidth * houselength; time := area div ftperhour; writeln('Area to be mowed ', area, ' time required ', time); end.
PROGRAM OOPPeople; CONST MAX_SKILLS = 10; TYPE Date = RECORD day, month, year : INTEGER; END; SkillArray = ARRAY [1..MAX_SKILLS] OF STRING; Person = ^PersonObj; PersonObj = OBJECT name : STRING; PRIVATE birthDate : Date; PUBLIC CONSTRUCTOR Init(n : STRING; bd : Date); PROCEDURE SayName; VIRTUAL; FUNCTION GetBirthDate : Date; END; (* Class Person *) SuperHero = ^SuperHeroObj; SuperHeroObj = OBJECT(PersonObj) PRIVATE alterEgo : STRING; FUNCTION HasSkill(s: STRING): BOOLEAN; PUBLIC skills : SkillArray; CONSTRUCTOR Init(n : STRING; bd : Date; altEgo : STRING; skills : SkillArray); PROCEDURE UseSkill(s : STRING); VIRTUAL; END; (* Class Superhero *) Villain = ^VillainObj; VillainObj = OBJECT(PersonObj) PRIVATE evilness : 1..10; FUNCTION HasSkill(s: STRING): BOOLEAN; PUBLIC skills : SkillArray; CONSTRUCTOR Init(n : STRING; bd : Date; evilness : INTEGER; skills : SkillArray); PROCEDURE UseSkill(s : STRING); VIRTUAL; END; (* Class Villain *) CONSTRUCTOR PersonObj.Init(n : STRING; bd : Date); BEGIN name := n; birthDate := bd; END; PROCEDURE PersonObj.SayName; BEGIN WriteLn('Hello my name is ', name); END; FUNCTION PersonObj.GetBirthDate: Date; BEGIN GetBirthDate := birthDate; END; CONSTRUCTOR SuperheroObj.Init(n : STRING; bd : Date; altEgo : STRING; skills : SkillArray); BEGIN INHERITED Init(n, bd); alterEgo := altEgo; SELF.skills := skills; (* SELF represents the current object *) END; PROCEDURE SuperHeroObj.UseSkill(s: STRING); BEGIN IF HasSkill(s) THEN BEGIN WriteLn('Using ', s, ' skill!'); END; END; FUNCTION SuperHeroObj.HasSkill(s: STRING): BOOLEAN; VAR i: INTEGER; hs: BOOLEAN; BEGIN hs := FALSE; i := 1; WHILE (NOT hs) AND (i <= MAX_SKILLS) DO BEGIN hs := skills[i] = s; Inc(i); END; HasSkill := hs; END; CONSTRUCTOR VillainObj.Init(n : STRING; bd : Date; evilness : INTEGER; skills : SkillArray); BEGIN INHERITED Init(n, bd); SELF.evilness := evilness; SELF.skills := skills; (* SELF represents the current object *) END; PROCEDURE VillainObj.UseSkill(s: STRING); BEGIN IF HasSkill(s) THEN BEGIN WriteLn('Using ', s, ' skill!'); END; END; FUNCTION VillainObj.HasSkill(s: STRING): BOOLEAN; VAR i: INTEGER; hs: BOOLEAN; BEGIN hs := FALSE; i := 1; WHILE (NOT hs) AND (i <= MAX_SKILLS) DO BEGIN hs := skills[i] = s; Inc(i); END; HasSkill := hs; END; VAR sh: SuperHero; v: Villain; sa: SkillArray; d: Date; BEGIN d.Day := 27; d.Month := 5; d.Year := 1949; sa[1] := 'Programming'; sa[2] := 'Laser-Eyes'; sa[3] := 'Teaching'; sa[3] := 'Charming'; New(sh, Init('Pomberger', d, 'Prof. Gust', sa)); sh^.UseSkill('Charming'); d.Day := 13; d.Month := 4; d.Year := 1976; sa[1] := 'Laser-Eyes'; sa[2] := 'Exmatrikulation'; New(v, Init('Endgegner', d, 8, sa)); v^.SayName; v^.UseSkill('Laser-Eyes'); WriteLn(SizeOf(v)); WriteLn(SizeOf(VillainObj)); Dispose(sh); Dispose(v); END.
{ ***************************************************************************** * * * This file is part of the iPhone Laz Extension * * * * See the file COPYING.modifiedLGPL.txt, included in this distribution, * * for details about the copyright. * * * * 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. * * * ***************************************************************************** } unit ideext; {$mode objfpc}{$H+} interface uses Unix, BaseUnix, process, Classes, SysUtils, contnrs, Graphics, Controls, Forms, Dialogs, FileUtil, {Lazarus Interface} LazIDEIntf, MenuIntf, ProjectIntf, IDEOptionsIntf, IDEMsgIntf, project_iphone_options, xcodetemplate, iPhoneExtOptions, iPhoneExtStr, iPhoneBundle, lazfilesutils; procedure Register; implementation type { TiPhoneExtension } TiPhoneExtension = class(TObject) protected procedure FillBunldeInfo(forSimulator: Boolean; var info: TiPhoneBundleInfo); procedure InstallAppToSim; function FixCustomOptions(const Options: String; isRealDevice: Boolean): String; function WriteIconTo(const FullName: String): Boolean; function ProjectBuilding(Sender: TObject): TModalResult; function ProjectOpened(Sender: TObject; AProject: TLazProject): TModalResult; //procedure OnProjOptionsChanged(Sender: TObject; Restore: Boolean); public constructor Create; procedure UpdateXcode(Sender: TObject); procedure SimRun(Sender: TObject); //procedure isProjectClicked(Sender: TObject); end; var Extension : TiPhoneExtension = nil; function GetProjectPlistName(Project: TLazProject): String; var ext : String; begin if Project.LazCompilerOptions.TargetFilename<>'' then Result:=ExtractFileName(Project.LazCompilerOptions.TargetFilename) else begin Result:=ExtractFileName(Project.MainFile.Filename); ext:=ExtractFileExt(Result); Result:=Copy(Result, 1, length(Result)-length( ext ) ); end; Result:=Result+'.plist'; end; function GetProjectExeName(Project: TLazProject): String; var ext : String; begin if Project.LazCompilerOptions.TargetFilename<>'' then Result:=Project.LazCompilerOptions.TargetFilename else begin Result:=Project.MainFile.Filename; ext:=ExtractFileExt(Result); Result:=Copy(Result, 1, length(Result)-length( ext ) ); end; Result := ResolveProjectPath(Result); end; { TiPhoneExtension } procedure TiPhoneExtension.FillBunldeInfo(forSimulator: Boolean; var info: TiPhoneBundleInfo); begin Info.AppID:=ProjOptions.AppID; Info.DisplayName:=LazarusIDE.ActiveProject.Title; Info.iPlatform:=EnvOptions.GetSDKName(ProjOptions.SDK, forSimulator); Info.SDKVersion:=ProjOptions.SDK; Info.MainNib:=UTF8Decode(ProjOptions.MainNib); end; procedure TiPhoneExtension.InstallAppToSim; var bundlename : string; bundlepath : WideString; exepath : WideString; nm : String; dstpath : String; Space : WideString; RealSpace : WideString; Info : TiPhoneBundleInfo; AProjectFile: TLazProjectFile; xiblist : TStringList; i : Integer; s : string; begin Space:=ProjOptions.SpaceName; // LazarusIDE.ActiveProject.CustomData.; bundleName:=ExtractFileName(LazarusIDE.ActiveProject.ProjectInfoFile); bundleName:=Copy(bundleName, 1, length(bundleName)-length(ExtractFileExt(bundleName))); if bundlename='' then bundlename:='project1'; nm:=GetProjectExeName(LazarusIDE.ActiveProject); FillBunldeInfo(true, Info); CreateBundle(bundleName, Space, ExtractFileName(nm), Info, RealSpace, bundlepath, exepath); WriteIconTo( IncludeTrailingPathDelimiter(bundlepath)+'Icon.png'); CopySymLinks( ResolveProjectPath(ProjOptions.ResourceDir), bundlepath, // don't copy .xib files, they're replaced by compiled nibs '*.xib; '+ ProjOptions.ExcludeMask ); if nm<>'' then begin dstpath:=UTF8Encode(exepath); FpUnlink(dstpath); fpSymlink(PChar(nm), PChar(dstpath)); end; xiblist := TStringList.Create; try // Scan for resource-files in the .xib file-format, which are // used by the iOSDesigner package for i := 0 to LazarusIDE.ActiveProject.FileCount-1 do begin AProjectFile := LazarusIDE.ActiveProject.Files[i]; s := ChangeFileExt(AProjectFile.filename,'.xib'); if (AProjectFile.IsPartOfProject) and FileExistsUTF8(s) then xiblist.add(s); end; EnumFilesAtDir(ResolveProjectPath(ProjOptions.ResourceDir), '*.xib', xiblist); for i:=0 to xiblist.Count-1 do begin dstpath:=IncludeTrailingPathDelimiter(bundlepath)+ChangeFileExt(ExtractFileName(xiblist[i]), '.nib'); ExecCmdLineNoWait(Format('ibtool --compile "%s" "%s"', [dstpath, xiblist[i]])); end; finally xiblist.free; end; end; function FindParam(const Source, ParamKey: String; var idx: Integer; var Content: String): Boolean; var i : Integer; quoted : Boolean; begin Result:=false; idx:=0; for i := 1 to length(Source)-1 do if (Source[i]='-') and ((i=1) or (Source[i-1] in [#9,#32,#10,#13])) then if Copy(Source, i, 3) = ParamKey then begin idx:=i; Result:=true; Break; end; if not Result then Exit; i:=idx+3; quoted:=(i<=length(Source)) and (Source[i]='"'); if not quoted then begin for i:=i to length(Source) do if (Source[i] in [#9,#32,#10,#13]) then begin Content:=Copy(Source, idx+3, i-idx); Exit; end; end else begin i:=i+1; for i:=i to length(Source) do if (Source[i] = '"') then begin Content:=Copy(Source, idx+3, i-idx+1); Exit; end; end; Content:=Copy(Source, idx+3, length(Source)-1); end; function TiPhoneExtension.FixCustomOptions(const Options: String; isRealDevice: Boolean): String; var prm : string; rawprm : string; idx : Integer; needfix : Boolean; sdkuse : String; sdkver : String; st : TStringList; begin sdkver:=ProjOptions.SDK; if sdkver='' then begin st := TStringList.Create; try EnvOptions.GetSDKVersions(st); if st.Count=0 then IDEMessagesWindow.AddMsg(strWNoSDK, '', 0) else begin sdkver:=st[0]; ProjOptions.SDK:=sdkver; end; finally st.Free; end; end; sdkuse:=EnvOptions.GetSDKFullPath(sdkver, not isRealDevice); Result:=Options; if FindParam(Result, '-XR', idx, rawprm) then begin if (rawprm='') or(rawprm[1]<>'"') then prm:=rawprm else prm:=rawprm; // there might be -XR option, and it might be the same as selected SDK needfix:=sdkuse<>prm; // there's -XR option, but it doesn't match the selection options if needfix then Delete(Result, idx, length(rawprm)+3); end else begin //there's no -XR string in custom options needfix:=true; idx:=1; sdkuse:=sdkuse+' '; end; if needfix then Insert('-XR'+sdkuse, Result, idx); end; constructor TiPhoneExtension.Create; begin inherited Create; LazarusIDE.AddHandlerOnProjectOpened(@ProjectOpened); LazarusIDE.AddHandlerOnProjectBuilding(@ProjectBuilding); //ProjOptions.OnAfterWrite:=@OnProjOptionsChanged; RegisterIDEMenuCommand(itmProjectWindowSection, 'mnuiPhoneSeparator', '-', nil, nil); RegisterIDEMenuCommand(itmProjectWindowSection, 'mnuiPhoneToXCode', strStartAtXcode, @UpdateXcode, nil); RegisterIDEMenuCommand(itmProjectWindowSection, 'mnuiPhoneRunSim', strRunSimulator, @SimRun, nil); end; function TiPhoneExtension.ProjectBuilding(Sender: TObject): TModalResult; begin Result:=mrOk; if not Assigned(LazarusIDE.ActiveProject) or not ProjOptions.isIPhoneApp then Exit; LazarusIDE.ActiveProject.LazCompilerOptions.CustomOptions := FixCustomOptions( LazarusIDE.ActiveProject.LazCompilerOptions.CustomOptions, false ); //const InfoFileName, BundleName, ExeName: WideString; const info: TiPhoneBundleInfo): Boolean; {MessageDlg('CustomOptions fixed = '+ LazarusIDE.ActiveProject.LazCompilerOptions.CustomOptions, mtInformation, [mbOK], 0);} InstallAppToSim; Result:=mrOk; end; function TiPhoneExtension.ProjectOpened(Sender: TObject; AProject: TLazProject): TModalResult; begin ProjOptions.Reset; ProjOptions.Load; Result:=mrOk; end; function TiPhoneExtension.WriteIconTo(const FullName: String): Boolean; var icofile : string; ico : TIcon; png : TPortableNetworkGraphic; i, idx : Integer; const iPhoneIconSize=57; begin Result:=false; //todo: find a better way of getting the file icofile:=ChangeFileExt(LazarusIDE.ActiveProject.MainFile.Filename, '.ico'); icofile := ResolveProjectPath(icofile); if not FileExists(icofile) then begin // no icon. it should be deleted! DeleteFile(FullName); Exit; end; try ico:=TIcon.Create; png:=TPortableNetworkGraphic.Create; try png.Width:=iPhoneIconSize; png.Height:=iPhoneIconSize; ico.LoadFromFile(icofile); idx:=-1; for i:=0 to ico.Count- 1 do begin ico.Current:=i; if (ico.Width=iPhoneIconSize) and (ico.Height=iPhoneIconSize) then begin idx:=i; Break; end; end; if (idx<0) and (ico.Count>0) then idx:=0; ico.Current:=idx; if (ico.Width=iPhoneIconSize) and (ico.Height=iPhoneIconSize) then png.Assign(ico) else begin //resize to adjust the image png.Canvas.CopyRect( Rect(0,0, iPhoneIconSize, iPhoneIconSize), ico.Canvas, Rect(0,0, ico.Width, ico.Height)); end; png.SaveToFile(FullName); finally ico.free; png.free; end; Result:=true; except end; end; procedure TiPhoneExtension.UpdateXcode(Sender: TObject); var templates : TStringList; build : TFPStringHashTable; dir : string; projdir : string; proj : TStringList; projname : string; ext : string; tname : string; plistname : string; Info : TiPhoneBundleInfo; name : string; opt : string; optSim: string; begin FillBunldeInfo(false, Info); // the create .plist would be used by XCode project // the simulator .plist in created with InstallAppToSim. // they differ with SDKs used build := TFPStringHashTable.Create; tname:=ExtractFileName( LazarusIDE.ActiveProject.MainFile.Filename); tname:=ChangeFileExt(tname, ''); plistname:=tname+'.plist'; build.Add('INFOPLIST_FILE','"'+plistname+'"'); build.Add('PRODUCT_NAME','"'+tname+'"'); build.Add('SDKROOT',EnvOptions.GetSDKName(ProjOptions.SDK, false)); build.Add('FPC_COMPILER_PATH','"'+EnvOptions.CompilerPath+'"'); build.Add('FPC_MAIN_FILE','"'+LazarusIDE.ActiveProject.MainFile.Filename+'"'); opt := ' -XR'+EnvOptions.GetSDKFullPath(ProjOptions.SDK, false)+' ' + ' -FD'+IncludeTrailingPathDelimiter(EnvOptions.PlatformsBaseDir)+'iPhoneOS.platform/Developer/usr/bin ' + EnvOptions.CommonOpt; optSim := ' -XR'+EnvOptions.GetSDKFullPath(ProjOptions.SDK, true)+' ' + ' -FD'+IncludeTrailingPathDelimiter(EnvOptions.PlatformsBaseDir)+'iPhoneSimulator.platform/Developer/usr/bin ' + EnvOptions.CommonOpt; with LazarusIDE.ActiveProject.LazCompilerOptions do begin opt:=opt + ' ' +BreakPathsStringToOption(OtherUnitFiles, '-Fu', '\"'); opt:=opt + ' ' +BreakPathsStringToOption(IncludePath, '-Fi', '\"'); opt:=opt + ' ' +BreakPathsStringToOption(ObjectPath, '-Fo', '\"'); opt:=opt + ' ' +BreakPathsStringToOption(Libraries, '-Fl', '\"'); optSim:=optSim + ' ' +BreakPathsStringToOption(OtherUnitFiles, '-Fu', '\"'); optSim:=optSim + ' ' +BreakPathsStringToOption(IncludePath, '-Fi', '\"'); optSim:=optSim + ' ' +BreakPathsStringToOption(ObjectPath, '-Fo', '\"'); optSim:=optSim + ' ' +BreakPathsStringToOption(Libraries, '-Fl', '\"'); end; build.Add('FPC_CUSTOM_OPTIONS','"'+opt+'"'); build.Add('"FPC_CUSTOM_OPTIONS[sdk=iphonesimulator*]"','"'+optSim+'"'); dir:=ResolveProjectPath('xcode'); dir:=dir+'/'; name:=ExtractFileName(GetProjectExeName(LazarusIDE.ActiveProject)); ForceDirectories(dir); WriteDefInfoList( dir + GetProjectPlistName(LazarusIDE.ActiveProject), name, name, Info); projname:=ExtractFileName(LazarusIDE.ActiveProject.MainFile.Filename); ext:=ExtractFileExt(projname); projname:=Copy(projname, 1, length(projname)-length(ext)); projdir:=dir+projname+'.xcodeproj'; ForceDirectories(projdir); projname:=IncludeTrailingPathDelimiter(projdir)+'project.pbxproj'; proj:=TStringList.Create; templates:=nil; try if not FileExists(projname) then begin templates:=TStringList.Create; if WriteIconTo( IncludeTrailingPathDelimiter(dir)+'Icon.png') then begin templates.Values['icon']:=XCodeProjectTemplateIcon; templates.Values['iconid']:=XCodeProjectTemplateIconID; templates.Values['iconfile']:=XCodeIconFile; templates.Values['iconfileref']:=XCodeIconFileRef; end else begin templates.Values['icon']:=''; templates.Values['iconid']:=''; templates.Values['iconfile']:=''; templates.Values['iconfileref']:=''; end; //todo: templates.Values['bundle']:=tname+'.app'; templates.Values['plist']:=plistname; templates.Values['targetname']:=tname; templates.Values['productname']:=tname; proj.Text:=XCodeProjectTemplate; end else proj.LoadFromFile(projname); PrepareTemplateFile(proj, templates, build); proj.SaveToFile(projname); except on e: exception do ShowMessage(e.Message); end; proj.Free; templates.Free; build.Free; IDEMessagesWindow.AddMsg(strXcodeUpdated, '', 0); end; procedure TiPhoneExtension.SimRun(Sender: TObject); var t : TProcess; path : String; begin t :=TProcess.Create(nil); try //ProjectBuilding(nil); path:=IncludeTrailingPathDelimiter(EnvOptions.SimBundle)+'Contents/MacOS/iPhone Simulator'; EnvOptions.SubstituteMacros(path); t.CommandLine:='"'+path+'"'; t.CurrentDirectory:=UTF8Encode(GetSandBoxDir(ProjOptions.SpaceName)); t.Execute; except on E: Exception do MessageDlg(E.Message, mtInformation, [mbOK], 0); end; t.Free; end; {procedure TiPhoneExtension.isProjectClicked(Sender: TObject); begin if not Assigned(Sender) or not Assigned(LazarusIDE.ActiveProject) then Exit; TIDEMenuCommand(Sender).Checked:=not TIDEMenuCommand(Sender).Checked; ProjOptions.isiPhoneApp:=TIDEMenuCommand(Sender).Checked; ProjOptions.Save; end;} procedure Register; begin // IDE integration is done in constructor Extension := TiPhoneExtension.Create; try EnvOptions.Load; EnvOptions.RefreshVersions; except end; end; initialization finalization Extension.Free; end.
unit m3DBProxyStream; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "m3" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/m3/m3DBProxyStream.pas" // Начат: 17.03.2009 18:19 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::m3::m3DB::Tm3DBProxyStream // // Поток, знающий про базу, с которой он работает // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\m3\m3Define.inc} interface uses l3Interfaces, m3DBInterfaces, l3ProxyStream, m3PrimDB ; type Tm3DBProxyStream = class(Tl3ProxyStream) {* Поток, знающий про базу, с которой он работает } private // private fields f_DB : Tm3PrimDB; {* Поле для свойства DB} f_ID : Tm3DBStreamIndexEx; {* Поле для свойства ID} protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public // public methods constructor Create(const aStream: IStream; aDB: Tm3PrimDB; const anID: Tm3DBStreamIndexEx); reintroduce; class function Make(const aStream: IStream; aDB: Tm3PrimDB; const anID: Tm3DBStreamIndexEx): IStream; reintroduce; {* Создаёт обёртку } protected // protected properties property DB: Tm3PrimDB read f_DB; {* База, с которой работает поток } public // public properties property ID: Tm3DBStreamIndexEx read f_ID; {* Идентификатор потока } end;//Tm3DBProxyStream implementation uses SysUtils, l3Base ; // start class Tm3DBProxyStream constructor Tm3DBProxyStream.Create(const aStream: IStream; aDB: Tm3PrimDB; const anID: Tm3DBStreamIndexEx); //#UC START# *49BFC03402A2_49BFBF3E00CD_var* //#UC END# *49BFC03402A2_49BFBF3E00CD_var* begin //#UC START# *49BFC03402A2_49BFBF3E00CD_impl* Assert(aDB <> nil); inherited Create(aStream); f_ID := anID; l3Set(f_DB, aDB); //#UC END# *49BFC03402A2_49BFBF3E00CD_impl* end;//Tm3DBProxyStream.Create class function Tm3DBProxyStream.Make(const aStream: IStream; aDB: Tm3PrimDB; const anID: Tm3DBStreamIndexEx): IStream; var l_Inst : Tm3DBProxyStream; begin l_Inst := Create(aStream, aDB, anID); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; procedure Tm3DBProxyStream.Cleanup; //#UC START# *479731C50290_49BFBF3E00CD_var* //#UC END# *479731C50290_49BFBF3E00CD_var* begin //#UC START# *479731C50290_49BFBF3E00CD_impl* l3Free(f_DB); inherited; //#UC END# *479731C50290_49BFBF3E00CD_impl* end;//Tm3DBProxyStream.Cleanup procedure Tm3DBProxyStream.ClearFields; {-} begin Finalize(f_ID); inherited; end;//Tm3DBProxyStream.ClearFields end.
unit DeleteConfigValueUnit; interface uses SysUtils, BaseExampleUnit, EnumsUnit; type TDeleteConfigValue = class(TBaseExample) public function Execute(Key: String): boolean; end; implementation function TDeleteConfigValue.Execute(Key: String): boolean; var ErrorString: String; begin Result := Route4MeManager.User.DeleteConfigValue(Key, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin if Result then WriteLn('DeleteConfigValue successfully') else WriteLn('DeleteConfigValue error'); WriteLn(''); end else WriteLn(Format('DeleteConfigValue error: "%s"', [ErrorString])); end; end.
unit TownHallSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, ExtCtrls, ComCtrls, InternationalizerComponent; const tidActualRuler = 'ActualRuler'; tidRulerPrestige = 'RulerPrestige'; tidRulerRating = 'RulerRating'; tidTycoonsRating = 'TycoonsRating'; tidCampainCount = 'CampaignCount'; tidYearsToElections = 'YearsToElections'; tidHasRuler = 'HasRuler'; tidTownName = 'Town'; tidNewspaper = 'NewspaperName'; tidCovCount = 'covCount'; tidRulerPeriods = 'RulerPeriods'; const facStoppedByTycoon = $04; type TTownHallPoliticSheetHandler = class; TPoliticSheetViewer = class(TVisualControl) Label9: TLabel; xfer_ActualRuler: TLabel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; xfer_RulerPrestige: TLabel; xfer_RulerRating: TLabel; xfer_TycoonRating: TLabel; xfer_RulerPeriods: TLabel; xfer_YearsToElections: TLabel; btnVisitPolitics: TFramedButton; Label8: TLabel; xfer_QOL: TLabel; Label14: TLabel; RateMayor: TFramedButton; ReadNews: TFramedButton; Panel1: TPanel; Coverage: TListView; InternationalizerComponent1: TInternationalizerComponent; procedure btnVisitPoliticsClick(Sender: TObject); procedure RateMayorClick(Sender: TObject); procedure ReadNewsClick(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TTownHallPoliticSheetHandler; protected procedure SetParent(which : TWinControl); override; end; TTownHallPoliticSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TPoliticSheetViewer; public function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure GetTownProperties(Names, Props : TStringList; Update : integer); procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure threadedGetCoverage(const parms : array of const); procedure syncGetCoverage(const parms : array of const); private fTown : string; fPaperName : string; end; var PoliticSheetViewer: TPoliticSheetViewer; function TownHallPoliticSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, FiveViewUtils, CacheCommon, VoyagerServerInterfaces, ObjectInspectorHandleViewer, ObjectInspectorHandler, Literals, {$IFDEF VER140} Variants, {$ENDIF} ClientMLS, CoolSB; {$R *.DFM} // TTownHallPoliticSheetHandler function TTownHallPoliticSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TPoliticSheetViewer.Create(Owner); fControl.fHandler := self; //fContainer.ChangeHeight(130); result := fControl; end; function TTownHallPoliticSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TTownHallPoliticSheetHandler.RenderProperties(Properties : TStringList); var hasRuler : boolean; years : string; count : integer; begin FiveViewUtils.SetViewProp(fControl, Properties); hasRuler := Properties.Values[tidHasRuler] = '1'; years := Properties.Values[tidYearsToElections]; fPaperName := Properties.Values[tidNewspaper]; if trim(years) > '1' then years := GetFormattedLiteral('Literal94', [years]) else years := GetLiteral('Literal95'); if hasRuler then begin fControl.xfer_ActualRuler.Caption := Properties.Values[tidActualRuler]; fControl.xfer_RulerPrestige.Caption := GetFormattedLiteral('Literal96', [Properties.Values[tidRulerPrestige]]); fControl.xfer_RulerRating.Caption := Properties.Values[tidRulerRating] + '%'; fControl.xfer_TycoonRating.Caption := Properties.Values[tidTycoonsRating] + '%'; //fControl.xfer_RulerPeriods.Caption := Properties.Values[tidCampainCount]; fControl.xfer_RulerPeriods.Caption := Properties.Values['RulerPeriods']; fControl.xfer_YearsToElections.Caption := years; end else begin fControl.xfer_ActualRuler.Caption := GetLiteral('Literal97'); fControl.xfer_RulerPrestige.Caption := GetLiteral('Literal98'); fControl.xfer_RulerRating.Caption := GetLiteral('Literal99'); fControl.xfer_TycoonRating.Caption := GetLiteral('Literal100'); fControl.xfer_RulerPeriods.Caption := GetLiteral('Literal101'); fControl.xfer_YearsToElections.Caption := years; end; fControl.btnVisitPolitics.Enabled := true; fControl.RateMayor.Enabled := true; fControl.ReadNews.Enabled := true; count := StrToInt(Properties.Values[tidCovCount]); fControl.Coverage.Items.Clear; Fork( threadedGetCoverage, priNormal, [count] ); end; procedure TTownHallPoliticSheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; Names := TStringList.Create; fControl.btnVisitPolitics.Enabled := false; fControl.RateMayor.Enabled := false; fControl.ReadNews.Enabled := false; Threads.Fork(threadedGetProperties, priHigher, [Names, fLastUpdate]); end; end; procedure TTownHallPoliticSheetHandler.Clear; begin inherited; //fControl.xfer_Cluster.Caption := 'n/a'; fControl.xfer_QOL.Caption := '0'; { fControl.xfer_covHealth.Caption := '0'; fControl.xfer_covSchool.Caption := '0'; fControl.xfer_covPolice.Caption := '0'; fControl.xfer_covFire.Caption := '0'; } fControl.xfer_ActualRuler.Caption := GetLiteral('Literal102'); fControl.xfer_RulerPrestige.Caption := GetLiteral('Literal103'); fControl.xfer_RulerRating.Caption := GetLiteral('Literal104'); fControl.xfer_RulerPeriods.Caption := GetLiteral('Literal105'); fControl.xfer_YearsToElections.Caption := GetLiteral('Literal106'); fControl.btnVisitPolitics.Enabled := false; fControl.RateMayor.Enabled := false; fControl.ReadNews.Enabled := false; end; procedure TTownHallPoliticSheetHandler.GetTownProperties(Names, Props : TStringList; Update : integer); var Proxy : OleVariant; Path : string; begin Proxy := fContainer.CreateCacheObjectProxy; Path := '\Towns\' + fTown + '.five\'; if (fLastUpdate = Update) and not VarIsEmpty(Proxy) and Proxy.SetPath(Path) then GetContainer.GetPropertyList(Proxy, Names, Props); end; procedure TTownHallPoliticSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList absolute parms[0].vPointer; Update : integer; Prop : TStringList; begin try Update := parms[1].vInteger; try Names.Add(tidTownName); FiveViewUtils.GetViewPropNames(fControl, Names); Prop := fContainer.GetProperties(Names); Names.Clear; fTown := Prop.Values[tidTownName]; if (Update = fLastUpdate) and (fTown <> '') then begin Names.Add(tidActualRuler); Names.Add(tidRulerPrestige); Names.Add(tidRulerRating); Names.Add(tidTycoonsRating); Names.Add(tidCampainCount); Names.Add(tidRulerPeriods); Names.Add(tidYearsToElections); Names.Add(tidHasRuler); Names.Add(tidNewspaper); Names.Add(tidCovCount); GetTownProperties(Names, Prop, Update); if Update = fLastUpdate then Threads.Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; end; finally Names.Free; end; except end; end; procedure TTownHallPoliticSheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if fLastUpdate = parms[1].vInteger then RenderProperties(Prop); finally Prop.Free; end; except end; end; procedure TTownHallPoliticSheetHandler.threadedGetCoverage(const parms : array of const); var count : integer absolute parms[0].vInteger; i : integer; iStr : string; Values : TStringList; covName : string; covValue : integer; Proxy : olevariant; begin try Proxy := fContainer.GetCacheObjectProxy; for i := 0 to pred(count) do begin Values := TStringList.Create; try iStr := IntToStr(i); GetContainer.GetPropertyArray(Proxy, ['covValue' + iStr, 'covName' + iStr + '.' + ActiveLanguage], Values); covName := Values.Values['covName' + iStr + '.' + ActiveLanguage]; try covValue := StrToInt(Values.Values['covValue' + iStr]); except covValue := 0; end; Threads.Join(syncGetCoverage, [covName, covValue]); Values.Clear; finally Values.Free; end; end; except end; end; procedure TTownHallPoliticSheetHandler.syncGetCoverage(const parms : array of const); begin with fControl.Coverage.Items.Add do begin Caption := parms[0].vPchar; SubItems.Add( IntToStr(parms[1].vInteger) + '%' ); end; end; // TownHallPoliticSheetHandlerCreator function TownHallPoliticSheetHandlerCreator : IPropertySheetHandler; begin result := TTownHallPoliticSheetHandler.Create; end; // TTownHallSheetViewer procedure TPoliticSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TPoliticSheetViewer.btnVisitPoliticsClick(Sender: TObject); var URL : string; Clv : IClientView; begin Clv := fHandler.GetContainer.GetClientView; URL := Clv.getWorldURL + 'Visual/Voyager/Politics/politics.asp' + '?WorldName=' + Clv.getWorldName + '&TycoonName=' + Clv.getUserName + '&Password=' + Clv.getUserPassword + '&TownName=' + fHandler.fTown + '&DAAddr=' + Clv.getDAAddr + '&DAPort=' + IntToStr(Clv.getDALockPort); URL := URL + '&frame_Id=PoliticsView&frame_Class=HTMLView&frame_NoBorder=Yes&frame_Align=client::?frame_Id=' + tidHandlerName_ObjInspector + '&frame_Close=yes'; fHandler.GetContainer.HandleURL(URL, false); end; procedure TPoliticSheetViewer.RateMayorClick(Sender: TObject); var URL : string; Clv : IClientView; begin Clv := fHandler.GetContainer.GetClientView; URL := Clv.getWorldURL + 'Visual/News/boardreader.asp' + '?WorldName=' + Clv.getWorldName + '&Tycoon=' + Clv.getUserName + '&Password=' + Clv.getUserPassword + '&TownName=' + fHandler.fTown + '&PaperName=' + fHandler.fPaperName + '&DAAddr=' + Clv.getDAAddr + '&DAPort=' + IntToStr(Clv.getDALockPort); URL := URL + '&frame_Id=NewsView&frame_Class=HTMLView&frame_NoBorder=Yes&frame_Align=client::?frame_Id=' + tidHandlerName_ObjInspector + '&frame_Close=yes'; fHandler.GetContainer.HandleURL(URL, false); end; procedure TPoliticSheetViewer.ReadNewsClick(Sender: TObject); var URL : string; Clv : IClientView; begin Clv := fHandler.GetContainer.GetClientView; URL := Clv.getWorldURL + 'Visual/News/newsreader.asp' + '?WorldName=' + Clv.getWorldName + '&Tycoon=' + Clv.getUserName + '&Password=' + Clv.getUserPassword + '&TownName=' + fHandler.fTown + '&PaperName=' + fHandler.fPaperName + '&DAAddr=' + Clv.getDAAddr + '&DAPort=' + IntToStr(Clv.getDALockPort); URL := URL + '&frame_Id=NewsView&frame_Class=HTMLView&frame_NoBorder=Yes&frame_Align=client::?frame_Id=' + tidHandlerName_ObjInspector + '&frame_Close=yes'; fHandler.GetContainer.HandleURL(URL, false); end; procedure TPoliticSheetViewer.SetParent(which: TWinControl); begin inherited; if InitSkinImage and (which<>nil) then begin InitializeCoolSB(Coverage.Handle); if hThemeLib <> 0 then SetWindowTheme(Coverage.Handle, ' ', ' '); end; end; initialization SheetHandlerRegistry.RegisterSheetHandler('townGeneral', TownHallPoliticSheetHandlerCreator); end.
unit unicode_external; interface function uni_fromUTF8(dest : PAnsiChar; const utf8: PAnsiChar; chars: Cardinal; utf_read: Cardinal; string_type: Cardinal; line_type: AnsiChar; written: Cardinal) : LongInt; cdecl; function uni_toUTF8(utf8: PAnsiChar; const src: PAnsiChar; chars: Cardinal; string_type: Cardinal; line_type: Byte; written: Cardinal) : LongInt; cdecl; implementation type uni_slong = Longint; uni_ulong = Cardinal; uni_uword = Cardinal; uni_ubyte = Byte; uni_ushort = Word; size_t = Cardinal; Puni_uword = ^uni_uword; puni_ulong = ^uni_ulong; puni_ushort = ^uni_ushort; puni_ubyte = ^uni_ubyte; {$LINK 'uni_base64.obj'} {$LINK 'uni_fromuni.obj'} {$LINK 'uni_touni.obj'} {$LINK 'uni_unicode.obj'} function strlen(const Str: PAnsiChar): Cardinal; cdecl; external 'msvcrt.dll' name 'strlen'; function sprintf(S: PAnsiChar; const Format: PChar): Integer; cdecl; varargs; external 'msvcrt.dll' name 'sprintf'; function strcpy(dest : PAnsiChar; const src : PAnsiChar) : PAnsiChar; cdecl; external 'msvcrt.dll' name 'strcpy'; function isdigit(c : Integer) : Integer; cdecl; external 'msvcrt.dll' name 'isdigit'; function memcpy(dest : Pointer; const src : Pointer; n : size_t ) : Pointer; cdecl; external 'msvcrt.dll' name 'memcpy'; function sscanf(const buffer : PAnsiChar; const format: PAnsiChar) : Integer; cdecl; varargs; external 'msvcrt.dll' name 'sscanf'; function _ltoupper(c: Integer): Integer; cdecl; external 'msvcrt.dll' name '_toupper'; function uni_isbase64char(c : AnsiChar; padding : Integer): Integer; cdecl; external; //function _uni_base64delen(datasize: uni_uword) : uni_uword; cdecl; external; function uni_base64decode(data : Pointer; carry : Smallint; const src : PChar; bytes_written : puni_uword) : uni_uword; cdecl; external; function uni_base64encode(dest : PAnsiChar; const data: Pointer; datasize: uni_uword; padding : Integer; funct : Pointer): uni_slong; cdecl; external; function uni_fromUTF8(dest : PAnsiChar; const utf8: PAnsiChar; chars: Cardinal; utf_read: Cardinal; string_type: Cardinal; line_type: AnsiChar; written: Cardinal) : LongInt; cdecl; external; function uni_toUTF8(utf8: PAnsiChar; const src: PAnsiChar; chars: Cardinal; string_type: Cardinal; line_type: Byte; written: Cardinal) : LongInt; cdecl; external; //function _uni_ucs4arraytoutf7(utf7 : PChar; ucs4 : puni_ulong; length : uni_ubyte) : uni_slong; cdecl; external; //function _uni_utf16toutf8(utf8 : PChar; const utf16: puni_ushort; s_read : puni_ubyte) : uni_slong; cdecl; external; end.
unit uFormaPagto; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBaseCadastro, Data.DB, Vcl.StdCtrls, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.ComCtrls, uDMformaPagto, uFormaPagtoController, Vcl.Mask, Vcl.DBCtrls, uFuncoesSIDomper; type TfrmFormaPagto = class(TfrmBaseCadastro) Label4: TLabel; Label5: TLabel; edtCodigo: TDBEdit; edtNome: TDBEdit; Ativo: TDBCheckBox; dbForma: TDBGrid; dsItens: TDataSource; procedure edtDescricaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnFiltroClick(Sender: TObject); procedure dbDadosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormDestroy(Sender: TObject); procedure btnNovoClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnFecharEdicaoClick(Sender: TObject); procedure btnImprimirClick(Sender: TObject); procedure dbDadosTitleClick(Column: TColumn); procedure dbFormaDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure dbFormaEnter(Sender: TObject); procedure dbFormaExit(Sender: TObject); procedure dbFormaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dsItensStateChange(Sender: TObject); private { Private declarations } FController: TFormaPagtoController; procedure Localizar(ATexto: string); procedure Excluir(Sender: TObject; var Key: Word; Shift: TShiftState); public { Public declarations } constructor create(APesquisar: Boolean = False); end; var frmFormaPagto: TfrmFormaPagto; implementation {$R *.dfm} uses uGrade, uDM; procedure TfrmFormaPagto.btnEditarClick(Sender: TObject); begin FController.Editar(dbDados.Columns[0].Field.AsInteger, Self); inherited; if edtNome.Enabled then edtNome.SetFocus; end; procedure TfrmFormaPagto.btnExcluirClick(Sender: TObject); begin if TFuncoes.Confirmar('Excluir Registro?') then begin FController.Excluir(dm.IdUsuario, dbDados.Columns[0].Field.AsInteger); inherited; end; end; procedure TfrmFormaPagto.btnFecharEdicaoClick(Sender: TObject); begin FController.Cancelar; inherited; end; procedure TfrmFormaPagto.btnFiltroClick(Sender: TObject); begin inherited; Localizar(edtDescricao.Text); end; procedure TfrmFormaPagto.btnImprimirClick(Sender: TObject); begin Localizar(edtDescricao.Text); FController.Imprimir(dm.IdUsuario); inherited; end; procedure TfrmFormaPagto.btnNovoClick(Sender: TObject); begin FController.Novo(dm.IdUsuario); inherited; edtCodigo.SetFocus; end; procedure TfrmFormaPagto.btnSalvarClick(Sender: TObject); begin FController.Salvar(dm.IdUsuario); FController.FiltrarCodigo(FController.CodigoAtual()); inherited; end; constructor TfrmFormaPagto.create(APesquisar: Boolean); begin inherited create(nil); FController := TFormaPagtoController.Create; dsPesquisa.DataSet := FController.Model.CDSConsulta; dsCad.DataSet := FController.Model.CDSCadastro; TGrade.RetornaCamposGrid(dbDados, cbbCampos); Localizar('ABCDE'); if APesquisar then begin cbbSituacao.ItemIndex := 0; Pesquisa := APesquisar; end; end; procedure TfrmFormaPagto.dbDadosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin dbDadosDblClick(Self); if edtCodigo.Enabled then edtCodigo.SetFocus; end; end; procedure TfrmFormaPagto.dbDadosTitleClick(Column: TColumn); begin inherited; TFuncoes.OrdenarCamposGrid(FController.Model.cdsconsulta, Column.FieldName); end; procedure TfrmFormaPagto.dbFormaDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin inherited; TGrade.Zebrar(dsItens.DataSet, dbForma, Sender, Rect, DataCol, Column, State); end; procedure TfrmFormaPagto.dbFormaEnter(Sender: TObject); begin inherited; Self.KeyPreview := False; end; procedure TfrmFormaPagto.dbFormaExit(Sender: TObject); begin inherited; Self.KeyPreview := True; end; procedure TfrmFormaPagto.dbFormaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then begin if dbForma.SelectedIndex < 1 then dbForma.SelectedIndex := dbForma.SelectedIndex + 1 else begin dbForma.SelectedIndex := 0; dsItens.DataSet.Append; end; end; if Key = VK_INSERT then Key := 0; case key of VK_F8: begin if btnSalvar.Enabled then begin btnSalvar.SetFocus; btnSalvarClick(Self); end; end; VK_ESCAPE: begin if btnCancelar.Enabled then begin btnCancelar.SetFocus; btnCancelarClick(Self); end; end; end; Excluir(Sender, Key, Shift); TGrade.DesabilitarTelcasDeleteGrid(Key, Shift); end; procedure TfrmFormaPagto.dsItensStateChange(Sender: TObject); begin inherited; if dsItens.State in [dsEdit, dsInsert] then TFuncoes.ModoEdicaoInsercao(dsCad.DataSet); end; procedure TfrmFormaPagto.edtDescricaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then Localizar(edtDescricao.Text); end; procedure TfrmFormaPagto.Excluir(Sender: TObject; var Key: Word; Shift: TShiftState); begin if tsEdicao.Showing then begin if (Shift = [ssCtrl]) and (Key = VK_DELETE) then begin if FController.Model.CDSItens.IsEmpty then raise Exception.Create('Não há Registro!') else begin if TFuncoes.Confirmar('Confirmar Exclsão do Item?') then begin FController.Model.CDSItens.Delete; TFuncoes.ModoEdicaoInsercao(dsCad.DataSet); end; end; end; end; end; procedure TfrmFormaPagto.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(FController); end; procedure TfrmFormaPagto.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; Excluir(Sender, Key, Shift); end; procedure TfrmFormaPagto.Localizar(ATexto: string); var sCampo: string; sSituacao: string; bContem: Boolean; begin sCampo := TGrade.FiltrarCampo(dbDados, cbbCampos); sSituacao := Copy(cbbSituacao.Items.Strings[cbbSituacao.ItemIndex], 1, 1); bContem := (cbbPesquisa.ItemIndex = 1); FController.Filtrar(sCampo, ATexto, sSituacao, bContem); end; end.
unit SDFrameDataViewer; interface uses Windows, Messages, Forms, BaseFrame, StdCtrls, Controls, ComCtrls, Classes, ExtCtrls, SysUtils, VirtualTrees, DealItemsTreeView, define_datasrc, define_StockDataApp, define_price, define_datetime, define_dealitem, define_stock_quotes, define_dealstore_file, BaseWinApp, StockDayDataAccess, StockDetailDataAccess, StockDataConsoleTask; type TfmeDataViewerData = record DownloadAllTasks: array[TDealDataSource] of PDownloadTask; DayDataAccess: StockDayDataAccess.TStockDayDataAccess; DetailDataAccess: TStockDetailDataAccess; DayDataSrc: TDealDataSource; WeightMode: TRT_WeightMode; DealItem: PRT_DealItem; OnGetDealItem: TOnDealItemFunc; end; TfmeDataViewer = class(TfmeBase) pnlRight: TPanel; mmo1: TMemo; pnlMiddle: TPanel; pnlDayDataTop: TPanel; Label1: TLabel; cmbDayDataSrc: TComboBoxEx; vtDayDatas: TVirtualStringTree; spl1: TSplitter; tmrRefreshDownloadTask: TTimer; btnDownloadDay: TButton; chkShutDown: TCheckBox; vtTasks: TVirtualStringTree; pnlDetailTop: TPanel; cmbDetailDataSrc: TComboBoxEx; vtDetailDatas: TVirtualStringTree; btnDownDetail: TButton; procedure btnDownloadDayClick(Sender: TObject); procedure tmrRefreshDownloadTaskTimer(Sender: TObject); procedure cmbDayDataSrcChange(Sender: TObject); procedure btnDownDetailClick(Sender: TObject); protected fDataViewerData: TfmeDataViewerData; procedure SetDayDataSrc(AValue: TDealDataSource); function GetDayDataSrc: TDealDataSource; function GetStockCode: integer; function NewDownloadAllTask(ATaskDataType: TTaskType; ADataSrc: TDealDataSource; ADownloadTask: PDownloadTask): PDownloadTask; procedure RequestDownloadStockData(ADownloadTask: PDownloadTask); procedure RequestDownloadProcessTaskStockData(AProcessTask: PDownloadProcessTask); procedure LoadDayDataTreeView(AStockItem: PRT_DealItem); procedure DayDataTreeViewInitialize; procedure vtDayDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure vtDayDatasChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TaskTreeViewInitialize; procedure AddTaskNode(ADownloadTask: PDownloadTask); procedure vtTasksGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); function GetDetailDataSrc: TDealDataSource; procedure DetailDataTreeViewInitialize; procedure vtDetailDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure LoadDetailTreeViewData; public constructor Create(Owner: TComponent); override; procedure Initialize; override; procedure NotifyDealItem(ADealItem: PRT_DealItem); property OnGetDealItem: TOnDealItemFunc read fDataViewerData.OnGetDealItem write fDataViewerData.OnGetDealItem; end; implementation {$R *.dfm} uses win.shutdown, define_deal, BaseStockFormApp, StockDataConsoleApp, StockDetailData_Load, StockDayData_Load; type PStockDayDataNode = ^TStockDayDataNode; TStockDayDataNode = record DayIndex: integer; QuoteData: PRT_Quote_Day; end; PStockDetailDataNode = ^TStockDetailDataNode; TStockDetailDataNode = record QuoteData: PRT_Quote_Detail; end; PTaskDataNode = ^TTaskDataNode; TTaskDataNode = record DownloadTask: PDownloadTask; DownProcessTask: PDownloadProcessTask; end; constructor TfmeDataViewer.Create(Owner: TComponent); begin inherited; FillChar(fDataViewerData, SizeOf(fDataViewerData), 0); end; procedure TfmeDataViewer.Initialize; begin cmbDayDataSrc.Clear; cmbDayDataSrc.Items.Add(GetDataSrcName(src_163)); cmbDayDataSrc.Items.Add(GetDataSrcName(src_sina)); cmbDayDataSrc.Items.Add(GetDataSrcName(src_all)); cmbDetailDataSrc.Clear; cmbDetailDataSrc.Items.Add(GetDataSrcName(src_163)); cmbDetailDataSrc.Items.Add(GetDataSrcName(src_sina)); DayDataTreeViewInitialize; TaskTreeViewInitialize; DetailDataTreeViewInitialize; end; procedure TfmeDataViewer.NotifyDealItem(ADealItem: PRT_DealItem); begin LoadDayDataTreeView(ADealItem); end; function TfmeDataViewer.GetStockCode: integer; var tmpCode: string; tmpPos: integer; begin Result := 0; tmpCode := Trim(cmbDayDataSrc.Text); tmpPos := Pos(':', tmpCode); if 0 < tmpPos then begin tmpCode := Copy(tmpCode, tmpPos + 1, maxint); Result := StrToIntDef(tmpCode, 0); end; end; function TfmeDataViewer.GetDayDataSrc: TDealDataSource; var s: string; tmpName: string; tmpSrc: TDealDataSource; begin Result := src_unknown; s := lowercase(Trim(cmbDayDataSrc.Text)); if 0 < cmbDayDataSrc.ItemIndex then s := Trim(cmbDayDataSrc.Items[cmbDayDataSrc.ItemIndex]); if '' <> s then begin for tmpSrc := Low(TDealDataSource) to High(TDealDataSource) do begin tmpName := lowercase(GetDataSrcName(tmpSrc)); if '' <> tmpName then begin if 0 < Pos(tmpName, s) then begin Result := tmpSrc; Break; end; end; end; end; end; function TfmeDataViewer.GetDetailDataSrc: TDealDataSource; var s: string; tmpName: string; tmpSrc: TDealDataSource; begin Result := src_unknown; s := lowercase(Trim(cmbDetailDataSrc.Text)); for tmpSrc := Low(TDealDataSource) to High(TDealDataSource) do begin tmpName := lowercase(GetDataSrcName(tmpSrc)); if '' <> tmpName then begin if 0 < Pos(tmpName, s) then begin Result := tmpSrc; exit; end; end; end; end; procedure TfmeDataViewer.RequestDownloadProcessTaskStockData(AProcessTask: PDownloadProcessTask); begin TStockDataConsoleApp(App.AppAgent).TaskConsole.RunProcessTask(AProcessTask); end; type TDayColumns = ( colIndex, colDate, colOpen, colClose, colHigh, colLow, colDayVolume, colDayAmount, colWeight ); const DayColumnsText: array[TDayColumns] of String = ( 'Index', '日期', '开盘', '收盘', '最高', '最低', '成交量', '成交金额', '权重' ); DayColumnsWidth: array[TDayColumns] of integer = ( 60, 0, 0, 0, 0, 0, 0, 0, 0 ); procedure TfmeDataViewer.TaskTreeViewInitialize; var tmpCol: TVirtualTreeColumn; begin vtTasks.NodeDataSize := SizeOf(TTaskDataNode); vtTasks.Header.Options := [hoColumnResize, hoAutoResize, hoVisible]; vtTasks.Header.Columns.Clear; vtTasks.OnGetText := vtTasksGetText; tmpCol := vtTasks.Header.Columns.Add; tmpCol.Text := '下载任务'; end; procedure TfmeDataViewer.DayDataTreeViewInitialize; var col_day: TDayColumns; tmpCol: TVirtualTreeColumn; begin vtDayDatas.NodeDataSize := SizeOf(TStockDayDataNode); vtDayDatas.Header.Options := [hoColumnResize, hoVisible]; vtDayDatas.Header.Columns.Clear; vtDayDatas.TreeOptions.SelectionOptions := [toFullRowSelect]; vtDayDatas.TreeOptions.AnimationOptions := []; vtDayDatas.TreeOptions.MiscOptions := [toAcceptOLEDrop,toFullRepaintOnResize,toInitOnSave,toToggleOnDblClick,toWheelPanning,toEditOnClick]; vtDayDatas.TreeOptions.PaintOptions := [toShowButtons,toShowDropmark,{toShowRoot} toShowTreeLines,toThemeAware,toUseBlendedImages]; vtDayDatas.TreeOptions.StringOptions := [toSaveCaptions,toAutoAcceptEditChange]; for col_day := low(TDayColumns) to high(TDayColumns) do begin tmpCol := vtDayDatas.Header.Columns.Add; tmpCol.Text := DayColumnsText[col_day]; case col_day of colIndex: tmpCol.Width := vtDayDatas.Canvas.TextWidth('2000'); colDate: tmpCol.Width := vtDayDatas.Canvas.TextWidth('2016-12-12'); colOpen: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000'); colClose: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000'); colHigh: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000'); colLow: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000'); colDayVolume: ; colDayAmount: ; colWeight: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000'); end; if 0 <> tmpCol.Width then begin tmpCol.Width := tmpCol.Width + vtDayDatas.TextMargin + vtDayDatas.Indent; end else begin if 0 = DayColumnsWidth[col_day] then begin tmpCol.Width := 120; end else begin tmpCol.Width := DayColumnsWidth[col_day]; end; end; end; vtDayDatas.OnGetText := vtDayDatasGetText; vtDayDatas.OnChange := vtDayDatasChange; //vtDayDatas.OnChange := vtDayDatasChange; end; procedure TfmeDataViewer.vtDayDatasChange(Sender: TBaseVirtualTree; Node: PVirtualNode); var tmpNodeData: PStockDayDataNode; tmpDataSrc: TDealDataSource; tmpFileUrl: string; begin inherited; if nil = Node then exit; tmpNodeData := Sender.GetNodeData(Node); if nil = tmpNodeData then exit; if nil = tmpNodeData.QuoteData then exit; tmpDataSrc := GetDetailDataSrc; if src_unknown = tmpDataSrc then exit; tmpFileUrl := TBaseStockApp(App).StockAppPath.GetFileUrl( fDataViewerData.DayDataAccess.StockItem.DBType, TStockDetailDataAccess.DataTypeDefine, GetDealDataSourceCode(tmpDataSrc), tmpNodeData.QuoteData.DealDate.Value, fDataViewerData.DayDataAccess.StockItem); if not FileExists(tmpFileUrl) then begin tmpFileUrl := ChangeFileExt(tmpFileUrl, '.sdet'); end; //tmpFileUrl := 'E:\StockApp\sdata\sdetsina\600000\600000_20151125.sdet'; if FileExists(tmpFileUrl) then begin if nil <> fDataViewerData.DetailDataAccess then FreeAndNil(fDataViewerData.DetailDataAccess); if nil = fDataViewerData.DetailDataAccess then fDataViewerData.DetailDataAccess := TStockDetailDataAccess.Create(fDataViewerData.DayDataAccess.StockItem, tmpDataSrc); fDataViewerData.DetailDataAccess.Clear; fDataViewerData.DetailDataAccess.StockItem := fDataViewerData.DayDataAccess.StockItem; fDataViewerData.DetailDataAccess.FirstDealDate := tmpNodeData.QuoteData.DealDate.Value; LoadStockDetailData( App, fDataViewerData.DetailDataAccess, tmpFileUrl); end; LoadDetailTreeViewData; end; procedure TfmeDataViewer.vtDayDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var tmpNodeData: PStockDayDataNode; begin CellText := ''; tmpNodeData := Sender.GetNodeData(Node); if nil <> tmpNodeData then begin if nil <> tmpNodeData.QuoteData then begin if Integer(colIndex) = Column then begin CellText := IntToStr(Node.Index); exit; end; if Integer(colDate) = Column then begin CellText := FormatDateTime('yyyymmdd', tmpNodeData.QuoteData.DealDate.Value); exit; end; if Integer(colOpen) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceOpen.Value); exit; end; if Integer(colClose) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceClose.Value); exit; end; if Integer(colHigh) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceHigh.Value); exit; end; if Integer(colLow) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceLow.Value); exit; end; if Integer(colDayVolume) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.DealVolume); exit; end; if Integer(colDayAmount) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.DealAmount); exit; end; if Integer(colWeight) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.Weight.Value); exit; end; end; end; end; procedure TfmeDataViewer.LoadDayDataTreeView(AStockItem: PRT_DealItem); var i: integer; tmpStockDataNode: PStockDayDataNode; tmpStockData: PRT_Quote_Day; tmpNode: PVirtualNode; tmpDataSrc: TDealDataSource; begin if nil = AStockItem then exit; vtDayDatas.BeginUpdate; try vtDayDatas.Clear; if nil = AStockItem then exit; //fFormSDConsoleData.DayDataAccess := AStockItem.StockDayDataAccess; tmpDataSrc := GetDayDataSrc; if src_unknown = tmpDataSrc then exit; if nil <> fDataViewerData.DayDataAccess then begin FreeAndNil(fDataViewerData.DayDataAccess); end; if nil = fDataViewerData.DayDataAccess then begin if src_163 = tmpDataSrc then fDataViewerData.WeightMode := weightNone; if src_sina = tmpDataSrc then fDataViewerData.WeightMode := weightBackward; fDataViewerData.DayDataAccess := TStockDayDataAccess.Create(AStockItem, tmpDataSrc, fDataViewerData.WeightMode); LoadStockDayData(App, fDataViewerData.DayDataAccess); end; //fDataViewerData.Rule_BDZX_Price := AStockItem.Rule_BDZX_Price; //fDataViewerData.Rule_CYHT_Price := AStockItem.Rule_CYHT_Price; for i := fDataViewerData.DayDataAccess.RecordCount - 1 downto 0 do begin tmpStockData := fDataViewerData.DayDataAccess.RecordItem[i]; tmpNode := vtDayDatas.AddChild(nil); tmpStockDataNode := vtDayDatas.GetNodeData(tmpNode); tmpStockDataNode.QuoteData := tmpStockData; tmpStockDataNode.DayIndex := i; end; finally vtDayDatas.EndUpdate; end; end; procedure TfmeDataViewer.RequestDownloadStockData(ADownloadTask: PDownloadTask); begin if IsWindow(TBaseWinApp(App).AppWindow) then begin PostMessage(TBaseWinApp(App).AppWindow, WM_Console_Command_Download, 1, Integer(ADownloadTask)); end; if not tmrRefreshDownloadTask.Enabled then tmrRefreshDownloadTask.Enabled := True; end; procedure TfmeDataViewer.tmrRefreshDownloadTaskTimer(Sender: TObject); function CheckTask(ADownloadTask: PDownloadTask): integer; var exitcode_process: DWORD; tick_gap: DWORD; waittime: DWORD; begin Result := 0; if nil = ADownloadTask then exit; Result := 1; if TaskStatus_End = ADownloadTask.TaskStatus then begin Result := 0; end else begin Windows.GetExitCodeProcess(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle, exitcode_process); if Windows.STILL_ACTIVE <> exitcode_process then begin ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle := 0; ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessId := 0; ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd := 0; // 这里下载进程 shutdown 了 if TaskStatus_Active = ADownloadTask.TaskStatus then begin if nil = ADownloadTask.DownProcessTaskArray[0].DealItem then begin ADownloadTask.DownProcessTaskArray[0].DealItem := TStockDataConsoleApp(App.AppAgent).TaskConsole.Console_GetNextDownloadDealItem(@ADownloadTask.DownProcessTaskArray[0]); end; if nil <> ADownloadTask.DownProcessTaskArray[0].DealItem then begin RequestDownloadProcessTaskStockData(@ADownloadTask.DownProcessTaskArray[0]); end; end; end else begin if ADownloadTask.DownProcessTaskArray[0].MonitorDealItem <> ADownloadTask.DownProcessTaskArray[0].DealItem then begin ADownloadTask.DownProcessTaskArray[0].MonitorDealItem := ADownloadTask.DownProcessTaskArray[0].DealItem; ADownloadTask.DownProcessTaskArray[0].MonitorTick := GetTickCount; end else begin //Log('SDConsoleForm.pas', 'tmrRefreshDownloadTaskTimer CheckTask TerminateProcess Wnd :' + // IntToStr(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd)); if 0 = ADownloadTask.DownProcessTaskArray[0].MonitorTick then begin ADownloadTask.DownProcessTaskArray[0].MonitorTick := GetTickCount; end else begin tick_gap := GetTickCount - ADownloadTask.DownProcessTaskArray[0].MonitorTick; waittime := 10 * 1000; case ADownloadTask.TaskDataSrc of src_all : waittime := 30 * 1000; src_ctp: waittime := 10 * 1000; src_offical: waittime := 10 * 1000; src_tongdaxin: waittime := 10 * 1000; src_tonghuasun: waittime := 10 * 1000; src_dazhihui: waittime := 10 * 1000; src_sina: waittime := 3 * 60 * 1000; src_163: waittime := 25 * 1000; src_qq: waittime := 20 * 1000; src_xq: waittime := 20 * 1000; end; if tick_gap > waittime then begin //Log('SDConsoleForm.pas', 'tmrRefreshDownloadTaskTimer CheckTask TerminateProcess Wnd :' + // IntToStr(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd)); TerminateProcess(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle, 0); ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle := 0; ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessId := 0; ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd := 0; end; end; end; end; end; end; var tmpActiveCount: integer; begin inherited; tmpActiveCount := CheckTask(fDataViewerData.DownloadAllTasks[src_163]); tmpActiveCount := tmpActiveCount + CheckTask(fDataViewerData.DownloadAllTasks[src_sina]); vtTasks.Invalidate; // tmpActiveCount := tmpActiveCount + CheckTask(fFormSDConsoleData.DownloadQQAllTask, edtStockQQ); // tmpActiveCount := tmpActiveCount + CheckTask(fFormSDConsoleData.DownloadXQAllTask, edtStockXQ); if 0 = tmpActiveCount then begin if chkShutDown.Checked then win.shutdown.ShutDown; end; end; procedure TfmeDataViewer.btnDownDetailClick(Sender: TObject); var tmpCode: integer; tmpSrc: TDealDataSource; tmpTask: TDownloadTask; begin tmpCode := GetStockCode; tmpSrc := GetDayDataSrc; if src_Unknown <> tmpSrc then begin if 0 <> tmpCode then begin FillChar(tmpTask, SizeOf(tmpTask), 0); tmpTask.TaskDataSrc := tmpSrc; tmpTask.TaskDealItemCode := tmpCode; tmpTask.TaskDataType := taskDetailData; RequestDownloadStockData(@tmpTask); end else begin if nil = fDataViewerData.DownloadAllTasks[tmpSrc] then begin fDataViewerData.DownloadAllTasks[tmpSrc] := NewDownloadAllTask(taskDetailData, tmpSrc, fDataViewerData.DownloadAllTasks[tmpSrc]); AddTaskNode(fDataViewerData.DownloadAllTasks[tmpSrc]); end; end; end; end; procedure TfmeDataViewer.btnDownloadDayClick(Sender: TObject); var tmpCode: integer; tmpSrc: TDealDataSource; tmpTask: TDownloadTask; begin tmpCode := GetStockCode; tmpSrc := GetDayDataSrc; if src_Unknown <> tmpSrc then begin if 0 <> tmpCode then begin FillChar(tmpTask, SizeOf(tmpTask), 0); tmpTask.TaskDataSrc := tmpSrc; tmpTask.TaskDealItemCode := tmpCode; tmpTask.TaskDataType := taskDayData; RequestDownloadStockData(@tmpTask); end else begin if nil = fDataViewerData.DownloadAllTasks[tmpSrc] then begin fDataViewerData.DownloadAllTasks[tmpSrc] := NewDownloadAllTask(taskDayData, tmpSrc, fDataViewerData.DownloadAllTasks[tmpSrc]); AddTaskNode(fDataViewerData.DownloadAllTasks[tmpSrc]); end; end; end; end; procedure TfmeDataViewer.AddTaskNode(ADownloadTask: PDownloadTask); var tmpVNode: PVirtualNode; tmpVNodeData: PTaskDataNode; begin tmpVNode := vtTasks.AddChild(nil); if nil = tmpVNode then exit; tmpVNodeData := vtTasks.GetNodeData(tmpVNode); if nil = tmpVNodeData then exit; tmpVNodeData.DownloadTask := ADownloadTask; end; procedure TfmeDataViewer.vtTasksGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var tmpVNodeData: PTaskDataNode; begin CellText := ''; tmpVNodeData := Sender.GetNodeData(Node); if nil <> tmpVNodeData then begin if nil <> tmpVNodeData.DownloadTask then begin if nil <> tmpVNodeData.DownloadTask.DownProcessTaskArray[0].DealItem then CellText := tmpVNodeData.DownloadTask.DownProcessTaskArray[0].DealItem.sCode; end; end; end; function TfmeDataViewer.NewDownloadAllTask(ATaskDataType: TTaskType; ADataSrc: TDealDataSource; ADownloadTask: PDownloadTask): PDownloadTask; begin Result := ADownloadTask; if nil = Result then begin Result := TStockDataConsoleApp(App.AppAgent).TaskConsole.GetDownloadTask(ATaskDataType, ADataSrc, 0); if nil = Result then begin Result := TStockDataConsoleApp(App.AppAgent).TaskConsole.NewDownloadTask(ATaskDataType, ADataSrc, 0); end; RequestDownloadStockData(Result); end; end; procedure TfmeDataViewer.SetDayDataSrc(AValue: TDealDataSource); begin end; procedure TfmeDataViewer.cmbDayDataSrcChange(Sender: TObject); begin inherited; if '' = Trim(cmbDayDataSrc.Text) then exit; // end; type TDetailColumns = ( colTime, colPrice, colDetailVolume, colDetailAmount, colType //, colBoll, colBollUP, colBollLP //, colCYHT_SK, colCYHT_SD //, colBDZX_AK, colBDZX_AD1, colBDZX_AJ ); const DetailColumnsText: array[TDetailColumns] of String = ( '时间', '价格', '成交量', '成交金额', '性质' ); DetailWidthText: array[TDetailColumns] of String = ( '15:00:00', '300.00', '成交量', '成交金额', '性质' ); procedure TfmeDataViewer.DetailDataTreeViewInitialize; var col_detail: TDetailColumns; tmpCol: TVirtualTreeColumn; begin vtDetailDatas.NodeDataSize := SizeOf(TStockDetailDataNode); vtDetailDatas.OnGetText := vtDetailDatasGetText; vtDetailDatas.Header.Options := [hoColumnResize, hoVisible]; vtDetailDatas.Header.Columns.Clear; for col_detail := low(TDetailColumns) to high(TDetailColumns) do begin tmpCol := vtDetailDatas.Header.Columns.Add; tmpCol.Text := DetailColumnsText[col_detail]; tmpCol.Width := vtDetailDatas.Canvas.TextWidth('XXX' + DetailWidthText[col_detail]); end; end; procedure TfmeDataViewer.vtDetailDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var tmpNodeData: PStockDetailDataNode; begin CellText := ''; tmpNodeData := Sender.GetNodeData(Node); if nil <> tmpNodeData then begin if nil <> tmpNodeData.QuoteData then begin if Integer(colTime) = Column then begin CellText := GetTimeText(@tmpNodeData.QuoteData.DealDateTime.Time); exit; end; if Integer(colPrice) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.Price.Value); exit; end; if Integer(colDetailVolume) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.DealVolume); exit; end; if Integer(colDetailAmount) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.DealAmount); exit; end; if Integer(colType) = Column then begin CellText := 'U'; if DealType_Buy = tmpNodeData.QuoteData.DealType then begin CellText := '买'; end; if DealType_Sale = tmpNodeData.QuoteData.DealType then begin CellText := '卖'; end; if DealType_Neutral = tmpNodeData.QuoteData.DealType then begin CellText := '中'; end; exit; end; end; end; end; procedure TfmeDataViewer.LoadDetailTreeViewData; var i: integer; tmpNodeData: PStockDetailDataNode; tmpDetailData: PRT_Quote_Detail; tmpNode: PVirtualNode; begin vtDetailDatas.Clear; vtDetailDatas.BeginUpdate; try if nil <> fDataViewerData.DetailDataAccess then begin for i := 0 to fDataViewerData.DetailDataAccess.RecordCount - 1 do begin tmpDetailData := fDataViewerData.DetailDataAccess.RecordItem[i]; tmpNode := vtDetailDatas.AddChild(nil); tmpNodeData := vtDetailDatas.GetNodeData(tmpNode); tmpNodeData.QuoteData := tmpDetailData; end; end; finally vtDetailDatas.EndUpdate; end; end; end.
unit GraphicExSavePictureDialog; interface uses SysUtils, Classes, Dialogs, ExtDlgs, graphics,controls,types, JPEG, buttons, extCtrls,pngImage; type TGraphicExSavePictureDialog = class(TSavePictureDialog) private { Private declarations } protected { Protected declarations } FGraphic: TGraphic; FGraphicToCompress: TGraphic; //paparazzi: stealing privacy from these controls //by FindComponent(name) - you can't hide if I know your name! CheatPreviewButton: TSpeedButton; CheatPicturePanel: TPanel; CheatPaintPanel: TPanel; ext: string; FMemoryStream: TMemoryStream; procedure DoTypeChange; override; procedure DoShow; override; procedure DoClose; override; public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; procedure DoSelectionChange; override; procedure ReloadPicture; procedure Save; //graphic is not owned by SavePictureDialog, property is just a reference to it property GraphicToSave: TGraphic read FGraphic write FGraphic; published { Published declarations } end; IGraphicPreferences = interface ['{36F23C04-76C9-4CDF-AA7D-FA7A556C8DF1}'] procedure ShowPreferences(control: TWinControl; var aBoundsRect: TRect; aFilterIndex: Integer); end; TGraphicExJPG = class(TJPEGImage, IGraphicPreferences) protected procedure CompressionRateChange(Sender: TObject); public procedure ShowPreferences(control: TWinControl; var aBoundsRect: TRect; aFilterIndex: Integer); end; TGraphicExPNG = class(TPNGObject, IGraphicPreferences) public procedure ShowPreferences(control: TWinControl; var aBoundsRect: TRect; aFilterIndex: Integer); end; TGraphicExBMP = class(TBitmap, IGraphicPreferences) protected procedure Monochromechange(Sender: TObject); public procedure ShowPreferences(control: TWinControl; var aBoundsRect: TRect; aFilterIndex: Integer); end; procedure Register; implementation uses GraphicEx,comCtrls,graphicStrings,stdCtrls; procedure Register; begin RegisterComponents('Nabbla', [TGraphicExSavePictureDialog]); end; constructor TGraphicExSavePictureDialog.Create(Owner: TComponent); begin inherited Create(Owner); fMemoryStream:=TMemoryStream.Create; CheatPreviewButton:=FindComponent('PreviewButton') as TSpeedButton; CheatPicturePanel:=FindComponent('PicturePanel') as TPanel; CheatPaintPanel:=FindComponent('PaintPanel') as TPanel; end; destructor TGraphicExSavePictureDialog.Destroy; begin fMemoryStream.Free; inherited Destroy; end; procedure TGraphicExSavePictureDialog.DoSelectionChange; begin //we don't want to show picture which is in file we want to overwrite //so we don't care at all about selection change, except event handling if Assigned(OnSelectionChange) then OnSelectionChange(Self); end; procedure TGraphicExSavePictureDialog.DoTypeChange; var i,j,k,counter: Integer; intf: IGraphicPreferences; PrefRect: TRect; begin // PictureLabel.Caption:=IntToStr(FilterIndex); counter:=1; //т.е идет 1-й интервал j:=0; for i:=1 to Length(Filter) do if Filter[i]='|' then begin inc(counter); if counter=2*FilterIndex then begin j:=i; break; end; end; if j=0 then Exit; k:=0; for i:=j+1 to Length(Filter) do if Filter[i]='|' then begin k:=i; break; end; if k=0 then k:=Length(Filter)+1; ext:=Copy(Filter,j+3,k-j-3); CheatPreviewButton.Enabled:=Assigned(FGraphic); if Assigned(FGraphic) then begin // ImageCtrl.Picture.Graphic:=ConvertToGraphicType(FGraphic,ext); FGraphicToCompress.Free; FGraphicToCompress:=ConvertToGraphicType(FGraphic,ext); ReloadPicture; i:=0; while i<CheatPaintPanel.ComponentCount do if CheatPaintPanel.Components[i].Tag<>FilterIndex then CheatPaintPanel.Components[i].Free else inc(i); if FGraphicToCompress.GetInterface(IGraphicPreferences,intf) then begin intf.ShowPreferences(CheatPaintPanel,PrefRect,FilterIndex); end; end; inherited DoTypeChange; end; resourcestring KiBcaption = ' КиБ'; procedure TGraphicExSavePictureDialog.ReloadPicture; begin FMemoryStream.Clear; FGraphicToCompress.SaveToStream(FMemoryStream); PictureLabel.Caption:=IntToStr(FMemoryStream.Size div 1024)+KiBcaption; FMemoryStream.Seek(0,soFromBeginning); ImageCtrl.Picture.Graphic:=FGraphicToCompress; ImageCtrl.Picture.Graphic.LoadFromStream(FMemoryStream); end; procedure TGraphicExSavePictureDialog.DoShow; begin inherited DoShow; DoTypeChange; end; procedure TGraphicExSavePictureDialog.Save; var FileStream: TFileStream; begin if Execute then begin FileStream:=TFileStream.Create(FileName,fmCreate); try FMemoryStream.Seek(0,soFromBeginning); FileStream.CopyFrom(FMemoryStream,FMemoryStream.Size); finally FileStream.Free; end; end; end; procedure TGraphicExSavePictureDialog.DoClose; var i: Integer; begin i:=0; while i<CheatPaintPanel.ComponentCount do if CheatPaintPanel.Components[i].Tag<>0 then CheatPaintPanel.Components[i].Free else inc(i); inherited DoClose; end; (* TGraphicExJPG *) resourceString JPEGCompressionCaption = 'Качество: '; procedure TGraphicExJPG.ShowPreferences(control: TWinControl; var aBoundsRect: TRect; aFilterIndex: Integer); var labl: TLabel; begin labl:=TLabel.Create(control); with labl do begin name:='lblCompressionRate'; Parent:=control; Align:=alTop; Caption:=JPEGCompressionCaption; Tag:=aFilterIndex; end; with TTrackBar.Create(control) do begin Parent:=control; Top:=labl.Top+labl.Height; Align:=alTop; Min:=1; Max:=100; Tag:=aFilterIndex; aBoundsRect.Bottom:=aBoundsRect.Top+height; onChange:=CompressionRateChange; Position:=80; end; end; procedure TGraphicExJPG.CompressionRateChange(Sender: TObject); var labl: TLabel; master: TGraphicExSavePictureDialog; begin CompressionQuality:=(Sender as TTrackBar).Position; labl:=(Sender as TTrackBar).Owner.FindComponent('lblCompressionRate') as TLabel; master:=(Sender as TTrackBar).Owner.Owner as TGraphicExSavePictureDialog; Assign(master.FGraphic); Compress; labl.Caption:=JPEGCompressionCaption+IntToStr(CompressionQuality); master.ReloadPicture; end; (* TGraphicExPNG *) procedure TGraphicExPNG.ShowPreferences(control: TWinControl; var aBoundsRect: TRect; aFilterIndex: Integer); begin //we want maximum compression we can get (it's lossless, so no need to ask) filters:=[pfNone, pfSub, pfUp, pfAverage, pfPaeth]; (control.Owner as TGraphicExSavePictureDialog).ReloadPicture; end; (* TGraphicExBMP *) resourcestring strIsMonochrome='Черно-белое'; procedure TGraphicExBMP.ShowPreferences(control: TWinControl; var aBoundsRect: TRect; aFilterIndex: Integer); var chkBox: TCheckBox; begin chkBox:=TCheckBox.Create(control); with chkBox do begin name:='chkMonochrome'; Parent:=control; Align:=alTop; Tag:=aFilterIndex; caption:=strIsMonochrome; OnClick:=MonochromeChange; end; end; procedure TGraphicExBMP.Monochromechange(Sender: TObject); begin Monochrome:=(Sender as TCheckBox).Checked; ((Sender as TCheckBox).Owner.Owner as TGraphicExSavePictureDialog).ReloadPicture; end; initialization with FileFormatList do begin RegisterFileFormat('jpg',gesJPGImages,'',[ftRaster,ftEnableSaving], true, False, TGraphicExJPG); RegisterFileFormat('jfif',gesJPGImages,'',[ftRaster,ftEnableSaving], true, False, TGraphicExJPG); RegisterFileFormat('jpe',gesJPEImages,'',[ftRaster,ftEnableSaving], true, False, TGraphicExJPG); RegisterFileFormat('jpeg',gesJPEGImages,'',[ftRaster,ftEnableSaving], true, False, TGraphicExJPG); RegisterFileFormat('png', gesPortableNetworkGraphic, '', [ftRaster,ftEnableSaving], True, True, TGraphicExPNG); RegisterFileFormat('bmp', gesBitmaps, '', [ftRaster,ftEnableSaving], true, False, TGraphicExBMP); end; end.
unit CustomCreature; interface uses Entity, Bar; type TCustomCreature = class(TEntity) private FLife: TBar; FMana: TBar; FExp: TBar; FLevel: Byte; FSkillPoints: Byte; FStatPoints: Byte; procedure SetLife(const Value: TBar); procedure SetMana(const Value: TBar); procedure SetExp(const Value: TBar); procedure SetLevel(const Value: Byte); procedure SetSkillPoints(const Value: Byte); procedure SetStatPoints(const Value: Byte); public constructor Create(MaxLife, MaxMana, MaxExp: Integer); destructor Destroy; override; property Life: TBar read FLife write SetLife; property Mana: TBar read FMana write SetMana; property Exp: TBar read FExp write SetExp; property Level: Byte read FLevel write SetLevel; property StatPoints: Byte read FStatPoints write SetStatPoints; property SkillPoints: Byte read FSkillPoints write SetSkillPoints; procedure Fill; end; implementation { TCustomCreature } constructor TCustomCreature.Create(MaxLife, MaxMana, MaxExp: Integer); begin inherited Create; Life := TBar.Create; Life.SetMax(MaxLife); Life.SetToMax; Mana := TBar.Create; Mana.SetMax(MaxMana); Mana.SetToMax; Exp := TBar.Create; Exp.SetMax(MaxExp); Exp.SetToMin; Level := 1; StatPoints := 0; SkillPoints := 0; end; destructor TCustomCreature.Destroy; begin Life.Free; Mana.Free; Exp.Free; inherited; end; procedure TCustomCreature.Fill; begin Life.SetToMax; Mana.SetToMax; end; procedure TCustomCreature.SetExp(const Value: TBar); begin FExp := Value; end; procedure TCustomCreature.SetLevel(const Value: Byte); begin FLevel := Value; end; procedure TCustomCreature.SetLife(const Value: TBar); begin FLife := Value; end; procedure TCustomCreature.SetMana(const Value: TBar); begin FMana := Value; end; procedure TCustomCreature.SetSkillPoints(const Value: Byte); begin FSkillPoints := Value; end; procedure TCustomCreature.SetStatPoints(const Value: Byte); begin FStatPoints := Value; end; end.
unit evdStyles; {$IfDef DesignTimeLibrary} {$WEAKPACKAGEUNIT ON} {$EndIf DesignTimeLibrary} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "EVD" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/EVD/evdStyles.pas" // Начат: 21.04.1997 18:05 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<Interfaces::Category>> Shared Delphi::EVD::Styles // // Идентификаторы стилей текстовых параграфов. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\EVD\evdDefine.inc} interface const { Идентификаторы стилей текстовых параграфов. } ev_saEmpty = 0; { "Пустое" значение. } ev_saTxtNormalANSI = -1; { Нормальный. } ev_saTxtNormalOEM = -2; { Нормальный (OEM). } ev_saTxtHeader1 = -3; { Заголовок 1. } ev_saTxtHeader2 = -4; { Заголовок 2. } ev_saTxtHeader3 = -5; { Заголовок 3. } ev_saTxtHeader4 = -6; { Заголовок 4. } ev_saTxtOutOfDate = -7; { Утратил силу. } ev_saHyperLink = -8; { Гипертекстовая ссылка. } ev_saTxtComment = -9; { Комментарий. } ev_saColorSelection = -10; { Цветовое выделение. } ev_saHyperLinkCont = -11; { Продолжение ссылки. } ev_saANSIDOS = -12; { Моноширинный. } ev_saFoundWords = -13; { Найденные слова. } ev_saNormalNote = -14; { Нормальный (справка). } ev_saArticleHeader = -15; { Заголовок статьи. } ev_saToLeft = -16; { Прижатый влево. } ev_saNormalTable = -17; { Нормальный для таблиц. } ev_saNormalSBSLeft = -18; { Нормальный для левых частей SBS. } ev_saNormalSBSRight = -19; { Нормальный для правых частей SBS. } ev_saNormalTableList = -20; { нормальный для списков в виде таблиц. } ev_saTechComment = -21; { технический комментарий. } ev_saVersionInfo = -22; { информация о версии. } ev_saUserComment = -23; { комментарий пользователя (для Гаранта 6х). } ev_saContents = -24; { оглавление (для Гаранта 6х). } ev_saNotApplied = -25; { не вступил в силу. } ev_saDictEntry = -26; { Словарная статья. } ev_saHFLeft = -27; { колонтитул (левый). } ev_saHFRight = -28; { колонтитул (правый). } ev_saMainMenu = -29; { основное меню. } ev_saNormalAnno = -30; { нормальный для аннотаций. } ev_saMainMenuConstPath = -31; { шрифт основного меню, постоянная часть. } ev_saMainMenuChangePath = -32; { шрифт основного меню, переменная часть. } ev_saMainMenuHeader = -33; { заголовки основного меню. } ev_saMainMenuInteractiveHeader = -34; { заголовки основного меню, являющиеся гипперссылками. } ev_saObject = -35; { псевдо-стиль, для объектных сегментов. } ev_saMistake = -36; { Слово с опечаткой. } ev_saEnclosureHeader = -37; { Заголовок приложения. } ev_saInterface = -38; { Стиль для интерфейсных элементов } ev_saActiveHyperlink = -39; { Активная гиперссылка } ev_saCenteredTable = -40; { Центрированный в таблице } ev_saAddedText = -41; { Добавленный текст. [$152961076] } ev_saDeletedText = -42; { Удалённый текст. [$152961076] } ev_saChatHeaderSender = -43; { Заголовок отправленных сообщений [$152408792] } ev_saChatHeaderRecipient = -44; { Заголовок полученных сообщений [$152408792] } ev_saHLE1 = -45; { Необходимые документы } ev_saHLE2 = -46; { Куда обратиться? } ev_saHLE3 = -47; { Внимание: недобросовестность! } ev_saHLE4 = -48; { Внимание: криминал!! } ev_saHLE5 = -49; { Примечание. } ev_saHLE6 = -50; { Пример. } ev_saColorSelectionForBaseSearch = - 51; ev_saChangesInfo = -52; { Информация об изменениях } ev_saItalicColorSelectionForBaseSearch = -53; ev_saHeaderForChangesInfo = -54; { Заголовок информации об изменениях в документе } ev_saFooterForChangesInfo = -55; { "Подвал" для информации об изменениях в документе } ev_saTextForChangesInfo = -56; { Текст информации об изменениях в документе } ev_saSubHeaderForChangesInfo = -57; { Подзаголовок для информации об изменениях в документе } ev_saControlsBlockHeader = -58; { Заголовок группы контролов } ev_saCloakHeader = -59; { Заголовок распахивающейся части диалогов } ev_saLinkToPublication = -60; { Ссылка на официальную публикацию } ev_saUnderlinedText = -61; { Текст с нижней рамкой } ev_saDialogs = -62; { Текст диалогов } ev_saEditionInterval = -63; { Интервал действия редакции } ev_saEdition = -64; { Редакция } ev_saEditionNumber = -65; { Порядковый номер редакции } ev_saNodeGroupHeader = -66; { Заголовок группы редакций } ev_saTOC = -67; { Оглавление } ev_saAttention = -68; ev_saWriteToUs = -69; { Напишите нам } ev_saTxtNormalAACSeeAlso = -70; { Текст ЭР (см. также) } ev_saHeaderAACLeftWindow = -71; { Заголовок ЭР (левое окно) } ev_saHeaderAACRightWindow = -72; { Заголовок ЭР (правое окно) } ev_saContextAACRightWindows = -73; { ЭР-содержание (правое окно) } ev_saFormulaInAAC = -74; ev_saSnippet = -75; { дочерний элемент списка } type TevStandardStyle = ev_saEnclosureHeader..ev_saTxtNormalANSI; {* Тип, определяющий диапазон стандартных стилей. } TevStandardStylesP = -High(TevStandardStyle)..-Low(TevStandardStyle); TevStandardStyles = set of TevStandardStylesP; {* Тип, определяющий множество из диапазона стандартных стилей. } TevStandardCachedStyle = ev_saFormulaInAAC..ev_saTxtNormalANSI; const { Имена для Standard } StandardNames : array [0..75] of PAnsiChar = ( 'Empty' { Имя для Empty } , 'TxtNormalANSI' { Имя для TxtNormalANSI } , 'TxtNormalOEM' { Имя для TxtNormalOEM } , 'TxtHeader1' { Имя для TxtHeader1 } , 'TxtHeader2' { Имя для TxtHeader2 } , 'TxtHeader3' { Имя для TxtHeader3 } , 'TxtHeader4' { Имя для TxtHeader4 } , 'TxtOutOfDate' { Имя для TxtOutOfDate } , 'HyperLink' { Имя для HyperLink } , 'TxtComment' { Имя для TxtComment } , 'ColorSelection' { Имя для ColorSelection } , 'HyperLinkCont' { Имя для HyperLinkCont } , 'ANSIDOS' { Имя для ANSIDOS } , 'FoundWords' { Имя для FoundWords } , 'NormalNote' { Имя для NormalNote } , 'ArticleHeader' { Имя для ArticleHeader } , 'ToLeft' { Имя для ToLeft } , 'NormalTable' { Имя для NormalTable } , 'NormalSBSLeft' { Имя для NormalSBSLeft } , 'NormalSBSRight' { Имя для NormalSBSRight } , 'NormalTableList' { Имя для NormalTableList } , 'TechComment' { Имя для TechComment } , 'VersionInfo' { Имя для VersionInfo } , 'UserComment' { Имя для UserComment } , 'Contents' { Имя для Contents } , 'NotApplied' { Имя для NotApplied } , 'DictEntry' { Имя для DictEntry } , 'HFLeft' { Имя для HFLeft } , 'HFRight' { Имя для HFRight } , 'MainMenu' { Имя для MainMenu } , 'NormalAnno' { Имя для NormalAnno } , 'MainMenuConstPath' { Имя для MainMenuConstPath } , 'MainMenuChangePath' { Имя для MainMenuChangePath } , 'MainMenuHeader' { Имя для MainMenuHeader } , 'MainMenuInteractiveHeader' { Имя для MainMenuInteractiveHeader } , 'Object' { Имя для Object } , 'Mistake' { Имя для Mistake } , 'EnclosureHeader' { Имя для EnclosureHeader } , 'Interface' { Имя для Interface } , 'ActiveHyperlink' { Имя для ActiveHyperlink } , 'CenteredTable' { Имя для CenteredTable } , 'AddedText' { Имя для AddedText } , 'DeletedText' { Имя для DeletedText } , 'ChatHeaderSender' { Имя для ChatHeaderSender } , 'ChatHeaderRecipient' { Имя для ChatHeaderRecipient } , 'HLE1' { Имя для HLE1 } , 'HLE2' { Имя для HLE2 } , 'HLE3' { Имя для HLE3 } , 'HLE4' { Имя для HLE4 } , 'HLE5' { Имя для HLE5 } , 'HLE6' { Имя для HLE6 } , 'ColorSelectionForBaseSearch' { Имя для ColorSelectionForBaseSearch } , 'ChangesInfo' { Имя для ChangesInfo } , 'ItalicColorSelectionForBaseSearch' { Имя для ItalicColorSelectionForBaseSearch } , 'HeaderForChangesInfo' { Имя для HeaderForChangesInfo } , 'FooterForChangesInfo' { Имя для FooterForChangesInfo } , 'TextForChangesInfo' { Имя для TextForChangesInfo } , 'SubHeaderForChangesInfo' { Имя для SubHeaderForChangesInfo } , 'ControlsBlockHeader' { Имя для ControlsBlockHeader } , 'CloakHeader' { Имя для CloakHeader } , 'LinkToPublication' { Имя для LinkToPublication } , 'UnderlinedText' { Имя для UnderlinedText } , 'Dialogs' { Имя для Dialogs } , 'EditionInterval' { Имя для EditionInterval } , 'Edition' { Имя для Edition } , 'EditionNumber' { Имя для EditionNumber } , 'NodeGroupHeader' { Имя для NodeGroupHeader } , 'TOC' { Имя для TOC } , 'Attention' { Имя для Attention } , 'WriteToUs' { Имя для WriteToUs } , 'TxtNormalAACSeeAlso' { Имя для TxtNormalAACSeeAlso } , 'HeaderAACLeftWindow' { Имя для HeaderAACLeftWindow } , 'HeaderAACRightWindow' { Имя для HeaderAACRightWindow } , 'ContextAACRightWindows' { Имя для ContextAACRightWindows } , 'FormulaInAAC' { Имя для FormulaInAAC } , 'Snippet' { Имя для Snippet } );//StandardNames implementation end.
(* * TASK #2 - Array Degree * * GUEST LANGUAGE: THIS IS THE Pascal VERSION OF ch-2.{c,pl}, * suitable for the Free Pascal compiler. *) uses sysutils; const maxints = 256; type intarray = array [0..maxints-1] of integer; var debug : boolean; type pair = record el : integer; (* an element *) freq : integer; (* and it's associated frequency *) end; type pairarray = array [ 1..1000 ] of pair; (* process_args( nel, v ); * Process command line arguments, * specifically process the -d flag, * set nel to the number of remaining arguments, * check that all those remaining arguments are +ve numbers, * copy remaining args to a new integer array v. *) procedure process_args( var nel : integer; var v : intarray ); (* note: paramStr(i)); for i in 1 to paramCount() *) var nparams : integer; arg : integer; i : integer; p : string; begin nparams := paramCount(); arg := 1; if (nparams>0) and SameText( paramStr(arg), '-d' ) then begin debug := true; arg := 2; end; nel := 1+nparams-arg; if nel < 2 then begin writeln( stderr, 'Usage: summations [-d] list of +ve numbers' ); halt; end; if nel > maxints then begin writeln( stderr, 'summations too many numbers (max ', maxints, ')' ); halt; end; if debug then begin writeln( 'debug: arg', arg, ', nparams=', nparams, ', nel=', nel ); end; // elements are in argv[arg..nparams], copy them to v[] // check that all remaining arguments are +ve integers, // and then copy them to v[] for i := arg to nparams do begin p := paramStr(i); if (p[1] < '0') or (p[1] > '9') then begin writeln( stderr, 'summations arg ', i, ' (', p, ') is not a +ve number' ); halt; end; v[i-arg] := StrToInt( p ); end; end; (* * rement the frequency of el in freq (adding an element if * it's not there yet) *) procedure incfreq( var freq : pairarray; var np : integer; el : integer ); var i : integer; over : boolean; begin over := false; for i:=0 to np-1 do begin if not over and (freq[i].el = el) then begin inc( freq[i].freq ); over := true; end; end; if not over then begin; freq[np].el := el; freq[np].freq := 1; inc( np ); end; end; (* * int deg = degree( arr, f, t ); * Calculate the degree (max frequency) of array[f..t]. *) function degree( arr : intarray; f, t : integer ) : integer; var i, max : integer; np : integer; (* number of pairs in freq *) freq : pairarray; begin np := 0; for i:=f to t do begin incfreq( freq, np, arr[i] ); end; (* now find the maximum frequency in freq[] *) max := 0; for i:=0 to np-1 do begin if freq[i].freq > max then begin max := freq[i].freq; end; end; degree := max; end; (* * makeslicestr( arr, f, t, slicestr ); * Build slicestr, a plain text string containing all elements * arr[f..t], comma separated * Sort of like slicestr = join(',', arr[f..t]); *) procedure makeslicestr( arr : intarray; f, t : integer; var slicestr : ansistring ); var i : integer; begin slicestr := ''; for i:=f to t do begin if i>f then begin AppendStr( slicestr, ',' ); end; AppendStr( slicestr, IntToStr( arr[i] ) ); end; end; procedure main; var nel : integer; ilist : intarray; wholedeg : integer; slicestr : ansistring; smallarray : ansistring; smallestarraysize : integer; f, t : integer; deg, size : integer; begin debug := false; process_args( nel, ilist ); wholedeg := degree( ilist, 0, nel-1 ); makeslicestr( ilist, 0, nel-1, slicestr ); if debug then begin writeln( 'debug: wholedeg = ', wholedeg ); end; smallestarraysize := nel+1; for f:=0 to nel-2 do begin for t:=f+1 to nel-1 do begin deg := degree( ilist, f, t ); if deg = wholedeg then begin makeslicestr( ilist, f, t, slicestr ); if debug then begin writeln( 'debug: found sub-array ', slicestr, ' with degree ', deg ); end; size := t+1-f; if size < smallestarraysize then begin smallestarraysize := size; smallarray := slicestr; end; end; end; end; writeln( smallarray ); end; begin main; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElTreeTreeComboEdit; interface uses Windows, Messages, Controls, Forms, SysUtils, Classes, {$ifdef VCL_6_USED} Types, {$endif} {$ifdef ELPACK_USE_STYLEMANAGER} ElStyleMan, {$endif} ElTree, ElHeader, ElTools, ElStrUtils, ElTreeCombo ; type TElTreeInplaceTreeComboEdit = class(TElTreeInplaceEditor) private SaveWndProc: TWndMethod; SaveTreeWndProc : TWndMethod; procedure EditorWndProc(var Message : TMessage); procedure TreeWndProc(var Message : TMessage); protected FEditor: TElTreeCombo; procedure DoStartOperation; override; procedure DoStopOperation(Accepted : boolean); override; function GetVisible: Boolean; override; procedure TriggerAfterOperation(var Accepted : boolean; var DefaultConversion : boolean); override; procedure TriggerBeforeOperation(var DefaultConversion : boolean); override; procedure SetEditorParent; override; {$ifdef ELPACK_USE_STYLEMANAGER} function GetStyleManager: TElStyleManager; function GetStyleName: string; procedure SetStyleManager(Value: TElStyleManager); procedure SetStyleName(const Value: string); {$endif} public constructor Create(AOwner : TComponent); override; destructor Destroy; override; property Editor: TElTreeCombo read FEditor; published {$ifdef ELPACK_USE_STYLEMANAGER} property StyleManager: TElStyleManager read GetStyleManager write SetStyleManager; property StyleName: string read GetStyleName write SetStyleName; {$endif} end; implementation constructor TElTreeInplaceTreeComboEdit.Create(AOwner : TComponent); begin inherited; FEditor := TElTreeCombo.Create(nil); FEditor.Visible := false; FEditor.HandleDialogKeys := true; SaveWndProc := FEditor.WindowProc; FEditor.WindowProc := EditorWndProc; SaveTreeWndProc := FEditor.GetTree.WindowProc; FEditor.GetTree.WindowProc := TreeWndProc; FEditor.Ctl3D := false; FTypes := [sftText]; end; destructor TElTreeInplaceTreeComboEdit.Destroy; begin FEditor.GetTree.WindowProc := SaveTreeWndProc; FEditor.WindowProc := SaveWndProc; FEditor.Free; FEditor := nil; inherited; end; type THackElTree = class(TCustomElTree); procedure TElTreeInplaceTreeComboEdit.TreeWndProc(var Message : TMessage); var InputValid : boolean; begin if (Message.Msg = WM_KILLFOCUS) then begin if FEditor.HandleAllocated and (TWMKillFocus(Message).FocusedWnd <> FEditor.Handle) and (FEditor.GetTree.HandleAllocated) and (TWMKillFocus(Message).FocusedWnd <> FEditor.GetTree.Handle) and (TWMKillFocus(Message).FocusedWnd <> FEditor.GetTree.Parent.Handle) then if FEditing then begin if THackElTree(Tree).ExplorerEditMode then begin InputValid := true; TriggerValidateResult(InputValid); CompleteOperation(InputValid); end else CompleteOperation(false); end; end; SaveTreeWndProc(Message); end; procedure TElTreeInplaceTreeComboEdit.DoStartOperation; begin FEditor.Visible := true; FEditor.SetFocus; end; procedure TElTreeInplaceTreeComboEdit.DoStopOperation(Accepted : boolean); begin FEditor.Visible := false; FEditor.Parent := nil; inherited; end; procedure TElTreeInplaceTreeComboEdit.EditorWndProc(var Message : TMessage); var InputValid : boolean; b : boolean; begin if Message.Msg = WM_KEYDOWN then begin if KeyDataToShiftState(TWMKey(Message).KeyData) = [] then begin if TWMKey(Message).CharCode = VK_RETURN then begin b := false; if Editor.Dropped then begin b := true; // Dropped := false; SaveWndProc(Message); end; // else begin InputValid := true; FEditing := false; TriggerValidateResult(InputValid); FEditing := true; if InputValid then begin CompleteOperation(true); TWMKey(Message).CharCode := 0; exit; end else Editor.SetFocus; TWMKey(Message).CharCode := 0; if b then exit; end; end else if TWMKey(Message).CharCode = VK_ESCAPE then begin CompleteOperation(false); TWMKey(Message).CharCode := 0; exit; end; end; end else if (Message.Msg = CM_CANCELMODE) then begin if (Message.lParam = 0) or ((TControl(TObject(Pointer(Message.lParam))).Parent <> Editor) and (TControl(TObject(Pointer(Message.lParam))).Parent <> Editor.GetTree) and (TObject(Pointer(Message.lParam)) <> Editor) and (TObject(Pointer(Message.lParam)) <> Editor.GetTree)) then if FEditing then begin if THackElTree(Tree).ExplorerEditMode then begin InputValid := true; TriggerValidateResult(InputValid); CompleteOperation(InputValid); end else CompleteOperation(false); end; end else if (Message.Msg = WM_KILLFOCUS) then begin if (FEditor.GetTree.HandleAllocated) and (TWMKillFocus(Message).FocusedWnd <> FEditor.GetTree.Handle) and (TWMKillFocus(Message).FocusedWnd <> FEditor.{GetTree.Parent.}Handle) then if FEditing then begin if THackElTree(Tree).ExplorerEditMode then begin InputValid := true; TriggerValidateResult(InputValid); CompleteOperation(InputValid); end else CompleteOperation(false); end; end; SaveWndProc(Message); end; function TElTreeInplaceTreeComboEdit.GetVisible: Boolean; begin Result := FEditor.Visible; end; procedure TElTreeInplaceTreeComboEdit.TriggerAfterOperation(var Accepted : boolean; var DefaultConversion : boolean); begin FEditor.OnExit := nil; inherited; if DefaultConversion then ValueAsText := FEditor.Text; end; procedure TElTreeInplaceTreeComboEdit.TriggerBeforeOperation(var DefaultConversion : boolean); begin inherited; if DefaultConversion then FEditor.Text := ValueAsText; FEditor.BoundsRect := FCellRect; end; procedure TElTreeInplaceTreeComboEdit.SetEditorParent; begin FEditor.Parent := FTree.View; end; {$ifdef ELPACK_USE_STYLEMANAGER} function TElTreeInplaceTreeComboEdit.GetStyleManager: TElStyleManager; begin Result := Editor.StyleManager; end; function TElTreeInplaceTreeComboEdit.GetStyleName: string; begin Result := Editor.StyleName; end; procedure TElTreeInplaceTreeComboEdit.SetStyleManager(Value: TElStyleManager); begin Editor.StyleManager := Value; end; procedure TElTreeInplaceTreeComboEdit.SetStyleName(const Value: string); begin Editor.StyleName := Value; end; {$endif} end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, clCertificateStore, clCertificate, clCryptAPI, exportfrm, importfrm, createfrm, DemoBaseFormUnit, ExtCtrls; type TForm1 = class(TclDemoBaseForm) Label1: TLabel; cbLocation: TComboBox; Label2: TLabel; cbName: TComboBox; btnLoad: TButton; btnExport: TButton; btnImport: TButton; btnDelete: TButton; btnCreateSelfSigned: TButton; btnClose: TButton; lvCertificates: TListView; Label3: TLabel; clCertificateStore1: TclCertificateStore; btnCreateSigned: TButton; btnSignRequest: TButton; OpenDialog1: TOpenDialog; procedure btnLoadClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnExportClick(Sender: TObject); procedure btnImportClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnCreateSelfSignedClick(Sender: TObject); procedure btnCreateSignedClick(Sender: TObject); procedure btnSignRequestClick(Sender: TObject); procedure FormCreate(Sender: TObject); private FIsOpened: Boolean; procedure CheckButtonsState; procedure LoadCertificateList; procedure InstallCerts; procedure PrepareStore(ADlg: TCreateCertForm); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.CheckButtonsState; begin btnClose.Enabled := FIsOpened; btnSignRequest.Enabled := FIsOpened and (lvCertificates.Items.Count > 0); btnCreateSigned.Enabled := FIsOpened and (lvCertificates.Items.Count > 0); btnExport.Enabled := lvCertificates.Items.Count > 0; btnImport.Enabled := FIsOpened; btnDelete.Enabled := lvCertificates.Items.Count > 0; btnCreateSelfSigned.Enabled := FIsOpened; end; procedure TForm1.btnLoadClick(Sender: TObject); begin btnCloseClick(nil); clCertificateStore1.Open(cbName.Text, TclCertificateStoreLocation(cbLocation.ItemIndex)); LoadCertificateList(); FIsOpened := True; CheckButtonsState; end; procedure TForm1.btnSignRequestClick(Sender: TObject); var cert, issuer: TclCertificate; begin if OpenDialog1.Execute() then begin issuer := TclCertificate(lvCertificates.Items[lvCertificates.ItemIndex].Data); cert := clCertificateStore1.SignCSR(issuer, OpenDialog1.FileName, Random(MaxInt)); clCertificateStore1.Items.Add(cert); InstallCerts(); btnLoadClick(nil); end; end; procedure TForm1.FormCreate(Sender: TObject); begin Randomize(); CheckButtonsState; end; procedure TForm1.btnCreateSignedClick(Sender: TObject); var dlg: TCreateCertForm; cert, issuer: TclCertificate; begin dlg := TCreateCertForm.Create(nil); try dlg.edtStoreName.Text := cbLocation.Text + '; ' + cbName.Text; if dlg.ShowModal() = mrOk then begin PrepareStore(dlg); issuer := TclCertificate(lvCertificates.Items[lvCertificates.ItemIndex].Data); cert := clCertificateStore1.CreateSigned(issuer, dlg.BuildSubjectString(), StrToInt(dlg.edtSerial.Text)); clCertificateStore1.Items.Add(cert); cert.FriendlyName := dlg.edtFriendlyName.Text; InstallCerts(); btnLoadClick(nil); end; finally dlg.Free(); end; end; procedure TForm1.LoadCertificateList; var i: Integer; item: TListItem; begin lvCertificates.Items.Clear(); for i := 0 to clCertificateStore1.Items.Count - 1 do begin item := lvCertificates.Items.Add(); item.Data := clCertificateStore1.Items[i]; item.Caption := clCertificateStore1.Items[i].IssuedTo; item.SubItems.Add(clCertificateStore1.Items[i].IssuedBy); item.SubItems.Add(DateTimeToStr(clCertificateStore1.Items[i].ValidTo)); item.SubItems.Add(clCertificateStore1.Items[i].FriendlyName); item.SubItems.Add(clCertificateStore1.Items[i].Email); end; CheckButtonsState; end; procedure TForm1.btnCloseClick(Sender: TObject); begin clCertificateStore1.Close(); LoadCertificateList(); FIsOpened := False; CheckButtonsState; end; procedure TForm1.btnExportClick(Sender: TObject); var cert: TclCertificate; dlg: TExportForm; begin cert := TclCertificate(lvCertificates.Items[lvCertificates.ItemIndex].Data); dlg := TExportForm.Create(nil); try dlg.edtName.Text := cert.FriendlyName; if (dlg.edtName.Text = '') then begin dlg.edtName.Text := cert.IssuedTo; end; if dlg.ShowModal() = mrOk then begin clCertificateStore1.ExportToPFX(cert, dlg.edtFileName.Text, dlg.edtPassword.Text, dlg.cbIncludeAll.Checked); end; finally dlg.Free(); end; end; procedure TForm1.btnImportClick(Sender: TObject); var i: Integer; dlg: TImportForm; begin dlg := TImportForm.Create(nil); try dlg.edtStoreName.Text := cbLocation.Text + '; ' + cbName.Text; if dlg.ShowModal() = mrOk then begin clCertificateStore1.ImportFromPFX(dlg.edtFileName.Text, dlg.edtPassword.Text); for i := 0 to clCertificateStore1.Items.Count - 1 do begin if not clCertificateStore1.IsInstalled(clCertificateStore1.Items[i]) then begin clCertificateStore1.Install(clCertificateStore1.Items[i]); end; end; btnLoadClick(nil); end; finally dlg.Free(); end; end; procedure TForm1.btnDeleteClick(Sender: TObject); var cert: TclCertificate; begin cert := TclCertificate(lvCertificates.Items[lvCertificates.ItemIndex].Data); clCertificateStore1.Uninstall(cert); clCertificateStore1.Items.Remove(cert); btnLoadClick(nil); end; procedure TForm1.btnCreateSelfSignedClick(Sender: TObject); var dlg: TCreateCertForm; cert: TclCertificate; begin dlg := TCreateCertForm.Create(nil); try dlg.edtStoreName.Text := cbLocation.Text + '; ' + cbName.Text; if dlg.ShowModal() = mrOk then begin PrepareStore(dlg); cert := clCertificateStore1.CreateSelfSigned(dlg.BuildSubjectString(), StrToInt(dlg.edtSerial.Text)); clCertificateStore1.Items.Add(cert); cert.FriendlyName := dlg.edtFriendlyName.Text; InstallCerts(); btnLoadClick(nil); end; finally dlg.Free(); end; end; procedure TForm1.PrepareStore(ADlg: TCreateCertForm); begin clCertificateStore1.ValidFrom := StrToDateTime(ADlg.edtValidFrom.Text); clCertificateStore1.ValidTo := StrToDateTime(ADlg.edtValidTo.Text); clCertificateStore1.KeyName := ADlg.edtKeyName.Text; clCertificateStore1.KeyLength := StrToInt(ADlg.edtKeyLength.Text); clCertificateStore1.EnhancedKeyUsage.Clear(); if ADlg.cbServerAuth.Checked then clCertificateStore1.EnhancedKeyUsage.Add(szOID_PKIX_KP_SERVER_AUTH); if ADlg.cbClientAuth.Checked then clCertificateStore1.EnhancedKeyUsage.Add(szOID_PKIX_KP_CLIENT_AUTH); if ADlg.cbCodeSigning.Checked then clCertificateStore1.EnhancedKeyUsage.Add(szOID_PKIX_KP_CODE_SIGNING); if ADlg.cbEmailProtection.Checked then clCertificateStore1.EnhancedKeyUsage.Add(szOID_PKIX_KP_EMAIL_PROTECTION); if (not clCertificateStore1.KeyExists(clCertificateStore1.KeyName)) then clCertificateStore1.CreateKey(clCertificateStore1.KeyName); end; procedure TForm1.InstallCerts; var i: Integer; begin for i := 0 to clCertificateStore1.Items.Count - 1 do if not clCertificateStore1.IsInstalled(clCertificateStore1.Items[i]) then begin clCertificateStore1.Install(clCertificateStore1.Items[i]); end; end; end.
unit tecmo_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,msm5205,ym_3812,rom_engine, pal_engine,sound_engine; function iniciar_tecmo:boolean; implementation const //Rygar rygar_rom:array[0..2] of tipo_roms=( (n:'5.5p';l:$8000;p:0;crc:$062cd55d),(n:'cpu_5m.bin';l:$4000;p:$8000;crc:$7ac5191b), (n:'cpu_5j.bin';l:$8000;p:$10000;crc:$ed76d606)); rygar_char:tipo_roms=(n:'cpu_8k.bin';l:$8000;p:0;crc:$4d482fb6); rygar_tiles1:array[0..3] of tipo_roms=( (n:'vid_6p.bin';l:$8000;p:0;crc:$9eae5f8e),(n:'vid_6o.bin';l:$8000;p:$8000;crc:$5a10a396), (n:'vid_6n.bin';l:$8000;p:$10000;crc:$7b12cf3f),(n:'vid_6l.bin';l:$8000;p:$18000;crc:$3cea7eaa)); rygar_tiles2:array[0..3] of tipo_roms=( (n:'vid_6f.bin';l:$8000;p:0;crc:$9840edd8),(n:'vid_6e.bin';l:$8000;p:$8000;crc:$ff65e074), (n:'vid_6c.bin';l:$8000;p:$10000;crc:$89868c85),(n:'vid_6b.bin';l:$8000;p:$18000;crc:$35389a7b)); rygar_adpcm:tipo_roms=(n:'cpu_1f.bin';l:$4000;p:0;crc:$3cc98c5a); rygar_sound:tipo_roms=(n:'cpu_4h.bin';l:$2000;p:0;crc:$e4a2fa87); rygar_sprites:array[0..3] of tipo_roms=( (n:'vid_6k.bin';l:$8000;p:0;crc:$aba6db9e),(n:'vid_6j.bin';l:$8000;p:$8000;crc:$ae1f2ed6), (n:'vid_6h.bin';l:$8000;p:$10000;crc:$46d9e7df),(n:'vid_6g.bin';l:$8000;p:$18000;crc:$45839c9a)); //Silkworm sw_rom:array[0..1] of tipo_roms=( (n:'silkworm.4';l:$10000;p:0;crc:$a5277cce),(n:'silkworm.5';l:$10000;p:$10000;crc:$a6c7bb51)); sw_char:tipo_roms=(n:'silkworm.2';l:$8000;p:0;crc:$e80a1cd9); sw_tiles1:array[0..3] of tipo_roms=( (n:'silkworm.10';l:$10000;p:0;crc:$8c7138bb),(n:'silkworm.11';l:$10000;p:$10000;crc:$6c03c476), (n:'silkworm.12';l:$10000;p:$20000;crc:$bb0f568f),(n:'silkworm.13';l:$10000;p:$30000;crc:$773ad0a4)); sw_tiles2:array[0..3] of tipo_roms=( (n:'silkworm.14';l:$10000;p:0;crc:$409df64b),(n:'silkworm.15';l:$10000;p:$10000;crc:$6e4052c9), (n:'silkworm.16';l:$10000;p:$20000;crc:$9292ed63),(n:'silkworm.17';l:$10000;p:$30000;crc:$3fa4563d)); sw_adpcm:tipo_roms=(n:'silkworm.1';l:$8000;p:0;crc:$5b553644); sw_sound:tipo_roms=(n:'silkworm.3';l:$8000;p:0;crc:$b589f587); sw_sprites:array[0..3] of tipo_roms=( (n:'silkworm.6';l:$10000;p:0;crc:$1138d159),(n:'silkworm.7';l:$10000;p:$10000;crc:$d96214f7), (n:'silkworm.8';l:$10000;p:$20000;crc:$0494b38e),(n:'silkworm.9';l:$10000;p:$30000;crc:$8ce3cdf5)); //Dip rygar_dip_a:array [0..4] of def_dip=( (mask:$3;name:'Coin A';number:4;dip:((dip_val:$1;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$3;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin B';number:4;dip:((dip_val:$4;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(dip_val:$8;dip_name:'1C 2C'),(dip_val:$c;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Lives';number:4;dip:((dip_val:$30;dip_name:'2'),(dip_val:$0;dip_name:'3'),(dip_val:$10;dip_name:'4'),(dip_val:$20;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Cabinet';number:2;dip:((dip_val:$40;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); rygar_dip_b:array [0..4] of def_dip=( (mask:$3;name:'Bonus Life';number:4;dip:((dip_val:$0;dip_name:'50k 200k 500k'),(dip_val:$1;dip_name:'100k 300k 600k'),(dip_val:$2;dip_name:'200k 500k'),(dip_val:$3;dip_name:'100k'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Difficulty';number:4;dip:((dip_val:$0;dip_name:'Easy'),(dip_val:$10;dip_name:'Normal'),(dip_val:$30;dip_name:'Hard'),(dip_val:$30;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'2P Can Start Anytime';number:2;dip:((dip_val:$40;dip_name:'Yes'),(dip_val:$0;dip_name:'No'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Allow Continue';number:2;dip:((dip_val:$80;dip_name:'Yes'),(dip_val:$0;dip_name:'No'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); sw_dip_a:array [0..4] of def_dip=( (mask:$3;name:'Coin A';number:4;dip:((dip_val:$1;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$3;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin B';number:4;dip:((dip_val:$4;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(dip_val:$8;dip_name:'1C 2C'),(dip_val:$c;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Lives';number:4;dip:((dip_val:$30;dip_name:'2'),(dip_val:$0;dip_name:'3'),(dip_val:$10;dip_name:'4'),(dip_val:$20;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'On'),(dip_val:$0;dip_name:'Off'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); sw_dip_b:array [0..3] of def_dip=( (mask:$7;name:'Bonus Life';number:8;dip:((dip_val:$0;dip_name:'50k 200k 500k'),(dip_val:$1;dip_name:'100k 300k 800k'),(dip_val:$2;dip_name:'50k 200k'),(dip_val:$3;dip_name:'100k 300k'),(dip_val:$4;dip_name:'50k'),(dip_val:$5;dip_name:'100k'),(dip_val:$6;dip_name:'200k'),(dip_val:$7;dip_name:'None'),(),(),(),(),(),(),(),())), (mask:$70;name:'Difficulty';number:5;dip:((dip_val:$10;dip_name:'1'),(dip_val:$20;dip_name:'2'),(dip_val:$30;dip_name:'3'),(dip_val:$40;dip_name:'4'),(dip_val:$50;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Allow Continue';number:2;dip:((dip_val:$80;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var mem_adpcm:array[0..$7fff] of byte; bank_rom:array[0..$1f,0..$7ff] of byte; adpcm_end,adpcm_pos,adpcm_data,scroll_x1,scroll_x2:word; nbank_rom,scroll_y1,scroll_y2,soundlatch,tipo_video:byte; bg_ram,fg_ram:array[0..$3ff] of byte; txt_ram:array[0..$7ff] of byte; procedure draw_sprites(prioridad:byte); const layout:array[0..7,0..7] of byte = ( (0,1,4,5,16,17,20,21), (2,3,6,7,18,19,22,23), (8,9,12,13,24,25,28,29), (10,11,14,15,26,27,30,31), (32,33,36,37,48,49,52,53), (34,35,38,39,50,51,54,55), (40,41,44,45,56,57,60,61), (42,43,46,47,58,59,62,63)); var nchar,dx,dy,sx,sy,x,y,f,color,size:word; flags,bank:byte; flipx,flipy:boolean; begin for f:=0 to $ff do begin flags:=memoria[$e003+(f*8)]; if prioridad=(flags shr 6) then begin bank:=memoria[$e000+(f*8)]; if (bank and 4)<>0 then begin //sprite visible if tipo_video=1 then nchar:=memoria[$e001+(f*8)]+((bank and $f8) shl 5) else nchar:=memoria[$e001+(f*8)]+((bank and $f0) shl 4); size:=memoria[$e002+(f*8)] and 3; nchar:=nchar and (not((1 shl (size*2))-1)); size:=1 shl size; dx:=memoria[$e005+(f*8)]-((flags and $10) shl 4); dy:=memoria[$e004+(f*8)]-((flags and $20) shl 3); color:=(flags and $f) shl 4; flipx:=(bank and $1)<>0; flipy:=(bank and $2)<>0; for y:=0 to (size-1) do begin for x:=0 to (size-1) do begin if flipx then sx:=dx+8*(size-1-x) else sx:=dx+8*x; if flipy then sy:=dy+8*(size-1-y) else sy:=dy+8*y; put_gfx_sprite(nchar+layout[y,x],color,flipx,flipy,2); actualiza_gfx_sprite(sx+48,sy,1,2); end; end; end; end; end; end; procedure update_video_tecmo; var f,color,nchar,x,y:word; atrib:byte; begin //chars for f:=0 to $3ff do begin atrib:=txt_ram[$400+f]; color:=atrib shr 4; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f mod 32; y:=f div 32; nchar:=txt_ram[f]+((atrib and $3) shl 8); put_gfx_trans(x*8,y*8,nchar,(color shl 4)+$100,6,0); gfx[0].buffer[f]:=false; end; end; for f:=0 to $1ff do begin //Background atrib:=bg_ram[$200+f]; color:=atrib shr 4; if (gfx[3].buffer[f] or buffer_color[color+$20]) then begin x:=f mod 32; y:=f div 32; nchar:=bg_ram[f]+((atrib and $7) shl 8); put_gfx_trans(x*16,y*16,nchar,(color shl 4)+$300,2,3); gfx[3].buffer[f]:=false; end; //Delante atrib:=fg_ram[$200+f]; color:=atrib shr 4; if (gfx[1].buffer[f] or buffer_color[color+$10]) then begin x:=f mod 32; y:=f div 32; nchar:=fg_ram[f]+((atrib and $7) shl 8); put_gfx_trans(x*16,y*16,nchar,(color shl 4)+$200,7,1); gfx[1].buffer[f]:=false; end; end; fill_full_screen(1,$100); draw_sprites(3); scroll_x_y(2,1,scroll_x2,scroll_y2); draw_sprites(2); scroll_x_y(7,1,scroll_x1,scroll_y1); draw_sprites(1); actualiza_trozo(0,0,256,256,6,48,0,256,256,1); draw_sprites(0); actualiza_trozo_final(48,16,256,224,1); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_tecmo; begin if event.arcade then begin //P1 if arcade_input.left[0] then marcade.in0:=(marcade.in0 or 1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.right[0] then marcade.in0:=(marcade.in0 or 2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or 4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.up[0] then marcade.in0:=(marcade.in0 or 8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); //P2 if arcade_input.left[1] then marcade.in3:=(marcade.in3 or 1) else marcade.in3:=(marcade.in3 and $fe); if arcade_input.right[1] then marcade.in3:=(marcade.in3 or 2) else marcade.in3:=(marcade.in3 and $fd); if arcade_input.down[1] then marcade.in3:=(marcade.in3 or 4) else marcade.in3:=(marcade.in3 and $fb); if arcade_input.up[1] then marcade.in3:=(marcade.in3 or 8) else marcade.in3:=(marcade.in3 and $f7); if arcade_input.but1[1] then marcade.in4:=(marcade.in4 or $1) else marcade.in4:=(marcade.in4 and $fe); if arcade_input.but0[1] then marcade.in4:=(marcade.in4 or $2) else marcade.in4:=(marcade.in4 and $fd); //SYSTEM if arcade_input.start[1] then marcade.in2:=(marcade.in2 or 1) else marcade.in2:=(marcade.in2 and $fe); if arcade_input.start[0] then marcade.in2:=(marcade.in2 or 2) else marcade.in2:=(marcade.in2 and $fd); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or 4) else marcade.in2:=(marcade.in2 and $fb); if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or 8) else marcade.in2:=(marcade.in2 and $f7); end; end; procedure tecmo_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound CPU z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; if f=239 then begin z80_0.change_irq(HOLD_LINE); update_video_tecmo; end; end; eventos_tecmo; video_sync; end; end; function rygar_getbyte(direccion:word):byte; begin case direccion of 0..$cfff,$e000..$e7ff:rygar_getbyte:=memoria[direccion]; $d000..$d7ff:rygar_getbyte:=txt_ram[direccion and $7ff]; $d800..$dbff:rygar_getbyte:=fg_ram[direccion and $3ff]; $dc00..$dfff:rygar_getbyte:=bg_ram[direccion and $3ff]; $e800..$efff:rygar_getbyte:=buffer_paleta[direccion and $7ff]; $f000..$f7ff:rygar_getbyte:=bank_rom[nbank_rom,direccion and $7ff]; $f800:rygar_getbyte:=marcade.in0; $f801:rygar_getbyte:=marcade.in1; $f802:rygar_getbyte:=marcade.in3; $f803:rygar_getbyte:=marcade.in4; $f804:rygar_getbyte:=marcade.in2; $f805,$f80f:rygar_getbyte:=0; $f806:rygar_getbyte:=marcade.dswa and $f; $f807:rygar_getbyte:=(marcade.dswa shr 4) and $f; $f808:rygar_getbyte:=marcade.dswb and $f; $f809:rygar_getbyte:=(marcade.dswb shr 4) and $f; end; end; procedure cambiar_color(numero:word); var color:tcolor; valor:byte; begin valor:=buffer_paleta[numero]; color.b:=pal4bit(valor); valor:=buffer_paleta[1+numero]; color.g:=pal4bit(valor); color.r:=pal4bit(valor shr 4); numero:=numero shr 1; set_pal_color(color,numero); case numero of 256..511:buffer_color[(numero shr 4) and $f]:=true; 512..767:buffer_color[((numero shr 4) and $f)+$10]:=true; 768..1023:buffer_color[((numero shr 4) and $f)+$20]:=true; end; end; procedure rygar_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff,$f000..$f7ff:; //ROM $c000..$cfff,$e000..$e7ff:memoria[direccion]:=valor; $d000..$d7ff:if txt_ram[direccion and $7ff]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; txt_ram[direccion and $7ff]:=valor; end; $d800..$dbff:if fg_ram[direccion and $3ff]<>valor then begin gfx[1].buffer[direccion and $1ff]:=true; fg_ram[direccion and $3ff]:=valor; end; $dc00..$dfff:if bg_ram[direccion and $3ff]<>valor then begin gfx[3].buffer[direccion and $1ff]:=true; bg_ram[direccion and $3ff]:=valor; end; $e800..$efff:if buffer_paleta[direccion and $7ff]<>valor then begin buffer_paleta[direccion and $7ff]:=valor; cambiar_color(direccion and $7fe); end; $f800:scroll_x1:=(scroll_x1 and $100) or valor; $f801:scroll_x1:=(scroll_x1 and $ff) or ((valor and 1) shl 8); $f802:scroll_y1:=valor; $f803:scroll_x2:=(scroll_x2 and $100) or valor; $f804:scroll_x2:=(scroll_x2 and $ff) or ((valor and 1) shl 8); $f805:scroll_y2:=valor; $f806:begin soundlatch:=valor; z80_1.change_nmi(ASSERT_LINE); end; $f807:main_screen.flip_main_screen:=(valor and $1)<>0; $f808:nbank_rom:=(valor and $f8) shr 3; end; end; function rygar_snd_getbyte(direccion:word):byte; begin case direccion of 0..$47ff:rygar_snd_getbyte:=mem_snd[direccion]; $c000:rygar_snd_getbyte:=soundlatch end; end; procedure rygar_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$3fff:; //ROM $4000..$47ff:mem_snd[direccion]:=valor; $8000:ym3812_0.control(valor); $8001:ym3812_0.write(valor); $c000:begin adpcm_pos:=(valor shl 8); msm5205_0.reset_w(0); end; $d000:adpcm_end:=((valor+1) shl 8); //$e000:volumen $f000:z80_1.change_nmi(CLEAR_LINE); end; end; //Silkworm function sw_getbyte(direccion:word):byte; begin case direccion of 0..$bfff,$d000..$e7ff:sw_getbyte:=memoria[direccion]; $c000..$c3ff:sw_getbyte:=bg_ram[direccion and $3ff]; $c400..$c7ff:sw_getbyte:=fg_ram[direccion and $3ff]; $c800..$cfff:sw_getbyte:=txt_ram[direccion and $7ff]; $e800..$efff:sw_getbyte:=buffer_paleta[direccion and $7ff]; $f000..$f7ff:sw_getbyte:=bank_rom[nbank_rom,direccion and $7ff]; $f800:sw_getbyte:=marcade.in0; $f801:sw_getbyte:=marcade.in1; $f802:sw_getbyte:=marcade.in3; $f803:sw_getbyte:=marcade.in4; $f804:sw_getbyte:=0; $f806:sw_getbyte:=marcade.dswa and $f; $f807:sw_getbyte:=(marcade.dswa shr 4) and $f; $f808:sw_getbyte:=marcade.dswb and $f; $f809:sw_getbyte:=(marcade.dswb shr 4) and $f; $f80f:sw_getbyte:=marcade.in2; end; end; procedure sw_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff,$f000..$f7ff:; //ROM $c000..$c3ff:if bg_ram[direccion and $3ff]<>valor then begin gfx[3].buffer[direccion and $1ff]:=true; bg_ram[direccion and $3ff]:=valor; end; $c400..$c7ff:if fg_ram[direccion and $3ff]<>valor then begin gfx[1].buffer[direccion and $1ff]:=true; fg_ram[direccion and $3ff]:=valor; end; $c800..$cfff:if txt_ram[direccion and $7ff]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; txt_ram[direccion and $7ff]:=valor; end; $d000..$e7ff:memoria[direccion]:=valor; $e800..$efff:if buffer_paleta[direccion and $7ff]<>valor then begin buffer_paleta[direccion and $7ff]:=valor; cambiar_color(direccion and $7fe); end; $f800:scroll_x1:=(scroll_x1 and $100) or valor; $f801:scroll_x1:=(scroll_x1 and $ff) or ((valor and 1) shl 8); $f802:scroll_y1:=valor; $f803:scroll_x2:=(scroll_x2 and $100) or valor; $f804:scroll_x2:=(scroll_x2 and $ff) or ((valor and 1) shl 8); $f805:scroll_y2:=valor; $f806:begin soundlatch:=valor; z80_1.change_nmi(ASSERT_LINE); end; $f807:main_screen.flip_main_screen:=(valor and $1)<>0; $f808:nbank_rom:=(valor and $f8) shr 3; end; end; function sw_snd_getbyte(direccion:word):byte; begin case direccion of 0..$87ff:sw_snd_getbyte:=mem_snd[direccion]; $c000:sw_snd_getbyte:=soundlatch end; end; procedure sw_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; //ROM $8000..$87ff:mem_snd[direccion]:=valor; $a000:ym3812_0.control(valor); $a001:ym3812_0.write(valor); $c000:begin adpcm_pos:=(valor shl 8); msm5205_0.reset_w(0); end; $c400:adpcm_end:=((valor+1) shl 8); //$c800:volumen $cc00:z80_1.change_nmi(CLEAR_LINE); end; end; procedure snd_irq(irqstate:byte); begin z80_1.change_irq(irqstate); end; procedure snd_sound_play; begin YM3812_0.update; end; procedure snd_adpcm; begin if ((adpcm_pos>=adpcm_end) or (adpcm_pos>$7fff)) then begin msm5205_0.reset_w(1); exit; end; if (adpcm_data<>$100) then begin msm5205_0.data_w(adpcm_data and $0f); adpcm_data:=$100; end else begin adpcm_data:=mem_adpcm[adpcm_pos]; adpcm_pos:=adpcm_pos+1; msm5205_0.data_w((adpcm_data and $f0) shr 4); end; end; //Main procedure reset_tecmo; begin z80_0.reset; z80_1.reset; ym3812_0.reset; msm5205_0.reset; reset_audio; adpcm_end:=0; adpcm_pos:=0; adpcm_data:=$100; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; marcade.in3:=0; marcade.in4:=0; nbank_rom:=0; scroll_x1:=0; scroll_x2:=0; scroll_y1:=0; scroll_y2:=0; soundlatch:=0; end; function iniciar_tecmo:boolean; const ps_x:array[0..15] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4, 32*8+0*4, 32*8+1*4, 32*8+2*4, 32*8+3*4, 32*8+4*4, 32*8+5*4, 32*8+6*4, 32*8+7*4); ps_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32); var memoria_temp:array[0..$7ffff] of byte; f:byte; procedure char_convert(num:word); begin init_gfx(0,8,8,num); gfx[0].trans[0]:=true; gfx_set_desc_data(4,0,32*8,0,1,2,3); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,false); end; procedure sprite_convert(num:word); begin init_gfx(2,8,8,num); gfx[2].trans[0]:=true; gfx_set_desc_data(4,0,32*8,0,1,2,3); convert_gfx(2,0,@memoria_temp,@ps_x,@ps_y,false,false); end; procedure tile_convert(ngfx:byte;num:word); begin init_gfx(ngfx,16,16,num); gfx[ngfx].trans[0]:=true; gfx_set_desc_data(4,0,128*8,0,1,2,3); convert_gfx(ngfx,0,@memoria_temp,@ps_x,@ps_y,false,false); end; begin llamadas_maquina.bucle_general:=tecmo_principal; llamadas_maquina.reset:=reset_tecmo; llamadas_maquina.fps_max:=59.185608; iniciar_tecmo:=false; iniciar_audio(false); screen_init(1,512,512,false,true); screen_init(2,512,256,true); screen_mod_scroll(2,512,256+48,511,256,256,255); screen_init(6,256,256,true); //chars //foreground screen_init(7,512,256,true); screen_mod_scroll(7,512,256+48,511,256,256,255); iniciar_video(256,224); //Sound CPU z80_1:=cpu_z80.create(4000000,$100); z80_1.init_sound(snd_sound_play); //Sound Chip msm5205_0:=MSM5205_chip.create(400000,MSM5205_S48_4B,0.5,snd_adpcm); //cargar roms case main_vars.tipo_maquina of 26:begin //Main z80_0:=cpu_z80.create(6000000,$100); z80_0.change_ram_calls(rygar_getbyte,rygar_putbyte); //Sound z80_1.change_ram_calls(rygar_snd_getbyte,rygar_snd_putbyte); ym3812_0:=ym3812_chip.create(YM3526_FM,4000000); ym3812_0.change_irq_calls(snd_irq); //Video tipo_video:=0; if not(roms_load(@memoria_temp,rygar_rom)) then exit; copymemory(@memoria,@memoria_temp,$c000); for f:=0 to $1f do copymemory(@bank_rom[f,0],@memoria_temp[$10000+(f*$800)],$800); //cargar sonido if not(roms_load(@mem_snd,rygar_sound)) then exit; if not(roms_load(@mem_adpcm,rygar_adpcm)) then exit; //convertir chars if not(roms_load(@memoria_temp,rygar_char)) then exit; char_convert(1024); //Sprites if not(roms_load(@memoria_temp,rygar_sprites)) then exit; sprite_convert(4096); //foreground if not(roms_load(@memoria_temp,rygar_tiles1)) then exit; tile_convert(1,$400); //background if not(roms_load(@memoria_temp,rygar_tiles2)) then exit; tile_convert(3,$400); //DIP marcade.dswa:=$40; marcade.dswb:=$80; marcade.dswa_val:=@rygar_dip_a; marcade.dswb_val:=@rygar_dip_b; end; 97:begin //Silk Worm //Main z80_0:=cpu_z80.create(8000000,$100); z80_0.change_ram_calls(sw_getbyte,sw_putbyte); //Sound z80_1.change_ram_calls(sw_snd_getbyte,sw_snd_putbyte); ym3812_0:=ym3812_chip.create(YM3812_FM,4000000); ym3812_0.change_irq_calls(snd_irq); //Video tipo_video:=1; if not(roms_load(@memoria_temp,sw_rom)) then exit; copymemory(@memoria,@memoria_temp,$10000); for f:=0 to $1f do copymemory(@bank_rom[f,0],@memoria_temp[$10000+(f*$800)],$800); //cargar sonido if not(roms_load(@mem_snd,sw_sound)) then exit; if not(roms_load(@mem_adpcm,sw_adpcm)) then exit; //convertir chars if not(roms_load(@memoria_temp,sw_char)) then exit; char_convert($400); //Sprites if not(roms_load(@memoria_temp,sw_sprites)) then exit; sprite_convert($2000); //background if not(roms_load(@memoria_temp,sw_tiles1)) then exit; tile_convert(1,$800); //foreground if not(roms_load(@memoria_temp,sw_tiles2)) then exit; tile_convert(3,$800); //DIP marcade.dswa:=$80; marcade.dswb:=$30; marcade.dswa_val:=@sw_dip_a; marcade.dswb_val:=@sw_dip_b; end; end; reset_tecmo; iniciar_tecmo:=true; end; end.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcTCPBuffer.pas } { File version: 5.08 } { Description: TCP buffer. } { } { Copyright: Copyright (c) 2007-2021, David J Butler } { All rights reserved. } { This file is licensed under the BSD License. } { See http://www.opensource.org/licenses/bsd-license.php } { 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. } { 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 REGENTS 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. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2008/12/23 0.01 Initial development. } { 2010/12/02 0.02 Revision. } { 2011/04/22 0.03 Simple test cases. } { 2011/06/16 0.04 Minor change in PeekPtr routine. } { 2011/09/03 4.05 Revised for Fundamentals 4. } { 2016/01/09 5.06 Revised for Fundamentals 5. } { 2019/04/10 5.07 Change default buffer size. } { 2019/12/29 5.08 Minimum buffer size. } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$INCLUDE flcTCP.inc} unit flcTCPBuffer; interface uses { System } SysUtils, { Utils } flcStdTypes; { } { TCP Buffer } { } type ETCPBuffer = class(Exception); TTCPBuffer = record Ptr : Pointer; Size : Integer; Min : Int32; Max : Int32; Head : Int32; Used : Int32; end; const ETHERNET_MTU = 1500; ETHERNET_MTU_JUMBO = 9000; TCP_BUFFER_DEFAULTMAXSIZE = ETHERNET_MTU_JUMBO * 8; // 72,000 bytes TCP_BUFFER_DEFAULTMINSIZE = ETHERNET_MTU * 6; // 9,000 bytes procedure TCPBufferInitialise( var TCPBuf: TTCPBuffer; const TCPBufMaxSize: Int32 = TCP_BUFFER_DEFAULTMAXSIZE; const TCPBufMinSize: Int32 = TCP_BUFFER_DEFAULTMINSIZE); procedure TCPBufferFinalise(var TCPBuf: TTCPBuffer); function TCPBufferGetMaxSize(const TCPBuf: TTCPBuffer): Int32; {$IFDEF UseInline}inline;{$ENDIF} procedure TCPBufferSetMaxSize( var TCPBuf: TTCPBuffer; const MaxSize: Int32); function TCPBufferGetMinSize(const TCPBuf: TTCPBuffer): Int32; {$IFDEF UseInline}inline;{$ENDIF} procedure TCPBufferSetMinSize( var TCPBuf: TTCPBuffer; const MinSize: Int32); procedure TCPBufferPack(var TCPBuf: TTCPBuffer); procedure TCPBufferResize( var TCPBuf: TTCPBuffer; const TCPBufSize: Int32); procedure TCPBufferExpand( var TCPBuf: TTCPBuffer; const Size: Int32); procedure TCPBufferShrink(var TCPBuf: TTCPBuffer); procedure TCPBufferMinimize(var TCPBuf: TTCPBuffer); procedure TCPBufferClear(var TCPBuf: TTCPBuffer); function TCPBufferAddPtr( var TCPBuf: TTCPBuffer; const Size: Int32): Pointer; procedure TCPBufferAdded( var TCPBuf: TTCPBuffer; const Size: Int32); procedure TCPBufferAddBuf( var TCPBuf: TTCPBuffer; const Buf; const Size: Int32); function TCPBufferPeekPtr( const TCPBuf: TTCPBuffer; var BufPtr: Pointer): Int32; {$IFDEF UseInline}inline;{$ENDIF} function TCPBufferPeek( var TCPBuf: TTCPBuffer; var Buf; const Size: Int32): Int32; function TCPBufferPeekByte( var TCPBuf: TTCPBuffer; out B: Byte): Boolean; function TCPBufferRemove( var TCPBuf: TTCPBuffer; var Buf; const Size: Int32): Int32; function TCPBufferRemoveBuf( var TCPBuf: TTCPBuffer; var Buf; const Size: Int32): Boolean; function TCPBufferDiscard( var TCPBuf: TTCPBuffer; const Size: Int32): Int32; function TCPBufferUsed(const TCPBuf: TTCPBuffer): Int32; {$IFDEF UseInline}inline;{$ENDIF} function TCPBufferEmpty(const TCPBuf: TTCPBuffer): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function TCPBufferAvailable(const TCPBuf: TTCPBuffer): Int32; {$IFDEF UseInline}inline;{$ENDIF} function TCPBufferPtr(const TCPBuf: TTCPBuffer): Pointer; {$IFDEF UseInline}inline;{$ENDIF} function TCPBufferLocateByteChar(const TCPBuf: TTCPBuffer; const Delimiter: ByteCharSet; const MaxSize: Integer): Int32; implementation { } { Resource strings } { } const SBufferOverflow = 'Buffer overflow'; { } { TCP Buffer } { } // Initialise a TCP buffer procedure TCPBufferInitialise( var TCPBuf: TTCPBuffer; const TCPBufMaxSize: Int32; const TCPBufMinSize: Int32); var L, M : Int32; begin TCPBuf.Ptr := nil; TCPBuf.Size := 0; TCPBuf.Head := 0; TCPBuf.Used := 0; L := TCPBufMinSize; if L < 0 then L := TCP_BUFFER_DEFAULTMINSIZE; M := TCPBufMaxSize; if M < 0 then M := TCP_BUFFER_DEFAULTMAXSIZE; if L > M then L := M; TCPBuf.Min := L; TCPBuf.Max := M; if L > 0 then GetMem(TCPBuf.Ptr, L); TCPBuf.Size := L; end; // Finalise a TCP buffer procedure TCPBufferFinalise(var TCPBuf: TTCPBuffer); var P : Pointer; begin P := TCPBuf.Ptr; if Assigned(P) then begin TCPBuf.Ptr := nil; FreeMem(P); end; TCPBuf.Size := 0; end; // Gets maximum buffer size function TCPBufferGetMaxSize(const TCPBuf: TTCPBuffer): Int32; begin Result := TCPBuf.Max; end; // Sets maximum buffer size // Note: This limit is not enforced. It is used by TCPBufferAvailable. procedure TCPBufferSetMaxSize( var TCPBuf: TTCPBuffer; const MaxSize: Int32); var L : Int32; begin L := MaxSize; if L < 0 then L := TCP_BUFFER_DEFAULTMAXSIZE; TCPBuf.Max := L; end; // Gets minimum buffer size function TCPBufferGetMinSize(const TCPBuf: TTCPBuffer): Int32; begin Result := TCPBuf.Min; end; procedure TCPBufferSetMinSize( var TCPBuf: TTCPBuffer; const MinSize: Int32); var L : Int32; begin L := MinSize; if L < 0 then L := TCP_BUFFER_DEFAULTMINSIZE; TCPBuf.Min := L; end; // Pack a TCP buffer // Moves data to front of buffer // Post: TCPBuf.Head = 0 procedure TCPBufferPack(var TCPBuf: TTCPBuffer); var P, Q : PByte; U, H : Int32; begin H := TCPBuf.Head; if H <= 0 then exit; U := TCPBuf.Used; if U <= 0 then begin TCPBuf.Head := 0; exit; end; Assert(Assigned(TCPBuf.Ptr)); P := TCPBuf.Ptr; Q := P; Inc(P, H); Move(P^, Q^, U); TCPBuf.Head := 0; end; // Resize a TCP buffer // New buffer size must be large enough to hold existing data // Post: TCPBuf.Size = TCPBufSize procedure TCPBufferResize( var TCPBuf: TTCPBuffer; const TCPBufSize: Int32); var U, L : Int32; begin L := TCPBufSize; U := TCPBuf.Used; // treat negative TCPBufSize parameter as zero if L < 0 then L := 0; // check if shrinking buffer to less than used size if U > L then raise ETCPBuffer.Create(SBufferOverflow); // check if packing required to fit buffer if U + TCPBuf.Head > L then TCPBufferPack(TCPBuf); Assert(U + TCPBuf.Head <= L); // resize ReallocMem(TCPBuf.Ptr, L); TCPBuf.Size := L; end; // Expand a TCP buffer // Expands the size of the TCP buffer to at least Size procedure TCPBufferExpand( var TCPBuf: TTCPBuffer; const Size: Int32); var S : Int32; N : Int64; I : Int64; begin S := TCPBuf.Size; N := Size; // check if expansion not required if N <= S then exit; // scale up new size proportional to current size // increase by at least quarter of current size // this reduces the number of resizes in growing buffers I := S + (S div 4); if N < I then N := I; // ensure new size is multiple of MTU size I := N mod ETHERNET_MTU; if I > 0 then Inc(N, ETHERNET_MTU - I); // resize buffer Assert(N >= Size); TCPBufferResize(TCPBuf, N); end; // Shrink the size of a TCP buffer to release all unused memory // Post: TCPBuf.Used = TCPBuf.Size and TCPBuf.Head = 0 procedure TCPBufferShrink(var TCPBuf: TTCPBuffer); var S, U : Int32; begin S := TCPBuf.Size; if S <= 0 then exit; U := TCPBuf.Used; if U = 0 then begin TCPBufferResize(TCPBuf, 0); TCPBuf.Head := 0; exit; end; if U = S then exit; TCPBufferPack(TCPBuf); // move data to front of buffer TCPBufferResize(TCPBuf, U); // set size equal to used bytes Assert(TCPBuf.Used = TCPBuf.Size); end; // Applies Min parameter to allocated memory procedure TCPBufferMinimize(var TCPBuf: TTCPBuffer); {$IFDEF UseInline}inline;{$ENDIF} var Mi : Int32; begin Mi := TCPBuf.Min; if Mi >= 0 then if TCPBuf.Used <= Mi then if TCPBuf.Size > Mi then TCPBufferResize(TCPBuf, Mi); end; // Clear the data from a TCP buffer procedure TCPBufferClear(var TCPBuf: TTCPBuffer); {$IFDEF UseInline}inline;{$ENDIF} begin TCPBuf.Used := 0; TCPBuf.Head := 0; TCPBufferMinimize(TCPBuf); end; // Returns a pointer to position in buffer to add new data of Size // Handles resizing and packing of buffer to fit new data function TCPBufferAddPtr( var TCPBuf: TTCPBuffer; const Size: Int32): Pointer; {$IFDEF UseInline}inline;{$ENDIF} var P : PByte; U : Int32; L : Int64; H : Int32; begin // return nil if nothing to add if Size <= 0 then begin Result := nil; exit; end; U := TCPBuf.Used; L := U + Size; // resize if necessary if L > TCPBuf.Size then TCPBufferExpand(TCPBuf, L); // pack if necessary if TCPBuf.Head + L > TCPBuf.Size then TCPBufferPack(TCPBuf); // buffer should now be large enough for new data H := TCPBuf.Head; Assert(TCPBuf.Size > 0); Assert(H + L <= TCPBuf.Size); // get buffer pointer Assert(Assigned(TCPBuf.Ptr)); P := TCPBuf.Ptr; Inc(P, H); Inc(P, U); Result := P; end; // Increases data used in buffer by Size. // TCPBufferAdded should only be called in conjuction with TCPBufferAddPtr. procedure TCPBufferAdded( var TCPBuf: TTCPBuffer; const Size: Int32); begin if Size <= 0 then exit; Assert(TCPBuf.Head + TCPBuf.Used + Size <= TCPBuf.Size); Inc(TCPBuf.Used, Size); end; // Adds new data from a buffer to a TCP buffer procedure TCPBufferAddBuf( var TCPBuf: TTCPBuffer; const Buf; const Size: Int32); {$IFDEF UseInline}inline;{$ENDIF} var P : PByte; begin if Size <= 0 then exit; // get TCP buffer pointer P := TCPBufferAddPtr(TCPBuf, Size); // move user buffer to TCP buffer Assert(Assigned(P)); Move(Buf, P^, Size); Inc(TCPBuf.Used, Size); Assert(TCPBuf.Head + TCPBuf.Used <= TCPBuf.Size); end; // Peek TCP buffer // Returns the number of bytes available to peek function TCPBufferPeekPtr( const TCPBuf: TTCPBuffer; var BufPtr: Pointer): Int32; {$IFDEF UseInline}inline;{$ENDIF} var P : PByte; L : Int32; begin // handle empty TCP buffer L := TCPBuf.Used; if L <= 0 then begin BufPtr := nil; Result := 0; exit; end; // get buffer pointer Assert(TCPBuf.Head + L <= TCPBuf.Size); Assert(Assigned(TCPBuf.Ptr)); P := TCPBuf.Ptr; Inc(P, TCPBuf.Head); BufPtr := P; // return size Result := L; end; // Peek data from a TCP buffer // Returns the number of bytes actually available and copied into the buffer function TCPBufferPeek( var TCPBuf: TTCPBuffer; var Buf; const Size: Int32): Int32; {$IFDEF UseInline}inline;{$ENDIF} var P : Pointer; L : Int32; begin // handle peeking zero bytes if Size <= 0 then begin Result := 0; exit; end; L := TCPBufferPeekPtr(TCPBuf, P); // peek from TCP buffer if L > Size then L := Size; Move(P^, Buf, L); Result := L; end; // Peek byte from a TCP buffer // Returns True if a byte is available function TCPBufferPeekByte( var TCPBuf: TTCPBuffer; out B: Byte): Boolean; var P : Pointer; L : Int32; begin L := TCPBufferPeekPtr(TCPBuf, P); // peek from TCP buffer if L = 0 then Result := False else begin B := PByte(P)^; Result := True; end; end; // Remove data from a TCP buffer // Returns the number of bytes actually available and copied into the user buffer function TCPBufferRemove( var TCPBuf: TTCPBuffer; var Buf; const Size: Int32): Int32; {$IFDEF UseInline}inline;{$ENDIF} var L, H, U : Int32; begin // peek data from buffer L := TCPBufferPeek(TCPBuf, Buf, Size); if L = 0 then begin Result := 0; exit; end; // remove from TCP buffer H := TCPBuf.Head; U := TCPBuf.Used; Dec(U, L); if U = 0 then H := 0 else Inc(H, L); TCPBuf.Head := H; TCPBuf.Used := U; TCPBufferMinimize(TCPBuf); Result := L; end; // Remove data from a TCP buffer // Returns True if Size bytes were available and copied into the user buffer // Returns False if Size bytes were not available function TCPBufferRemoveBuf( var TCPBuf: TTCPBuffer; var Buf; const Size: Int32): Boolean; {$IFDEF UseInline}inline;{$ENDIF} var H, U : Int32; P : PByte; begin // handle invalid size if Size <= 0 then begin Result := False; exit; end; // check if enough data available U := TCPBuf.Used; if U < Size then begin Result := False; exit; end; // get buffer H := TCPBuf.Head; Assert(H + Size <= TCPBuf.Size); P := TCPBuf.Ptr; Assert(Assigned(P)); Inc(P, H); Move(P^, Buf, Size); // remove from TCP buffer Dec(U, Size); if U = 0 then H := 0 else Inc(H, Size); TCPBuf.Head := H; TCPBuf.Used := U; TCPBufferMinimize(TCPBuf); Result := True; end; // Discard a number of bytes from the TCP buffer // Returns the number of bytes actually discarded from buffer function TCPBufferDiscard( var TCPBuf: TTCPBuffer; const Size: Int32): Int32; {$IFDEF UseInline}inline;{$ENDIF} var L, U : Int32; begin // handle discarding zero bytes from buffer L := Size; if L <= 0 then begin Result := 0; exit; end; // handle discarding the complete buffer U := TCPBuf.Used; if L >= U then begin TCPBuf.Used := 0; TCPBuf.Head := 0; TCPBufferMinimize(TCPBuf); Result := U; exit; end; // discard partial buffer Inc(TCPBuf.Head, L); Dec(U, L); TCPBuf.Used := U; TCPBufferMinimize(TCPBuf); Result := L; end; // Returns number of bytes used in TCP buffer function TCPBufferUsed(const TCPBuf: TTCPBuffer): Int32; {$IFDEF UseInline}inline;{$ENDIF} begin Result := TCPBuf.Used; end; function TCPBufferEmpty(const TCPBuf: TTCPBuffer): Boolean; {$IFDEF UseInline}inline;{$ENDIF} begin Result := TCPBuf.Used = 0; end; // Returns number of bytes available in TCP buffer // Note: this function can return a negative number if the TCP buffer uses more bytes than set in Max function TCPBufferAvailable(const TCPBuf: TTCPBuffer): Int32; {$IFDEF UseInline}inline;{$ENDIF} begin Result := TCPBuf.Max - TCPBuf.Used; end; // Returns pointer to TCP buffer head function TCPBufferPtr(const TCPBuf: TTCPBuffer): Pointer; {$IFDEF UseInline}inline;{$ENDIF} var P : PByte; begin Assert(Assigned(TCPBuf.Ptr)); P := TCPBuf.Ptr; Inc(P, TCPBuf.Head); Result := P; end; // LocateByteChar // Returns position of Delimiter in buffer // Returns >= 0 if found in buffer // Returns -1 if not found in buffer // MaxSize specifies maximum bytes before delimiter, of -1 for no limit function TCPBufferLocateByteChar(const TCPBuf: TTCPBuffer; const Delimiter: ByteCharSet; const MaxSize: Integer): Int32; var BufSize : Int32; LocLen : Int32; BufPtr : PByteChar; I : Int32; begin if MaxSize = 0 then begin Result := -1; exit; end; BufSize := TCPBuf.Used; if BufSize <= 0 then begin Result := -1; exit; end; if MaxSize < 0 then LocLen := BufSize else if BufSize < MaxSize then LocLen := BufSize else LocLen := MaxSize; BufPtr := TCPBufferPtr(TCPBuf); for I := 0 to LocLen - 1 do if BufPtr^ in Delimiter then begin Result := I; exit; end else Inc(BufPtr); Result := -1; end; end.
unit AppTips; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, RangeStrUtils; type TApplicationTips = class( TForm ) imHintIcon : TImage; llWelcome : TLabel; llAppName : TLabel; btSeeTour : TButton; btWhatsNew : TButton; btOnlineRegistration : TButton; btNextTip : TButton; bvButtonSep : TBevel; btClose : TButton; paHintText : TPanel; llDidYouKnow : TLabel; meHintText : TMemo; cbShowWelcome : TCheckBox; llcbAppName : TLabel; procedure FormCreate( Sender : TObject ); procedure btNextTipClick( Sender : TObject ); procedure btSeeTourClick( Sender : TObject ); procedure btWhatsNewClick( Sender : TObject ); procedure btOnlineRegistrationClick( Sender : TObject ); protected fTipRange : TRangeStr; fTipCurrent : integer; fTipsKey : HKEY; procedure GetNextTip; protected fOnSeeTour : TNotifyEvent; fOnWhatsNew : TNotifyEvent; fOnOnlineReg : TNotifyEvent; public procedure ShowWelcome; procedure ShowTips; published property OnSeeTour : TNotifyEvent read fOnSeeTour write fOnSeeTour; property OnWhatsNew : TNotifyEvent read fOnWhatsNew write fOnWhatsNew; property OnOnlineReg : TNotifyEvent read fOnOnlineReg write fOnOnlineReg; end; var ApplicationTips : TApplicationTips; var AppRegistryPath : string; AppName : string; procedure RegisterTip( Indx : integer; const TipText : string ); procedure TipRangeRegister( const TipsName : string; FromIndx, ToIndx : integer ); function TipRangeRegistered( const TipsName : string ) : boolean; implementation {$R *.DFM} uses Registry, RegUtils, WinUtils; procedure RegisterTip( Indx : integer; const TipText : string ); begin SetRegValue( HKEY_LOCAL_MACHINE, AppRegistryPath + '\Tips\' + IntToStr( Indx ), TipText ); end; function TipRangeRegistered( const TipsName : string ) : boolean; begin Result := GetRegValue( HKEY_LOCAL_MACHINE, AppRegistryPath + '\Tips\' + TipsName ) = '1'; end; procedure TipRangeRegister( const TipsName : string; FromIndx, ToIndx : integer ); var TipsKey : HKEY; TipRange : TRangeStr; begin TipsKey := GetWritableKey( HKEY_LOCAL_MACHINE, pchar( AppRegistryPath + '\Tips' ) ); //RegOpenKeyEx( HKEY_LOCAL_MACHINE, pchar( AppRegistryPath + '\Tips' ), 0, KEY_WRITE, TipsKey ); TipRange := TRangeStr.Create( GetRegValue( TipsKey, 'TipRange' ) ); TipRange.Add( FromIndx, ToIndx ); SetRegValue( TipsKey, 'TipRange', TipRange.RangeStr ); SetRegValue( TipsKey, TipsName, '1' ); RegCloseKey( TipsKey ); TipRange.Free; end; procedure TApplicationTips.ShowWelcome; var OldCloseTop : integer; OldHeight : integer; begin btNextTip.Visible := false; cbShowWelcome.Visible := false; llcbAppName.Visible := false; bvButtonSep.Visible := false; OldCloseTop := btClose.Top; btClose.Top := bvButtonSep.Top; OldHeight := Height; Height := btClose.Top + btClose.Height + paHintText.Top; // Bottom of btClose + Margin... ShowTips; btNextTip.Visible := true; cbShowWelcome.Visible := true; bvButtonSep.Visible := true; llcbAppName.Visible := true; btClose.Top := OldCloseTop; Height := OldHeight; end; // This might be a little messy, but since it's not that important I'm not fixing it // The problem is I'm using a TRegIniFile for accessing HKEY_CURRENT_USER keys, and // my own RegUtils for accessing HKEY_LOCAL_MACHINE keys. I should have standarized // on one of them! Knowing that, you'll should have no trouble finding in which branch // the registry information is stored. procedure TApplicationTips.ShowTips; var HinterIni : TRegIniFile; ShowMsg : boolean; begin HinterIni := TRegIniFile.Create( AppRegistryPath ); try with HinterIni do begin ShowMsg := ReadBool( 'Tips', 'ShowWelcome', true ); // HKCU if ShowMsg then begin fTipsKey := GetWritableKey( HKEY_LOCAL_MACHINE, AppRegistryPath + '\Tips' ); // HKLM try if ( fTipsKey <> 0 ) and ( GetRegValue( fTipsKey, 'LastRead' ) <> DateTimeToStr( Date ) ) // HKLM then begin cbShowWelcome.Checked := true; llcbAppName.Caption := AppName; llAppName.Caption := AppName; // Read registry keys fTipRange := TRangeStr.Create( GetRegValue( fTipsKey, 'TipRange' ) ); // HKLM SetRegValue( fTipsKey, 'TipRange', fTipRange.RangeStr ); // HKLM fTipCurrent := ReadInteger( 'Tips', 'TipCurrent', 0 ); // HKCU GetNextTip; Position := poScreenCenter; ShowModal; fTipRange.Free; WriteInteger( 'Tips', 'TipCurrent', fTipCurrent ); // HKCU SetRegValue( fTipsKey, 'LastRead', DateTimeToStr( Date ) ); // HKLM if not cbShowWelcome.Checked then WriteBool( 'Tips', 'ShowWelcome', false ); // HKCU end; finally RegCloseKey( fTipsKey ); end; end; end; finally HinterIni.Free; end; end; procedure TApplicationTips.FormCreate( Sender : TObject ); begin Icon := Application.Icon; SetWindowSizeable( Handle, false ); end; procedure TApplicationTips.GetNextTip; begin meHintText.Text := GetRegValue( fTipsKey, IntToStr( fTipCurrent ) ); fTipCurrent := fTipRange.Next( fTipCurrent ); end; procedure TApplicationTips.btNextTipClick( Sender : TObject ); begin GetNextTip; end; procedure TApplicationTips.btSeeTourClick( Sender : TObject ); begin if Assigned( OnSeeTour ) then OnSeeTour( Self ); end; procedure TApplicationTips.btWhatsNewClick( Sender : TObject ); begin if Assigned( OnWhatsNew ) then OnWhatsNew( Self ); end; procedure TApplicationTips.btOnlineRegistrationClick( Sender : TObject ); begin if Assigned( OnOnlineReg ) then OnOnlineReg( Self ); end; end.
PROGRAM Prime(INPUT, OUTPUT); CONST MaxNumber = 100; VAR Number, Prime, Temp: INTEGER; Sieve: SET OF 2 .. 100; BEGIN {Prime} Number := 2; Prime := 2; Sieve := [2 .. MaxNumber]; WRITE('Primes in range to ', MaxNumber, ': '); WHILE Sieve <> [] DO BEGIN IF Prime IN Sieve THEN WRITE(Prime, ' '); Temp := Number; WHILE Number <= MaxNumber DO BEGIN IF Number MOD Prime = 0 THEN Sieve := Sieve - [Number]; Number := Number + 1 END; Number := Temp + 1; Prime := Number END; WRITELN END. {Prime}
unit codewriter; {$mode delphi} interface uses Classes, SysUtils; type { TCodeWriter } TCodeWriter = class(TObject) private fnewline:Boolean; fText : AnsiString; fIdent : AnsiString; fIdDelta : AnsiString; newline : Boolean; fCurLine : AnsiString; fSection : AnsiString; fMaxLen : Integer; fCheckLineLen : Boolean; public constructor Create; procedure IncIdent; procedure DecIdent; procedure W(const s: AnsiString=''); procedure Wln(const s: AnsiString=''); procedure StartNewLine; property Section: AnsiString read fSection write fSection; property Text: AnsiString read fText write fText; property LineStarts: Boolean read fnewline; property MaxLineLen: Integer read fMaxLen write fMaxLen; property CheckLineLen: Boolean read fCheckLineLen write fCheckLineLen; end; procedure SetPasSection(wr: TCodeWriter; const SectionName: AnsiString; DoIdent: Boolean=true); implementation procedure SetPasSection(wr: TCodeWriter; const SectionName: AnsiString; DoIdent: Boolean); begin if wr.Section=SectionName then Exit; if (wr.Section<>'') and DoIdent then wr.DecIdent; if SectionName<>'' then wr.Wln(SectionName); wr.Section:=SectionName; if (wr.Section<>'') and DoIdent then wr.IncIdent; end; { TCodeWriter } constructor TCodeWriter.Create; begin fIdDelta:=' '; newline:=True; fMaxLen:=80; end; procedure TCodeWriter.IncIdent; begin fIdent:=fIdent+fIdDelta; end; procedure TCodeWriter.DecIdent; begin fIdent:=Copy(fIdent, 1, length(fIdent)-length(fIdDelta)); end; procedure TCodeWriter.W(const s:String); var AutoBreak: Boolean; begin //todo: check eoln symbols in s if s ='' then Exit; AutoBreak:=CheckLineLen and (fCurLine<>'') and ( length(fCurLine+fIdent)+length(s) > fMaxLen); if AutoBreak then begin fText:=fText+LineEnding; fCurLine:=''; fText:=fText+fIdent+fIdDelta; end; if newline then fText:=fText+fIdent; fText:=fText+s; fCurLine:=fCurLine+s; newline:=False; end; procedure TCodeWriter.Wln(const s:String); begin W(s+LineEnding); newline:=True; fCurLine:=''; end; procedure TCodeWriter.StartNewLine; begin if not newline then Wln; end; end.
unit K565842263; {* [Requestlink:565842263] } // Модуль: "w:\common\components\rtl\Garant\Daily\K565842263.pas" // Стереотип: "TestCase" // Элемент модели: "K565842263" MUID: (542BF156004C) // Имя типа: "TK565842263" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , NSRCtoEVDTest ; type TK565842263 = class(TNSRCtoEVDTest) {* [Requestlink:565842263] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK565842263 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *542BF156004Cimpl_uses* //#UC END# *542BF156004Cimpl_uses* ; function TK565842263.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'NSRCTests'; end;//TK565842263.GetFolder function TK565842263.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '542BF156004C'; end;//TK565842263.GetModelElementGUID initialization TestFramework.RegisterTest(TK565842263.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { This program is free software; you can redistribute it and/or } { modify it under the terms of the GNU General Public } { License as published by the Free Software Foundation; either } { version 2 of the License, or (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU } { General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uDisplayProperties; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,Qt, QImgList, QButtons, uXPColorSelector, uRegistry, uXPIPC, uCommon, uGraphics; type TDisplayPropertiesDlg = class(TForm) Button15:TButton; Label19:TLabel; cbPosition: TComboBox; lbPosition: TLabel; btnBrowse: TButton; lvPictures: TListView; Label17:TLabel; Label16:TLabel; Button13:TButton; Image4:TImage; Panel4:TPanel; GroupBox4:TGroupBox; CheckBox1:TCheckBox; Label15:TLabel; Edit1:TEdit; Label14:TLabel; Button12:TButton; Button11:TButton; ComboBox7:TComboBox; GroupBox3:TGroupBox; Image3:TImage; Panel3:TPanel; Button10:TButton; Button9:TButton; ComboBox6:TComboBox; Label13:TLabel; ComboBox5:TComboBox; Label12:TLabel; ComboBox4:TComboBox; Label11:TLabel; Button8:TButton; Button7:TButton; Image2:TImage; Panel2:TPanel; ComboBox3:TComboBox; GroupBox2:TGroupBox; Label10:TLabel; Label9:TLabel; Label8:TLabel; TrackBar1:TTrackBar; GroupBox1:TGroupBox; Label7:TLabel; ComboBox2:TComboBox; Label6:TLabel; Label5:TLabel; Label4:TLabel; Image1:TImage; Panel1:TPanel; Label3:TLabel; Button6:TButton; Button5:TButton; ComboBox1:TComboBox; Label2:TLabel; Label1:TLabel; TabSheet5:TTabSheet; TabSheet4:TTabSheet; TabSheet3:TTabSheet; TabSheet2:TTabSheet; PageControl1:TPageControl; Button4:TButton; btnApply: TButton; btnCancel: TButton; btnOk: TButton; TabSheet1:TTabSheet; Image5: TImage; imgList: TImageList; csBackground: TXPColorSelector; pnColor: TPanel; imgBack: TImage; odPictures: TOpenDialog; procedure FormCreate(Sender: TObject); procedure lvPicturesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure btnOkClick(Sender: TObject); procedure lvPicturesCustomDrawItem(Sender: TCustomViewControl; Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure csBackgroundChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure cbPositionChange(Sender: TObject); procedure btnBrowseClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnApplyClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } selectenabled: boolean; lastimage:string; function addimagetolist(const filename:string):TListItem; procedure loadPictureDir; procedure loadImage(const filename:string); procedure storeproperties; end; type TTilemode=(tmCenter, tmTile, tmStretch); TDesktop=record color:TColor; method: integer; desktopimage:string; end; var DisplayPropertiesDlg: TDisplayPropertiesDlg=nil; desktop:TDesktop; resourcestring sNone='(None)'; procedure customizeDesktop; implementation {$R *.xfm} procedure customizeDesktop; begin //Creates the dialog if not assigned(DisplayPropertiesDlg) then begin Application.CreateForm(TDisplayPropertiesDlg,DisplayPropertiesDlg); end; end; procedure TDisplayPropertiesDlg.FormCreate(Sender: TObject); var reg:TRegistry; col: string; path:string; method:integer; b:TBitmap; wallpapers_dir: string; begin //Load the images image5.Picture.LoadFromFile(getSystemInfo(XP_MISC_DIR)+'/desktoppropertiesmonitor.png'); b:=TBitmap.create; try b.LoadFromFile(getSystemInfo(XP_MISC_DIR)+'/none.png'); b.width:=imgList.Width; b.height:=imgList.height; imgList.AddMasked(b,clFuchsia); b.LoadFromFile(getSystemInfo(XP_MISC_DIR)+'/bmp.png'); b.width:=imgList.Width; b.height:=imgList.height; imgList.AddMasked(b,clFuchsia); b.LoadFromFile(getSystemInfo(XP_MISC_DIR)+'/jpg.png'); b.width:=imgList.Width; b.height:=imgList.height; imgList.Add(b,b); b.LoadFromFile(getSystemInfo(XP_MISC_DIR)+'/png.png'); b.width:=imgList.Width; b.height:=imgList.height; imgList.Add(b,b); finally b.free; end; //Load the configurations selectenabled:=false; try PageControl1.ActivePageIndex:=1; reg:=TRegistry.create; try if reg.OpenKey('Software/XPde/Desktop/Background',false) then begin if reg.ValueExists('Color') then begin col:=reg.ReadString('Color'); desktop.color:=stringtocolor(col); end else desktop.color:=clHighLight; end else desktop.color:=clHighLight; finally reg.free; end; reg:=TRegistry.create; try if reg.OpenKey('Software/XPde/Desktop/Background',false) then begin path:=reg.ReadString('Image'); method:=reg.ReadInteger('Method'); if path='none' then begin desktop.desktopimage:=''; end else begin desktop.desktopimage:=path; desktop.method:=method; end; end else begin wallpapers_dir:=getSystemInfo(XP_WALLPAPERS_DIR); if (fileexists(wallpapers_dir+'/default.png')) then begin desktop.desktopimage:=wallpapers_dir+'/default.png'; desktop.method:=2; end else desktop.color:=clHighLight; end; finally reg.Free; end; loadPictureDir; csBackground.color:=Desktop.color; cbPosition.itemindex:=Desktop.method; pnColor.color:=csBackground.color; if desktop.desktopimage='' then begin imgBack.Visible:=false; lbPosition.enabled:=false; cbPosition.enabled:=false; end else begin loadimage(extractfilename(desktop.desktopimage)); end; finally selectenabled:=true; end; end; procedure TDisplayPropertiesDlg.loadPictureDir; var list:TStringList; sr: TSearchRec; dir:string; i:longint; ext: string; li:TListItem; img: string; ts: TListItem; begin //Load a list of images located on the wallpapers dir ts:=nil; img:=extractfilename(desktop.desktopimage); list:=TStringList.create; try dir:=getSystemInfo(XP_WALLPAPERS_DIR)+'/'; if findfirst(dir+'*.jpg',faAnyFile,sr)=0 then begin repeat list.add(sr.name); until findnext(sr)<>0; findclose(sr); end; if findfirst(dir+'*.png',faAnyFile,sr)=0 then begin repeat list.add(sr.name); until findnext(sr)<>0; findclose(sr); end; if findfirst(dir+'*.bmp',faAnyFile,sr)=0 then begin repeat list.add(sr.name); until findnext(sr)<>0; findclose(sr); end; list.sorted:=true; list.sorted:=false; list.Insert(0,sNone); lvPictures.Items.BeginUpdate; try for i:=0 to list.count-1 do begin ext:=ansilowercase(extractfileext(list[i])); li:=lvPictures.Items.Add; if extractfilename(list[i])=img then ts:=li; li.Caption:=changefileext(extractfilename(list[i]),''); if (ext='.png') then begin li.ImageIndex:=3; end else if (ext='.jpg') then begin li.ImageIndex:=2; end else if ext='.bmp' then begin li.ImageIndex:=1; end else begin li.ImageIndex:=0; ts:=li; end; end; finally lvPictures.items.endupdate; end; finally lvPictures.Selected:=ts; lvPictures.Selected.MakeVisible; list.free; end; end; procedure TDisplayPropertiesDlg.loadImage(const filename:string); var dir:string; b:TBitmap; im:TPicture; ax,ay:integer; begin dir:=getSystemInfo(XP_WALLPAPERS_DIR)+'/'; im:=TPicture.create; b:=TBitmap.create; try im.loadfromfile(dir+filename); b.Canvas.brush.color:=csBackground.color; b.Width:=screen.width; b.height:=screen.Height; case cbPosition.ItemIndex of 0: begin ax:=(b.width-im.Graphic.Width) div 2; ay:=(b.height-im.Graphic.height) div 2; b.Canvas.draw(ax,ay,im.graphic); end; 1: begin ax:=0; while (ax<b.width) do begin ay:=0; while (ay<b.height) do begin b.Canvas.draw(ax,ay,im.graphic); inc(ay,im.graphic.height); end; inc(ax,im.graphic.width); end; end; 2: begin b.canvas.StretchDraw(rect(0,0,b.width,b.height),im.graphic); end; end; imgBack.picture.assign(b); imgBack.Visible:=true; lastimage:=dir+filename; finally b.free; im.free; end; end; procedure TDisplayPropertiesDlg.lvPicturesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); var ext:string; begin if selectenabled then begin if item.ImageIndex=0 then begin lbPosition.enabled:=false; cbPosition.enabled:=false; //Rellenar aqui el imgBack con el color de fondo if assigned(imgBack.picture.graphic) then imgBack.Picture.Graphic.assign(nil); imgBack.Visible:=false; lastimage:='none'; end else begin lbPosition.enabled:=true; cbPosition.enabled:=true; if item.ImageIndex=1 then ext:='.bmp' else if item.ImageIndex=2 then ext:='.jpg' else if item.ImageIndex=3 then ext:='.png'; loadImage(Item.caption+ext); end; end; end; procedure TDisplayPropertiesDlg.btnOkClick(Sender: TObject); begin storeproperties; XPIPC.broadcastMessage(XPDE_DESKTOPCHANGED,0); close; end; procedure TDisplayPropertiesDlg.lvPicturesCustomDrawItem( Sender: TCustomViewControl; Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); var bcolor:TColor; b: TBitmap; r: TRect; tx: integer; ty: integer; cap: string; res: TBitmap; begin canvas.font.name:=(sender as TListview).font.name; canvas.font.height:=(sender as TListview).font.height; canvas.font.size:=(sender as TListview).font.size; bcolor:=canvas.brush.color; canvas.brush.color:=clBtnHighlight; canvas.pen.color:=clBtnHighlight; canvas.Rectangle(rect); cap:=(item as TListItem).Caption; b:=TBitmap.create; res:=TBitmap.create; try b.width:=(sender as TListView).Images.Width; b.height:=(sender as TListView).Images.height; (sender as TListView).Images.GetBitmap((item as TListItem).imageindex,b); b.transparent:=true; if cdsSelected in state then begin MaskedBitmap(b,res); res.transparent:=true; Canvas.Draw(rect.left+4,rect.top,res); end else Canvas.Draw(rect.left+4,rect.top,b); finally res.free; b.free; end; tx:=rect.left+4+(sender as TListView).Images.Width; ty:=rect.top+1; r.left:=tx; r.top:=ty; r.right:=r.left+canvas.TextWidth(cap)+4+2; r.bottom:=r.top+canvas.TextHeight(cap)+2; canvas.brush.color:=bcolor; canvas.pen.color:=bcolor; canvas.Rectangle(r); canvas.TextOut(tx+2,ty+1,cap); if (cdsSelected in state) then begin canvas.DrawFocusRect(r); end; defaultdraw:=false; end; procedure TDisplayPropertiesDlg.csBackgroundChange(Sender: TObject); begin pnColor.color:=csBackground.color; lvPicturesSelectItem(lvPictures,lvPictures.Selected,true); end; procedure TDisplayPropertiesDlg.FormShow(Sender: TObject); begin left:=(screen.width-clientwidth) div 2; top:=(screen.height-clientheight) div 2; end; procedure TDisplayPropertiesDlg.cbPositionChange(Sender: TObject); begin lvPicturesSelectItem(lvPictures,lvPictures.Selected,true); end; procedure TDisplayPropertiesDlg.btnBrowseClick(Sender: TObject); var dir:string; destination: string; ls: TListItem; begin if odPictures.execute then begin dir:=getSystemInfo(XP_WALLPAPERS_DIR)+'/'; destination:=odPictures.filename; if extractfilepath(odPictures.FileName)<>dir then begin destination:=dir+extractfilename(odPictures.filename); copyfile(odPictures.filename,destination); end; ls:=addimagetolist(destination); if assigned(ls) then begin lvPictures.Selected:=ls; end; end; end; function TDisplayPropertiesDlg.addimagetolist(const filename: string):TListitem; var ext:string; begin ext:=ansilowercase(extractfileext(filename)); result:=lvPictures.Items.Add; result.Caption:=changefileext(extractfilename(filename),''); if ext='.png' then begin result.ImageIndex:=3; end else if ext='.jpg' then begin result.ImageIndex:=2; end else if ext='.bmp' then begin result.ImageIndex:=1; end else begin result.ImageIndex:=0; end; end; procedure TDisplayPropertiesDlg.btnCancelClick(Sender: TObject); begin close; end; procedure TDisplayPropertiesDlg.storeproperties; var reg: TRegistry; begin //Aqui tengo que guardar toda la información en el registro reg:=TRegistry.create; try if reg.OpenKey('Software/XPde/Desktop/Background',true) then begin reg.WriteString('Image',lastimage); reg.WriteInteger('Method',cbPosition.itemindex); end; finally reg.Free; end; reg:=TRegistry.create; try if reg.OpenKey('Software/XPde/Desktop/Background',true) then begin reg.WriteString('Color',colortostring(csBackground.color)); end; finally reg.free; end; end; procedure TDisplayPropertiesDlg.btnApplyClick(Sender: TObject); begin storeproperties; XPIPC.broadcastMessage(XPDE_DESKTOPCHANGED,0); end; procedure TDisplayPropertiesDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin action:=caFree; DisplayPropertiesDlg:=nil; end; end.
unit upaymo; {< This is the core of the FPC Paymo Widget. This unit contains the main class to interact with the Paymo API. @author(Leandro Diaz (http://lainz.github.io)) } {$mode objfpc}{$H+} interface uses Classes, SysUtils, fphttpclient, jsonConf, fpjson, jsonparser, Dialogs, DateUtils, LazUTF8, udebug, uresourcestring; const { URL used for GET, POST and DELETE } PAYMOAPIBASEURL = 'https://app.paymoapp.com/api/'; { URL used to get the API Key to start using the application } PAYMOAPIKEYURL = 'https://app.paymoapp.com/#Paymo.module.myaccount/'; { Number of max additional timers } ADDITIONALTIMERS = 2; { Sort function by name property, case insensitive } function NameSort(Item1, Item2: Pointer): integer; { Sort function by 'seq' property, it allows to sort like in the Paymo website } function SeqSort(Item1, Item2: Pointer): integer; { Sort function by 'seq' property plus sort by project name, case insensitive } function SeqSortProjectName(Item1, Item2: Pointer): integer; { Sort function by name property, case insensitive, from bottom to top } function InverseNameSort(Item1, Item2: Pointer): integer; type { Status for any GET, POST, DELETE operation } TPaymoResponseStatus = ( prOK, //< operation went well prERROR, //< operation went bad prTRYAGAIN, //< server is bussy prNOInternet //< offline ); { TPaymo -- Main class to interact with Paymo API } TPaymo = class(TObject) private FAPIKey: string; FAPIKeyURL: string; FAPIURL: string; FLoggedIn: boolean; FMe: TJSONObject; FOffline: boolean; FProjects: TJSONObject; FRunningTimer: TJSONObject; FSettingsFile: string; FSettingsFolder: string; FTaskLists: TJSONObject; FTasks: TJSONObject; FCompany: TJSONObject; FOfflineData: TJSONArray; FAdditionalTimers: TJSONArray; FUsers: TJSONObject; FUsersRunningTimer: TJSONArray; function GetFHasOfflineData: boolean; procedure SetFAPIKey(AValue: string); procedure SetFAPIKeyURL(AValue: string); procedure SetFAPIURL(AValue: string); procedure SetFLoggedIn(AValue: boolean); procedure SetFOffline(AValue: boolean); procedure SetFSettingsFile(AValue: string); procedure SetFSettingsFolder(AValue: string); public { List of Projects } function ProjectsArray: TJSONArray; { List of Tasks } function TasksArray: TJSONArray; { List of Task Lists} function TaskListsArray: TJSONArray; { User information } function MyData: TJSONData; { Company information } function CompanyData: TJSONData; { Current running timer } function RunningTimerData: TJSONData; { Company users } function Users: TJSONArray; { All users running timers} function UsersRunningTimer: TJSONArray; { Returns the name of the Project given the ID } function GetProjectName(ProjectID: int64): string; { Returns the name of the Task given the ID} function GetTaskName(TaskID: int64): string; { Returns the task data given the ID} function GetTask(TaskID: int64): TJSONData; { Returns the time entry data given the ID} function GetTimeEntry(EntryID: integer): TJSONData; { Returns the task list data given the ID} function GetTaskList(TaskListID: integer): TJSONData; { Returns the additional running timers } function GetAdditionalRunningTimers: TJSONArray; { Returns the timer tabs } function GetTimerTabs: string; public { Constructor } constructor Create; { Destructor } destructor Destroy; override; { The key to connect to the API } property APIKey: string read FAPIKey write SetFAPIKey; { The base URL used to connect to the API} property APIURL: string read FAPIURL write SetFAPIURL; { The URL used to obtain an API Key} property APIKeyURL: string read FAPIKeyURL write SetFAPIKeyURL; { Check if the user is Logged In } property LoggedIn: boolean read FLoggedIn write SetFLoggedIn; { Calls GetMe() and test the response } function Login: TPaymoResponseStatus; { Get data from an endpoint, stores the server response in the response variable } function Get(Endpoint: string; var Response: string): TPaymoResponseStatus; { Retrieve tasks online or offline } function GetTasks(): TPaymoResponseStatus; { Retrieve a task given it's id } function GetSingleTask(id: integer): TJSONData; { Retrieve projects online or offline } function GetProjects(): TPaymoResponseStatus; { Retrieve task lists online or offline } function GetTaskLists(): TPaymoResponseStatus; { Retrieve user information } function GetMe(): TPaymoResponseStatus; { Retrieve current running timer } function GetRunningTimer(): TPaymoResponseStatus; { Retrieve all users running timer } function GetAllUsersRunningTimer(): TPaymoResponseStatus; { Retrieve company information } function GetCompany(): TPaymoResponseStatus; { Retrieve users } function GetUsers(): TPaymoResponseStatus; { Creates or updates data to an endpoint, providing a JSON string, stores the server response in the response variable } function Post(Endpoint: string; sJSON: TJSONStringType; var Response: string): TPaymoResponseStatus; { Delete the data of an endpoint, stores the server response in the response variable } function Delete(Endpoint: string; var Response: string): TPaymoResponseStatus; { Post a new task, if went OK it adds it to the list of tasks } function CreateTask(Name, Description: string; TaskListID: integer; var task: TJSONData): TPaymoResponseStatus; { Updates task 'complete' status } function UpdateTaskCompletion(Complete: boolean; task: TJSONData): TPaymoResponseStatus; { Persists the running timer, if time interval is less than a second the data is discarded } function StopRunningTimer(start_time, end_time: TDateTime; Description: string): TPaymoResponseStatus; { Set the running timer } function StartRunningTimer(task_id: int64; start_time: TDateTime): TPaymoResponseStatus; { Delete a time entry, given the ID } function DeleteTimeEntry(TimeEntryID: string): TPaymoResponseStatus; { Updates a time entry start and end time, and also project, task and tasklist related } function UpdateTimeEntry(TimeEntryID: integer; start_time, end_time: TDateTime; project_id, task_id, tasklist_id: int64): TPaymoResponseStatus; { Create a time entry with start and end time } function CreateTimeEntry(start_time, end_time: TDateTime; task_id: int64): TPaymoResponseStatus; { Stop additional timer } function StopAdditionalTimer(index: integer; end_time: TDateTime): TPaymoResponseStatus; public { Persists a JSON to file, used to save offline data } function SaveJSON(FileName: string; sJSON: string): TPaymoResponseStatus; { Loads into memory a JSON file, used to retrieve previously saved offline data } function LoadJSON(FileName: string; var response: string): TPaymoResponseStatus; public { Retrieves the API Key and offline data previously saved } procedure LoadSettings; { Stores the API Key} procedure SaveSettings; { Stores into offline.json the data send to Post method, if the user is offline } procedure POST_Offline(Endpoint: string; sJSON: TJSONStringType; var Response: string); { Stores into offline.json the data send to Delete method, if the user is offline } procedure DELETE_Offline(Endpoint: string; var Response: string); { Creates a Post or Delete for each element stored in offline.json } function SYNC_OfflineData: integer; { Get / Set the Offline status } property Offline: boolean read FOffline write SetFOffline; { Check if there is offline data loaded into memory, used to see if SYNC_OfflineData must be called } property HasOfflineData: boolean read GetFHasOfflineData; { The folder where the API Key and json files must be saved } property SettingsFolder: string read FSettingsFolder write SetFSettingsFolder; { The API Key file name } property SettingsFile: string read FSettingsFile write SetFSettingsFile; end; var { Used internally by the sort function SeqSortProjectName because it requires to retrieve the names of the projects } PAYMO_SORT_INSTANCE: TPaymo; implementation uses utasklist; function NameSort(Item1, Item2: Pointer): integer; begin if UTF8LowerCase(TJSONData(Item1).GetPath('name').AsString) > UTF8LowerCase(TJSONData(Item2).GetPath('name').AsString) then exit(1); if UTF8LowerCase(TJSONData(Item1).GetPath('name').AsString) < UTF8LowerCase(TJSONData(Item2).GetPath('name').AsString) then exit(-1); exit(0); end; function SeqSort(Item1, Item2: Pointer): integer; begin if TJSONData(Item1).GetPath('project_id').AsInt64 > TJSONData(Item2).GetPath('project_id').AsInt64 then exit(-1); if TJSONData(Item1).GetPath('project_id').AsInt64 < TJSONData(Item2).GetPath('project_id').AsInt64 then exit(1); if TJSONData(Item1).GetPath('seq').AsInteger > TJSONData(Item2).GetPath('seq').AsInteger then exit(-1); if TJSONData(Item1).GetPath('seq').AsInteger < TJSONData(Item2).GetPath('seq').AsInteger then exit(1); exit(0); end; function SeqSortProjectName(Item1, Item2: Pointer): integer; begin if UTF8LowerCase(PAYMO_SORT_INSTANCE.GetProjectName( TJSONData(Item1).GetPath('project_id').AsInt64)) > UTF8LowerCase(PAYMO_SORT_INSTANCE.GetProjectName( TJSONData(Item2).GetPath('project_id').AsInt64)) then exit(-1); if UTF8LowerCase(PAYMO_SORT_INSTANCE.GetProjectName( TJSONData(Item1).GetPath('project_id').AsInt64)) < UTF8LowerCase(PAYMO_SORT_INSTANCE.GetProjectName( TJSONData(Item2).GetPath('project_id').AsInt64)) then exit(1); if TJSONData(Item1).GetPath('seq').AsInteger > TJSONData(Item2).GetPath('seq').AsInteger then exit(-1); if TJSONData(Item1).GetPath('seq').AsInteger < TJSONData(Item2).GetPath('seq').AsInteger then exit(1); exit(0); end; function InverseNameSort(Item1, Item2: Pointer): integer; begin if UTF8LowerCase(TJSONData(Item1).GetPath('name').AsString) < UTF8LowerCase(TJSONData(Item2).GetPath('name').AsString) then exit(1); if UTF8LowerCase(TJSONData(Item1).GetPath('name').AsString) > UTF8LowerCase(TJSONData(Item2).GetPath('name').AsString) then exit(-1); exit(0); end; { TPaymo } procedure TPaymo.SetFAPIKey(AValue: string); begin if FAPIKey = AValue then Exit; FAPIKey := AValue; end; function TPaymo.GetFHasOfflineData: boolean; begin Result := FOfflineData.Count > 0; end; procedure TPaymo.SetFAPIKeyURL(AValue: string); begin if FAPIKeyURL = AValue then Exit; FAPIKeyURL := AValue; end; procedure TPaymo.SetFAPIURL(AValue: string); begin if FAPIURL = AValue then Exit; FAPIURL := AValue; end; procedure TPaymo.SetFLoggedIn(AValue: boolean); begin if FLoggedIn = AValue then Exit; FLoggedIn := AValue; end; procedure TPaymo.SetFOffline(AValue: boolean); begin if FOffline = AValue then Exit; FOffline := AValue; end; procedure TPaymo.SetFSettingsFile(AValue: string); begin if FSettingsFile = AValue then Exit; FSettingsFile := AValue; end; procedure TPaymo.SetFSettingsFolder(AValue: string); begin if FSettingsFolder = AValue then Exit; FSettingsFolder := AValue; end; function TPaymo.ProjectsArray: TJSONArray; begin FProjects.Find('projects', Result); end; function TPaymo.TasksArray: TJSONArray; begin FTasks.Find('tasks', Result); end; function TPaymo.TaskListsArray: TJSONArray; begin FTaskLists.Find('tasklists', Result); end; function TPaymo.MyData: TJSONData; var arr: TJSONArray; begin FMe.Find('users', arr); Result := arr[0]; end; function TPaymo.CompanyData: TJSONData; begin if not Assigned(FCompany) then exit(nil); FCompany.Find('company', Result); end; function TPaymo.RunningTimerData: TJSONData; var arr: TJSONArray; begin if not Assigned(FRunningTimer) then exit(nil); FRunningTimer.Find('entries', arr); if (arr <> nil) and (arr.Count > 0) then Result := arr[0] else Result := nil; end; function TPaymo.Users: TJSONArray; begin if not Assigned(FUsers) then exit(nil); FUsers.Find('users', Result); end; function TPaymo.UsersRunningTimer: TJSONArray; begin Result := FUsersRunningTimer; end; function TPaymo.GetProjectName(ProjectID: int64): string; var i: integer; arr: TJSONArray; begin Result := ''; arr := ProjectsArray; for i := 0 to arr.Count - 1 do begin if ProjectID = arr[i].GetPath('id').AsInteger then exit(arr[i].GetPath('name').AsString); end; end; function TPaymo.GetTaskName(TaskID: int64): string; var i: integer; arr: TJSONArray; begin Result := ''; arr := TasksArray; for i := 0 to arr.Count - 1 do begin if TaskID = arr[i].GetPath('id').AsInt64 then exit(arr[i].GetPath('name').AsString); end; end; function TPaymo.GetTask(TaskID: int64): TJSONData; var i: integer; arr: TJSONArray; begin Result := nil; arr := TasksArray; for i := 0 to arr.Count - 1 do begin if TaskID = arr[i].GetPath('id').AsInt64 then exit(arr[i]); end; end; function TPaymo.GetTimeEntry(EntryID: integer): TJSONData; var arr, arrEntries: TJSONArray; i, j: integer; begin Result := nil; arr := TasksArray; for i := 0 to arr.Count - 1 do begin arrEntries := TJSONArray(arr[i].GetPath('entries')); for j := 0 to arrEntries.Count - 1 do begin if arrEntries[j].GetPath('id').AsInteger = EntryID then exit(arrEntries[j]); end; end; end; function TPaymo.GetTaskList(TaskListID: integer): TJSONData; var i: integer; arr: TJSONArray; begin Result := nil; arr := TaskListsArray; for i := 0 to arr.Count - 1 do begin if TaskListID = arr[i].GetPath('id').AsInteger then exit(arr[i]); end; end; function TPaymo.GetAdditionalRunningTimers: TJSONArray; begin Result := FAdditionalTimers; end; function TPaymo.GetTimerTabs: string; var i: integer; begin Result := ''; if RunningTimerData <> nil then begin Result := GetProjectName(GetTask(RunningTimerData.GetPath( 'task_id').AsInt64).GetPath('project_id').AsInt64) + LineEnding; end; for i := 0 to FAdditionalTimers.Count - 1 do Result += GetProjectName(GetTask(FAdditionalTimers[i].GetPath( 'task_id').AsInt64).GetPath('project_id').AsInt64) + ' [' + (i + 1).ToString + ']' + LineEnding; end; constructor TPaymo.Create; begin inherited Create; APIKeyURL := PAYMOAPIKEYURL; APIURL := PAYMOAPIBASEURL; FOffline := False; FOfflineData := TJSONArray.Create; FAdditionalTimers := TJSONArray.Create; end; destructor TPaymo.Destroy; begin if Assigned(FProjects) then FProjects.Free; if Assigned(FTasks) then FTasks.Free; if Assigned(FMe) then FMe.Free; if Assigned(FTaskLists) then FTaskLists.Free; if Assigned(FRunningTimer) then FRunningTimer.Free; if Assigned(FCompany) then FCompany.Free; if Assigned(FOfflineData) then FOfflineData.Free; if Assigned(FAdditionalTimers) then FAdditionalTimers.Free; if Assigned(FUsers) then FUsers.Free; if Assigned(FUsersRunningTimer) then FUsersRunningTimer.Free; inherited Destroy; end; function TPaymo.Login: TPaymoResponseStatus; begin Result := GetMe(); case Result of prOK: FLoggedIn := True; prTRYAGAIN: FLoggedIn := False; prERROR: FLoggedIn := False; end; end; function TPaymo.Get(Endpoint: string; var Response: string): TPaymoResponseStatus; var client: TFPHTTPClient; begin DebugLog('FPC Paymo Widget', 'Get:' + endpoint, 'Start'); Result := prERROR; try client := TFPHttpClient.Create(nil); client.AddHeader('Accept', 'application/json'); client.UserName := FAPIKey; client.Password := ''; try Response := client.Get(APIURL + Endpoint); if (client.ResponseStatusCode >= 200) and (client.ResponseStatusCode <= 300) then Result := prOK else if (client.ResponseStatusCode = 429) then begin DebugLog('', 'Get/' + Endpoint, 'prTRYAGAIN'); Result := prTRYAGAIN; end else begin DebugLog('', 'Get/' + Endpoint, 'prERROR'); Result := prERROR; end; except on e: Exception do begin DebugLog('', 'Get/' + Endpoint, 'Exception: ' + e.message); if (Pos('HOST NAME RESOLUTION', UpperCase(e.message)) > 0) then Result := prNOInternet else Result := prERROR; end; end; finally DebugLog('FPC Paymo Widget', 'Get:' + endpoint, 'Finish'); client.Free; end; end; function TPaymo.GetTasks(): TPaymoResponseStatus; var response: string; begin if not FOffline then Result := Get('tasks?where=mytasks=true&include=entries', response) else Result := LoadJSON('tasks.json', response); case Result of prOK: begin if Assigned(FTasks) then FTasks.Free; FTasks := TJSONObject(GetJSON(response)); TasksArray.Sort(@NameSort); SaveJSON('tasks.json', FTasks.FormatJSON()); end; end; end; function TPaymo.GetSingleTask(id: integer): TJSONData; var response: string; begin if not FOffline then case Get('tasks/' + IntToStr(id), response) of prOK: begin Result := GetJSON(response); end; else Result := TJSONData.Create; end; end; function TPaymo.GetProjects(): TPaymoResponseStatus; var response: string; begin if not FOffline then Result := Get('projects', response) else Result := LoadJSON('projects.json', response); case Result of prOK: begin if Assigned(FProjects) then FProjects.Free; FProjects := TJSONObject(GetJSON(response)); ProjectsArray.Sort(@NameSort); SaveJSON('projects.json', FProjects.FormatJSON()); end; end; end; function TPaymo.GetTaskLists(): TPaymoResponseStatus; var response: string; begin if not FOffline then Result := Get('tasklists', response) else Result := LoadJSON('tasklists.json', response); case Result of prOK: begin if Assigned(FTaskLists) then FTaskLists.Free; FTaskLists := TJSONObject(GetJSON(response)); TaskListsArray.Sort(@NameSort); SaveJSON('tasklists.json', FTaskLists.FormatJSON()); end; end; end; function TPaymo.GetMe(): TPaymoResponseStatus; var response: string; begin if not FOffline then Result := Get('me', response) else Result := LoadJSON('me.json', response); case Result of prOK: begin if Assigned(FMe) then FMe.Free; FMe := TJSONObject(GetJSON(response)); SaveJSON('me.json', FMe.FormatJSON()); end; end; end; function TPaymo.GetRunningTimer(): TPaymoResponseStatus; var response: string; begin if not FOffline then Result := Get('entries?where=user_id=' + MyData.GetPath('id').AsString + '%20and%20end_time=null', response) else Result := prNOInternet; //LoadJSON('runningtimer.json', response); case Result of prOK: begin if Assigned(FRunningTimer) then FRunningTimer.Free; FRunningTimer := TJSONObject(GetJSON(response)); //SaveJSON('runningtimer.json', FRunningTimer.FormatJSON()); end; end; end; function TPaymo.GetAllUsersRunningTimer(): TPaymoResponseStatus; var response: string; i: integer; begin if Assigned(FUsersRunningTimer) then FUsersRunningTimer.Clear else FUsersRunningTimer := TJSONArray.Create; for i := 0 to Users.Count - 1 do begin if not FOffline and Assigned(Users.Items[i].GetPath('id')) then Result := Get('entries?where=user_id=' + Users.Items[i].GetPath('id').AsString + '%20and%20end_time=null', response) else begin Result := prNOInternet; //exit; end; case Result of prOK: begin FUsersRunningTimer.Add(GetJSON(response)); end; end; end; //SaveJSON('userstimer.json',FUsersRunningTimer.FormatJSON()); end; function TPaymo.GetCompany(): TPaymoResponseStatus; var response: string; begin if not FOffline then Result := Get('company', response) else Result := LoadJSON('company.json', response); case Result of prOK: begin if Assigned(FCompany) then FCompany.Free; FCompany := TJSONObject(GetJSON(response)); SaveJSON('company.json', FCompany.FormatJSON()); end; end; end; function TPaymo.GetUsers(): TPaymoResponseStatus; var response: string; begin if not FOffline then Result := Get('users?where=active=true', response) else Result := LoadJSON('users.json', response); case Result of prOK: begin if Assigned(FUsers) then FUsers.Free; FUsers := TJSONObject(GetJSON(response)); SaveJSON('users.json', FUsers.FormatJSON()); end; end; end; function TPaymo.Post(Endpoint: string; sJSON: TJSONStringType; var Response: string): TPaymoResponseStatus; var client: TFPHTTPClient; ss: TMemoryStream; begin Result := prERROR; try client := TFPHttpClient.Create(nil); client.AddHeader('Content-type', 'application/json'); client.AddHeader('Accept', 'application/json'); client.UserName := FAPIKey; client.Password := ''; ss := TMemoryStream.Create(); ss.Write(Pointer(sJSON)^, length(sJSON)); ss.Position := 0; client.RequestBody := ss; if not FOffline then begin try Response := client.Post(APIURL + Endpoint); if (client.ResponseStatusCode >= 200) and (client.ResponseStatusCode <= 300) then Result := prOK else if (client.ResponseStatusCode = 429) then begin DebugLog('', 'Post/' + Endpoint, 'prTRYAGAIN'); Result := prTRYAGAIN; end else begin DebugLog('', 'Post/' + Endpoint, 'prERROR'); Result := prERROR; end; except on e: Exception do begin DebugLog('', 'Post/' + Endpoint, 'Exception: ' + e.message); Result := prERROR; end; end; end else begin POST_Offline(Endpoint, sJSON, response); Result := prNOInternet; end; finally ss.Free; client.Free; end; end; function TPaymo.Delete(Endpoint: string; var Response: string): TPaymoResponseStatus; var client: TFPHTTPClient; begin Result := prERROR; try client := TFPHttpClient.Create(nil); client.AddHeader('Accept', 'application/json'); client.UserName := FAPIKey; client.Password := ''; if not FOffline then begin try Response := client.Delete(APIURL + Endpoint); if (client.ResponseStatusCode >= 200) and (client.ResponseStatusCode <= 300) then Result := prOK else if (client.ResponseStatusCode = 429) then begin DebugLog('', 'Delete/' + Endpoint, 'prTRYAGAIN'); Result := prTRYAGAIN; end else begin DebugLog('', 'Delete/' + Endpoint, 'prERROR'); Result := prERROR; end; except on e: Exception do begin DebugLog('', 'Delete/' + Endpoint, 'Exception: ' + e.message); Result := prERROR; end; end; end else begin DELETE_Offline(Endpoint, response); Result := prNOInternet; end; finally client.Free; end; end; function TPaymo.CreateTask(Name, Description: string; TaskListID: integer; var task: TJSONData): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; jArr: TJSONArray; begin // logged in user jArr := TJSONArray.Create([MyData.GetPath('id').AsInteger]); jObj := TJSONObject.Create; jObj.Add('name', Name); jObj.Add('description', Description); jObj.Add('tasklist_id', TaskListID); jObj.Add('users', jArr); if FOffline then begin // values used internally, needed even if offline jObj.Add('id', DateTimeToUnix(now)); jObj.Add('complete', False); jObj.Add('seq', 0); jObj.Add('project_id', GetTaskList(TaskListID).GetPath('project_id').AsInt64); jObj.Add('entries', TJSONArray.Create); // required by task list jObj.Add('created_on', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(now))); // required by task list // detect that this is an offline created task jObj.Add('offline', True); jObj.Add('source', 'createtask'); end; sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('tasks', sJSON, response); case Result of prOK: begin task := GetJSON(response).GetPath('tasks').Items[0]; TasksArray.Add(task); end; prNOInternet: begin task := GetJSON(response); TasksArray.Add(task); SaveJSON('tasks.json', FTasks.FormatJSON()); end; end; end; function TPaymo.UpdateTaskCompletion(Complete: boolean; task: TJSONData): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; begin jObj := TJSONObject.Create; jObj.Add('complete', Complete); if FOffline then begin jObj.Add('offline', True); jObj.Add('source', 'updatetaskcompletion'); jObj.Add('task_id', task.GetPath('id').AsInt64); end; sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('tasks/' + task.GetPath('id').AsString, sJSON, response); if FOffline then SaveJSON('tasks.json', FTasks.FormatJSON()); {case Result of prOK: begin task := GetJSON(response).GetPath('tasks').Items[0]; end; end;} end; function TPaymo.StopRunningTimer(start_time, end_time: TDateTime; Description: string): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; begin // https://github.com/paymoapp/api/blob/master/sections/entries.md#stopping-a-timer // more than a minute = POST if SecondsBetween(start_time, end_time) >= 60 then begin jObj := TJSONObject.Create; jObj.Add('end_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(end_time))); jObj.Add('description', Description); if FOffline then begin jObj.Add('offline', True); jObj.Add('source', 'stoprunningtimer'); end; sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('entries/' + RunningTimerData.GetPath('id').AsString, sJSON, response); end // less than a minute = DELETE else begin Result := Delete('entries/' + RunningTimerData.GetPath('id').AsString, response); end; end; function TPaymo.StartRunningTimer(task_id: int64; start_time: TDateTime): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; begin jObj := TJSONObject.Create; jObj.Add('start_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(start_time))); jObj.Add('user_id', MyData.GetPath('id').AsInteger); jObj.Add('task_id', task_id); if FOffline then begin jObj.Add('offline', True); jObj.Add('source', 'startrunningtimer'); end; //jObj.Add('description', ''); sJSON := jObj.FormatJSON(); if (RunningTimerData = nil) and not (FOffline) then begin Result := Post('entries', sJSON, response); jObj.Free; end else begin if FAdditionalTimers.Count = ADDITIONALTIMERS then begin jObj.Free; exit(prERROR); end; jObj.Add('project_id', GetTask(task_id).GetPath('project_id').AsInt64); FAdditionalTimers.Add(jObj); SaveJSON('additionaltimers.json', FAdditionalTimers.FormatJSON()); Result := prOK; end; end; function TPaymo.DeleteTimeEntry(TimeEntryID: string): TPaymoResponseStatus; var response: string; begin Result := Delete('entries/' + TimeEntryID, response); // ToDo: delete time entry from list if FOffline then SaveJSON('tasks.json', FTasks.FormatJSON()); end; function TPaymo.UpdateTimeEntry(TimeEntryID: integer; start_time, end_time: TDateTime; project_id, task_id, tasklist_id: int64): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; r: TPaymoResponseStatus; begin jObj := TJSONObject.Create; jObj.Add('start_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(start_time))); jObj.Add('end_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(end_time))); jObj.Add('project_id', project_id); jObj.Add('task_id', task_id); if FOffline then begin jObj.Add('offline', True); jObj.Add('source', 'updatetimeentry_entry'); end; sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('entries/' + TimeEntryID.ToString, sJSON, response); jObj := TJSONObject.Create; jObj.Add('tasklist_id', tasklist_id); if FOffline then begin jObj.Add('offline', True); jObj.Add('source', 'updatetimeentry_task'); jObj.Add('task_id', task_id); end; sJSON := jObj.FormatJSON(); jObj.Free; r := Post('tasks/' + task_id.ToString, sJSON, response); if FOffline then SaveJSON('tasks.json', FTasks.FormatJSON()); end; function TPaymo.CreateTimeEntry(start_time, end_time: TDateTime; task_id: int64): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; begin // more than a minute = POST, less than a minute ignore if SecondsBetween(start_time, end_time) >= 60 then begin jObj := TJSONObject.Create; jObj.Add('start_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(start_time))); jObj.Add('end_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(end_time))); jObj.Add('task_id', task_id); if FOffline then begin jObj.Add('id', 99999999); // offline time entries are read only jObj.Add('user_id', MyData.GetPath('id').AsInteger); jObj.Add('offline', True); jObj.Add('source', 'createtimeentry'); end; sJSON := jObj.FormatJSON(); // add to list of objects if FOffline then begin TJSONArray(GetTask(task_id).GetPath('entries')).Add(jObj.Clone); end; jObj.Free; Result := Post('entries/', sJSON, response); if FOffline then SaveJSON('tasks.json', FTasks.FormatJSON()); end else Result := prOK; end; function TPaymo.StopAdditionalTimer(index: integer; end_time: TDateTime): TPaymoResponseStatus; begin Result := CreateTimeEntry(TTaskList.StringToDateTime( FAdditionalTimers[index].GetPath('start_time').AsString), end_time, FAdditionalTimers[index].GetPath('task_id').AsInt64); if (Result = prOK) or (Result = prNOInternet) then begin FAdditionalTimers.Remove(FAdditionalTimers[index]); SaveJSON('additionaltimers.json', FAdditionalTimers.FormatJSON()); end; end; function TPaymo.SaveJSON(FileName: string; sJSON: string): TPaymoResponseStatus; var s: TStringList; begin s := TStringList.Create; s.DefaultEncoding := TEncoding.UTF8; try try s.Add(sJSON); s.SaveToFile(SettingsFolder + FileName); Result := prOK; except Result := prERROR; end; finally s.Free; end; end; function TPaymo.LoadJSON(FileName: string; var response: string): TPaymoResponseStatus; var s: TStringList; begin s := TStringList.Create; s.DefaultEncoding := TEncoding.UTF8; try try s.LoadFromFile(SettingsFolder + FileName); response := s.Text; Result := prOK; except response := '[]'; Result := prERROR; end; finally s.Free; end; end; procedure TPaymo.LoadSettings; var c: TJSONConfig; response: string; begin c := TJSONConfig.Create(nil); try if ForceDirectories(SettingsFolder) then begin c.Filename := SettingsFile; APIKey := c.GetValue('apikey', ''); end; finally c.Free; end; if FileExists(SettingsFolder + 'offline.json') then begin case LoadJSON('offline.json', response) of prOK: begin if Assigned(FOfflineData) then FOfflineData.Free; FOfflineData := TJSONArray(GetJSON(response)); end; end; end; if FileExists(SettingsFolder + 'additionaltimers.json') then begin case LoadJSON('additionaltimers.json', response) of prOK: begin if Assigned(FAdditionalTimers) then FAdditionalTimers.Free; FAdditionalTimers := TJSONArray(GetJSON(response)); end; end; end; end; procedure TPaymo.SaveSettings; var c: TJSONConfig; begin c := TJSONConfig.Create(nil); try if ForceDirectories(SettingsFolder) then begin c.Filename := SettingsFile; c.SetValue('apikey', APIKey); end; finally c.Free; end; end; procedure TPaymo.POST_Offline(Endpoint: string; sJSON: TJSONStringType; var Response: string); var i: integer; obj: TJSONObject; s, t: TJSONStringType; found: boolean; begin obj := TJSONObject.Create; obj.add('Type', 'POST'); obj.add('Endpoint', Endpoint); obj.add('Data', GetJSON(sJSON)); s := obj.FormatJSON(); Response := sJSON; found := False; for i := 0 to FOfflineData.Count - 1 do begin t := FOfflineData.Items[i].FormatJSON(); if s = t then begin found := True; break; end; end; if not found then begin FOfflineData.Add(obj); SaveJSON('offline.json', FOfflineData.FormatJSON()); end; end; procedure TPaymo.DELETE_Offline(Endpoint: string; var Response: string); var i: integer; obj: TJSONObject; s, t: TJSONStringType; found: boolean; begin obj := TJSONObject.Create; obj.add('Type', 'DELETE'); obj.add('Endpoint', Endpoint); s := obj.FormatJSON(); Response := '{}'; found := False; for i := 0 to FOfflineData.Count - 1 do begin t := FOfflineData.Items[i].FormatJSON(); if s = t then begin found := True; break; end; end; if not found then begin FOfflineData.Add(obj); SaveJSON('offline.json', FOfflineData.FormatJSON()); end; end; function TPaymo.SYNC_OfflineData: integer; var i: integer; items_err: integer = 0; obj: TJSONObject; task, temp_obj: TJSONData; response, Source: string; s: TStringList; begin s := TStringList.Create; for i := 0 to FOfflineData.Count - 1 do begin obj := TJSONObject(FOfflineData.Items[i]); // POST items if obj.GetPath('Type').AsString = 'POST' then begin Source := obj.GetPath('Data').GetPath('source').AsString; // create task and get the real id if (Source = 'createtask') then begin case POST(obj.GetPath('Endpoint').AsString, obj.GetPath('Data').AsJSON, response) of prERROR, prTRYAGAIN: begin //obj.Add('SyncError', 'True'); DebugLog('Error', 'SYNC_OfflineData', obj.FormatJSON()); Inc(items_err); end; prOK: begin temp_obj := GetJSON(response).GetPath('tasks').Items[0]; // real id available now on stringlist s.AddPair(obj.GetPath('Data').GetPath('id').AsString, temp_obj.GetPath('id').AsString); temp_obj.Free; end; end; end // update task completion with the 'real_id' else if ((Source = 'updatetaskcompletion') or (Source = 'updatetimeentry_task')) then begin // get task and determine if it is an online task or an offline task // if is an online task do a normal post // if is an offline task do a post replacing the id of the task // with the real id in the stringlist task := GetTask(obj.GetPath('Data').GetPath('task_id').AsInt64); // with already online task if task <> nil then begin case POST(obj.GetPath('Endpoint').AsString, obj.GetPath('Data').AsJSON, response) of prERROR, prTRYAGAIN: begin //obj.Add('SyncError', 'True'); DebugLog('Error', 'SYNC_OfflineData', obj.FormatJSON()); Inc(items_err); end; end; end // with offline task else begin case POST('tasks/' + s.Values[obj.GetPath('Data').GetPath('task_id').AsString], obj.GetPath('Data').AsJSON, response) of prERROR, prTRYAGAIN: begin //obj.Add('SyncError', 'True'); DebugLog('Error', 'SYNC_OfflineData', obj.FormatJSON()); Inc(items_err); end; end; end; end // additional timer time entry else if (Source = 'createtimeentry') then begin task := GetTask(obj.GetPath('Data').GetPath('task_id').AsInt64); // with already online task if task <> nil then begin case POST(obj.GetPath('Endpoint').AsString, obj.GetPath('Data').AsJSON, response) of prERROR, prTRYAGAIN: begin //obj.Add('SyncError', 'True'); DebugLog('Error', 'SYNC_OfflineData', obj.FormatJSON()); Inc(items_err); end; end; end // with offline task else begin obj.GetPath('Data').GetPath('task_id').AsString := s.Values[obj.GetPath('Data').GetPath('task_id').AsString]; case POST(obj.GetPath('Endpoint').AsString, obj.GetPath('Data').AsJSON, response) of prERROR, prTRYAGAIN: begin //obj.Add('SyncError', 'True'); DebugLog('Error', 'SYNC_OfflineData', obj.FormatJSON()); Inc(items_err); end; end; end; end // change time entry data else if (Source = 'updatetimeentry_entry') then begin task := GetTask(obj.GetPath('Data').GetPath('task_id').AsInt64); // with already online task if task <> nil then begin case POST(obj.GetPath('Endpoint').AsString, obj.GetPath('Data').AsJSON, response) of prERROR, prTRYAGAIN: begin //obj.Add('SyncError', 'True'); DebugLog('Error', 'SYNC_OfflineData', obj.FormatJSON()); Inc(items_err); end; end; end // with offline task else begin case POST('entries/' + s.Values[obj.GetPath('Data').GetPath('task_id').AsString], obj.GetPath('Data').AsJSON, response) of prERROR, prTRYAGAIN: begin //obj.Add('SyncError', 'True'); DebugLog('Error', 'SYNC_OfflineData', obj.FormatJSON()); Inc(items_err); end; end; end; end; end // DELETE items else if obj.GetPath('Type').AsString = 'DELETE' then begin case Delete(obj.GetPath('Endpoint').AsString, response) of prERROR, prTRYAGAIN: begin //obj.Add('SyncError', 'True'); DebugLog('Error', 'SYNC_OfflineData', obj.FormatJSON()); Inc(items_err); end; end; end; end; s.Free; FOfflineData.Clear; SaveJSON('offline.json', FOfflineData.FormatJSON()); Result := items_err; end; end.
unit fmuDocDsEx; interface uses // VCL Classes, Controls, Grids, SysUtils, ExtCtrls, StdCtrls, // This untPages, untTypes, untDriver; type { TfmDocDsEx } TfmDocDsEx = class(TPage) Grid: TStringGrid; Label1: TLabel; Bevel1: TBevel; Label2: TLabel; procedure FormResize(Sender: TObject); private procedure Initialize; public constructor Create(AOwner: TComponent); override; procedure UpdateObject; override; function LoadDefaults: Boolean; override; procedure ExecuteCommand(var ResultCode, Count: Integer); override; end; implementation {$R *.DFM} const DiscountChargeSlipEx: array[0..11] of TIntParam = ( (Name: 'Кол-во строк в операции'; Value: 2), (Name: 'Строка текста'; Value: 0), (Name: 'Строка названия операции'; Value: 1), (Name: 'Строка суммы'; Value: 2), (Name: 'Шрифт текста'; Value: 1), (Name: 'Шрифт названия операции'; Value: 1), (Name: 'Шрифт суммы'; Value: 1), (Name: 'Кол-во символов текста'; Value: 40), (Name: 'Кол-во символов суммы'; Value: 40), (Name: 'Смещение текста'; Value: 1), (Name: 'Смещение названия суммы'; Value: 1), (Name: 'Смещение суммы'; Value: 1) ); { TfmDocDsEx } constructor TfmDocDsEx.Create(AOwner: TComponent); begin inherited Create(AOwner); Initialize; end; procedure TfmDocDsEx.Initialize; var i: Integer; begin Grid.RowCount := 12; for i := Low(DiscountChargeSlipEx) to High(DiscountChargeSlipEx) do begin Grid.Cells[0,i] := DiscountChargeSlipEx[i].Name; Grid.Cells[1,i] := IntToStr(DiscountChargeSlipEx[i].Value); end; end; procedure TfmDocDsEx.UpdateObject; function GetVal(Row: Integer): Integer; begin Result := StrToInt(Trim(Grid.Cells[1,Row])); end; begin Driver.StringQuantityinOperation := GetVal(0); Driver.TextStringNumber := GetVal(1); Driver.OperationNameStringNumber := GetVal(2); Driver.SummStringNumber := GetVal(3); Driver.TextFont := GetVal(4); Driver.OperationNameFont := GetVal(5); Driver.SummFont := GetVal(6); Driver.TextSymbolNumber := GetVal(7); Driver.SummSymbolNumber := GetVal(8); Driver.TextOffset := GetVal(9); Driver.OperationnameOffset := GetVal(10); Driver.SummOffset := GetVal(11); end; function TfmDocDsEx.LoadDefaults: Boolean; var i: Integer; begin Driver.TableNumber := 15; Result := Driver.GetTableStruct = 0; if not Result then Exit; Driver.RowNumber := 1; for i:=1 to Driver.FieldNumber do begin Driver.FieldNumber := i; Result := Driver.ReadTable = 0; if not Result then Exit; Grid.Cells[1, i-1] := IntToSTr(Driver.ValueOfFieldInteger); end; end; procedure TfmDocDsEx.ExecuteCommand(var ResultCode, Count: Integer); begin ResultCode := Driver.DiscountOnSlipDocument; if ResultCode = 0 then Count := Count + Driver.StringQuantityinOperation; end; procedure TfmDocDsEx.FormResize(Sender: TObject); begin Grid.ColWidths[0] := Round(0.75*(Grid.Width-24)); Grid.ColWidths[1] := Round(0.25*(Grid.Width-24)); end; end.
unit MainForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, SocketComp, Spin; const BlackBoxPort = 2000; type TBlackBoxForm = class(TForm) lbBoxes: TListBox; btnStart: TButton; sePort: TSpinEdit; Label1: TLabel; spMaxLogs: TSpinEdit; Label2: TLabel; procedure btnStartClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lbBoxesDblClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure spMaxLogsChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbBoxesKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private procedure OnClientConnect(Sender : TObject; Socket : TCustomWinSocket); procedure OnClientDisconnect(Sender : TObject; Socket : TCustomWinSocket); procedure OnClientRead(Sender : TObject; Socket : TCustomWinSocket); procedure RefreshBoxes; private fSocket : TServerSocket; fTmpLog : TStringList; fBoxes : TList; end; var BlackBoxForm: TBlackBoxForm; implementation uses BlackBox; {$R *.DFM} var MaxLogs : integer; type TBlackBoxStatus = (bbsReadingName, bbsLogging); TBlackBox = class public constructor Create(aName : string; MaxLogs : integer); destructor Destroy; override; private fName : string; fLogs : TStringList; fMax : integer; fAlive : boolean; fDate : string; fStatus : TBlackBoxStatus; public property Name : string read fName; property Logs : TStringList read fLogs; property Max : integer read fMax; property Alive : boolean read fAlive write fAlive; property Date : string read fDate; public procedure Log(text : TStringList); procedure LogStr(text : string); end; // TBlackBox constructor TBlackBox.Create(aName : string; MaxLogs : integer); begin inherited Create; fName := aName; fLogs := TStringList.Create; fMax := MaxLogs; fAlive := true; fDate := DateTimeToStr(Now); fStatus := bbsReadingName; end; destructor TBlackBox.Destroy; begin fLogs.Free; inherited; end; procedure TBlackBox.Log(text : TStringList); var i : integer; begin for i := 0 to pred(text.Count) do fLogs.Add(text[i]); while fLogs.Count > MaxLogs do fLogs.Delete(0); end; procedure TBlackBox.LogStr(text : string); begin fLogs.Add(text); while fLogs.Count > MaxLogs do fLogs.Delete(0); end; // TBlackBox procedure TBlackBoxForm.OnClientConnect(Sender : TObject; Socket : TCustomWinSocket); begin Socket.Data := nil; end; procedure TBlackBoxForm.OnClientDisconnect(Sender : TObject; Socket : TCustomWinSocket); begin if Socket.Data <> nil then TBlackBox(Socket.Data).Alive := false; RefreshBoxes; end; procedure TBlackBoxForm.OnClientRead(Sender : TObject; Socket : TCustomWinSocket); var BlackBox : TBlackBox; text : string; p : integer; begin text := Socket.ReceiveText; if text <> '' then begin if Socket.Data = nil then begin BlackBox := TBlackBox.Create('', 200); Socket.Data := BlackBox; fBoxes.Add(BlackBox); end else BlackBox := TBlackBox(Socket.Data); if BlackBox.fStatus = bbsReadingName then begin p := pos(^M^J, text); if p = 0 then begin BlackBox.fName := BlackBox.fName + text; text := ''; end else begin BlackBox.fName := BlackBox.fName + copy(text, 1, p - 1); text := copy(text, p + 2, length(text) - p - 1); RefreshBoxes; BlackBox.fStatus := bbsLogging; end; if text <> '' then BlackBox.LogStr(text); end else BlackBox.LogStr(text); end; end; procedure TBlackBoxForm.RefreshBoxes; var i : integer; Box : TBlackBox; begin lbBoxes.Items.BeginUpdate; fSocket.Socket.Lock; try lbBoxes.Items.Clear; for i := 0 to pred(fBoxes.Count) do begin Box := TBlackBox(fBoxes[i]); if Box.Alive then lbBoxes.Items.Add(Box.Date + ' ' + Box.Name) else lbBoxes.Items.Add(Box.Date + ' ' + Box.Name + ' (Dead)'); end; finally lbBoxes.Items.EndUpdate; fSocket.Socket.Unlock; end; end; procedure TBlackBoxForm.btnStartClick(Sender: TObject); begin if fSocket <> nil then fSocket.Free; fSocket := TServerSocket.Create(self); fSocket.Port := sePort.Value; fSocket.OnClientConnect := OnClientConnect; fSocket.OnClientDisconnect := OnClientDisconnect; fSocket.OnClientRead := OnClientRead; fSocket.Active := true; end; procedure TBlackBoxForm.FormCreate(Sender: TObject); begin fTmpLog := TStringList.Create; fBoxes := TList.Create; end; procedure TBlackBoxForm.lbBoxesDblClick(Sender: TObject); var index : integer; Box : TBlackBox; begin index := lbBoxes.ItemIndex; if index <> -1 then begin Box := TBlackBox(fBoxes[index]); LogForm.mLogs.Lines.BeginUpdate; try LogForm.mLogs.Lines.Clear; LogForm.mLogs.Lines := Box.Logs; finally LogForm.mLogs.Lines.EndUpdate; end; LogForm.Show; end else Beep; end; procedure TBlackBoxForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if fSocket <> nil then begin fSocket.OnClientConnect := nil; fSocket.OnClientDisconnect := nil; fSocket.OnClientRead := nil; end; end; procedure TBlackBoxForm.spMaxLogsChange(Sender: TObject); begin MaxLogs := spMaxLogs.Value; end; procedure TBlackBoxForm.FormShow(Sender: TObject); begin MaxLogs := spMaxLogs.Value; end; procedure TBlackBoxForm.lbBoxesKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var BlackBox : TBlackBox; index : integer; begin index := lbBoxes.ItemIndex; if (Key = VK_DELETE) and (index <> -1) then begin BlackBox := TBlackBox(fBoxes[index]); if not BlackBox.fAlive then begin fBoxes.Delete(index); BlackBox.Free; RefreshBoxes; end; end; end; end.
unit QRWebColorProperty; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, DesignEditors, DesignIntf, Vcl.ExtCtrls, QRColorBox; type TQRWebColorEditor = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: String; override; procedure SetValue(const Value: String); override; end; TQRWebColorDialog = class(TForm) SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; QRColorBox1: TQRColorBox; procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); protected FQRWebColor : string; private function GetQRWebColor: string; procedure setQRWebColor(const Value: string); public property QRWebColor: string read GetQRWebColor write setQRWebColor; end; var QRWebColorDialog: TQRWebColorDialog; trace : TStringlist; implementation {$R *.dfm} function WebColorToVCLColor( wc : string ) : integer; var lwc : string; tmpc : integer; r,g,b : byte; begin lwc := '$' + copy(wc,2,6); tmpc := strtoint(lwc); b := ($000000FF and tmpc); G := ($0000FF00 and tmpc) Shr 8; r := ($00FF0000 and tmpc) Shr 16; result := rgb(r,g,b); end; function WebColorToColor( wc : string ) : integer; var lwc : string; begin lwc := '$' + copy(wc,2,6); result := strtoint(lwc); end; function ColTrans( ct : TColor ) : string; var RGBColour: longint; begin RGBColour := ColorToRGB(ct); result := Format('#%2.2x%2.2x%2.2x',[GetRValue(RGBColour),GetGValue(RGBColour),GetBValue(RGBColour)]); end; // property editor procedure TQRWebColorEditor.Edit; var F: TQRWebColorDialog; cstr : string; begin //Initialize the property editor window F:= TQRWebColorDialog.Create(Application); try F.QRWebColor := GetValue; // F.Panel1.Color := WebColorToVCLColor(F.QRWebColor); if F.ShowModal = mrOK then begin cstr := F.QRWebColor; SetValue(cstr); end; finally F.Free; end; end; function TQRWebColorEditor.GetAttributes: TPropertyAttributes; begin //Makes the small button show to the right of the property Result := inherited GetAttributes + [paDialog]; end; function TQRWebColorEditor.GetValue: String; begin Result:= GetStrValue; end; procedure TQRWebColorEditor.SetValue(const Value: String); begin SetStrValue(value); end; {TQRWebColorDialog} function TQRWebColorDialog.GetQRWebColor: string; begin result := coltrans(QRColorBox1.Color); end; procedure TQRWebColorDialog.setQRWebColor(const Value: string); begin QRColorBox1.Color := WebColorToVCLColor( value); end; procedure TQRWebColorDialog.SpeedButton1Click(Sender: TObject); begin self.ModalResult := mrOK; end; procedure TQRWebColorDialog.SpeedButton2Click(Sender: TObject); begin self.ModalResult := mrCancel; end; procedure TQRWebColorDialog.SpeedButton3Click(Sender: TObject); begin end; { in qreport.pas procedure Register; begin RegisterPropertyEditor(TypeInfo(string), nil, 'QRWebColor', TQRWebColorEditor); end; } end.
{ Subroutine SST_W_C_SYMBOLS (GLOBAL_ONLY) * * Write the declaration for all symbols that need it in the current scope. * * As much as possible, the symbols will be written in the order of * constants, data types, common blocks, procedures, and variables. * * Only global symbols that are actually defined here (and any dependencies) * will be written when GLOBAL_ONLY is TRUE. } module sst_w_c_SYMBOLS; define sst_w_c_symbols; %include 'sst_w_c.ins.pas'; const n_symtypes = 8; {number of entries in SYMTYPE array} var symtype: {the symbol types to declare, in order} array[1..n_symtypes] of sst_symtype_k_t := [ sst_symtype_const_k, sst_symtype_dtype_k, sst_symtype_dtype_k, sst_symtype_com_k, sst_symtype_proc_k, sst_symtype_var_k, sst_symtype_abbrev_k, sst_symtype_label_k {not declared, but need to be named} ] ; procedure sst_w_c_symbols ( {declare all used symbols not decl before} in global_only: boolean); {declare only global symbols def here if TRUE} var pos: string_hash_pos_t; {position handle into hash table} name_p: univ_ptr; {unused subroutine argument} sym_p: sst_symbol_p_t; {pointer to to current symbol to write out} sym_pp: sst_symbol_pp_t; {pointer to hash table user data area} dt_p: sst_dtype_p_t; {pointer to base data type if sym is dtype} i: sys_int_machine_t; {loop counter} found: boolean; {TRUE if hash table entry was found} pop: boolean; {TRUE if need to pop writing position} pnt_ok: boolean; {TRUE if OK to request pointer data types} begin if not global_only then begin {declaring all symbols in this scope ?} sst_scope_unused_show (sst_scope_p^); {complain about unused symbols} end; pop := false; {init to no position pop needed at end} if global_only then begin {declare only global symbols defined here ?} sst_w_c_header_decl (sment_type_declg_k, pop); end; pnt_ok := false; {init to not do pointer data types yet} { * Actually declare the used symbols at this level for real. As much as * possible, the symbols will be declared in the order given in the * SYMTYPE array, above. } for i := 1 to n_symtypes do begin {once for each type of symbol to look for} sst_w.blank_line^; string_hash_pos_first (sst_scope_p^.hash_h, pos, found); {get pos for first sym} while found do begin {once for each hash table entry} string_hash_ent_atpos (pos, name_p, sym_pp); {get pointer to user data area} sym_p := sym_pp^; {get pointer to symbol descriptor} dt_p := nil; {init to symbol is not a data type} if sym_p^.symtype = sst_symtype_dtype_k then begin {symbol is a data type ?} dt_p := sym_p^.dtype_dtype_p; while ((dt_p <> nil) and then (dt_p^.dtype = sst_dtype_copy_k)) do dt_p := dt_p^.copy_dtype_p; end; {done handling symbol is a data type} if {declare this symbol now ?} (sym_p^.symtype = symtype[i]) and {the kind of symbol we are looking for ?} (not (sst_symflag_written_k in sym_p^.flags)) and {not already written ?} ( (sst_symflag_used_k in sym_p^.flags) or {symbol is used ?} sst_writeall or {supposed to write all symbols ?} sst_char_from_ins(sym_p^.char_h) or {from the special include file ?} ( {global symbol defined here ?} (sst_symflag_global_k in sym_p^.flags) and (not (sst_symflag_extern_k in sym_p^.flags)) ) ) and ( (not global_only) or (sst_symflag_global_k in sym_p^.flags) {symbol globally known ?} ) and ( (sym_p^.symtype <> sst_symtype_dtype_k) or {suppressed pointer dtype ?} (dt_p = nil) or pnt_ok or else (dt_p^.dtype <> sst_dtype_pnt_k) ) then begin sst_w_c_symbol (sym_p^); {declare symbol} end; string_hash_pos_next (pos, found); {advance to next hash table entry} end; {back and do this new hash table entry} pnt_ok := pnt_ok or (symtype[i] = sst_symtype_dtype_k); {pointers OK next time ?} end; {back to look for next symbol type} if pop then begin {need to pop writing position ?} sst_w_c_pos_pop; end; end;
unit define_stock_quotes; interface uses Define_Price, define_datetime; type { 日线数据 } PRT_Quote_Day = ^TRT_Quote_Day; TRT_Quote_Day = packed record // 56 DealDate : TDateStock; // 4 PriceRange : TRT_PricePack_Range; // 16 - 20 DealVolume : Int64; // 8 - 28 成交量 DealAmount : Int64; // 8 - 36 成交金额 Weight : TRT_WeightPackValue; // 4 - 40 复权权重 * 100 TotalValue : Int64; // 8 - 48 总市值 DealValue : Int64; // 8 - 56 流通市值 end; { 及时行情数据 1 分钟 -- 60 分钟 < 日线 } PRT_Quote_Minute = ^TRT_Quote_Minute; TRT_Quote_Minute = packed record DealDateTime : TDateTimeStock; // 8 PriceRange : TRT_PricePack_Range; // 16 - 24 DealVolume : Integer; // 4 - 28 成交量 DealAmount : Integer; // 4 - 32 成交金额 end; { 交易明细 } PRT_Quote_Detail = ^TRT_Quote_Detail; TRT_Quote_Detail = packed record DealDateTime : TDateTimeStock; // 4 - 4 Price : TRT_PricePack; // 4 - 8 DealVolume : Integer; // 4 - 12 成交量 DealAmount : Integer; // 4 - 16 DealType : Integer; // Buyer: Integer; // Saler: Integer; end; { M1 区间数据 1 分钟 5 分钟 --- 日线 周线 月线 都是 区间数据 Open High Low Close M2 明细数据 Price Time Volume Acount } PStore32 = ^TStore32; TStore32 = packed record Data : array[0..32 - 1] of Byte; end; PStore64 = ^TStore64; TStore64 = packed record Data : array[0..64 - 1] of Byte; end; { 日线数据 } PStore_Quote64_Day = ^TStore_Quote64_Day; TStore_Quote64_Day = packed record // 56 PriceRange : TStore_PriceRange; // 16 DealVolume : Int64; // 8 - 24 成交量 DealAmount : Int64; // 8 - 32 成交金额 DealDate : Integer; // 4 - 36 交易日期 Weight : TStore_Weight; // 4 - 40 复权权重 * 100 TotalValue : Int64; // 8 - 48 总市值 DealValue : Int64; // 8 - 56 流通市值 end; { 分时数据 detail } PStore_Quote32_Minute = ^TStore_Quote32_Minute; // TStore_Quote32_Minute = packed record // 28 PriceRange : TStore_PriceRange; // 16 DealVolume : Integer; // 4 - 20 成交量 DealAmount : Integer; // 4 - 24 成交金额 StockDateTime : TDateTimeStock; // 4 - 28 交易日期 end; // 只有一个价格 必然是 及时报价数据 PStore_Quote_Detail32 = ^TStore_Quote_Detail32; TStore_Quote_Detail32 = packed record // 8 QuoteDealTime : Word; // 2 - 1 小时 3600 秒 9 -- 15 QuoteDealDate : Word; // 2 - 4 Price : TStore_Price; // 4 - 8 DealVolume : Integer; // 4 - 12 成交量 DealAmount : Integer; // 4 - 16 成交金额 DealType : Byte; // 1 - 17 买盘卖盘中性盘 end; PStore_Quote32_Detail = ^TStore_Quote32_Detail; TStore_Quote32_Detail = packed record Quote : TStore_Quote_Detail32; Reserve : array [0..32 - SizeOf(TStore_Quote_Detail32) - 1] of Byte; end; implementation uses Sysutils; end.
unit UPascalCoinProtocol; interface uses URawBytes, UOperationBlock; type { TPascalCoinProtocol } TPascalCoinProtocol = Class public Class Function GetRewardForNewLine(line_index: Cardinal): UInt64; Class Function TargetToCompact(target: TRawBytes): Cardinal; Class Function TargetFromCompact(encoded: Cardinal): TRawBytes; Class Function GetNewTarget(vteorical, vreal: Cardinal; protocol_version : Integer; isSlowMovement : Boolean; Const actualTarget: TRawBytes): TRawBytes; Class Procedure CalcProofOfWork_Part1(const operationBlock : TOperationBlock; out Part1 : TRawBytes); Class Procedure CalcProofOfWork_Part3(const operationBlock : TOperationBlock; out Part3 : TRawBytes); Class Procedure CalcProofOfWork(const operationBlock : TOperationBlock; out PoW : TRawBytes); Class Function IsValidMinerBlockPayload(const newBlockPayload : TRawBytes) : Boolean; class procedure GetRewardDistributionForNewBlock(const OperationBlock : TOperationBlock; out acc_0_miner_reward, acc_4_dev_reward : Int64; out acc_4_for_dev : Boolean); end; implementation uses UBigNum, UConst, Classes, UAccountComp, UCrypto, SysUtils; { TPascalCoinProtocol } class function TPascalCoinProtocol.GetNewTarget(vteorical, vreal: Cardinal; protocol_version : Integer; isSlowMovement : Boolean; const actualTarget: TRawBytes): TRawBytes; Var bnact, bnaux: TBigNum; tsTeorical, tsReal, factor, factorMin, factorMax, factorDivider: Int64; begin { Given a teorical time in seconds (vteorical>0) and a real time in seconds (vreal>0) and an actual target, calculates a new target by % of difference of teorical vs real. Increment/decrement is adjusted to +-200% in a full CT_CalcNewTargetBlocksAverage round ...so each new target is a maximum +-(100% DIV (CT_CalcNewTargetBlocksAverage DIV 2)) of previous target. This makes target more stable. } tsTeorical := vteorical; tsReal := vreal; { On protocol 1,2 the increment was limited in a integer value between -10..20 On protocol 3 we increase decimals, so increment could be a integer between -1000..2000, using 2 more decimals for percent. Also will introduce a "isSlowMovement" variable that will limit to a maximum +-0.5% increment} if (protocol_version<CT_PROTOCOL_3) then begin factorDivider := 1000; factor := (((tsTeorical - tsReal) * 1000) DIV (tsTeorical)) * (-1); { Important: Note that a -500 is the same that divide by 2 (-100%), and 1000 is the same that multiply by 2 (+100%), so we limit increase in a limit [-500..+1000] for a complete (CT_CalcNewTargetBlocksAverage DIV 2) round } if CT_CalcNewTargetBlocksAverage>1 then begin factorMin := (-500) DIV (CT_CalcNewTargetBlocksAverage DIV 2); factorMax := (1000) DIV (CT_CalcNewTargetBlocksAverage DIV 2); end else begin factorMin := (-500); factorMax := (1000); end; end else begin // Protocol 3: factorDivider := 100000; If (isSlowMovement) then begin // Limit to 0.5% instead of 2% (When CT_CalcNewTargetBlocksAverage = 100) factorMin := (-50000) DIV (CT_CalcNewTargetBlocksAverage * 2); factorMax := (100000) DIV (CT_CalcNewTargetBlocksAverage * 2); end else begin if CT_CalcNewTargetBlocksAverage>1 then begin factorMin := (-50000) DIV (CT_CalcNewTargetBlocksAverage DIV 2); factorMax := (100000) DIV (CT_CalcNewTargetBlocksAverage DIV 2); end else begin factorMin := (-50000); factorMax := (100000); end; end; end; factor := (((tsTeorical - tsReal) * factorDivider) DIV (tsTeorical)) * (-1); if factor < factorMin then factor := factorMin else if factor > factorMax then factor := factorMax else if factor=0 then begin Result := actualTarget; exit; end; // Calc new target by increasing factor (-500 <= x <= 1000) bnact := TBigNum.Create(0); try bnact.RawValue := actualTarget; bnaux := bnact.Copy; try bnact.Multiply(factor).Divide(factorDivider).Add(bnaux); finally bnaux.Free; end; // Adjust to TargetCompact limitations: Result := TargetFromCompact(TargetToCompact(bnact.RawValue)); finally bnact.Free; end; end; class procedure TPascalCoinProtocol.CalcProofOfWork_Part1(const operationBlock: TOperationBlock; out Part1: TRawBytes); var ms : TMemoryStream; s : AnsiString; begin ms := TMemoryStream.Create; try // Part 1 ms.Write(operationBlock.block,Sizeof(operationBlock.block)); // Little endian s := TAccountComp.AccountKey2RawString(operationBlock.account_key); ms.WriteBuffer(s[1],length(s)); ms.Write(operationBlock.reward,Sizeof(operationBlock.reward)); // Little endian ms.Write(operationBlock.protocol_version,Sizeof(operationBlock.protocol_version)); // Little endian ms.Write(operationBlock.protocol_available,Sizeof(operationBlock.protocol_available)); // Little endian ms.Write(operationBlock.compact_target,Sizeof(operationBlock.compact_target)); // Little endian SetLength(Part1,ms.Size); ms.Position:=0; ms.Read(Part1[1],ms.Size); finally ms.Free; end; end; class procedure TPascalCoinProtocol.CalcProofOfWork_Part3(const operationBlock: TOperationBlock; out Part3: TRawBytes); var ms : TMemoryStream; begin ms := TMemoryStream.Create; try ms.WriteBuffer(operationBlock.initial_safe_box_hash[1],length(operationBlock.initial_safe_box_hash)); ms.WriteBuffer(operationBlock.operations_hash[1],length(operationBlock.operations_hash)); // Note about fee: Fee is stored in 8 bytes, but only digest first 4 low bytes ms.Write(operationBlock.fee,4); SetLength(Part3,ms.Size); ms.Position := 0; ms.ReadBuffer(Part3[1],ms.Size); finally ms.Free; end; end; class procedure TPascalCoinProtocol.CalcProofOfWork(const operationBlock: TOperationBlock; out PoW: TRawBytes); var ms : TMemoryStream; s : AnsiString; begin ms := TMemoryStream.Create; try // Part 1 ms.Write(operationBlock.block,Sizeof(operationBlock.block)); // Little endian s := TAccountComp.AccountKey2RawString(operationBlock.account_key); ms.WriteBuffer(s[1],length(s)); ms.Write(operationBlock.reward,Sizeof(operationBlock.reward)); // Little endian ms.Write(operationBlock.protocol_version,Sizeof(operationBlock.protocol_version)); // Little endian ms.Write(operationBlock.protocol_available,Sizeof(operationBlock.protocol_available)); // Little endian ms.Write(operationBlock.compact_target,Sizeof(operationBlock.compact_target)); // Little endian // Part 2 ms.WriteBuffer(operationBlock.block_payload[1],length(operationBlock.block_payload)); // Part 3 ms.WriteBuffer(operationBlock.initial_safe_box_hash[1],length(operationBlock.initial_safe_box_hash)); ms.WriteBuffer(operationBlock.operations_hash[1],length(operationBlock.operations_hash)); // Note about fee: Fee is stored in 8 bytes (Int64), but only digest first 4 low bytes ms.Write(operationBlock.fee,4); ms.Write(operationBlock.timestamp,4); ms.Write(operationBlock.nonce,4); TCrypto.DoDoubleSha256(ms.Memory,ms.Size,PoW); finally ms.Free; end; end; class function TPascalCoinProtocol.IsValidMinerBlockPayload(const newBlockPayload: TRawBytes): Boolean; var i : Integer; begin Result := False; if Length(newBlockPayload)>CT_MaxPayloadSize then Exit; // Checking Miner Payload valid chars for i := 1 to length(newBlockPayload) do begin if Not (newBlockPayload[i] in [#32..#254]) then begin exit; end; end; Result := True; end; class procedure TPascalCoinProtocol.GetRewardDistributionForNewBlock(const OperationBlock : TOperationBlock; out acc_0_miner_reward, acc_4_dev_reward : Int64; out acc_4_for_dev : Boolean); begin if OperationBlock.protocol_version<CT_PROTOCOL_3 then begin acc_0_miner_reward := OperationBlock.reward + OperationBlock.fee; acc_4_dev_reward := 0; acc_4_for_dev := False; end else begin acc_4_dev_reward := (OperationBlock.reward * CT_Protocol_v3_PIP11_Percent) DIV 100; acc_0_miner_reward := OperationBlock.reward + OperationBlock.fee - acc_4_dev_reward; acc_4_for_dev := True; end; end; class function TPascalCoinProtocol.GetRewardForNewLine(line_index: Cardinal): UInt64; Var n, i : Cardinal; begin {$IFDEF TESTNET} // TESTNET used (line_index +1), but PRODUCTION must use (line_index) n := (line_index + 1) DIV CT_NewLineRewardDecrease; // TESTNET BAD USE (line_index + 1) {$ELSE} n := line_index DIV CT_NewLineRewardDecrease; // FOR PRODUCTION {$ENDIF} Result := CT_FirstReward; for i := 1 to n do begin Result := Result DIV 2; end; if (Result < CT_MinReward) then Result := CT_MinReward; end; class function TPascalCoinProtocol.TargetFromCompact(encoded: Cardinal): TRawBytes; Var nbits, high, offset, i: Cardinal; bn: TBigNum; raw : TRawBytes; begin { Compact Target is a 4 byte value that tells how many "0" must have the hash at left if presented in binay format. First byte indicates haw many "0 bits" are on left, so can be from 0x00 to 0xE7 (Because 24 bits are reserved for 3 bytes, and 1 bit is implicit, max: 256-24-1=231=0xE7) Next 3 bytes indicates next value in XOR, stored in RAW format Example: If we want a hash lower than 0x0000 0000 0000 65A0 A2F4 +29 bytes Binary "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 0101 1010 0000 1010 0010 1111 0100" That is 49 zeros on left before first 1. So first byte is 49 decimal = 0x31 After we have "110 0101 1010 0000 1010 0010 1111 0100 1111 0100" but we only can accept first 3 bytes, also note that first "1" is implicit, so value is transformed in binary as "10 0101 1010 0000 1010 0010 11" that is 0x96828B But note that we must XOR this value, so result offset is: 0x697D74 Compacted value is: 0x31697D74 When translate compact target back to target: ( 0x31697D74 ) 0x31 = 49 bits at "0", then 1 bit at "1" followed by XOR 0x697D74 = 0x96828B 49 "0" bits "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0" 0x96828B "1001 0110 1000 0010 1000 1011" Hash target = "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 0101 1010 0000 1010 0010 11.. ...." Fill last "." with "1" Hash target = "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 0101 1010 0000 1010 0010 1111 1111" Hash target = 0x00 00 00 00 00 00 65 A0 A2 FF + 29 bytes Note that is not exactly the same than expected due to compacted format } nbits := encoded shr 24; i := CT_MinCompactTarget shr 24; if nbits < i then nbits := i; // min nbits if nbits > 231 then nbits := 231; // max nbits offset := (encoded shl 8) shr 8; // Make a XOR at offset and put a "1" on the left offset := ((offset XOR $00FFFFFF) OR ($01000000)); bn := TBigNum.Create(offset); Try bn.LShift(256 - nbits - 25); raw := bn.RawValue; SetLength(Result,32); FillChar(Result[1],32,0); for i:=1 to Length(raw) do begin result[i+32-length(raw)] := raw[i]; end; Finally bn.Free; End; end; class function TPascalCoinProtocol.TargetToCompact(target: TRawBytes): Cardinal; Var bn, bn2: TBigNum; i: Int64; nbits: Cardinal; c: AnsiChar; raw : TRawBytes; j : Integer; begin { See instructions in explanation of TargetFromCompact } Result := 0; if length(target)>32 then begin raise Exception.Create('Invalid target to compact: '+TCrypto.ToHexaString(target)+' ('+inttostr(length(target))+')'); end; SetLength(raw,32); FillChar(raw[1],32,0); for j:=1 to length(target) do begin raw[j+32-length(target)] := target[j]; end; target := raw; bn := TBigNum.Create(0); bn2 := TBigNum.Create('8000000000000000000000000000000000000000000000000000000000000000'); // First bit 1 followed by 0 try bn.RawValue := target; nbits := 0; while (bn.CompareTo(bn2) < 0) And (nbits < 231) do begin bn2.RShift(1); inc(nbits); end; i := CT_MinCompactTarget shr 24; if (nbits < i) then begin Result := CT_MinCompactTarget; exit; end; bn.RShift((256 - 25) - nbits); Result := (nbits shl 24) + ((bn.value AND $00FFFFFF) XOR $00FFFFFF); finally bn.Free; bn2.Free; end; end; end.
unit alcuService; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs, alcuAutoPipeServer; type TaluService = class(TService) procedure ServiceAfterInstall(Sender: TService); procedure ServiceAfterUninstall(Sender: TService); procedure ServiceContinue(Sender: TService; var Continued: Boolean); procedure ServiceCreate(Sender: TObject); procedure ServiceDestroy(Sender: TObject); procedure ServiceExecute(Sender: TService); procedure ServicePause(Sender: TService; var Paused: Boolean); procedure ServiceShutdown(Sender: TService); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); private f_Server: TalcuServerPrim; procedure CreateServer; procedure DestroyServer; public function GetServiceController: TServiceController; override; end; var aluService: TaluService; implementation {$R *.DFM} Uses l3Base; procedure ServiceController(CtrlCode: DWord); stdcall; begin aluService.Controller(CtrlCode); end; procedure TaluService.CreateServer; begin l3System.Msg2Log('TalcuServerPrim.Create(nil)'); f_Server:= TalcuServerPrim.Create(nil); l3System.Msg2Log('f_Server.Service:= Self;'); f_Server.Service:= Self; l3System.Msg2Log('f_Server.Initialize'); f_Server.Initialize; l3System.Msg2Log('Created'); end; procedure TaluService.DestroyServer; begin l3Free(f_Server); end; function TaluService.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TaluService.ServiceAfterInstall(Sender: TService); begin l3System.Msg2Log('Служба установлена'); end; procedure TaluService.ServiceAfterUninstall(Sender: TService); begin l3System.Msg2Log('Служба снята'); end; procedure TaluService.ServiceContinue(Sender: TService; var Continued: Boolean); begin // Продолжение работы l3System.Msg2Log('Перезапуск службы (%d)', [GetCurrentThreadId]); // Продолжение работы Continued:= f_Server.Continue; end; procedure TaluService.ServiceCreate(Sender: TObject); begin // Создание сервиса l3System.Msg2Log('-= Создание службы =-(%d)', [GetCurrentThreadId]); // тут можно создавать необходимые объекты // Вызывается из другой нити, TyTech не работает end; procedure TaluService.ServiceDestroy(Sender: TObject); begin // Уничтожение сервиса l3System.Msg2Log('-= Уничтожение службы =-(%d)', [GetCurrentThreadId]); // тут уничтожаются все объекты // Вызывается из другой нити, TyTech не работает end; procedure TaluService.ServiceExecute(Sender: TService); begin l3System.Msg2Log('Выполнение службы(%d)', [GetCurrentThreadId]); while not Terminated do begin f_Server.Execute; ServiceThread.ProcessRequests(True); end; end; procedure TaluService.ServicePause(Sender: TService; var Paused: Boolean); begin l3System.Msg2Log('Приостановка службы(%d)', [GetCurrentThreadId]); // Приостановить выполнение процессов Paused:= f_server.Pause; end; procedure TaluService.ServiceShutdown(Sender: TService); begin // Выключение сервиса l3System.Msg2Log('Выключение службы(%d)', [GetCurrentThreadId]); // Тут останавливаются все процессы end; procedure TaluService.ServiceStart(Sender: TService; var Started: Boolean); begin l3System.Msg2Log('Запуск службы(%d)', [GetCurrentThreadId]); // Тут нужно запустить все необходимые процессы CreateServer; Started:= f_Server.Start; f_Server.ChecksSetup; end; procedure TaluService.ServiceStop(Sender: TService; var Stopped: Boolean); begin l3System.Msg2Log('Остановка службы(%d)', [GetCurrentThreadId]); // Тут нужно остановить все процессы Stopped := f_Server.Stop; DestroyServer; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.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. * ********************************************************************************************************************** * TERRA_UIMenu * Implements a menu widget *********************************************************************************************************************** } Unit TERRA_UIMenu; Interface Uses TERRA_Utils, TERRA_UI, TERRA_Widgets, TERRA_Classes, TERRA_Vector2D, TERRA_Vector3D, TERRA_Color; Const MenuAnimationDuration = 250; Type UIMenuItem = Class(Widget) Protected _Open:Boolean; _Caption:TERRAString; _Entries:Array Of UIMenuItem; _EntryCount:Integer; _Width:Single; _Height:Single; _OpenWidth:Single; _OpenHeight:Single; _OpenMenu:UIMenuItem; _Animated:Boolean; _AnimationTime:Cardinal; Public OnMouseClick:WidgetEventHandler; Constructor Create(Caption:TERRAString; Z:Single = 0.3); Procedure Release; Procedure Render; Override; Procedure UpdateRects; Override; Procedure AddItem(Item:UIMenuItem); Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Property Caption:TERRAString Read _Caption Write _Caption; End; Implementation Uses TERRA_OS, TERRA_Math; { UIMenuItem } Function UIMenuItem.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Var I:Integer; Pos:Vector2D; Begin Result := False; If (_Parent = Nil) Then Begin For I:=0 To Pred(_EntryCount) Do If _Entries[I].Visible Then Begin Result := _Entries[I].OnMouseDown(X, Y, Button); If Result Then Exit; End; Exit; End; Pos := Self.Position; If (X>=Pos.X) And (X<=Pos.X + _Width) And (Y>=Pos.Y) And (Y<=Pos.Y+_Height) Then Begin Result := True; _Open := True; If (_Open) And (Assigned(_Parent)) And (_Parent Is UIMenuItem) Then Begin If Assigned(UIMenuItem(_Parent)._OpenMenu) Then UIMenuItem(_Parent)._OpenMenu._Open := False; UIMenuItem(_Parent)._OpenMenu := Self; Self._Animated := True; Self._AnimationTime := GetTime(); End; End; End; Procedure UIMenuItem.AddItem(Item: UIMenuItem); Begin If Not Assigned(Item) Then Exit; Item.Parent := Self; Inc(_EntryCount); SetLength(_Entries, _EntryCount); _Entries[Pred(_EntryCount)] := Item; Self.UpdateRects(); End; Constructor UIMenuItem.Create(Caption:TERRAString; Z:Single); Begin Self._Visible := True; Self._Name := Name; Self._Layer := Z; Self._Parent := Nil; Self.SetPosition(VectorCreate2D(0,0)); UI.Instance.AddWidget(Self); Self.LoadComponent('ui_menu_item'); Self.LoadComponent('ui_menu_list'); _Open := False; _Caption := Caption; _EntryCount := 0; If _ComponentCount>=1 Then Begin _Width := _ComponentList[0].Buffer.Width; _Height := _ComponentList[0].Buffer.Height; End; If _ComponentCount>=2 Then Begin _OpenWidth := _ComponentList[1].Buffer.Width; _OpenHeight := _ComponentList[1].Buffer.Height; End; End; Procedure UIMenuItem.Release; Begin _EntryCount := 0; Inherited; End; Procedure UIMenuItem.UpdateRects; Begin _Size.X := _Width; _Size.Y := _Height; End; Procedure UIMenuItem.Render; Var TextRect:Vector2D; OfsX, OfsY, TX, Delta:Single; I:Integer; Begin Self.UpdateRects(); Self.UpdateTransform(); Self.UpdateHighlight(); If (_Parent = Nil) Then Begin _Width := 0; _Height := 0; For I:=0 To Pred(_EntryCount) Do If _Entries[I].Visible Then Begin _Entries[I].SetPosition(VectorCreate2D(_Width, 0)); _Entries[I].Render(); _Width := _Width + _Entries[I].Size.X; _Height := FloatMax(_Height, _Entries[I].Size.Y); End; End Else Begin TextRect := Self.Font.GetTextRect(_Caption); OfsX := (_Width - TextRect.X) * 0.5; OfsY := (_Height - TextRect.Y) * 0.5; DrawComponent(0, VectorCreate(0.0, 0.0, 0.0), 0.0, 0.0, 1.0, 1.0, ColorWhite); DrawText(_Caption, VectorCreate(OfsX, OfsY, 0.5), ColorWhite, 1.0); If (_Open) Then Begin If _Animated Then Begin Delta := GetTime() - _AnimationTime; Delta := Delta / MenuAnimationDuration; _Animated := Delta<1.0; End Else Delta := 1.0; For I:=0 To Pred(_EntryCount) Do Begin TextRect := Self.Font.GetTextRect(_Entries[I]._Caption); OfsX := (_OpenWidth - TextRect.X) * 0.5; OfsY := (_OpenHeight - TextRect.Y) * 0.5; DrawComponent(1, VectorCreate(0.0, _Height + _OpenHeight*I*Delta, 0.0), 0.0, 0.0, 1.0, 1.0, ColorWhite); DrawText(_Entries[I].Caption, VectorCreate(OfsX, OfsY + _Height + _OpenHeight*I*Delta, 1.2), ColorWhite, 1.0); End; End; End; Inherited; End; End.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.MemoryCache.Compressor.GZip Description : Compress Cache data Author : Kike Pérez Version : 1.0 Created : 14/07/2019 Modified : 15/09/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.MemoryCache.Compressor.GZip; {$i QuickLib.inc} interface uses Quick.Compression, Quick.MemoryCache.Types; type TCacheCompressorGZip = class(TInterfacedObject,ICacheCompressor) public function Compress(const aValue : string) : string; function Decompress(const aValue : string) : string; end; implementation { TCacheCompresorGZip } function TCacheCompressorGZip.Compress(const aValue: string): string; begin Result := CompressGZipString(aValue,TCompressionLevel.zcFastest); end; function TCacheCompressorGZip.Decompress(const aValue: string): string; begin Result := DeCompressGZipString(aValue); end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clUdpClient; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, WinSock,{$IFDEF DEMO} Forms, Windows,{$ENDIF} {$ELSE} System.Classes, System.SysUtils, Winapi.WinSock,{$IFDEF DEMO} Vcl.Forms, Winapi.Windows,{$ENDIF} {$ENDIF} clSocket; type TclUdpPacketEvent = procedure (Sender: TObject; AData: TStream) of object; TclUdpClient = class(TComponent) private FServer: string; FPort: Integer; FConnection: TclUdpClientConnection; FOnChanged: TNotifyEvent; FOnSendPacket: TclUdpPacketEvent; FOnReceivePacket: TclUdpPacketEvent; FCharSet: string; procedure SetServer(const Value: string); procedure SetPort_(const Value: Integer); procedure SetDatagramSize(const Value: Integer); procedure SetTimeOut(const Value: Integer); procedure SetBitsPerSec(const Value: Integer); function GetDatagramSize: Integer; function GetBitsPerSec: Integer; function GetTimeOut: Integer; function GetLocalBinding: string; procedure SetLocalBinding(const Value: string); procedure SetCharSet(const Value: string); protected procedure OpenConnection(const AServer: string; APort: Integer); virtual; procedure DoDestroy; virtual; procedure Changed; dynamic; procedure DoReceivePacket(AData: TStream); dynamic; procedure DoSendPacket(AData: TStream); dynamic; function GetDefaultPort: Integer; virtual; abstract; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Open; procedure Close; procedure SendPacket(AData: TStream); overload; procedure ReceivePacket(AData: TStream); overload; procedure SendPacket(const AData: string); overload; function ReceivePacket: string; overload; property Connection: TclUdpClientConnection read FConnection; published property Server: string read FServer write SetServer; property Port: Integer read FPort write SetPort_; property DatagramSize: Integer read GetDatagramSize write SetDatagramSize default 8192; property TimeOut: Integer read GetTimeOut write SetTimeOut default 5000; property BitsPerSec: Integer read GetBitsPerSec write SetBitsPerSec default 0; property LocalBinding: string read GetLocalBinding write SetLocalBinding; property CharSet: string read FCharSet write SetCharSet; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; property OnReceivePacket: TclUdpPacketEvent read FOnReceivePacket write FOnReceivePacket; property OnSendPacket: TclUdpPacketEvent read FOnSendPacket write FOnSendPacket; end; implementation uses clTranslator, clUtils{$IFDEF LOGGER}, clLogger{$ENDIF}; { TclUdpClient } procedure TclUdpClient.Changed; begin if Assigned(FOnChanged) then begin FOnChanged(Self); end; end; constructor TclUdpClient.Create(AOwner: TComponent); begin inherited Create(AOwner); StartupSocket(); FConnection := TclUdpClientConnection.Create(); FConnection.NetworkStream := TclNetworkStream.Create(); DatagramSize := 8192; TimeOut := 5000; BitsPerSec := 0; Port := GetDefaultPort(); end; destructor TclUdpClient.Destroy; begin DoDestroy(); FConnection.Free(); CleanupSocket(); inherited Destroy(); end; procedure TclUdpClient.DoDestroy; begin end; procedure TclUdpClient.SetDatagramSize(const Value: Integer); begin if (DatagramSize <> Value) then begin Connection.BatchSize := Value; Changed(); end; end; procedure TclUdpClient.SetLocalBinding(const Value: string); begin if (LocalBinding <> Value) then begin Connection.LocalBinding := Value; Changed(); end; end; procedure TclUdpClient.SetPort_(const Value: Integer); begin if (FPort <> Value) then begin FPort := Value; Changed(); end; end; procedure TclUdpClient.SetServer(const Value: string); begin if (FServer <> Value) then begin FServer := Value; Changed(); end; end; procedure TclUdpClient.SetTimeOut(const Value: Integer); begin if (TimeOut <> Value) then begin Connection.TimeOut := Value; Changed(); end; end; procedure TclUdpClient.SetBitsPerSec(const Value: Integer); begin if (BitsPerSec <> Value) then begin Connection.BitsPerSec := Value; Changed(); end; end; procedure TclUdpClient.SetCharSet(const Value: string); begin if (FCharSet <> Value) then begin FCharSet := Value; Changed(); end; end; function TclUdpClient.GetDatagramSize: Integer; begin Result := Connection.BatchSize; end; function TclUdpClient.GetLocalBinding: string; begin Result := Connection.LocalBinding; end; function TclUdpClient.GetBitsPerSec: Integer; begin Result := Connection.BitsPerSec; end; function TclUdpClient.GetTimeOut: Integer; begin Result := Connection.TimeOut; end; procedure TclUdpClient.OpenConnection(const AServer: string; APort: Integer); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end; {$ENDIF} {$ENDIF} Connection.Open(TclHostResolver.GetIPAddress(AServer), APort); end; procedure TclUdpClient.Open; begin OpenConnection(Server, Port); end; procedure TclUdpClient.Close; begin Connection.Close(False); end; procedure TclUdpClient.ReceivePacket(AData: TStream); begin Connection.ReadData(AData); {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ReceivePacket(%d)', nil, [AData.Size]);{$ENDIF} DoReceivePacket(AData); end; procedure TclUdpClient.SendPacket(AData: TStream); begin Connection.WriteData(AData); DoSendPacket(AData); end; procedure TclUdpClient.DoReceivePacket(AData: TStream); begin if Assigned(OnReceivePacket) then begin OnReceivePacket(Self, AData); end; end; procedure TclUdpClient.DoSendPacket(AData: TStream); begin if Assigned(OnSendPacket) then begin OnSendPacket(Self, AData); end; end; function TclUdpClient.ReceivePacket: string; var stream: TStream; size: Integer; buffer: TclByteArray; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} stream := TMemoryStream.Create(); try ReceivePacket(stream); stream.Position := 0; size := stream.Size - stream.Position; if (size > 0) then begin SetLength(buffer, size); stream.Read(buffer[0], size); Result := TclTranslator.GetString(buffer, 0, size, CharSet); end else begin Result := ''; end; finally stream.Free(); end; end; procedure TclUdpClient.SendPacket(const AData: string); var stream: TStream; buffer: TclByteArray; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} stream := TMemoryStream.Create(); try if (AData <> '') then begin buffer := TclTranslator.GetBytes(AData, CharSet); stream.WriteBuffer(buffer[0], Length(buffer)); stream.Position := 0; end; SendPacket(stream); finally stream.Free(); end; end; end.
unit DW.Androidapi.JNI.App; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // Android AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os, Androidapi.JNI.Net, Androidapi.JNI.Media, Androidapi.JNI.App; type JNotificationChannel = interface; JNotificationChannelGroup = interface; JNotificationChannelClass = interface(JObjectClass) ['{2C435911-AD3A-4461-8860-779ECA70D332}'] function _GetCREATOR: JParcelable_Creator; cdecl; function _GetDEFAULT_CHANNEL_ID: JString; cdecl; function init(id: JString; name: JCharSequence; importance: Integer): JNotificationChannel; cdecl; property CREATOR: JParcelable_Creator read _GetCREATOR; property DEFAULT_CHANNEL_ID: JString read _GetDEFAULT_CHANNEL_ID; end; [JavaSignature('android/app/NotificationChannel')] JNotificationChannel = interface(JObject) ['{3AA9585E-BF01-40A2-933E-73DFEB241BB9}'] function canBypassDnd: boolean; cdecl; function canShowBadge: boolean; cdecl; function describeContents: Integer; cdecl; function equals(o: JObject): boolean; cdecl; function getAudioAttributes: JAudioAttributes; cdecl; function getDescription: JString; cdecl; function getGroup: JString; cdecl; function getId: JString; cdecl; function getImportance: Integer; cdecl; function getLightColor: Integer; cdecl; function getLockscreenVisibility: Integer; cdecl; function getName: JCharSequence; cdecl; function getSound: Jnet_Uri; cdecl; function getVibrationPattern: TJavaArray<Int64>; cdecl; function hashCode: Integer; cdecl; function shouldShowLights: boolean; cdecl; function shouldVibrate: boolean; cdecl; function toString: JString; cdecl; procedure enableLights(lights: boolean); cdecl; procedure enableVibration(vibration: boolean); cdecl; procedure setBypassDnd(bypassDnd: boolean); cdecl; procedure setDescription(description: JString); cdecl; procedure setGroup(groupId: JString); cdecl; procedure setImportance(importance: Integer); cdecl; procedure setLightColor(argb: Integer); cdecl; procedure setLockscreenVisibility(lockscreenVisibility: Integer); cdecl; procedure setName(&name: JCharSequence); cdecl; procedure setShowBadge(showBadge: boolean); cdecl; procedure setSound(sound: Jnet_Uri; audioAttributes: JAudioAttributes); cdecl; procedure setVibrationPattern(vibrationPattern: TJavaArray<Int64>); cdecl; procedure writeToParcel(dest: JParcel; flags: Integer); cdecl; end; TJNotificationChannel = class(TJavaGenericImport<JNotificationChannelClass, JNotificationChannel>) end; JNotificationChannelGroupClass = interface(JObjectClass) ['{E62DA0EE-18A8-439E-BE8D-A9D0A89A2EF9}'] function _GetCREATOR : JParcelable_Creator; cdecl; function init(id : JString; &name : JCharSequence) : JNotificationChannelGroup; cdecl; property CREATOR : JParcelable_Creator read _GetCREATOR; end; [JavaSignature('android/app/NotificationChannelGroup')] JNotificationChannelGroup = interface(JObject) ['{CA4F183A-9CD3-4261-805A-A0CCBC9A5389}'] function clone: JNotificationChannelGroup; cdecl; function describeContents: Integer; cdecl; function equals(o: JObject): boolean; cdecl; function getChannels: JList; cdecl; function getDescription: JString; cdecl; function getId: JString; cdecl; function getName: JCharSequence; cdecl; function hashCode: Integer; cdecl; function isBlocked: Boolean; cdecl; procedure setDescription(description: JString); cdecl; function toString: JString; cdecl; procedure writeToParcel(dest: JParcel; flags: Integer); cdecl; end; TJNotificationChannelGroup = class(TJavaGenericImport<JNotificationChannelGroupClass, JNotificationChannelGroup>) end; [JavaSignature('android/app/NotificationManager')] JNotificationManager = interface(Androidapi.JNI.App.JNotificationManager) ['{F2C96815-29C4-4A83-994A-4F49F30B8CF4}'] procedure createNotificationChannel(channel: JNotificationChannel); cdecl; procedure createNotificationChannelGroup(group: JNotificationChannelGroup); cdecl; procedure createNotificationChannelGroups(groups: JList); cdecl; procedure createNotificationChannels(channels: JList); cdecl; procedure deleteNotificationChannel(channelId: JString); cdecl; procedure deleteNotificationChannelGroup(groupId: JString); cdecl; end; TJNotificationManager = class(TJavaGenericImport<JNotificationManagerClass, JNotificationManager>) end; implementation end.
unit csRequestTypes; interface type TcsRequestStatus = (cs_rsNone, cs_rsQuery, { в очереди } cs_rsRun, { выполняется } cs_rsFrozen, { заморожено } cs_rsFrozenRun, { выполнение приостановлено } cs_rsDelivery, { ожидание доставки пользователю } cs_rsDone, { обработано } cs_rsDeleted, { удалено } cs_rsError { выполнение привело к ошибке } ); TcsRequestType = ( cs_rtNone, // Пустой тип cs_rtImport, // Импорт cs_rtExport, // Экспорт документов cs_rtAutoClass, // Автоклассификация cs_rtAnnoExport, // Экспорт специальных аннотаций cs_rtDictEdit, cs_rtRequest, cs_rtGetTask, cs_rtLine, cs_rtServerStatus, cs_rtTaskResult, cs_rtFNSExport, cs_rtUserEdit, cs_rtDeleteDocs, cs_rtCommonData, cs_rtAExportDoc, cs_rtAExportAnno, cs_rtRemoteDictEdit, cs_rtRegionUpload, cs_rtRunCommand, cs_rtDossierMake, cs_rtCaseCode, cs_rtPrimeExport ); TddFileRenameMode = (dd_frmUnique, // создать уникальное имя Для нового файла dd_frmBackup, // создать bak-копию старого файла dd_frmAdd, // добавить в существующие dd_frmReplace // Заменить существующий ); TcsRequestTypes = set of TcsRequestType; TcsRequestNotifyEvent = procedure (Sender: TObject; PrevStatus : TcsRequestStatus) of object; implementation end.
unit Mat.ProjectGroupParser; interface uses System.Generics.Collections, System.Classes, System.SysUtils, System.IOUtils, Mat.ProjectParser; type // Class for ProjectGroup file parsing. TProjectGroupFile = class private FFullPath: string; FTitle: string; FVersion: string; FProjects: TProjectsList; function GetFileName: string; protected function ParseItem(const AStr: string): TProjectFile; public constructor Create; destructor Destroy; override; property FullPath: string read FFullPath write FFullPath; property FileName: string read GetFileName; property Title: string read FTitle write FTitle; property Projects: TProjectsList read FProjects write FProjects; property Version: string read FVersion write FVersion; procedure ParseVersion(const ABlock: string); end; TProjectsGroupList = class(TList<TProjectGroupFile>) protected function ParseFile(const APath: string): TProjectGroupFile; public procedure ParseDirectory(const ADirectory: string; AIsRecursively: Boolean); end; implementation uses Mat.Constants, Mat.AnalysisProcessor; { TProjectFile } constructor TProjectGroupFile.Create; begin FProjects := TProjectsList.Create; end; destructor TProjectGroupFile.Destroy; begin FProjects.Free; inherited; end; function TProjectGroupFile.GetFileName: string; begin Result := TPath.GetFileNameWithoutExtension(FFullPath); end; function TProjectGroupFile.ParseItem(const AStr: string): TProjectFile; var LData: string; P: PChar; S: string; Index: Integer; Pause: Boolean; function PathCombine(A, B: string): string; var Sl1, Sl2: TStringList; Drive: string; i: Integer; begin Drive := ''; Sl1 := TStringList.Create; Sl2 := TStringList.Create; try if A[2] = ':' then begin Drive := A[1]; Sl1.StrictDelimiter := True; Sl1.Delimiter := TPath.DirectorySeparatorChar; Sl1.DelimitedText := A.Substring(2); end else begin Sl1.StrictDelimiter := True; Sl1.DelimitedText := A; end; Sl2.StrictDelimiter := True; Sl2.Delimiter := TPath.DirectorySeparatorChar; Sl2.DelimitedText := B; while (Sl2.Count > 0) and (Sl2[0] = '..') do begin Sl1.Delete(Sl1.Count - 1); Sl2.Delete(0); end; if not Drive.IsEmpty then Result := Drive + ':'; for i := 0 to Sl1.Count - 1 do if not Sl1[i].IsEmpty then Result := Result + TPath.DirectorySeparatorChar + Sl1[i]; for i := 0 to Sl2.Count - 1 do Result := Result + TPath.DirectorySeparatorChar + Sl2[i]; finally Sl2.Free; Sl1.Free; end; end; begin LData := AStr.Trim + ' '; P := PChar(LData); Result := TProjectFile.Create; Index := 1; Pause := False; S := ''; while (P^ <> #0) do begin if not Pause then S := S + P^; if ((P^ = ' ') and (S[S.Trim.Length] <> ' ')) or (P^ = #0) then begin S := S.Trim; if S.Equals(':') then S := '' else Pause := True; end; if Pause and not S.IsEmpty then begin case index of 1: Result.Title := S; 2: begin if S.Trim[1] = '''' then S := S.Substring(1); if S.Trim[S.Trim.Length] = '''' then S := S.Substring(0, S.Trim.Length - 1); if (not S.IsEmpty) and (not((S[1] = '.') and (S[2] = '.'))) then begin S := TPath.Combine (TPath.GetDirectoryName(FFullPath), S); end else if (not S.IsEmpty) and ((S[1] = '.') and (S[2] = '.')) then begin S := PathCombine (TPath.GetDirectoryName(FFullPath), S); end else if TPath.GetFileName(S) <> S then S := TPath.GetDirectoryName(FFullPath) + TPath.DirectorySeparatorChar + S; Result.FullPath := S; end; end; Pause := False; inc(Index); S := ''; end; inc(P); end; FProjects.Add(FAnalysisProcessor.ProjectsList.ParseFile(Result.FullPath)); end; procedure TProjectGroupFile.ParseVersion(const ABlock: string); var S: string; begin S := ABlock.Substring(Pos(VERSION_CONST, ABlock.ToLower) + Mat.Constants.VERSION_CONST.Length).Trim; if S[1] = '=' then S := S.Substring(2).Trim; FVersion := S; end; { TProjectsList } procedure TProjectsGroupList.ParseDirectory(const ADirectory: string; AIsRecursively: Boolean); var LDirectories: TArray<string>; LFiles: TArray<string>; LCurrentPath: string; LPF: TProjectGroupFile; begin if AIsRecursively then begin LDirectories := TDirectory.GetDirectories(ADirectory); for LCurrentPath in LDirectories do ParseDirectory(LCurrentPath, True); end; LFiles := TDirectory.GetFiles(ADirectory, PROJECT_GROUP_EXT_AST); for LCurrentPath in LFiles do begin LPF := ParseFile(LCurrentPath); Add(LPF); end; end; function TProjectsGroupList.ParseFile(const APath: string): TProjectGroupFile; var LRowProjectsList: TStringList; LFileData: TStringList; i: Integer; LBlock: string; LIsVersionFound: Boolean; begin Result := TProjectGroupFile.Create; LBlock := ''; LRowProjectsList := nil; LFileData := nil; try LFileData := TStringList.Create; LRowProjectsList := TStringList.Create; if TFile.Exists(APath) then begin LFileData.LoadFromFile(APath, TEncoding.ANSI); Result.FullPath := APath; LIsVersionFound := False; for i := 0 to Pred(LFileData.Count) do begin if (Pos(Mat.Constants.PROJECT_EXT, LFileData[i].Trim.ToLower) > 0) then begin LRowProjectsList.Add(LFileData[i].Trim.ToLower); Result.ParseItem(LFileData[i].Trim); end; if not LIsVersionFound then begin if (Pos(Mat.Constants.VERSION_CONST, LFileData[i].Trim.ToLower) > 0) then begin Result.ParseVersion(LFileData[i]); LIsVersionFound := not Result.FVersion.IsEmpty; end; end; end; end; finally LRowProjectsList.Free; LFileData.Free end; end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Cajas; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QMenus, QTypes, QcurrEdit, QGrids, QDBGrids, Inifiles, QButtons; type TfrmCajas = class(TForm) btnInsertar: TBitBtn; btnEliminar: TBitBtn; btnModificar: TBitBtn; btnGuardar: TBitBtn; btnCancelar: TBitBtn; gddListado: TDBGrid; lblRegistros: TLabel; txtRegistros: TcurrEdit; grpDatos: TGroupBox; Label1: TLabel; txtTicket: TEdit; mnuMenu: TMainMenu; Archivo1: TMenuItem; mnuInsertar: TMenuItem; mnuEliminar: TMenuItem; mnuModificar: TMenuItem; N3: TMenuItem; mnuGuardar: TMenuItem; mnuCancelar: TMenuItem; N2: TMenuItem; Salir1: TMenuItem; mnuConsulta: TMenuItem; mnuAvanza: TMenuItem; mnuRetrocede: TMenuItem; Label2: TLabel; txtCaja: TcurrEdit; Label3: TLabel; txtFactura: TEdit; Label4: TLabel; txtNota: TEdit; Label5: TLabel; Label6: TLabel; txtNombre: TEdit; procedure FormShow(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnInsertarClick(Sender: TObject); procedure btnGuardarClick(Sender: TObject); procedure btnEliminarClick(Sender: TObject); procedure btnModificarClick(Sender: TObject); procedure Salir1Click(Sender: TObject); procedure mnuAvanzaClick(Sender: TObject); procedure mnuRetrocedeClick(Sender: TObject); procedure FormCreate(Sender: TObject); private sModo:String; iClave:Integer; procedure RecuperaConfig; procedure LimpiaDatos; procedure Listar; procedure ActivaControles; procedure RecuperaDatos; procedure GuardaDatos; function VerificaIntegridad:boolean; function VerificaDatos:boolean; public end; var frmCajas: TfrmCajas; implementation uses dm; {$R *.xfm} procedure TfrmCajas.FormShow(Sender: TObject); begin btnCancelarClick(Sender); end; procedure TfrmCajas.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('Cajas', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Cajas', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; Free; end; end; procedure TfrmCajas.btnCancelarClick(Sender: TObject); begin sModo := 'Consulta'; LimpiaDatos; Listar; ActivaControles; Height := 220; btnInsertar.SetFocus; end; procedure TfrmCajas.LimpiaDatos; begin txtNombre.Clear; txtCaja.Value := 0; txtTicket.Clear; txtNota.Clear; txtFactura.Clear; end; procedure TfrmCajas.Listar; var sBM : String; begin with dmDatos.qryListados do begin sBM := dmDatos.cdsCliente.Bookmark; dmDatos.cdsCliente.Active := false; Close; SQL.Clear; SQL.Add('SELECT numero, nombre, serieticket, serienota, seriefactura FROM cajas ORDER BY numero'); Open; dmDatos.cdsCliente.Active := true; dmDatos.cdsCliente.FieldByName('numero').DisplayLabel := 'Caja'; dmDatos.cdsCliente.FieldByName('nombre').DisplayLabel := 'Nombre'; dmDatos.cdsCliente.FieldByName('numero').DisplayWidth := 6; dmDatos.cdsCliente.FieldByName('nombre').DisplayWidth := 13; dmDatos.cdsCliente.FieldByName('serieticket').Visible := false; dmDatos.cdsCliente.FieldByName('serienota').Visible := false; dmDatos.cdsCliente.FieldByName('seriefactura').Visible := false; txtRegistros.Value := dmDatos.cdsCliente.RecordCount; try dmDatos.cdsCliente.Bookmark := sBM; except txtRegistros.Value := txtRegistros.Value; end; end; RecuperaDatos; end; procedure TfrmCajas.ActivaControles; begin if( (sModo = 'Insertar') or (sModo = 'Modificar') ) then begin btnInsertar.Enabled := false; btnModificar.Enabled := false; btnEliminar.Enabled := false; mnuInsertar.Enabled := false; mnuModificar.Enabled := false; mnuEliminar.Enabled := false; btnGuardar.Enabled := true; btnCancelar.Enabled := true; mnuGuardar.Enabled := true; mnuCancelar.Enabled := true; mnuConsulta.Enabled := false; txtNombre.ReadOnly := false; txtNombre.TabStop := true; txtCaja.ReadOnly := False; txtCaja.TabStop := True; txtTicket.ReadOnly := False; txtTicket.TabStop := True; txtFactura.ReadOnly := False; txtFactura.TabStop := True; txtNota.ReadOnly := False; txtNota.TabStop := True; end; if(sModo = 'Consulta') then begin btnInsertar.Enabled := true; mnuInsertar.Enabled := true; if(txtRegistros.Value > 0) then begin btnModificar.Enabled := true; btnEliminar.Enabled := true; mnuModificar.Enabled := true; mnuEliminar.Enabled := true; end else begin btnModificar.Enabled := false; btnEliminar.Enabled := false; mnuModificar.Enabled := false; mnuEliminar.Enabled := false; end; btnGuardar.Enabled := false; btnCancelar.Enabled := false; mnuGuardar.Enabled := false; mnuCancelar.Enabled := false; mnuConsulta.Enabled := true; txtNombre.ReadOnly := true; txtNombre.TabStop := false; txtCaja.ReadOnly := true; txtCaja.TabStop := false; txtTicket.ReadOnly := true; txtTicket.TabStop := false; txtFactura.ReadOnly := true; txtFactura.TabStop := false; txtNota.ReadOnly := true; txtNota.TabStop := false; end; end; procedure TfrmCajas.RecuperaDatos; begin with dmDatos.cdsCliente do begin if(Active) then begin iClave := FieldByName('numero').AsInteger; txtCaja.Value := FieldByName('numero').AsInteger; txtNombre.Text := Trim(FieldByName('Nombre').AsString); txtTicket.Text := Trim(FieldByName('serieticket').AsString); txtNota.Text := Trim(FieldByName('serienota').AsString); txtFactura.Text := Trim(FieldByName('seriefactura').AsString); end; end; end; procedure TfrmCajas.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('Cajas', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Cajas', 'Posx', IntToStr(Left)); Free; end; dmDatos.qryListados.Close; dmDatos.cdsCliente.Active := false; end; procedure TfrmCajas.btnInsertarClick(Sender: TObject); begin limpiaDatos; sModo := 'Insertar'; Height := 358; ActivaControles; txtCaja.SetFocus; end; procedure TfrmCajas.btnGuardarClick(Sender: TObject); begin if(VerificaDatos) then begin GuardaDatos; btnCancelarClick(Sender); end; end; function TfrmCajas.VerificaDatos:boolean; var bRegreso : boolean; begin btnGuardar.SetFocus; bRegreso := true; if(Length(txtNombre.Text) = 0) then begin Application.MessageBox('Introduce el nombre de la caja','Error',[smbOK],smsCritical); txtNombre.SetFocus; bRegreso := false; end else if(not VerificaIntegridad) then bRegreso := false; Result := bRegreso; end; function TfrmCajas.VerificaIntegridad:boolean; var bRegreso : boolean; begin bRegreso := true; with dmDatos.qryConsulta do begin Close; SQL.Clear; SQL.Add('SELECT numero FROM cajas WHERE numero = ' + FloatToStr(txtCaja.Value)); Open; if(not Eof) and ((sModo = 'Insertar') or ((FieldByName('numero').AsInteger <> iClave) and (sModo = 'Modificar'))) then begin bRegreso := false; Application.MessageBox('La caja ya existe','Error',[smbOK],smsCritical); txtNombre.SetFocus; end; Close; end; Result := bRegreso; end; procedure TfrmCajas.GuardaDatos; var sCaja : String; begin if(txtCaja.Value = 0) then sCaja := 'null' else sCaja := FloatToStr(txtCaja.Value); if(sModo = 'Insertar') then begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('INSERT INTO cajas (numero, nombre, serieticket, serienota, seriefactura, fecha_umov) VALUES('); SQL.Add('''' + txtCaja.Text + ''',''' + txtNombre.Text + ''','); SQL.Add('''' + txtTicket.Text + ''',''' + txtNota.Text + ''','); SQL.Add('''' + txtFactura.Text + ''',''' + FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + ''')'); ExecSQL; Close; end; end else begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('UPDATE cajas SET nombre = ''' + txtNombre.Text + ''','); SQL.Add('numero = ' + FloatToStr(txtCaja.Value) + ', serieticket = ''' + txtTicket.Text + ''','); SQL.Add('serienota = ''' + txtNota.Text + ''', seriefactura = ''' + txtFactura.Text + ''','); SQL.Add('fecha_umov = ''' + FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + ''''); SQL.Add('WHERE numero = ' + IntToStr(iClave)); ExecSQL; Close; end; end; end; procedure TfrmCajas.btnEliminarClick(Sender: TObject); begin if(Application.MessageBox('Se eliminará la caja seleccionada','Eliminar',[smbOK]+[smbCancel]) = smbOK) then begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM cajas WHERE numero = ' + dmDatos.cdsCliente.FieldByName('numero').AsString); ExecSQL; Close; end; btnCancelarClick(Sender); end; end; procedure TfrmCajas.btnModificarClick(Sender: TObject); begin if(txtRegistros.Value > 0) then begin sModo := 'Modificar'; RecuperaDatos; ActivaControles; Height := 358; txtCaja.SetFocus; end; end; procedure TfrmCajas.Salir1Click(Sender: TObject); begin Close; end; procedure TfrmCajas.mnuAvanzaClick(Sender: TObject); begin dmDatos.cdsCliente.Next; end; procedure TfrmCajas.mnuRetrocedeClick(Sender: TObject); begin dmDatos.cdsCliente.Prior; end; procedure TfrmCajas.FormCreate(Sender: TObject); begin RecuperaConfig; end; end.
// P2Ada test with FreePascal... { The Computer Language Shootout http://shootout.alioth.debian.org Calculate digits of pi using the Unbounded Spigot Algorithms contributed by Vincent Snijders gmp headers by Karl-Michael Schindler } program pidigits; {$linklib libgmp.so} {$mode objfpc} uses ctypes; type mp_limb_t = cuint; mp_ptr = ^mp_limb_t; mpz_t = record mp_alloc, mp_size : cint; mp_d : mp_ptr end; procedure mpz_init (var Dest: mpz_t); cdecl; external name '__gmpz_init'; procedure mpz_init_set_ui (var Dest: mpz_t; Src: culong); cdecl; external name '__gmpz_init_set_ui'; procedure mpz_mul_ui (var Dest: mpz_t; var Src1: mpz_t; Src2: culong); cdecl; external name '__gmpz_mul_ui'; procedure mpz_mul_si (var Dest: mpz_t; var Src1: mpz_t; Src2: cint); cdecl; external name '__gmpz_mul_si'; procedure mpz_add (var Dest: mpz_t; var Src1, Src2: mpz_t); cdecl; external name '__gmpz_add'; procedure mpz_tdiv_q (var Dest: mpz_t; var Src1, Src2: mpz_t); cdecl; external name '__gmpz_tdiv_q'; function mpz_get_ui (var Src: mpz_t): culong; cdecl; external name '__gmpz_get_ui'; procedure PrintPiDigits(NumDigits: integer); var q, r, s, t: mpz_t; // Transformation matrix components. u, v, w: mpz_t; // Temporary variables i, k, digit, c: integer; line: string[10]; function Extract(x:cardinal) : integer; begin mpz_mul_ui(u, q, x); mpz_add(u, u, r); mpz_mul_ui(v, s, x); mpz_add(v, v, t); mpz_tdiv_q(w, u, v); result := mpz_get_ui(w); end; function IsSafe : boolean; begin result := digit = Extract(4); end; procedure Produce; begin mpz_mul_si(r, r, 10); mpz_mul_si(v, t, -10 * digit); mpz_add(r, r, v); mpz_mul_si(q, q, 10); end; procedure Consume; begin inc(k); mpz_mul_si(r, r, 2*k+1); mpz_mul_si(u, q, 4*k+2); mpz_add(r, r, u); mpz_mul_si(t, t, 2*k+1); mpz_mul_si(v, s, 4*k+2); mpz_add(t, t, v); mpz_mul_si(s, s, k); mpz_mul_si(q, q, k); end; begin k := 0; i := 0; c := 0; setlength(line, 10); mpz_init_set_ui(q, 1); mpz_init_set_ui(r, 0); mpz_init_set_ui(s, 0); mpz_init_set_ui(t, 1); mpz_init(u); mpz_init(v); mpz_init(w); while (i<NumDigits) do begin digit := Extract(3); while not IsSafe do begin Consume; digit:= Extract(3); end; Produce; inc(c); line[c] := chr(ord('0')+digit); inc(i); if c=10 then begin writeln(line, #9+':', i); c := 0; end; end; if c<>0 then begin SetLength(line, c); writeln(line); end; end; var n: integer = 27; begin if (ParamCount=1) then val(ParamStr(1), n); PrintPiDigits(n); Writeln('//'); // Test with a "//" comment end.
program ejercicio5; const dimF = 6;// son 100 type vnum = array[1..dimF] of Integer; procedure cargarVector(var v:vnum; var dimL:Integer); var numero: Integer; begin write('Ingrese un numero: '); readln(numero); while (dimL < 100) and (numero <> 0) do begin dimL:= dimL + 1; v[dimL]:= numero; write('Ingrese un numero: '); readln(numero); end; end; procedure maximoYMinimo(v:vnum; dimL:Integer; var max,min:Integer; var posMax, posMin: Integer); var i: Integer; begin for i := 1 to dimL do begin if (v[i] >= max) then begin max:= v[i]; posMax:= i; end; if (v[i] <= min) then begin min:= v[i]; posMin:= i; end; end; end; procedure intercambio(var v:vnum; dimL:Integer; max,min:Integer; posMax,posMin:Integer); var i: Integer; begin for i := 1 to dimL do begin if (i = posMax) then v[i]:= min else if (i = posMin) then v[i]:= max; end; writeln('El elemento Maximo ', max, ' que se encontraba en la posicion ', posMax, ' fue intercambiado con el elemento minimo ', min, ' que se encontraba en la posicion ', posMin); end; procedure imprimirVector(v:vnum; dimL:Integer); var i: Integer; begin for i := 1 to dimL do begin write(v[i], ' '); end; end; var v: vnum; max,min,posMax,posMin,dimL: Integer; begin max:=-9999; min:=9999; dimL:=0; cargarVector(v,dimL); imprimirVector(v,dimL); writeln(); maximoYMinimo(v,dimL,max,min,posMax,posMin); intercambio(v,dimL,max,min,posMax,posMin); readln(); end.
unit ProdutoPedidoClass; interface uses SysUtils; Type TPedidoProduto = class private FID_Produto: integer; FID_PedidoProduto: integer; FValorUnitario: double; FID: integer; FValorTotal: double; FQuantidade: integer; FsID_Produto: String; FsDescProduto: String; FsID_PedidoProduto: String; FsValorUnitario: String; FsID: String; FsValorTotal: String; FsQuantidade: String; procedure SetID(const Value: integer); procedure SetsID(const Value: String); procedure SetID_PedidoProduto(const Value: integer); procedure SetsID_PedidoProduto(const Value: String); procedure SetID_Produto(const Value: integer); procedure SetsID_Produto(const Value: String); procedure SetQuantidade(const Value: integer); procedure SetsQuantidade(const Value: String); procedure SetValorTotal(const Value: double); procedure SetsValorTotal(const Value: String); procedure SetValorUnitario(const Value: double); procedure SetsValorUnitario(const Value: String); protected public property ID: integer read FID write SetID; property ID_PedidoProduto: integer read FID_PedidoProduto write SetID_PedidoProduto; property ID_Produto: integer read FID_Produto write SetID_Produto; property Quantidade: integer read FQuantidade write SetQuantidade; property ValorUnitario: double read FValorUnitario write SetValorUnitario; property ValorTotal: double read FValorTotal write SetValorTotal; property sID: String read FsID write SetsID; property sID_PedidoProduto: String read FsID_PedidoProduto write SetsID_PedidoProduto; property sID_Produto: String read FsID_Produto write SetsID_Produto; property sDescProduto: String read FsDescProduto; property sQuantidade: String read FsQuantidade write SetsQuantidade; property sValorUnitario: String read FsValorUnitario write SetsValorUnitario; property sValorTotal: String read FsValorTotal write SetsValorTotal; function LerDescProduto: String; function CriarTabelaTemp: boolean; function Salvar(): boolean; function Validar(): WideString; function LerProdPed(iID: integer): boolean; function LerProdutos(iID: integer): boolean; function Excluir: boolean; {published} end; implementation uses DMU, FuncoesU; const NOMETABELA: String = 'pedidoprodutotmp'; { TPedidoProduto } function TPedidoProduto.LerProdutos(iID: integer): boolean; begin DM.pedidoprodutotmp.Close; DM.somaprodtmp.Close; try with DM.SQLSalvar do begin Close; SQL.Clear; SQL.Add('start transaction'); ExecSQL; SQL.Clear; SQL.Add('insert into '+NOMETABELA ); SQL.Add('( id_pedidoproduto, id_produto, '); SQL.Add('quantidade, valorunitario, '); SQL.Add('valortotal) '); SQL.Add('select pp.id, pp.id_produto, '); SQL.Add('pp.quantidade, pp.valorunitario, '); SQL.Add('pp.valortotal '); SQL.Add('from pedidoproduto as pp '); SQL.Add('where pp.id_pedido = :vid_pedido '); SQL.Add('order by pp.id '); ParamByName('vid_pedido').Value := iID; ExecSQL; SQL.Clear; SQL.Add('commit'); ExecSQL; end; Result := True; except Result := False; end; DM.pedidoprodutotmp.Open; DM.pedidoprodutotmp.Refresh; DM.somaprodtmp.Open; DM.somaprodtmp.Refresh; end; function TPedidoProduto.Excluir: boolean; begin DM.pedidoprodutotmp.Close; DM.somaprodtmp.Close; try with DM.SQLExcluir do begin SQL.Clear; SQL.Add('start transaction;'); ExecSQL; SQL.Clear; SQL.Add('delete from '+NOMETABELA ); SQL.Add(' where id = :vid;'); ParamByName('vid').Value := ID; ExecSQL; SQL.Clear; SQL.Add('commit;'); ExecSQL; end; Result := True; except Result := False; end; DM.pedidoprodutotmp.Open; DM.somaprodtmp.Open; end; function TPedidoProduto.LerDescProduto: String; begin if LocalizarSQL('produto',FsID_Produto) then begin fsDescProduto := DM.SQLLocalizar.FindField('descricao').Value; Result := fsDescProduto; end else begin Result := ''; end; end; function TPedidoProduto.LerProdPed(iID: integer): boolean; begin if LocalizarSQL(NOMETABELA,IntToStr(iID)) then begin with DM.SQLLocalizar do begin ID := FindField('id').AsInteger; ID_PedidoProduto := FindField('id_pedidoproduto').AsInteger; ID_Produto := FindField('id_produto').AsInteger; Quantidade := FindField('quantidade').AsInteger; ValorUnitario := FindField('valorunitario').AsFloat; ValorTotal := FindField('valortotal').AsFloat; end; LerDescProduto; Result := True; end else begin Result := False; end; end; function TPedidoProduto.Validar(): WideString; var cMensagem: WideString; begin cMensagem := ''; if not LocalizarSQL('produto',IntToStr(ID_Produto)) then begin cMensagem := cMensagem + '- O Campo Código do Produto esta inválido!'+#13+#10; end; if (Quantidade <= 0) then begin cMensagem := cMensagem + '- O Campo Quantidade deve ser maior que zero!'+#13+#10; end; if (ValorUnitario <= 0) then begin cMensagem := cMensagem + '- O Campo Valor Unitário deve ser maior que zero!'+#13+#10; end; if (Length(Trim(cMensagem)) > 0) then begin cMensagem := 'ATENÇÂO!'+#13#10+#13#10+ 'Divergência(s) encontrada(s) no preenchimento.'+#13+#10+ #13+#10+cMensagem+#13+#10+ 'Corrija e tente salvar novamente.'+#13+#10; end; Result := cMensagem; end; function TPedidoProduto.Salvar(): boolean; begin try with DM.SQLSalvar do begin SQL.Clear; SQL.Add('start transaction'); ExecSQL; SQL.Clear; if (ID = 0) then begin // incluir novo produto SQL.Add('insert into '+NOMETABELA+' ( '); SQL.Add('id_pedidoproduto, id_produto, '); SQL.Add('quantidade, valorunitario, '); SQL.Add('valortotal) '); SQL.Add('values ( '); SQL.Add(':vid_pedidoproduto, :vid_produto, '); SQL.Add(':vquantidade, :vvalorunitario, '); SQL.Add(':vvalortotal)'); ParamByName('vid_pedidoproduto').Value := ID_PedidoProduto; ParamByName('vid_produto').Value := ID_Produto; end else begin // alterar produto SQL.Add('update '+NOMETABELA+' set '); SQL.Add('quantidade = :vquantidade, '); SQL.Add('valorunitario = :vvalorunitario, '); SQL.Add('valortotal = :vvalortotal '); SQL.Add('where id = :vid '); ParamByName('vid').Value := ID; end; ParamByName('vquantidade').Value := Quantidade; ParamByName('vvalorunitario').Value := ValorUnitario; ParamByName('vvalortotal').Value := ValorTotal; ExecSQL; SQL.Clear; SQL.Add('commit'); ExecSQL; end; DM.pedidoprodutotmp.Refresh; DM.pedidoprodutotmp.Last; DM.somaprodtmp.Refresh; Result := True; except Result := False; end; end; function TPedidoProduto.CriarTabelaTemp: boolean; begin DM.pedidoprodutotmp.Close; DM.somaprodtmp.Close; try with DM.SQLCriarTabela do begin SQL.Clear; SQL.Add('start transaction'); ExecSQL; SQL.Clear; SQL.Add('drop table if exists '+NOMETABELA); ExecSQL; SQL.Clear; SQL.Add('create table '+NOMETABELA); SQL.Add('(id int primary key auto_increment not null, '); SQL.Add('id_pedidoproduto int, '); SQL.Add('id_produto int, '); SQL.Add('quantidade int, '); SQL.Add('valorunitario double, '); SQL.Add('valortotal double ) '); ExecSQL; SQL.Clear; SQL.Add('commit'); ExecSQL; end; Result := True; except Result := False; end; DM.pedidoprodutotmp.Open; DM.pedidoprodutotmp.Refresh; DM.somaprodtmp.Open; DM.somaprodtmp.Refresh; end; procedure TPedidoProduto.SetID(const Value: integer); begin if (Length(FsID) = 0) then FID := Value; if (Length(FsID) = 0) then FsID := IntToStr(Value); end; procedure TPedidoProduto.SetsID(const Value: String); begin if (Length(FsID) = 0) then FsID := Value; if (Length(FsID) = 0) then FID := StrToInt(Value); end; procedure TPedidoProduto.SetID_PedidoProduto(const Value: integer); begin if (Length(FsID_PedidoProduto) = 0) then FID_PedidoProduto := Value; if (Length(FsID_PedidoProduto) = 0) then FsID_PedidoProduto := IntToStr(Value); end; procedure TPedidoProduto.SetsID_PedidoProduto(const Value: String); begin if (Length(FsID_PedidoProduto) = 0) then FsID_PedidoProduto := Value; if (Length(FsID_PedidoProduto) = 0) then FID_PedidoProduto := StrToInt(Value); end; procedure TPedidoProduto.SetID_Produto(const Value: integer); begin FID_Produto := Value; FsID_Produto := IntToStr(Value); end; procedure TPedidoProduto.SetsID_Produto(const Value: String); begin FsID_Produto := Value; FID_Produto := StrToInt(Value); end; procedure TPedidoProduto.SetQuantidade(const Value: integer); begin FQuantidade := Value; FsQuantidade := IntToStr(Value); end; procedure TPedidoProduto.SetsQuantidade(const Value: String); begin FsQuantidade := Value; FQuantidade := StrToInt(Value); end; procedure TPedidoProduto.SetValorTotal(const Value: double); begin FValorTotal := Value; FsValorTotal := FormatFloat('###,###,##0.00',Value); end; procedure TPedidoProduto.SetsValorTotal(const Value: String); begin FsValorTotal := Value; FValorTotal := StrparaFloat(Value); end; procedure TPedidoProduto.SetValorUnitario(const Value: double); begin FValorUnitario := Value; FsValorUnitario := FormatFloat('###,###,##0.00',Value); end; procedure TPedidoProduto.SetsValorUnitario(const Value: String); begin FsValorUnitario := Value; FValorUnitario := StrparaFloat(Value); end; end.
unit RESTRequest4D.Request.Headers.Intf; interface uses REST.Types; type /// <summary> /// Interface to represent the headers that a request can have. /// </summary> IRequestHeaders = interface ['{619A1A04-A54E-4684-914B-D5AB1EA867A3}'] /// <summary> /// Removes all added headers. /// </summary> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Clear: IRequestHeaders; /// <summary> /// Adds a new header. /// </summary> /// <param name="AName"> /// Name of header. /// </param> /// <param name="AValue"> /// Header value. /// </param> /// <param name="AOptions"> /// Additional options for the header. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> /// <remarks> /// If the parameter already exists, its value will change. /// </remarks> function Add(const AName, AValue: string; const AOptions: TRESTRequestParameterOptions = []): IRequestHeaders; end; implementation end.
unit CheckListBoxWordsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\CheckListBoxWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "CheckListBoxWordsPack" MUID: (552D23C300F1) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , CheckLst , tfwClassLike , tfwScriptingInterfaces , TypInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *552D23C300F1impl_uses* //#UC END# *552D23C300F1impl_uses* ; type TkwPopCheckListBoxGetChecked = {final} class(TtfwClassLike) {* Слово скрипта pop:CheckListBox:GetChecked } private function GetChecked(const aCtx: TtfwContext; aCheckListBox: TCheckListBox; anIndex: Integer): Boolean; {* Реализация слова скрипта pop:CheckListBox:GetChecked } 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; end;//TkwPopCheckListBoxGetChecked TkwPopCheckListBoxSetChecked = {final} class(TtfwClassLike) {* Слово скрипта pop:CheckListBox:SetChecked } private procedure SetChecked(const aCtx: TtfwContext; aCheckListBox: TCheckListBox; anIndex: Integer; aValue: Boolean); {* Реализация слова скрипта pop:CheckListBox:SetChecked } 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; end;//TkwPopCheckListBoxSetChecked TkwPopCheckListBoxUncheckAll = {final} class(TtfwClassLike) {* Слово скрипта pop:CheckListBox:UncheckAll } private procedure UncheckAll(const aCtx: TtfwContext; aCheckListBox: TCheckListBox); {* Реализация слова скрипта pop:CheckListBox:UncheckAll } 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; end;//TkwPopCheckListBoxUncheckAll function TkwPopCheckListBoxGetChecked.GetChecked(const aCtx: TtfwContext; aCheckListBox: TCheckListBox; anIndex: Integer): Boolean; {* Реализация слова скрипта pop:CheckListBox:GetChecked } //#UC START# *552D24400252_552D24400252_51F24E890269_Word_var* //#UC END# *552D24400252_552D24400252_51F24E890269_Word_var* begin //#UC START# *552D24400252_552D24400252_51F24E890269_Word_impl* Result := aCheckListBox.Checked[anIndex]; //#UC END# *552D24400252_552D24400252_51F24E890269_Word_impl* end;//TkwPopCheckListBoxGetChecked.GetChecked class function TkwPopCheckListBoxGetChecked.GetWordNameForRegister: AnsiString; begin Result := 'pop:CheckListBox:GetChecked'; end;//TkwPopCheckListBoxGetChecked.GetWordNameForRegister function TkwPopCheckListBoxGetChecked.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopCheckListBoxGetChecked.GetResultTypeInfo function TkwPopCheckListBoxGetChecked.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopCheckListBoxGetChecked.GetAllParamsCount function TkwPopCheckListBoxGetChecked.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TCheckListBox), TypeInfo(Integer)]); end;//TkwPopCheckListBoxGetChecked.ParamsTypes procedure TkwPopCheckListBoxGetChecked.DoDoIt(const aCtx: TtfwContext); var l_aCheckListBox: TCheckListBox; var l_anIndex: Integer; begin try l_aCheckListBox := TCheckListBox(aCtx.rEngine.PopObjAs(TCheckListBox)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aCheckListBox: TCheckListBox : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(GetChecked(aCtx, l_aCheckListBox, l_anIndex)); end;//TkwPopCheckListBoxGetChecked.DoDoIt procedure TkwPopCheckListBoxSetChecked.SetChecked(const aCtx: TtfwContext; aCheckListBox: TCheckListBox; anIndex: Integer; aValue: Boolean); {* Реализация слова скрипта pop:CheckListBox:SetChecked } //#UC START# *552D24650138_552D24650138_51F24E890269_Word_var* //#UC END# *552D24650138_552D24650138_51F24E890269_Word_var* begin //#UC START# *552D24650138_552D24650138_51F24E890269_Word_impl* aCheckListBox.Checked[anIndex] := aValue; //#UC END# *552D24650138_552D24650138_51F24E890269_Word_impl* end;//TkwPopCheckListBoxSetChecked.SetChecked class function TkwPopCheckListBoxSetChecked.GetWordNameForRegister: AnsiString; begin Result := 'pop:CheckListBox:SetChecked'; end;//TkwPopCheckListBoxSetChecked.GetWordNameForRegister function TkwPopCheckListBoxSetChecked.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopCheckListBoxSetChecked.GetResultTypeInfo function TkwPopCheckListBoxSetChecked.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 3; end;//TkwPopCheckListBoxSetChecked.GetAllParamsCount function TkwPopCheckListBoxSetChecked.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TCheckListBox), TypeInfo(Integer), TypeInfo(Boolean)]); end;//TkwPopCheckListBoxSetChecked.ParamsTypes procedure TkwPopCheckListBoxSetChecked.DoDoIt(const aCtx: TtfwContext); var l_aCheckListBox: TCheckListBox; var l_anIndex: Integer; var l_aValue: Boolean; begin try l_aCheckListBox := TCheckListBox(aCtx.rEngine.PopObjAs(TCheckListBox)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aCheckListBox: TCheckListBox : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aValue := aCtx.rEngine.PopBool; except on E: Exception do begin RunnerError('Ошибка при получении параметра aValue: Boolean : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetChecked(aCtx, l_aCheckListBox, l_anIndex, l_aValue); end;//TkwPopCheckListBoxSetChecked.DoDoIt procedure TkwPopCheckListBoxUncheckAll.UncheckAll(const aCtx: TtfwContext; aCheckListBox: TCheckListBox); {* Реализация слова скрипта pop:CheckListBox:UncheckAll } //#UC START# *552D24A702F3_552D24A702F3_51F24E890269_Word_var* var i: Integer; //#UC END# *552D24A702F3_552D24A702F3_51F24E890269_Word_var* begin //#UC START# *552D24A702F3_552D24A702F3_51F24E890269_Word_impl* for i := 0 to aCheckListBox.Count - 1 do aCheckListBox.Checked[i] := False; //#UC END# *552D24A702F3_552D24A702F3_51F24E890269_Word_impl* end;//TkwPopCheckListBoxUncheckAll.UncheckAll class function TkwPopCheckListBoxUncheckAll.GetWordNameForRegister: AnsiString; begin Result := 'pop:CheckListBox:UncheckAll'; end;//TkwPopCheckListBoxUncheckAll.GetWordNameForRegister function TkwPopCheckListBoxUncheckAll.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopCheckListBoxUncheckAll.GetResultTypeInfo function TkwPopCheckListBoxUncheckAll.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopCheckListBoxUncheckAll.GetAllParamsCount function TkwPopCheckListBoxUncheckAll.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TCheckListBox)]); end;//TkwPopCheckListBoxUncheckAll.ParamsTypes procedure TkwPopCheckListBoxUncheckAll.DoDoIt(const aCtx: TtfwContext); var l_aCheckListBox: TCheckListBox; begin try l_aCheckListBox := TCheckListBox(aCtx.rEngine.PopObjAs(TCheckListBox)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aCheckListBox: TCheckListBox : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except UncheckAll(aCtx, l_aCheckListBox); end;//TkwPopCheckListBoxUncheckAll.DoDoIt initialization TkwPopCheckListBoxGetChecked.RegisterInEngine; {* Регистрация pop_CheckListBox_GetChecked } TkwPopCheckListBoxSetChecked.RegisterInEngine; {* Регистрация pop_CheckListBox_SetChecked } TkwPopCheckListBoxUncheckAll.RegisterInEngine; {* Регистрация pop_CheckListBox_UncheckAll } TtfwTypeRegistrator.RegisterType(TypeInfo(TCheckListBox)); {* Регистрация типа TCheckListBox } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit GX_GrepReplace; interface uses Classes, Controls, StdCtrls, Forms, GX_GrepExpert, GX_GrepBackend, GX_BaseForm; type TfmGrepReplace = class(TfmBaseForm) lblWith: TLabel; cbReplace: TComboBox; btnOK: TButton; btnCancel: TButton; btnHelp: TButton; lblIn: TLabel; lblInString: TLabel; lblReplace: TLabel; lblReplaceString: TLabel; chkUseRegEx: TCheckBox; procedure btnHelpClick(Sender: TObject); private FGrepExpert: TGrepExpert; procedure LoadFormSettings; procedure SaveFormSettings; procedure SetSearchString(const Value: string); procedure SetReplaceInString(const Value: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RetrieveSettings(var Value: TGrepSettings); property GrepExpert: TGrepExpert read FGrepExpert; property SearchString: string write SetSearchString; property ReplaceInString: string write SetReplaceInString; end; implementation {$R *.dfm} uses SysUtils, GX_GenericUtils, GX_GxUtils, GX_GrepResults; constructor TfmGrepReplace.Create(AOwner: TComponent); begin inherited; LoadFormSettings; end; destructor TfmGrepReplace.Destroy; begin SaveFormSettings; inherited; end; procedure TfmGrepReplace.SaveFormSettings; begin AddMRUString(cbReplace.Text, FGrepExpert.ReplaceList, False); end; procedure TfmGrepReplace.LoadFormSettings; resourcestring SGrepResultsNotActive = 'The Grep Results window is not active'; begin if not Assigned(fmGrepResults) then raise Exception.Create(SGrepResultsNotActive); FGrepExpert := fmGrepResults.GrepExpert; cbReplace.Items.Assign(FGrepExpert.ReplaceList); chkUseRegEx.Checked := FGrepExpert.GrepRegEx; if cbReplace.Items.Count > 0 then begin cbReplace.Text := cbReplace.Items[0]; cbReplace.SelectAll; end; end; procedure TfmGrepReplace.RetrieveSettings(var Value: TGrepSettings); begin Value.Replace := cbReplace.Text; Value.RegEx := chkUseRegEx.Checked; end; procedure TfmGrepReplace.btnHelpClick(Sender: TObject); begin GxContextHelp(Self, 3); end; procedure TfmGrepReplace.SetSearchString(const Value: string); begin lblReplaceString.Caption := Value; end; procedure TfmGrepReplace.SetReplaceInString(const Value: string); begin lblInString.Caption := Value; end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.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 LogViewer.MessageFilter.Data; { Holds fields and criteria to filter messages on. } interface uses System.Classes, Spring, Spring.Collections, VirtualTrees, DDuce.Logger.Interfaces; type TFilterData = class private FMessageTypes : TLogMessageTypes; FCaption : string; FImageIndex : Integer; {$REGION 'property access methods'} function GetMessageTypes: TLogMessageTypes; procedure SetMessageTypes(const Value: TLogMessageTypes); function GetCaption: string; procedure SetCaption(const Value: string); function GetImageIndex: Integer; procedure SetImageIndex(const Value: Integer); {$ENDREGION} public procedure AfterConstruction; override; constructor Create( const ACaption : string; AMessageTypes : TLogMessageTypes; AImageIndex : Integer = -1 ); property MessageTypes: TLogMessageTypes read GetMessageTypes write SetMessageTypes; property Caption: string read GetCaption write SetCaption; property ImageIndex: Integer read GetImageIndex write SetImageIndex; end; implementation {$REGION 'property access methods'} procedure TFilterData.AfterConstruction; begin inherited AfterConstruction; end; constructor TFilterData.Create(const ACaption: string; AMessageTypes: TLogMessageTypes; AImageIndex: Integer); begin FMessageTypes := AMessageTypes; FCaption := ACaption; FImageIndex := AImageIndex; end; {$ENDREGION} {$REGION 'property access methods'} function TFilterData.GetCaption: string; begin Result := FCaption; end; function TFilterData.GetImageIndex: Integer; begin Result := FImageIndex; end; procedure TFilterData.SetImageIndex(const Value: Integer); begin FImageIndex := Value; end; procedure TFilterData.SetCaption(const Value: string); begin FCaption := Value; end; function TFilterData.GetMessageTypes: TLogMessageTypes; begin Result := FMessageTypes; end; procedure TFilterData.SetMessageTypes(const Value: TLogMessageTypes); begin FMessageTypes := Value; end; {$ENDREGION} end.
unit UPicasaDemo; interface uses FMX.Forms, FMX.TMSCloudBase, FMX.TMSCloudPicasa, FMX.Controls, FMX.Dialogs, FMX.Grid, FMX.Layouts, FMX.TMSCloudListView, FMX.Objects, SysUtils, FMX.TMSCloudImage, FMX.StdCtrls, FMX.Edit, System.Classes, FMX.Types, UITypes, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomGoogle, FMX.TMSCloudGoogleFMX, FMX.TMSCloudCustomPicasa; type TForm5 = class(TForm) StyleBook1: TStyleBook; TMSFMXCloudPicasa1: TTMSFMXCloudPicasa; OpenDialog1: TOpenDialog; Panel1: TPanel; btConnect: TButton; GroupBox3: TGroupBox; Label1: TLabel; edPhotoDescription: TEdit; btUpload: TButton; lvPhotos: TTMSFMXCloudListView; btDeletePhoto: TSpeedButton; btUpdatePhoto: TButton; edPhotoTags: TEdit; Label4: TLabel; lbPhotoCount: TLabel; btPrev: TButton; btNext: TButton; SaveDialog1: TSaveDialog; btDownload: TButton; edLatitude: TEdit; edLongitude: TEdit; Label6: TLabel; Label7: TLabel; Image1: TImage; edSearch: TEdit; btSearch: TButton; GroupBox2: TGroupBox; lvAlbums: TTMSFMXCloudListView; edAlbumDescription: TEdit; Label3: TLabel; Label2: TLabel; btAlbums: TButton; btCreateAlbum: TButton; btUploadFolder: TButton; edAlbumTitle: TEdit; GroupBox1: TGroupBox; TMSFMXCloudCloudImage1: TTMSFMXCloudImage; btRemove: TButton; lvComments: TTMSFMXCloudListView; TMSFMXCloudCloudImage2: TTMSFMXCloudImage; btComments: TButton; Label5: TLabel; lbAuthor: TLabel; btDeleteAlbum: TSpeedButton; procedure btConnectClick(Sender: TObject); procedure TMSFMXCloudPicasa1ReceivedAccessToken(Sender: TObject); procedure btAlbumsClick(Sender: TObject); procedure btUploadClick(Sender: TObject); procedure btCreateAlbumClick(Sender: TObject); procedure btDeleteAlbumClick(Sender: TObject); procedure btDeletePhotoClick(Sender: TObject); procedure btUpdatePhotoClick(Sender: TObject); procedure btSearchClick(Sender: TObject); procedure btNextClick(Sender: TObject); procedure btPrevClick(Sender: TObject); procedure btDownloadClick(Sender: TObject); procedure btCommentsClick(Sender: TObject); procedure btUploadFolderClick(Sender: TObject); procedure btRemoveClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lvAlbumsChange(Sender: TObject); procedure lvPhotosChange(Sender: TObject); private { Private declarations } public { Public declarations } connected: boolean; PageIndex: integer; procedure ToggleControls; procedure GetAlbums; procedure GetPhotos; procedure FillPhotos(Photos: TPicasaPhotos); procedure FillComments(Photo: TPicasaPhoto); procedure DoSearch; end; var Form5: TForm5; 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 // GAppkey = 'xxxxxxxxx'; // GAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm5.TMSFMXCloudPicasa1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudPicasa1.SaveTokens; Connected := true; ToggleControls; end; procedure TForm5.btAlbumsClick(Sender: TObject); begin GetAlbums; end; procedure TForm5.btCommentsClick(Sender: TObject); begin if lvPhotos.ItemIndex >= 0 then begin TMSFMXCloudPicasa1.GetComments(TPicasaPhoto(lvPhotos.Selected.Data)); FillComments(TPicasaPhoto(lvPhotos.Selected.Data)); end; end; procedure TForm5.btConnectClick(Sender: TObject); var acc: boolean; begin TMSFMXCloudPicasa1.App.Key := GAppkey; TMSFMXCloudPicasa1.App.Secret := GAppSecret; if TMSFMXCloudPicasa1.App.Key <> '' then begin TMSFMXCloudPicasa1.PersistTokens.Key := ExtractFilePath(Paramstr(0)) + 'picasa.ini'; TMSFMXCloudPicasa1.PersistTokens.Section := 'tokens'; TMSFMXCloudPicasa1.LoadTokens; acc := TMSFMXCloudPicasa1.TestTokens; if not acc then begin TMSFMXCloudPicasa1.RefreshAccess; TMSFMXCloudPicasa1.DoAuth; end else begin connected := true; ToggleControls; end; end else ShowMessage('Please provide a valid application ID for the client component'); end; procedure TForm5.btCreateAlbumClick(Sender: TObject); var Album: TPicasaAlbum; begin Album := TMSFMXCloudPicasa1.Albums.Add; Album.Title := edAlbumTitle.Text; Album.Summary := edAlbumDescription.Text; TMSFMXCloudPicasa1.CreateAlbum(Album); end; procedure TForm5.btUpdatePhotoClick(Sender: TObject); var Photo: TPicasaPhoto; begin if Assigned(lvAlbums.Selected) and Assigned(lvPhotos.Selected) then begin Photo := TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].Photos[lvPhotos.ItemIndex]; Photo.Summary := edPhotoDescription.Text; Photo.Tags.CommaText := edPhotoTags.Text; Photo.Latitude := StrToFloat(edLatitude.Text); Photo.Longitude := StrToFloat(edLongitude.Text); TMSFMXCloudPicasa1.UpdatePhoto(Photo); end; end; procedure TForm5.btUploadClick(Sender: TObject); begin if (OpenDialog1.Execute) and Assigned(lvAlbums.Selected) then begin TMSFMXCloudPicasa1.UploadPhoto(TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex], OpenDialog1.FileName, edPhotoDescription.Text, edPhotoTags.Text, StrToFloat(StringReplace(edLatitude.Text, '.', FormatSettings.DecimalSeparator, [rfIgnoreCase])), StrToFloat(StringReplace(edLongitude.Text, '.', FormatSettings.DecimalSeparator, [rfIgnoreCase]))); end; end; procedure TForm5.btUploadFolderClick(Sender: TObject); begin if edAlbumTitle.Text = '' then begin ShowMessage('No title set for album'); Exit; end; if (OpenDialog1.Execute) then begin TMSFMXCloudPicasa1.AddFolderToAlbum(OpenDialog1.FileName, edAlbumTitle.Text, edAlbumDescription.Text); TMSFMXCloudPicasa1.GetAlbums; end; end; procedure TForm5.FillComments(Photo: TPicasaPhoto); var I: integer; li: TListItem; begin lvComments.Items.Clear; if Photo.Comments.Count > 0 then begin for I := 0 to Photo.Comments.Count - 1 do begin li := lvComments.Items.Add; li.Data := Photo.Comments[i]; li.Text := Photo.Comments[i].Author.FullName; li.SubItems.Add(Photo.Comments[i].Text); end; end else ShowMessage('There are no comments for this photo.'); end; procedure TForm5.FillPhotos(Photos: TPicasaPhotos); var I: integer; li: TListItem; begin if Photos.Count > 0 then begin lbPhotoCount.Text := 'Results: ' + IntToStr((PageIndex * 10) + 1) + ' to ' + IntToStr((PageIndex * 10) + Photos.Count); end else lbPhotoCount.Text := 'Results: 0'; lvPhotos.Items.Clear; TMSFMXCloudCloudImage1.URL := ''; TMSFMXCloudCloudImage2.URL := ''; lbAuthor.Text := ''; for I := 0 to Photos.Count - 1 do begin li := lvPhotos.Items.Add; li.Data := Photos[i]; li.Text := Photos[i].FileName; li.SubItems.Add(Photos[i].Summary); end; end; procedure TForm5.FormCreate(Sender: TObject); begin ToggleControls; TMSFMXCloudPicasa1.Albums.Clear; btPrev.Enabled := false; btNext.Enabled := false; lvAlbums.ColumnByIndex(1).Width := 300; lvPhotos.ColumnByIndex(1).Width := 300; lvComments.ColumnByIndex(1).Width := 180; end; procedure TForm5.GetAlbums; var I: Integer; li: TListItem; begin TMSFMXCloudPicasa1.Albums.Clear; TMSFMXCloudPicasa1.GetAlbums; lvAlbums.Items.Clear; for I := 0 to TMSFMXCloudPicasa1.Albums.Count - 1 do begin li := lvAlbums.Items.Add; li.Data := TMSFMXCloudPicasa1.Albums[i]; li.Text := TMSFMXCloudPicasa1.Albums[i].Title; li.SubItems.Add(TMSFMXCloudPicasa1.Albums[i].Summary); end; end; procedure TForm5.GetPhotos; begin if lvAlbums.ItemIndex >= 0 then begin TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].Photos.Clear; TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].GetPhotos; FillPhotos(TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].Photos); end; end; procedure TForm5.lvAlbumsChange(Sender: TObject); begin if Assigned(lvAlbums.Selected) then begin edAlbumTitle.Text := TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].Title; edAlbumDescription.Text := TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].Summary; TMSFMXCloudCloudImage2.URL := ''; edPhotoDescription.Text := ''; edPhotoTags.Text := ''; GetPhotos; TMSFMXCloudCloudImage1.URL := TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].ImageURL; end; end; procedure TForm5.lvPhotosChange(Sender: TObject); var pic: TPicasaPhoto; begin if lvPhotos.ItemIndex >= 0 then begin pic := TPicasaPhoto(lvPhotos.Selected.Data); edPhotoDescription.Text := pic.Summary; edPhotoTags.Text := pic.Tags.CommaText; edLatitude.Text := FloatToStr(pic.Latitude); edLongitude.Text := FloatToStr(pic.Longitude); TMSFMXCloudCloudImage1.URL := ''; TMSFMXCloudCloudImage2.URL := ''; TMSFMXCloudCloudImage1.URL := pic.ImageURL; TMSFMXCloudCloudImage2.URL := pic.ThumbnailURL; lbAuthor.Text := 'Author: ' + pic.Author.NickName; lvComments.Items.Clear; end; end; procedure TForm5.btDeleteAlbumClick(Sender: TObject); var buttonSelected: integer; begin if Assigned(lvAlbums.Selected) then begin buttonSelected := MessageDlg('Are you sure you want to delete the selected album?', TMsgDlgType.mtConfirmation, mbOKCancel, 0); if buttonSelected = mrOk then begin lvPhotos.Items.Clear; TMSFMXCloudCloudImage1.URL := ''; TMSFMXCloudCloudImage2.URL := ''; TMSFMXCloudPicasa1.DeleteAlbum(TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex]); GetAlbums; end; end else begin ShowMessage('No album selected.'); end; end; procedure TForm5.btDeletePhotoClick(Sender: TObject); var buttonSelected: integer; begin if Assigned(lvAlbums.Selected) and Assigned(lvPhotos.Selected) then begin buttonSelected := MessageDlg('Are you sure you want to delete the selected photo?', TMsgDlgType.mtConfirmation, mbOKCancel, 0); if buttonSelected = mrOk then begin TMSFMXCloudCloudImage1.URL := ''; TMSFMXCloudCloudImage2.URL := ''; TMSFMXCloudPicasa1.DeletePhoto(TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].Photos[lvPhotos.ItemIndex]); GetPhotos; end; end else begin ShowMessage('No photo selected.'); end; end; procedure TForm5.btDownloadClick(Sender: TObject); var ph: TPicasaPhoto; begin if Assigned(lvPhotos.Selected) then begin ph := TPicasaPhoto(lvPhotos.Selected.Data); SaveDialog1.FileName := ph.FileName; if (SaveDialog1.Execute) then TMSFMXCloudPicasa1.DownloadPhoto(SaveDialog1.FileName, ph); end; end; procedure TForm5.btNextClick(Sender: TObject); begin PageIndex := PageIndex + 1; btPrev.Enabled := true; DoSearch; end; procedure TForm5.btPrevClick(Sender: TObject); begin if PageIndex > 0 then begin PageIndex := PageIndex - 1; if PageIndex = 0 then btPrev.Enabled := false; DoSearch; end end; procedure TForm5.btRemoveClick(Sender: TObject); begin TMSFMXCloudPicasa1.ClearTokens; Connected := false; ToggleControls; end; procedure TForm5.btSearchClick(Sender: TObject); begin if edSearch.Text <> '' then begin PageIndex := 0; btPrev.Enabled := false; DoSearch; end; end; procedure TForm5.DoSearch; var EnableNextButton: boolean; begin TMSFMXCloudPicasa1.SearchPhotos(edSearch.Text, EnableNextButton, PageIndex); FillPhotos(TMSFMXCloudPicasa1.SearchResults); btNext.Enabled := EnableNextButton; end; procedure TForm5.ToggleControls; begin btConnect.Enabled := not connected; btRemove.Enabled := connected; btUpload.Enabled := connected; btDeletePhoto.Enabled := connected; btUpdatePhoto.Enabled := connected; btDownload.Enabled := connected; btSearch.Enabled := connected; btAlbums.Enabled := connected; btCreateAlbum.Enabled := connected; btDeleteAlbum.Enabled := connected; btUploadFolder.Enabled := connected; btComments.Enabled := connected; edPhotoDescription.Enabled := connected; edPhotoTags.Enabled := connected; edLatitude.Enabled := connected; edLongitude.Enabled := connected; edSearch.Enabled := connected; edAlbumDescription.Enabled := connected; edAlbumTitle.Enabled := connected; lvPhotos.Enabled := connected; lvAlbums.Enabled := connected; lvComments.Enabled := connected; end; end.