text
stringlengths
14
6.51M
{ Batch NIF to JSON and JSON to NIF Converter Performs conversion of NIF files to JSON and vice versa in specified directory including subdirectories. Keep in mind that reconstructed (from json) NIF files won't be binary identical to the source nifs because of floating values rounding when converting to text and back. You can increase precision by setting larger number of FP decimal digits if needed. Saving a nif file also does minor automatic sanitizations (collapsing array links and removing unused string) which also could lead to binary differences and changed files sizes. Some fields are automatically updated when saving a nif and there is no point in changing them in json, including: - NiHeader Block Types, Block Types Index, Block Sizes and Strings - fields containing "Data Size" in name Supports all game NIF formats starting from Morrowind. } unit NifBatchJsonConverter; const bJsonCompact = False; // True to save Json files without formatting //============================================================================ procedure Convert(aPath: string; aDigits: integer); var TDirectory: TDirectory; // to access member functions i, d: integer; Nif: TwbNifFile; files: TStringDynArray; f, ext: string; begin if aPath = '' then Exit; d := dfFloatDecimalDigits; dfFloatDecimalDigits := aDigits; Nif := TwbNifFile.Create; try files := TDirectory.GetFiles(aPath, '*.*', soAllDirectories); AddMessage('Processing files in "' + aPath + '", press and hold ESC to abort...'); for i := 0 to Pred(Length(files)) do begin f := files[i]; ext := ExtractFileExt(f); // break the files processing loop if Escape is pressed if GetKeyState(VK_ESCAPE) and 128 = 128 then Break; if SameText(ext, '.nif') then begin AddMessage('Converting to Json: ' + f); Nif.LoadFromFile(files[i]); Nif.SaveToJsonFile(ChangeFileExt(f, '.json'), bJsonCompact); end else if SameText(ext, '.json') then begin AddMessage('Converting to Nif: ' + f); Nif.LoadFromJsonFile(files[i]); Nif.SaveToFile(ChangeFileExt(f, '.nif')); end end; finally Nif.Free; dfFloatDecimalDigits := d; end; end; //============================================================================ procedure btnSrcClick(Sender: TObject); var edSrc: TLabeledEdit; s: string; begin edSrc := TLabeledEdit(TForm(Sender.Parent).FindComponent('edSrc')); s := SelectDirectory('Select a directory', '', edSrc.Text, nil); if s <> '' then edSrc.Text := s; end; //============================================================================ function Initialize: Integer; var frm: TForm; edSrc: TLabeledEdit; btnOk, btnCancel, btnSrc: TButton; lbl: TLabel; cmbDigits: TComboBox; pnl: TPanel; i: integer; begin frm := TForm.Create(nil); try frm.Caption := 'Batch JSON Converter'; frm.Width := 500; frm.Height := 190; frm.Position := poMainFormCenter; frm.BorderStyle := bsDialog; edSrc := TLabeledEdit.Create(frm); edSrc.Parent := frm; edSrc.Name := 'edSrc'; edSrc.Left := 12; edSrc.Top := 24; edSrc.Width := frm.Width - 70; edSrc.LabelPosition := lpAbove; edSrc.EditLabel.Caption := 'Source folder with *.nif or *.json files'; edSrc.Text := wbDataPath; btnSrc := TButton.Create(frm); btnSrc.Parent := frm; btnSrc.Top := edSrc.Top - 1; btnSrc.Left := edSrc.Left + edSrc.Width + 6; btnSrc.Width := 32; btnSrc.Height := 22; btnSrc.Caption := '...'; btnSrc.OnClick := btnSrcClick; lbl := TLabel.Create(frm); lbl.Parent := frm; lbl.Left := edSrc.Left; lbl.Top := edSrc.Top + 32; lbl.Caption := 'Json floating values decimal digits'; cmbDigits := TComboBox.Create(frm); cmbDigits.Parent := frm; cmbDigits.Left := edSrc.Left; cmbDigits.Top := lbl.Top + 18; cmbDigits.Width := 40; cmbDigits.Style := csDropDownList; cmbDigits.DropDownCount := 12; for i := dfFloatDecimalDigits to dfFloatDecimalDigits + 10 do cmbDigits.Items.Add(IntToStr(i)); cmbDigits.ItemIndex := 0; btnOk := TButton.Create(frm); btnOk.Parent := frm; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnOk.Left := frm.Width - 176; btnOk.Top := frm.Height - 62; btnCancel := TButton.Create(frm); btnCancel.Parent := frm; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := btnOk.Left + btnOk.Width + 8; btnCancel.Top := btnOk.Top; pnl := TPanel.Create(frm); pnl.Parent := frm; pnl.Left := 8; pnl.Top := btnOk.Top - 12; pnl.Width := frm.Width - 20; pnl.Height := 2; if frm.ShowModal = mrOk then if edSrc.Text <> '' then Convert( edSrc.Text, StrToInt(cmbDigits.Text) ); finally frm.Free; end; Result := 1; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2023, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Systems.Scene3DGroup; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses SysUtils,Classes,PasMP, PasVulkan.Application, PasVulkan.Framework, PasVulkan.Types, PasVulkan.Math, PasVulkan.PooledObject, PasVulkan.EntityComponentSystem.BaseComponents, PasVulkan.EntityComponentSystem, PasVulkan.Utils; type TpvSystemScene3DGroup=class; TpvSystemScene3DGroupEntityTransform=class private fMatrix:TpvMatrix4x4; fStatic:boolean; public constructor Create; destructor Destroy; override; procedure Assign(const aFrom:TpvSystemScene3DGroupEntityTransform); reintroduce; procedure InterpolateFrom(const aFromA,aFromB:TpvSystemScene3DGroupEntityTransform;const aStateInterpolation:TpvFloat); property Matrix:TpvMatrix4x4 read fMatrix write fMatrix; property Static:boolean read fStatic write fStatic; end; TpvSystemScene3DGroupEntity=class(TpvPooledObject) private fRenderer:TpvSystemScene3DGroup; fEntityID:TpvEntityID; fSeen:longbool; fDeleted:longbool; fTransform:TpvSystemScene3DGroupEntityTransform; public constructor Create(const aRenderer:TpvSystemScene3DGroup;const aEntityID:TpvEntityID); destructor Destroy; override; procedure Clear; procedure Assign(const aFrom:TpvSystemScene3DGroupEntity); reintroduce; procedure Interpolate(const aFromA,aFromB:TpvSystemScene3DGroupEntity;const aStateInterpolation:TpvFloat); property Render:TpvSystemScene3DGroup read fRenderer; property EntityID:TpvEntityID read fEntityID; property Seen:longbool read fSeen write fSeen; property Deleted:longbool read fDeleted write fDeleted; end; TpvSystemScene3DGroupEntityArray=array of TpvSystemScene3DGroupEntity; TpvSystemScene3DGroupEntities=class private fRenderer:TpvSystemScene3DGroup; fEntities:TpvSystemScene3DGroupEntityArray; fCriticalSection:TPasMPCriticalSection; function GetMaxEntityID:TpvEntityID; function GetEntity(const aEntityID:TpvEntityID):TpvSystemScene3DGroupEntity; inline; procedure SetEntity(const aEntityID:TpvEntityID;const aEntity:TpvSystemScene3DGroupEntity); inline; public constructor Create(const aRenderer:TpvSystemScene3DGroup); destructor Destroy; override; procedure Clear; property Entities[const pEntityID:TpvEntityID]:TpvSystemScene3DGroupEntity read GetEntity write SetEntity; default; property MaxEntityID:TpvEntityID read GetMaxEntityID; end; TpvSystemScene3DGroup=class(TpvSystem) private fPasMP:TPasMP; // fRenderer:TRenderer; fComponentTransformClassDataWrapper:TpvComponentClassDataWrapper; fComponentTransformClassID:TpvComponentClassID; fLastEntities:TpvSystemScene3DGroupEntities; fCurrentEntities:TpvSystemScene3DGroupEntities; fRenderableEntities:array[0..MaxInFlightFrames-1] of TpvSystemScene3DGroupEntities; fCurrentRenderableEntities:TpvSystemScene3DGroupEntities; fLastEntityIDs:TpvSystemEntityIDs; fCurrentEntityIDs:TpvSystemEntityIDs; fRenderableEntityIDs:array[0..MaxInFlightFrames-1] of TpvSystemEntityIDs; fLastRenderableEntityIDs:TpvSystemEntityIDs; fCurrentRenderableEntityIDs:TpvSystemEntityIDs; fStateInterpolation:TpvFloat; procedure FinalizeUpdateLastParallelForJobFunction(const aJob:PPasMPJob;const aThreadIndex:TPasMPInt32;const aData:pointer;const aFromIndex,aToIndex:TPasMPNativeInt); procedure FinalizeUpdateCurrentParallelForJobFunction(const aJob:PPasMPJob;const aThreadIndex:TPasMPInt32;const aData:pointer;const aFromIndex,aToIndex:TPasMPNativeInt); procedure PrepareRenderCurrentParallelForJobFunction(const aJob:PPasMPJob;const aThreadIndex:TPasMPInt32;const aData:pointer;const aFromIndex,aToIndex:TPasMPNativeInt); procedure PrepareRenderLastParallelForJobFunction(const aJob:PPasMPJob;const aThreadIndex:TPasMPInt32;const aData:pointer;const aFromIndex,aToIndex:TPasMPNativeInt); public constructor Create(const AWorld:TpvWorld); override; destructor Destroy; override; procedure Added; override; procedure Removed; override; function AddEntityToSystem(const aEntityID:TpvEntityID):boolean; override; function RemoveEntityFromSystem(const aEntityID:TpvEntityID):boolean; override; procedure ProcessEvent(const aEvent:TpvEvent); override; procedure InitializeUpdate; override; procedure UpdateEntities(const aFirstEntityIndex,aLastEntityIndex:TpvInt32); override; procedure FinalizeUpdate; override; procedure PrepareRender(const aPrepareInFlightFrameIndex:TpvInt32;const aStateInterpolation:TpvFloat); procedure Render(const aInFlightFrameIndex:TpvInt32); end; implementation uses PasVulkan.Components.Scene3DGroup, PasVulkan.Components.Transform; constructor TpvSystemScene3DGroupEntityTransform.Create; begin inherited Create; end; destructor TpvSystemScene3DGroupEntityTransform.Destroy; begin inherited Destroy; end; procedure TpvSystemScene3DGroupEntityTransform.Assign(const aFrom:TpvSystemScene3DGroupEntityTransform); begin fMatrix:=aFrom.fMatrix; fStatic:=aFrom.fStatic; end; procedure TpvSystemScene3DGroupEntityTransform.InterpolateFrom(const aFromA,aFromB:TpvSystemScene3DGroupEntityTransform;const aStateInterpolation:TpvFloat); begin fMatrix:=aFromA.fMatrix.Slerp(aFromB.fMatrix,aStateInterpolation); fStatic:=aFromB.fStatic; end; constructor TpvSystemScene3DGroupEntity.Create(const aRenderer:TpvSystemScene3DGroup;const aEntityID:TpvEntityID); begin inherited Create; fRenderer:=aRenderer; fEntityID:=aEntityID; fSeen:=true; fDeleted:=false; fTransform:=nil; end; destructor TpvSystemScene3DGroupEntity.Destroy; begin fTransform.Free; inherited Destroy; end; procedure TpvSystemScene3DGroupEntity.Clear; begin FreeAndNil(fTransform); end; procedure TpvSystemScene3DGroupEntity.Assign(const aFrom:TpvSystemScene3DGroupEntity); begin begin if assigned(aFrom.fTransform) then begin if not assigned(fTransform) then begin fTransform:=TpvSystemScene3DGroupEntityTransform.Create; end; fTransform.Assign(aFrom.fTransform); end else if assigned(fTransform) then begin FreeAndNil(fTransform); end; end; end; procedure TpvSystemScene3DGroupEntity.Interpolate(const aFromA,aFromB:TpvSystemScene3DGroupEntity;const aStateInterpolation:TpvFloat); begin begin if assigned(aFromB.fTransform) then begin if not assigned(fTransform) then begin fTransform:=TpvSystemScene3DGroupEntityTransform.Create; end; if assigned(aFromA.fTransform) and assigned(aFromB.fTransform) then begin fTransform.InterpolateFrom(aFromA.fTransform,aFromB.fTransform,aStateInterpolation); end else begin fTransform.Assign(aFromB.fTransform); end; end else if assigned(fTransform) then begin FreeAndNil(fTransform); end; end; end; constructor TpvSystemScene3DGroupEntities.Create(const aRenderer:TpvSystemScene3DGroup); var Index:TpvInt32; begin inherited Create; fRenderer:=aRenderer; fEntities:=nil; SetLength(fEntities,4096); for Index:=0 to length(fEntities)-1 do begin fEntities[Index]:=nil; end; fCriticalSection:=TPasMPCriticalSection.Create; end; destructor TpvSystemScene3DGroupEntities.Destroy; begin Clear; SetLength(fEntities,0); fCriticalSection.Free; inherited Destroy; end; procedure TpvSystemScene3DGroupEntities.Clear; var Index:TpvInt32; begin for Index:=0 to length(fEntities)-1 do begin FreeAndNil(fEntities[Index]); end; end; function TpvSystemScene3DGroupEntities.GetMaxEntityID:TpvEntityID; begin result:=length(fEntities)-1; end; function TpvSystemScene3DGroupEntities.GetEntity(const aEntityID:TpvEntityID):TpvSystemScene3DGroupEntity; begin if (aEntityID>=0) and (aEntityID<length(fEntities)) then begin result:=fEntities[aEntityID]; end else begin result:=nil; end; end; procedure TpvSystemScene3DGroupEntities.SetEntity(const aEntityID:TpvEntityID;const aEntity:TpvSystemScene3DGroupEntity); var Index,Old:TpvInt32; begin if aEntityID>=0 then begin if length(fEntities)<=aEntityID then begin fCriticalSection.Acquire; try Old:=length(fEntities); if Old<=aEntityID then begin SetLength(fEntities,(aEntityID+1)*2); for Index:=Old to length(fEntities)-1 do begin fEntities[Index]:=nil; end; end; finally fCriticalSection.Release; end; end; fEntities[aEntityID]:=aEntity; end; end; constructor TpvSystemScene3DGroup.Create(const AWorld:TpvWorld); var Index:TpvInt32; begin inherited Create(AWorld); fPasMP:=pvApplication.PasMPInstance; AddRequiredComponent(TpvComponentScene3DGroup); fLastEntities:=TpvSystemScene3DGroupEntities.Create(self); fCurrentEntities:=TpvSystemScene3DGroupEntities.Create(self); for Index:=low(fRenderableEntities) to high(fRenderableEntities) do begin fRenderableEntities[Index]:=TpvSystemScene3DGroupEntities.Create(self); end; fLastEntityIDs:=TpvSystemEntityIDs.Create; fCurrentEntityIDs:=TpvSystemEntityIDs.Create; for Index:=low(fRenderableEntityIDs) to high(fRenderableEntityIDs) do begin fRenderableEntityIDs[Index]:=TpvSystemEntityIDs.Create; end; fLastRenderableEntityIDs:=TpvSystemEntityIDs.Create; Flags:=(Flags+[TpvSystem.TSystemFlag.ParallelProcessing])-[TpvSystem.TSystemFlag.Secluded]; EntityGranularity:=1024; fComponentTransformClassDataWrapper:=World.Components[TpvComponentTransform]; fComponentTransformClassID:=World.Universe.RegisteredComponentClasses.ComponentIDs[TpvComponentTransform]; end; destructor TpvSystemScene3DGroup.Destroy; var Index:TpvInt32; begin fLastEntities.Free; fCurrentEntities.Free; for Index:=low(fRenderableEntities) to high(fRenderableEntities) do begin FreeAndNil(fRenderableEntities[Index]); end; fLastEntityIDs.Free; fCurrentEntityIDs.Free; for Index:=low(fRenderableEntityIDs) to high(fRenderableEntityIDs) do begin FreeAndNil(fRenderableEntityIDs[Index]); end; FreeAndNil(fLastRenderableEntityIDs); inherited Destroy; end; procedure TpvSystemScene3DGroup.Added; begin inherited Added; end; procedure TpvSystemScene3DGroup.Removed; begin inherited Removed; end; function TpvSystemScene3DGroup.AddEntityToSystem(const aEntityID:TpvEntityID):boolean; begin result:=inherited AddEntityToSystem(aEntityID); end; function TpvSystemScene3DGroup.RemoveEntityFromSystem(const aEntityID:TpvEntityID):boolean; begin result:=inherited RemoveEntityFromSystem(aEntityID); end; procedure TpvSystemScene3DGroup.ProcessEvent(const aEvent:TpvEvent); begin end; procedure TpvSystemScene3DGroup.InitializeUpdate; var TempEntities:TpvSystemScene3DGroupEntities; TempEntityIDs:TpvSystemEntityIDs; begin TempEntities:=fLastEntities; fLastEntities:=fCurrentEntities; fCurrentEntities:=TempEntities; TempEntityIDs:=fLastEntityIDs; fLastEntityIDs:=fCurrentEntityIDs; fCurrentEntityIDs:=TempEntityIDs; fCurrentEntityIDs.Assign(EntityIDs); inherited InitializeUpdate; end; procedure TpvSystemScene3DGroup.UpdateEntities(const aFirstEntityIndex,aLastEntityIndex:TpvInt32); var Index:TpvInt32; EntityID:TpvEntityID; Entity:TpvEntity; pvSystemScene3DGroupEntity:TpvSystemScene3DGroupEntity; ComponentTransform:TpvComponentTransform; EntityTransform:TpvSystemScene3DGroupEntityTransform; begin for Index:=aFirstEntityIndex to aLastEntityIndex do begin EntityID:=EntityIDs[Index]; Entity:=Entities[Index]; pvSystemScene3DGroupEntity:=fCurrentEntities.Entities[EntityID]; if not assigned(pvSystemScene3DGroupEntity) then begin pvSystemScene3DGroupEntity:=TpvSystemScene3DGroupEntity.Create(self,EntityID); fCurrentEntities.Entities[EntityID]:=pvSystemScene3DGroupEntity; end; begin ComponentTransform:=TpvComponentTransform(Entity.ComponentByClassID[fComponentTransformClassID]); if assigned(ComponentTransform) then begin if not assigned(pvSystemScene3DGroupEntity.fTransform) then begin pvSystemScene3DGroupEntity.fTransform:=TpvSystemScene3DGroupEntityTransform.Create; end; EntityTransform:=pvSystemScene3DGroupEntity.fTransform; EntityTransform.fMatrix:=ComponentTransform.RawMatrix; EntityTransform.fStatic:=TpvComponentTransformFlag.Static in ComponentTransform.Flags; end else begin if assigned(pvSystemScene3DGroupEntity.fTransform) then begin FreeAndNil(pvSystemScene3DGroupEntity.fTransform); end; end; end; pvSystemScene3DGroupEntity.Seen:=true; end; inherited UpdateEntities(aFirstEntityIndex,aLastEntityIndex); end; procedure TpvSystemScene3DGroup.FinalizeUpdateLastParallelForJobFunction(const aJob:PPasMPJob;const aThreadIndex:TPasMPInt32;const aData:pointer;const aFromIndex,aToIndex:TPasMPNativeInt); var EntityIndex:TpvInt32; EntityID:TpvEntityID; CurrentpvSystemScene3DGroupEntity:TpvSystemScene3DGroupEntity; begin for EntityIndex:=aFromIndex downto aToIndex do begin EntityID:=fLastEntityIDs[EntityIndex]; CurrentpvSystemScene3DGroupEntity:=fCurrentEntities.Entities[EntityID]; if assigned(CurrentpvSystemScene3DGroupEntity) and not CurrentpvSystemScene3DGroupEntity.Seen then begin CurrentpvSystemScene3DGroupEntity.Free; fCurrentEntities.Entities[EntityID]:=nil; end; end; end; procedure TpvSystemScene3DGroup.FinalizeUpdateCurrentParallelForJobFunction(const aJob:PPasMPJob;const aThreadIndex:TPasMPInt32;const aData:pointer;const aFromIndex,aToIndex:TPasMPNativeInt); var EntityIndex:TpvInt32; EntityID:TpvEntityID; CurrentpvSystemScene3DGroupEntity:TpvSystemScene3DGroupEntity; begin for EntityIndex:=aFromIndex downto aToIndex do begin EntityID:=fCurrentEntityIDs[EntityIndex]; CurrentpvSystemScene3DGroupEntity:=fCurrentEntities.Entities[EntityID]; if assigned(CurrentpvSystemScene3DGroupEntity) then begin CurrentpvSystemScene3DGroupEntity.Seen:=false; end; end; end; procedure TpvSystemScene3DGroup.FinalizeUpdate; begin fPasMP.ParallelFor(nil,0,fLastEntityIDs.Count-1,FinalizeUpdateLastParallelForJobFunction,1024); fPasMP.ParallelFor(nil,0,fCurrentEntityIDs.Count-1,FinalizeUpdateCurrentParallelForJobFunction,1024); inherited FinalizeUpdate; end; procedure TpvSystemScene3DGroup.PrepareRenderCurrentParallelForJobFunction(const aJob:PPasMPJob;const aThreadIndex:TPasMPInt32;const aData:pointer;const aFromIndex,aToIndex:TPasMPNativeInt); var EntityIndex:TpvInt32; EntityID:TpvEntityID; RenderableScene3DGroupEntity:TpvSystemScene3DGroupEntity; LastpvSystemScene3DGroupEntity:TpvSystemScene3DGroupEntity; CurrentScene3DGroupEntity:TpvSystemScene3DGroupEntity; RenderableEntities:TpvSystemScene3DGroupEntities; begin RenderableEntities:=fCurrentRenderableEntities; for EntityIndex:=aFromIndex to aToIndex do begin EntityID:=fCurrentRenderableEntityIDs[EntityIndex]; RenderableScene3DGroupEntity:=RenderableEntities.Entities[EntityID]; LastpvSystemScene3DGroupEntity:=fLastEntities.Entities[EntityID]; CurrentScene3DGroupEntity:=fCurrentEntities.Entities[EntityID]; if assigned(CurrentScene3DGroupEntity) then begin if not assigned(RenderableScene3DGroupEntity) then begin RenderableScene3DGroupEntity:=TpvSystemScene3DGroupEntity.Create(self,EntityID); RenderableEntities.Entities[EntityID]:=RenderableScene3DGroupEntity; end; if assigned(LastpvSystemScene3DGroupEntity) then begin RenderableScene3DGroupEntity.Interpolate(LastpvSystemScene3DGroupEntity, CurrentScene3DGroupEntity, fStateInterpolation); end else begin RenderableScene3DGroupEntity.Assign(CurrentScene3DGroupEntity); end; RenderableScene3DGroupEntity.Seen:=true; RenderableScene3DGroupEntity.Deleted:=false; end; end; end; procedure TpvSystemScene3DGroup.PrepareRenderLastParallelForJobFunction(const aJob:PPasMPJob;const aThreadIndex:TPasMPInt32;const aData:pointer;const aFromIndex,aToIndex:TPasMPNativeInt); var EntityIndex:TpvInt32; EntityID:TpvEntityID; RenderableScene3DGroupEntity:TpvSystemScene3DGroupEntity; RenderableEntities:TpvSystemScene3DGroupEntities; begin RenderableEntities:=fCurrentRenderableEntities; for EntityIndex:=aFromIndex to aToIndex do begin EntityID:=fLastRenderableEntityIDs[EntityIndex]; RenderableScene3DGroupEntity:=RenderableEntities.Entities[EntityID]; if assigned(RenderableScene3DGroupEntity) then begin if RenderableScene3DGroupEntity.Seen then begin RenderableScene3DGroupEntity.Seen:=false; end else begin RenderableScene3DGroupEntity.Free; RenderableEntities.Entities[EntityID]:=nil; end; end; end; end; procedure TpvSystemScene3DGroup.PrepareRender(const aPrepareInFlightFrameIndex:TpvInt32;const aStateInterpolation:TpvFloat); begin fCurrentRenderableEntities:=fRenderableEntities[aPrepareInFlightFrameIndex]; fCurrentRenderableEntityIDs:=fRenderableEntityIDs[aPrepareInFlightFrameIndex]; fStateInterpolation:=aStateInterpolation; fLastRenderableEntityIDs.Assign(fCurrentRenderableEntityIDs); fCurrentRenderableEntityIDs.Assign(fCurrentEntityIDs); fPasMP.ParallelFor(nil,0,fCurrentRenderableEntityIDs.Count-1,PrepareRenderCurrentParallelForJobFunction,1024); fPasMP.ParallelFor(nil,0,fLastRenderableEntityIDs.Count-1,PrepareRenderLastParallelForJobFunction,1024); end; procedure TpvSystemScene3DGroup.Render(const aInFlightFrameIndex:TpvInt32); begin end; initialization end.
unit database_lib; {$mode objfpc}{$H+} {$include ../../define.inc} interface uses {$ifdef GREYHOUND} ghSQL, ghSQLdbLib, {$endif} fpcgi, fphttp, db, fpjson, jsonparser, fgl, sqldb, sqldblib, mysql50conn, mysql51conn, mysql55conn, mysql56conn, sqlite3conn, pqconnection, variants, Classes, SysUtils; type generic TStringHashMap<T> = class(specialize TFPGMap<String,T>) end; TFieldValueMap = specialize TStringHashMap<variant>; { TSimpleModel } TSimpleModel = class private FConnector : TSQLConnector; FFieldList : TStrings; FTableName : string; FGroupField : string; FSelectField : string; FJoinList : TStrings; primaryKeyValue : string; FGenFields : TStringList; function GetEOF: boolean; function GetRecordCount: Longint; function GetTablePrefix: string; procedure _queryPrepare; function _queryOpen:boolean; procedure DoAfterOpen(DataSet: TDataSet); procedure DoBeforeOpen(DataSet: TDataSet); function getFieldList_mysql: TStrings; function getFieldList_sqlite: TStrings; function getFieldList_postgresql: TStrings; function GetFieldList: TStrings; function GetFieldValue( FieldName: String): Variant; procedure SetFieldValue( FieldName: String; AValue: Variant); public FieldValueMap : TFieldValueMap; primaryKey : string; Data : TSQLQuery; StartTime, StopTime, ElapsedTime : Cardinal; constructor Create( const DefaultTableName:string=''; const pPrimaryKey:string=''); destructor Destroy; override; property TableName : string Read FTableName write FTableName; property TablePrefix : string read GetTablePrefix; Property Value[ FieldName: String] : Variant Read GetFieldValue Write SetFieldValue; default; Property FieldLists: TStrings Read GetFieldList; property RecordCount: Longint read GetRecordCount; property EOF: boolean read GetEOF; function ParamByName(Const AParamName : String) : TParam; function All:boolean; function GetAll:boolean; //function Get( where, order):boolean; function Find( const KeyIndex:integer):boolean; function Find( const KeyIndex:String):boolean; function Find( const Where:array of string; const Order:string = ''; const Limit:integer = 0; const CustomField:string=''):boolean; function FindFirst( const Where:array of string; const Order:string = ''; const CustomField:string=''):boolean; procedure AddJoin( const JoinTable:string; const JoinField:string; const RefField: string; const FieldNameList:array of string); procedure AddLeftJoin( const JoinTable:string; const JoinField:string; const RefField: string; const FieldNameList:array of string); procedure AddInnerJoin( const JoinTable:string; const JoinField:string; const RefField: string; const FieldNameList:array of string); procedure AddCustomJoin( const JointType:string; const JoinTable:string; const JoinField:string; const RefField: string; const FieldNameList:array of string); procedure GroupBy( const GroupField:string); procedure Clear; procedure New; function Save( Where:string='';AutoCommit:boolean=True):boolean; function Delete( Where:string='';AutoCommit:boolean=True):boolean; procedure Next; procedure StartTransaction; procedure ReStartTransaction; procedure Commit; procedure CommitRetaining; procedure Rollback; procedure RollbackRetaining; end; procedure DataBaseInit( const RedirecURL:string = ''); function QueryOpenToJson( SQL: string; var ResultJSON: TJSONObject): boolean; function QueryExecToJson( SQL: string; var ResultJSON: TJSONObject): boolean; function DataToJSON( Data : TSQLQuery; var ResultJSON: TJSONArray):boolean; implementation uses common, config_lib, fastplaz_handler, logutil_lib; var DB_Connector : TSQLConnector; DB_Transaction : TSQLTransaction; DB_LibLoader : TSQLDBLibraryLoader; DB_Connector_Write : TSQLConnector; DB_Transaction_Write : TSQLTransaction; DB_LibLoader_Write : TSQLDBLibraryLoader; procedure DataBaseInit(const RedirecURL: string); var s : string; begin AppData.useDatabase := True; // multidb - prepare AppData.databaseRead := Config.GetValue( _DATABASE_OPTIONS_READ, 'default'); AppData.databaseWrite := Config.GetValue( _DATABASE_OPTIONS_WRITE, AppData.databaseRead); AppData.tablePrefix := Config.GetValue( format( _DATABASE_TABLE_PREFIX, [AppData.databaseRead]), ''); // currentdirectory mesti dipindah s := GetCurrentDir + DirectorySeparator + string( Config.GetValue( format( _DATABASE_LIBRARY, [AppData.databaseRead]), '')); if not SetCurrentDir( ExtractFilePath( s)) then begin DisplayError( Format(_ERR_DATABASE_LIBRARY_NOT_EXIST, [ AppData.databaseRead, s])); end; s := GetCurrentDir + DirectorySeparator + ExtractFileName( string( Config.GetValue( format( _DATABASE_LIBRARY, [AppData.databaseRead]), ''))); if not FileExists( s) then begin SetCurrentDir(ExtractFilePath(Application.ExeName)); DisplayError( Format(_ERR_DATABASE_LIBRARY_NOT_EXIST, [ AppData.databaseRead, s])); end; if Config.GetValue( format( _DATABASE_LIBRARY, [AppData.databaseRead]), '') <> '' then begin try DB_LibLoader.ConnectionType:= string( Config.GetValue( format( _DATABASE_DRIVER, [AppData.databaseRead]), '')); DB_LibLoader.LibraryName:= s; DB_LibLoader.Enabled:= True; DB_LibLoader.LoadLibrary; except on E: Exception do begin if RedirecURL = '' then //TODO: check if database library cannot loaded DisplayError( 'Database Init: Load Library, ' + E.Message) else Redirect( RedirecURL); end; end; end; // back to app directory SetCurrentDir(ExtractFilePath(Application.ExeName)); DB_Connector.HostName:= string( Config.GetValue( format( _DATABASE_HOSTNAME, [AppData.databaseRead]), 'localhost')); DB_Connector.ConnectorType := string( Config.GetValue( format( _DATABASE_DRIVER, [AppData.databaseRead]), '')); DB_Connector.UserName:= string( Config.GetValue( format( _DATABASE_USERNAME, [AppData.databaseRead]), '')); DB_Connector.Password:= string( Config.GetValue( format( _DATABASE_PASSWORD, [AppData.databaseRead]), '')); DB_Connector.DatabaseName:= string( Config.GetValue( format( _DATABASE_DATABASENAME, [AppData.databaseRead]), 'test')); if Config.GetValue( format( _DATABASE_PORT, [AppData.databaseRead]), '') <> '' then DB_Connector.Params.Values['port'] := string( Config.GetValue( format( _DATABASE_PORT, [AppData.databaseRead]), '')); //tabletype := Config.GetValue( _DATABASE_TABLETYPE, ''); //log database try DB_Connector.Open; AppData.databaseActive := True; except on E: Exception do begin if RedirecURL = '' then begin DisplayError( 'Database Error: '+ E.Message) end else Redirect( RedirecURL); end; end; end; function QueryOpenToJson(SQL: string; var ResultJSON: TJSONObject): boolean; var q : TSQLQuery; data : TJSONArray; begin Result := False; q := TSQLQuery.Create(nil); q.UniDirectional:=True; q.DataBase := DB_Connector; q.SQL.Text:= SQL; try q.Open; data := TJSONArray.Create(); DataToJSON( q, data); //ResultJSON.Add( 'count', q.RowsAffected); ResultJSON.Add( 'count', data.Count); ResultJSON.Add( 'data', data); Result := True; except on E: Exception do begin ResultJSON.Add( 'msg', E.Message); end; end; {$ifdef debug} ResultJSON.Add( 'sql', SQL); {$endif} FreeAndNil( q); end; function DatabaseSecond_Prepare( const ConnectionName:string = 'default'; Mode:string = ''):TSQLConnector; var s : string; begin Result := nil; //DB_Connector_Write if ((Assigned( DB_Connector_Write)) and (Mode = 'write')) then begin Result := DB_Connector_Write; Exit; end; s := GetCurrentDir + DirectorySeparator + string( Config.GetValue( format( _DATABASE_LIBRARY, [ConnectionName]), '')); if not SetCurrentDir( ExtractFilePath( s)) then begin DisplayError( Format(_ERR_DATABASE_LIBRARY_NOT_EXIST, [ ConnectionName, s])); end; s := GetCurrentDir + DirectorySeparator + ExtractFileName( string( Config.GetValue( format( _DATABASE_LIBRARY, [ ConnectionName]), ''))); if not FileExists( s) then begin SetCurrentDir(ExtractFilePath(Application.ExeName)); DisplayError( Format(_ERR_DATABASE_LIBRARY_NOT_EXIST, [ ConnectionName, s])); end; if Config.GetValue( format( _DATABASE_LIBRARY, [ ConnectionName]), '') <> '' then begin if not Assigned( DB_LibLoader_Write) then DB_LibLoader_Write := TSQLDBLibraryLoader.Create( nil); try DB_LibLoader_Write.ConnectionType:= string( Config.GetValue( format( _DATABASE_DRIVER, [ConnectionName]), '')); DB_LibLoader_Write.LibraryName:= s; DB_LibLoader_Write.Enabled:= True; DB_LibLoader_Write.LoadLibrary; except on E: Exception do begin DisplayError( 'Database Init ('+ConnectionName+'): Load Library, '+E.Message) end; end; end; // back to app directory SetCurrentDir(ExtractFilePath(Application.ExeName)); if not Assigned( DB_Connector_Write) then begin DB_Transaction_Write := TSQLTransaction.Create( nil); DB_Connector_Write := TSQLConnector.Create( nil); DB_Connector_Write.Transaction := DB_Transaction_Write; end; DB_Connector_Write.HostName:= string( Config.GetValue( format( _DATABASE_HOSTNAME, [ConnectionName]), 'localhost')); DB_Connector_Write.ConnectorType := string( Config.GetValue( format( _DATABASE_DRIVER, [ConnectionName]), '')); DB_Connector_Write.UserName:= string( Config.GetValue( format( _DATABASE_USERNAME, [ConnectionName]), '')); DB_Connector_Write.Password:= string( Config.GetValue( format( _DATABASE_PASSWORD, [ConnectionName]), '')); DB_Connector_Write.DatabaseName:= string( Config.GetValue( format( _DATABASE_DATABASENAME, [ConnectionName]), 'test')); if Config.GetValue( format( _DATABASE_PORT, [ConnectionName]), '') <> '' then DB_Connector_Write.Params.Values['port'] := string( Config.GetValue( format( _DATABASE_PORT, [ConnectionName]), '')); //tabletype := Config.GetValue( _DATABASE_TABLETYPE, ''); //log database try DB_Connector_Write.Open; except on E: Exception do begin DisplayError( 'Database ("'+ConnectionName+'") Error : '+ E.Message) end; end; Result := DB_Connector_Write; end; function QueryExecToJson(SQL: string; var ResultJSON: TJSONObject): boolean; var q : TSQLQuery; begin Result:=false; q := TSQLQuery.Create(nil); q.UniDirectional:=True; if AppData.databaseRead = AppData.databaseWrite then q.DataBase := DB_Connector else begin q.DataBase := DatabaseSecond_Prepare( AppData.databaseWrite, 'write'); if q.DataBase = nil then begin DisplayError( format( _ERR_DATABASE_CANNOT_CONNECT, [ AppData.databaseWrite])); end; end; try q.SQL.Text:= SQL; q.ExecSQL; ResultJSON.Add( 'count', q.RowsAffected); TSQLConnector( q.DataBase).Transaction.Commit; //DB_Connector.Transaction.Commit; Result:=True; except on E: Exception do begin ResultJSON.Add( 'msg', E.Message); end; end; {$ifdef debug} ResultJSON.Add( 'sql', SQL); {$endif} FreeAndNil(q); end; function DataToJSON(Data: TSQLQuery; var ResultJSON: TJSONArray): boolean; var item : TJSONObject; field_name : string; i,j:integer; begin Result:=False; i:=1; try while not Data.EOF do begin item := TJSONObject.Create(); for j:=0 to Data.FieldCount-1 do begin field_name:= Data.FieldDefs.Items[j].Name; item.Add(field_name, Data.FieldByName(field_name).AsString); end; ResultJSON.Add( item); i:=i+1; Data.Next; end; Result:=True; except on E: Exception do begin die( E.Message); end; end; end; { TSimpleModel } procedure TSimpleModel._queryPrepare; begin FieldLists; if Data.Active then Data.Close; end; function TSimpleModel.GetRecordCount: Longint; begin Result := -1; if not Data.Active then Exit; Result := Data.RecordCount; end; function TSimpleModel.GetTablePrefix: string; begin Result := AppData.tablePrefix; end; function TSimpleModel.GetEOF: boolean; begin Result := Data.EOF; end; function TSimpleModel._queryOpen: boolean; var s : string; begin Result := False; try if Data.Active then Data.Close; Data.Open; if Data.RecordCount > 0 then Result := True; except on E: Exception do begin if AppData.debug then begin LogUtil.add( E.Message); LogUtil.add( Data.SQL.Text); s := #13'<pre>'#13+Data.SQL.Text+#13'</pre>'#13; end; DisplayError( E.Message + s); end; end; end; procedure TSimpleModel.DoAfterOpen(DataSet: TDataSet); var s : string; begin StopTime:= _GetTickCount; ElapsedTime:= StopTime - StartTime; if not AppData.debug then Exit; s := StringReplace( 'sql||'+i2s(ElapsedTime)+'||'+Data.SQL.Text, #13#10, #9#9#9, [rfReplaceAll]); _DebugInfo.Add( s); end; procedure TSimpleModel.DoBeforeOpen(DataSet: TDataSet); begin StartTime:= _GetTickCount; end; function TSimpleModel.getFieldList_mysql: TStrings; begin Data.SQL.Text:= 'SHOW COLUMNS FROM ' + FTableName; Data.Open; FSelectField := ''; while not Data.Eof do begin FFieldList.Add( FTableName + '.' +Data.FieldByName('Field').AsString); FSelectField := FSelectField + ',' + FTableName + '.' + Data.FieldByName('Field').AsString; Data.Next; end; Data.Close; FSelectField := Copy( FSelectField, 2, Length(FSelectField)-1); Result := FFieldList; end; function TSimpleModel.getFieldList_sqlite: TStrings; begin Data.SQL.Text:= 'PRAGMA table_info('+FTableName+');'; Data.Open; FSelectField := ''; while not Data.Eof do begin FFieldList.Add( FTableName + '.' +Data.FieldByName('name').AsString); FSelectField := FSelectField + ',' + FTableName + '.' + Data.FieldByName('name').AsString; Data.Next; end; Data.Close; FSelectField := Copy( FSelectField, 2, Length(FSelectField)-1); Result := FFieldList; end; function TSimpleModel.getFieldList_postgresql: TStrings; begin Data.SQL.Text:= 'SELECT column_name as name FROM information_schema.columns WHERE table_name = ''' + FTableName + ''''; Data.Open; FSelectField := ''; while not Data.Eof do begin FFieldList.Add( FTableName + '.' +Data.FieldByName('name').AsString); FSelectField := FSelectField + ',' + FTableName + '.' + Data.FieldByName('name').AsString; Data.Next; end; Data.Close; FSelectField := Copy( FSelectField, 2, Length(FSelectField)-1); Result := FFieldList; end; function TSimpleModel.GetFieldList: TStrings; var s : string; begin If Assigned(FFieldList) then begin Result:=FFieldList; end else begin Result := Nil; FFieldList:=TStringList.Create; if Data.Active then Data.Close; //TODO: create auto query, depend on databasetype s := lowercase(DB_Connector.ConnectorType); if (Pos('mysql', s) > 0) then Result := getFieldList_mysql; if (Pos('sqlite3', s) > 0) then Result := getFieldList_sqlite; if (Pos('postgre', s) > 0) then Result := getFieldList_postgresql; end; end; function TSimpleModel.GetFieldValue(FieldName: String): Variant; begin if not Data.Active then Exit; Result := Data.FieldByName( FieldName).AsVariant; end; procedure TSimpleModel.SetFieldValue(FieldName: String; AValue: Variant); begin if not Assigned( FGenFields) then begin FGenFields := TStringList.Create; FGenFields := TStringList.Create; FieldValueMap := TFieldValueMap.Create; end; FieldValueMap[FieldName] := AValue; FGenFields.Add( FieldName); end; constructor TSimpleModel.Create(const DefaultTableName: string; const pPrimaryKey: string); var i : integer; begin primaryKey := pPrimaryKey; primaryKeyValue := ''; FConnector := DB_Connector; if DefaultTableName = '' then begin for i:=2 to length( ToString) do begin if (ToString[i] in ['A'..'Z']) then begin if FTableName <> '' then FTableName := FTableName + '_' + LowerCase( ToString[i]) else FTableName := FTableName + LowerCase( ToString[i]) end else FTableName := FTableName + ToString[i]; end; FTableName:= copy( FTableName, 1, Length(FTableName)-6) + 's'; end else FTableName:= DefaultTableName; FTableName:= AppData.tablePrefix+FTableName; FJoinList := TStringList.Create; {$ifdef zeos} still not supported {$else} FGenFields := nil; FieldValueMap := nil; Data := TSQLQuery.Create(nil); Data.UniDirectional:=True; Data.DataBase := DB_Connector; Data.AfterOpen:= @DoAfterOpen; Data.BeforeOpen:= @DoBeforeOpen; {$endif} end; destructor TSimpleModel.Destroy; begin if Data.Active then Data.Close; FreeAndNil( FJoinList); if Assigned( FFieldList) then FreeAndNil( FFieldList); if Assigned( FGenFields) then FreeAndNil( FGenFields); if Assigned( FieldValueMap) then FreeAndNil( FieldValueMap); FreeAndNil( Data); end; function TSimpleModel.ParamByName(const AParamName: String): TParam; begin Result := Data.ParamByName( AParamName); end; function TSimpleModel.All: boolean; begin result := GetAll(); end; { same with: Object.Find([]); } function TSimpleModel.GetAll: boolean; begin _queryPrepare; Data.SQL.Text := 'SELECT ' + FSelectField + ' FROM ' + FTableName; _queryOpen; Result := true; end; function TSimpleModel.Find(const KeyIndex: integer): boolean; var s : string; begin if primaryKey = '' then begin Die( 'primayKey not defined'); end; s := primaryKey + '=' + i2s( KeyIndex); result := Find( [s], ''); end; function TSimpleModel.Find(const KeyIndex: String): boolean; var s : string; begin if primaryKey = '' then begin Die( 'primayKey not defined'); end; s := primaryKey + '=''' + KeyIndex + ''''; result := Find( [s], ''); end; function TSimpleModel.Find(const Where: array of string; const Order: string; const Limit: integer; const CustomField: string): boolean; var i,j : integer; _selectField, _joinSQL, sWhere : string; _joinfield, _join : TStrings; begin Clear; primaryKeyValue := ''; Result := false; sWhere := ''; if high(Where)>=0 then for i:=low(Where) to high(Where) do begin if sWhere = '' then sWhere := Where[i] else begin if trim( Where[i]) <> '' then sWhere := sWhere + ' AND ' + Where[i]; end; end; if CustomField = '' then begin _queryPrepare; _selectField := FSelectField; end else begin _selectField:= CustomField; end; _joinSQL := ' '; // prepare join if FJoinList.Count > 0 then begin for i:=0 to FJoinList.Count-1 do begin _join := Explode( FJoinList[i], '|'); _joinSQL:= _joinSQL + #13#10 + _join[0] + ' ' + _join[1] + ' ON ' + _join[1] + '.' + _join[2] + '=' + _join[3] ; _selectField := _selectField + #13; if _join.count > 4 then begin // if view joined field _joinfield := Explode( _join[4], ','); for j:=0 to _joinfield.Count-1 do begin _selectField := _selectField + ' ,' + _join[1] + '.' + _joinfield[j]; end; FreeAndNil( _joinfield); end; FreeAndNil( _join); end; end; // prepare join - end Data.SQL.Text := 'SELECT ' + _selectField + #13#10'FROM ' + FTableName + ' ' + FTableName + _joinSQL; if sWhere <> '' then Data.SQL.Add( 'WHERE ' + sWhere); if FGroupField <> '' then Data.SQL.Add( 'GROUP BY ' + FGroupField); if Order <> '' then Data.SQL.Add( 'ORDER BY ' + Order); if Limit > 0 then begin Data.SQL.Add( 'LIMIT ' + IntToStr( Limit)); end; Data.UniDirectional:=False; Result := _queryOpen; Data.Last; Data.First; if (Data.RecordCount = 1) and (primaryKey <> '') then begin primaryKeyValue := Data.FieldByName( primaryKey).AsString; end; end; function TSimpleModel.FindFirst(const Where: array of string; const Order: string; const CustomField: string): boolean; begin Result := Find( Where, Order, 1, CustomField); end; procedure TSimpleModel.AddJoin(const JoinTable: string; const JoinField: string; const RefField: string; const FieldNameList: array of string); begin AddCustomJoin( 'LEFT', JoinTable, JoinField, RefField, FieldNameList); end; procedure TSimpleModel.AddLeftJoin(const JoinTable: string; const JoinField: string; const RefField: string; const FieldNameList: array of string); begin AddCustomJoin( 'LEFT', JoinTable, JoinField, RefField, FieldNameList); end; procedure TSimpleModel.AddInnerJoin(const JoinTable: string; const JoinField: string; const RefField: string; const FieldNameList: array of string); begin AddCustomJoin( 'INNER', JoinTable, JoinField, RefField, FieldNameList); end; procedure TSimpleModel.AddCustomJoin(const JointType: string; const JoinTable: string; const JoinField: string; const RefField: string; const FieldNameList: array of string); var i : integer; s : string; begin s:=''; for i:=low(FieldNameList) to high(FieldNameList) do begin if s = '' then s := FieldNameList[i] else s := s + ','+FieldNameList[i]; end; FJoinList.Add( JointType + ' JOIN|'+AppData.tablePrefix+JoinTable+'|'+JoinField+'|'+AppData.tablePrefix+RefField+'|'+s); end; procedure TSimpleModel.GroupBy(const GroupField: string); begin FGroupField:= GroupField; end; procedure TSimpleModel.Clear; begin New; end; procedure TSimpleModel.New; begin if Assigned( FGenFields) then FGenFields.Clear; if Assigned( FieldValueMap) then FieldValueMap.Clear; primaryKeyValue:=''; end; function TSimpleModel.Save(Where: string; AutoCommit: boolean): boolean; var sSQL : TStringList; i : integer; s : string; begin Result := false; if AppData.databaseRead = AppData.databaseWrite then begin if ((Data.Active) and (primaryKeyValue='')) then Exit; if Data.Active then Data.Close; //Data.DataBase := DB_Connector; end else begin if Data.Active then Data.Close; Data.DataBase := DatabaseSecond_Prepare( AppData.databaseWrite, 'write'); if Data.DataBase = nil then begin DisplayError( format( _ERR_DATABASE_CANNOT_CONNECT, [ AppData.databaseWrite])); end; end; sSQL := TStringList.Create; if Where <> '' then begin sSQL.Add( 'UPDATE ' + TableName + ' SET '); for i:=0 to FGenFields.Count-1 do begin s := FGenFields[i]+'=:'+FGenFields[i]; if i <> FGenFields.Count-1 then s:= s + ',' ; sSQL.Add( s); end; if Where <> '' then begin sSQL.Add( 'WHERE ' + Where); primaryKeyValue:=''; end else sSQL.Add( 'WHERE ' + primaryKey + '=''' + primaryKeyValue + ''''); end else begin //-- new data sSQL.Add( 'INSERT INTO '+TableName+' ('); s := Implode( FGenFields, ','); sSQL.Add( s); sSQL.Add( ') VALUES ('); s := Implode( FGenFields, ',', ':'); //s := Implode( FGenValues, ',', '''', ''''); sSQL.Add(s); sSQL.Add( ')'); end; try Data.SQL.Text:= sSQL.Text; for i:=0 to FieldValueMap.Count-1 do begin s := FieldValueMap.Keys[i]; Data.Params.ParamByName( FGenFields[i]).Value := FieldValueMap[s]; end; Data.ExecSQL; if AutoCommit then Commit; Result := True; except on E: Exception do begin if AppData.debug then begin LogUtil.add( E.Message); LogUtil.add( Data.SQL.Text); end; DisplayError( e.Message); end; end; FreeAndNil(sSQL); Data.DataBase := DB_Connector; end; function TSimpleModel.Delete(Where: string; AutoCommit: boolean): boolean; var s : string; begin Result := false; if ((Where='') and (Data.Active)) then begin if RecordCount <> 1 then exit; end; if Data.Active then Data.Close; if AppData.databaseRead = AppData.databaseWrite then begin //Data.DataBase := DB_Connector; end else begin Data.DataBase := DatabaseSecond_Prepare( AppData.databaseWrite, 'write'); if Data.DataBase = nil then begin DisplayError( format( _ERR_DATABASE_CANNOT_CONNECT, [ AppData.databaseWrite])); end; end; s := 'DELETE FROM ' + TableName + ' WHERE '; if Where = '' then begin s:= s + primaryKey + '=' + primaryKeyValue; end else begin s := s + Where; end; try Data.SQL.Text:= s; Data.ExecSQL; if AutoCommit then Commit; Result := True; except on E: Exception do begin if AppData.debug then begin LogUtil.add( E.Message); LogUtil.add( Data.SQL.Text); end; DisplayError( 'DB:' + e.Message); end; end; Data.DataBase := DB_Connector; end; procedure TSimpleModel.Next; begin Data.Next; end; procedure TSimpleModel.StartTransaction; begin DB_Transaction.StartTransaction; end; procedure TSimpleModel.ReStartTransaction; begin if DB_Transaction.Active then DB_Transaction.Active:= false; DB_Transaction.StartTransaction; end; procedure TSimpleModel.Commit; begin DB_Transaction.Commit; end; procedure TSimpleModel.CommitRetaining; begin DB_Transaction.CommitRetaining; end; procedure TSimpleModel.Rollback; begin DB_Transaction.Rollback; end; procedure TSimpleModel.RollbackRetaining; begin DB_Transaction.RollbackRetaining; end; initialization DB_LibLoader := TSQLDBLibraryLoader.Create( nil); DB_Transaction := TSQLTransaction.Create( nil); DB_Connector := TSQLConnector.Create( nil); DB_Connector.Transaction := DB_Transaction; DB_Connector_Write := nil; DB_Transaction_Write := nil; DB_LibLoader_Write := nil; finalization FreeAndNil( DB_Connector); FreeAndNil( DB_Transaction); FreeAndNil( DB_LibLoader); if not Assigned( DB_Connector_Write) then FreeAndNil( DB_Connector_Write); if not Assigned( DB_Transaction_Write) then FreeAndNil( DB_Transaction_Write); if not Assigned( DB_LibLoader_Write) then FreeAndNil( DB_LibLoader_Write); end.
{ Convert overrides into new records, all references are updated with reindexed FormIDs too so they must already exist in a plugin. For example if you have an override of worldspace record [WRLD:00001234] which references water [WATR:00005678], after applying script it would become [WRLD:01001234] referencing [WATR:01005678] (assuming plugin is loaded at index 01). } unit OverridesToNewRecords; procedure UpdateReferences(e: IInterface; ModLoadOrder: integer); var ref: IInterface; i: integer; begin ref := LinksTo(e); if Assigned(ref) then if GetLoadOrder(GetFile(ref)) <> ModLoadOrder then begin i := GetLoadOrderFormID(ref); i := (i and $FFFFFF) or (ModLoadOrder shl 24); AddMessage('Updating ref: ' + Path(e) + ' \ ' + GetEditValue(e)); SetEditValue(e, IntToHex(i, 8)); end; if CanContainFormIDs(e) then for i := 0 to ElementCount(e) - 1 do UpdateReferences(ElementByIndex(e, i), ModLoadOrder); end; function Process(e: IInterface): integer; var i, fid: integer; begin // not an override if IsMaster(e) then Exit; AddMessage('Override to new record: ' + Name(e)); i := GetLoadOrder(GetFile(e)); UpdateReferences(e, i); fid := GetLoadOrderFormID(e); fid := (fid and $FFFFFF) or (i shl 24); SetLoadOrderFormID(e, fid); end; end.
unit Lunar2; interface uses Windows, SysUtils; const START_YEAR = 1901; END_YEAR = 2050; //返回iYear年iMonth月的天数 1年1月 --- 65535年12月 function MonthDays(iYear, iMonth: word): word; //返回阴历iLunarYer年阴历iLunarMonth月的天数,如果iLunarMonth为闰月, //高字为第二个iLunarMonth月的天数,否则高字为0 1901年1月---2050年12月 function LunarMonthDays(iLunarYear, iLunarMonth: word): Longword; //返回阴历iLunarYear年的总天数 1901年1月---2050年12月 function LunarYearDays(iLunarYear: word): word; //返回阴历iLunarYear年的闰月月份,如没有返回0 1901年1月---2050年12月 function GetLeapMonth(iLunarYear: word): word; //把iYear年格式化成天干记年法表示的字符串 procedure FormatLunarYear(iYear: word; var pBuffer: string); overload; function FormatLunarYear(iYear: word): string; overload; //把iMonth格式化成中文字符串 procedure FormatMonth(iMonth: word; var pBuffer: string; bLunar: Boolean = True); overload; function FormatMonth(iMonth: word; bLunar: Boolean = True): string; overload; //把iDay格式化成中文字符串 procedure FormatLunarDay(iDay: word; var pBuffer: string); overload; function FormatLunarDay(iDay: word): string; overload; //计算公历两个日期间相差的天数 1年1月1日 --- 65535年12月31日 function CalcDateDiff(iEndYear, iEndMonth, iEndDay: word; iStartYear: word = START_YEAR; iStartMonth: word = 1; iStartDay: word = 1): Longword; overload; function CalcDateDiff(EndDate, StartDate: TDateTime): Longword; overload; //计算公历iYear年iMonth月iDay日对应的阴历日期,返回对应的阴历节气 0-24 //1901年1月1日---2050年12月31日 function GetLunarHolDay(InDate: TDateTime): string; overload; function GetLunarHolDay(iYear, iMonth, iDay: word): string; overload; //private function-------------------------------------- //计算从1901年1月1日过iSpanDays天后的阴历日期 procedure l_CalcLunarDate(var iYear, iMonth, iDay: word; iSpanDays: Longword); //计算公历iYear年iMonth月iDay日对应的节气 0-24,0表不是节气 function l_GetLunarHolDay(iYear, iMonth, iDay: word): word; implementation var //数组gLunarDay存入阴历1901年到2100年每年中的月天数信息, //阴历每月只能是29或30天,一年用12(或13)个二进制位表示,对应位为1表30天,否则为29天 gLunarMonthDay: array[0..149] of word = ( //测试数据只有1901.1.1 --2050.12.31 $4AE0, $A570, $5268, $D260, $D950, $6AA8, $56A0, $9AD0, $4AE8, $4AE0, //1910 $A4D8, $A4D0, $D250, $D548, $B550, $56A0, $96D0, $95B0, $49B8, $49B0, //1920 $A4B0, $B258, $6A50, $6D40, $ADA8, $2B60, $9570, $4978, $4970, $64B0, //1930 $D4A0, $EA50, $6D48, $5AD0, $2B60, $9370, $92E0, $C968, $C950, $D4A0, //1940 $DA50, $B550, $56A0, $AAD8, $25D0, $92D0, $C958, $A950, $B4A8, $6CA0, //1950 $B550, $55A8, $4DA0, $A5B0, $52B8, $52B0, $A950, $E950, $6AA0, $AD50, //1960 $AB50, $4B60, $A570, $A570, $5260, $E930, $D950, $5AA8, $56A0, $96D0, //1970 $4AE8, $4AD0, $A4D0, $D268, $D250, $D528, $B540, $B6A0, $96D0, $95B0, //1980 $49B0, $A4B8, $A4B0, $B258, $6A50, $6D40, $ADA0, $AB60, $9370, $4978, //1990 $4970, $64B0, $6A50, $EA50, $6B28, $5AC0, $AB60, $9368, $92E0, $C960, //2000 $D4A8, $D4A0, $DA50, $5AA8, $56A0, $AAD8, $25D0, $92D0, $C958, $A950, //2010 $B4A0, $B550, $B550, $55A8, $4BA0, $A5B0, $52B8, $52B0, $A930, $74A8, //2020 $6AA0, $AD50, $4DA8, $4B60, $9570, $A4E0, $D260, $E930, $D530, $5AA0, //2030 $6B50, $96D0, $4AE8, $4AD0, $A4D0, $D258, $D250, $D520, $DAA0, $B5A0, //2040 $56D0, $4AD8, $49B0, $A4B8, $A4B0, $AA50, $B528, $6D20, $ADA0, $55B0); //2050 //数组gLanarMonth存放阴历1901年到2050年闰月的月份,如没有则为0,每字节存两年 gLunarMonth: array[0..74] of byte = ( $00, $50, $04, $00, $20, //1910 $60, $05, $00, $20, $70, //1920 $05, $00, $40, $02, $06, //1930 $00, $50, $03, $07, $00, //1940 $60, $04, $00, $20, $70, //1950 $05, $00, $30, $80, $06, //1960 $00, $40, $03, $07, $00, //1970 $50, $04, $08, $00, $60, //1980 $04, $0A, $00, $60, $05, //1990 $00, $30, $80, $05, $00, //2000 $40, $02, $07, $00, $50, //2010 $04, $09, $00, $60, $04, //2020 $00, $20, $60, $05, $00, //2030 $30, $B0, $06, $00, $50, //2040 $02, $07, $00, $50, $03); //2050 //数组gLanarHoliDay存放每年的二十四节气对应的阳历日期 //每年的二十四节气对应的阳历日期几乎固定,平均分布于十二个月中 // 1月 2月 3月 4月 5月 6月 //小寒 大寒 立春 雨水 惊蛰 春分 清明 谷雨 立夏 小满 芒种 夏至 // 7月 8月 9月 10月 11月 12月 //小暑 大暑 立秋 处暑 白露 秋分 寒露 霜降 立冬 小雪 大雪 冬至 {********************************************************************************* 节气无任何确定规律,所以只好存表,要节省空间,所以.... **********************************************************************************} //数据格式说明: //如1901年的节气为 // 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月 // 6, 21, 4, 19, 6, 21, 5, 21, 6,22, 6,22, 8, 23, 8, 24, 8, 24, 8, 24, 8, 23, 8, 22 // 9, 6, 11,4, 9, 6, 10,6, 9,7, 9,7, 7, 8, 7, 9, 7, 9, 7, 9, 7, 8, 7, 15 //上面第一行数据为每月节气对应日期,15减去每月第一个节气,每月第二个节气减去15得第二行 // 这样每月两个节气对应数据都小于16,每月用一个字节存放,高位存放第一个节气数据,低位存放 //第二个节气的数据,可得下表 gLunarHolDay: array[0..1799] of byte = ( $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1901 $96, $A4, $96, $96, $97, $87, $79, $79, $79, $69, $78, $78, //1902 $96, $A5, $87, $96, $87, $87, $79, $69, $69, $69, $78, $78, //1903 $86, $A5, $96, $A5, $96, $97, $88, $78, $78, $79, $78, $87, //1904 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1905 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, //1906 $96, $A5, $87, $96, $87, $87, $79, $69, $69, $69, $78, $78, //1907 $86, $A5, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1908 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1909 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, //1910 $96, $A5, $87, $96, $87, $87, $79, $69, $69, $69, $78, $78, //1911 $86, $A5, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1912 $95, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1913 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $78, //1914 $96, $A5, $97, $96, $97, $87, $79, $79, $69, $69, $78, $78, //1915 $96, $A5, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1916 $95, $B4, $96, $A6, $96, $97, $78, $79, $78, $69, $78, $87, //1917 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $77, //1918 $96, $A5, $97, $96, $97, $87, $79, $79, $69, $69, $78, $78, //1919 $96, $A5, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1920 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $69, $78, $87, //1921 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $77, //1922 $96, $A4, $96, $96, $97, $87, $79, $79, $69, $69, $78, $78, //1923 $96, $A5, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1924 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $69, $78, $87, //1925 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1926 $96, $A4, $96, $96, $97, $87, $79, $79, $79, $69, $78, $78, //1927 $96, $A5, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1928 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1929 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1930 $96, $A4, $96, $96, $97, $87, $79, $79, $79, $69, $78, $78, //1931 $96, $A5, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1932 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1933 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1934 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, //1935 $96, $A5, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1936 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1937 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1938 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, //1939 $96, $A5, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1940 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1941 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1942 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, //1943 $96, $A5, $96, $A5, $A6, $96, $88, $78, $78, $78, $87, $87, //1944 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1945 $95, $B4, $96, $A6, $97, $97, $78, $79, $78, $69, $78, $77, //1946 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $78, //1947 $96, $A5, $A6, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //1948 $A5, $B4, $96, $A5, $96, $97, $88, $79, $78, $79, $77, $87, //1949 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $69, $78, $77, //1950 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $78, //1951 $96, $A5, $A6, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //1952 $A5, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1953 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $68, $78, $87, //1954 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1955 $96, $A5, $A5, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //1956 $A5, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1957 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1958 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1959 $96, $A4, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, //1960 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1961 $96, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1962 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1963 $96, $A4, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, //1964 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1965 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1966 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1967 $96, $A4, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, //1968 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1969 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1970 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, //1971 $96, $A4, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, //1972 $A5, $B5, $96, $A5, $A6, $96, $88, $78, $78, $78, $87, $87, //1973 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1974 $96, $B4, $96, $A6, $97, $97, $78, $79, $78, $69, $78, $77, //1975 $96, $A4, $A5, $B5, $A6, $A6, $88, $89, $88, $78, $87, $87, //1976 $A5, $B4, $96, $A5, $96, $96, $88, $88, $78, $78, $87, $87, //1977 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $78, $87, //1978 $96, $B4, $96, $A6, $96, $97, $78, $79, $78, $69, $78, $77, //1979 $96, $A4, $A5, $B5, $A6, $A6, $88, $88, $88, $78, $87, $87, //1980 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $77, $87, //1981 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1982 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $69, $78, $77, //1983 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $87, //1984 $A5, $B4, $A6, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //1985 $A5, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //1986 $95, $B4, $96, $A5, $96, $97, $88, $79, $78, $69, $78, $87, //1987 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //1988 $A5, $B4, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, //1989 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $79, $77, $87, //1990 $95, $B4, $96, $A5, $86, $97, $88, $78, $78, $69, $78, $87, //1991 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //1992 $A5, $B3, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, //1993 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1994 $95, $B4, $96, $A5, $96, $97, $88, $76, $78, $69, $78, $87, //1995 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //1996 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, //1997 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //1998 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //1999 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //2000 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, //2001 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //2002 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //2003 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //2004 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, //2005 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //2006 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, //2007 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $87, $78, $87, $86, //2008 $A5, $B3, $A5, $B5, $A6, $A6, $88, $88, $88, $78, $87, $87, //2009 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //2010 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $78, $87, //2011 $96, $B4, $A5, $B5, $A5, $A6, $87, $88, $87, $78, $87, $86, //2012 $A5, $B3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $87, //2013 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //2014 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, //2015 $95, $B4, $A5, $B4, $A5, $A6, $87, $88, $87, $78, $87, $86, //2016 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $87, //2017 $A5, $B4, $A6, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //2018 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $79, $77, $87, //2019 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $86, //2020 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //2021 $A5, $B4, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, //2022 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $79, $77, $87, //2023 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, //2024 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //2025 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, //2026 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //2027 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, //2028 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //2029 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, //2030 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, //2031 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, //2032 $A5, $C3, $A5, $B5, $A6, $A6, $88, $88, $88, $78, $87, $86, //2033 $A5, $B3, $A5, $A5, $A6, $A6, $88, $78, $88, $78, $87, $87, //2034 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //2035 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, //2036 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, //2037 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, //2038 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //2039 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, //2040 $A5, $C3, $A5, $B5, $A5, $A6, $87, $88, $87, $78, $87, $86, //2041 $A5, $B3, $A5, $B5, $A6, $A6, $88, $88, $88, $78, $87, $87, //2042 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //2043 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $88, $87, $96, //2044 $A5, $C3, $A5, $B4, $A5, $A6, $87, $88, $87, $78, $87, $86, //2045 $A5, $B3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $87, //2046 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, //2047 $95, $B4, $A5, $B4, $A5, $A5, $97, $87, $87, $88, $86, $96, //2048 $A4, $C3, $A5, $A5, $A5, $A6, $97, $87, $87, $78, $87, $86, //2049 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $78, $78, $87, $87); //2050 function IsLeapYear(AYear: Integer): Boolean; begin result := (AYear mod 4 = 0) and ((AYear mod 100 <> 0) or (AYear mod 400 = 0)); end; function MonthDays(iYear, iMonth: word): word; begin case iMonth of 1, 3, 5, 7, 8, 10, 12: result := 31; 4, 6, 9, 11: result := 30; 2: //如果是闰年 if IsLeapYear(iYear) then result := 29 else result := 28 else result := 0; end; end; function GetLeapMonth(iLunarYear: word): word; var Flag: byte; begin Flag := gLunarMonth[(iLunarYear - START_YEAR) div 2]; if (iLunarYear - START_YEAR) mod 2 = 0 then result := Flag shr 4 else result := Flag and $0F; end; function LunarMonthDays(iLunarYear, iLunarMonth: word): Longword; var Height, Low: word; iBit: Integer; begin if iLunarYear < START_YEAR then begin result := 30; Exit; end; Height := 0; Low := 29; iBit := 16 - iLunarMonth; if (iLunarMonth > GetLeapMonth(iLunarYear)) and (GetLeapMonth(iLunarYear) > 0) then Dec(iBit); if (gLunarMonthDay[iLunarYear - START_YEAR] and (1 shl iBit)) > 0 then inc(Low); if iLunarMonth = GetLeapMonth(iLunarYear) then if (gLunarMonthDay[iLunarYear - START_YEAR] and (1 shl (iBit - 1))) > 0 then Height := 30 else Height := 29; //Result := MakeLong(Low, Height); end; function LunarYearDays(iLunarYear: word): word; var Days, i: word; tmp: Longword; begin Days := 0; for i := 1 to 12 do begin tmp := LunarMonthDays(iLunarYear, i); Days := Days + HiWord(tmp); Days := Days + LoWord(tmp); end; result := Days; end; procedure FormatLunarYear(iYear: word; var pBuffer: string); var szText1, szText2, szText3: string; begin szText1 := '甲乙丙丁戊己庚辛壬癸'; szText2 := '子丑寅卯辰巳午未申酉戌亥'; szText3 := '鼠牛虎免龙蛇马羊猴鸡狗猪'; pBuffer := Copy(szText1, ((iYear - 4) mod 10) * 2 + 1, 2); pBuffer := pBuffer + Copy(szText2, ((iYear - 4) mod 12) * 2 + 1, 2); pBuffer := pBuffer + ' '; pBuffer := pBuffer + Copy(szText3, ((iYear - 4) mod 12) * 2 + 1, 2); pBuffer := pBuffer + '年'; end; function FormatLunarYear(iYear: word): string; var pBuffer: string; begin FormatLunarYear(iYear, pBuffer); result := pBuffer; end; procedure FormatMonth(iMonth: word; var pBuffer: string; bLunar: Boolean); var szText: string; begin if (not bLunar) and (iMonth = 1) then begin pBuffer := ' 一月'; Exit; end; szText := '正二三四五六七八九十'; if iMonth <= 10 then begin pBuffer := ' '; pBuffer := pBuffer + Copy(szText, (iMonth - 1) * 2 + 1, 2); pBuffer := pBuffer + '月'; Exit; end; if iMonth = 11 then pBuffer := '十一' else pBuffer := '十二'; pBuffer := pBuffer + '月'; end; function FormatMonth(iMonth: word; bLunar: Boolean): string; var pBuffer: string; begin FormatMonth(iMonth, pBuffer, bLunar); result := pBuffer; end; procedure FormatLunarDay(iDay: word; var pBuffer: string); var szText1, szText2: string; begin szText1 := '初十廿三'; szText2 := '一二三四五六七八九十'; if (iDay <> 20) and (iDay <> 30) then begin pBuffer := Copy(szText1, ((iDay - 1) div 10) * 2 + 1, 2); pBuffer := pBuffer + Copy(szText2, ((iDay - 1) mod 10) * 2 + 1, 2); end else begin pBuffer := Copy(szText1, (iDay div 10) * 2 + 1, 2); pBuffer := pBuffer + '十'; end; end; function FormatLunarDay(iDay: word): string; var pBuffer: string; begin FormatLunarDay(iDay, pBuffer); result := pBuffer; end; function CalcDateDiff(iEndYear, iEndMonth, iEndDay: word; iStartYear: word; iStartMonth: word; iStartDay: word): Longword; begin result := Trunc(EncodeDate(iEndYear, iEndMonth, iEndDay) - EncodeDate(iStartYear, iStartMonth, iStartDay)); end; function CalcDateDiff(EndDate, StartDate: TDateTime): Longword; begin result := Trunc(EndDate - StartDate); end; procedure l_CalcLunarDate(var iYear, iMonth, iDay: word; iSpanDays: Longword); var tmp: Longword; begin //阳历1901年2月19日为阴历1901年正月初一 //阳历1901年1月1日到2月19日共有49天 if iSpanDays < 49 then begin iYear := START_YEAR - 1; if iSpanDays < 19 then begin iMonth := 11; iDay := 11 + word(iSpanDays); end else begin iMonth := 12; iDay := word(iSpanDays) - 18; end; Exit; end; //下面从阴历1901年正月初一算起 iSpanDays := iSpanDays - 49; iYear := START_YEAR; iMonth := 1; iDay := 1; //计算年 tmp := LunarYearDays(iYear); while iSpanDays >= tmp do begin iSpanDays := iSpanDays - tmp; inc(iYear); tmp := LunarYearDays(iYear); end; //计算月 tmp := LoWord(LunarMonthDays(iYear, iMonth)); while iSpanDays >= tmp do begin iSpanDays := iSpanDays - tmp; if iMonth = GetLeapMonth(iYear) then begin tmp := HiWord(LunarMonthDays(iYear, iMonth)); if iSpanDays < tmp then break; iSpanDays := iSpanDays - tmp; end; inc(iMonth); tmp := LoWord(LunarMonthDays(iYear, iMonth)); end; //计算日 iDay := iDay + word(iSpanDays); end; function l_GetLunarHolDay(iYear, iMonth, iDay: word): word; var Flag: byte; Day: word; begin Flag := gLunarHolDay[(iYear - START_YEAR) * 12 + iMonth - 1]; if iDay < 15 then Day := 15 - ((Flag shr 4) and $0F) else Day := (Flag and $0F) + 15; if iDay = Day then if iDay > 15 then result := (iMonth - 1) * 2 + 2 else result := (iMonth - 1) * 2 + 1 else result := 0; end; function GetLunarHolDay(InDate: TDateTime): string; var i, iYear, iMonth, iDay: word; begin DecodeDate(InDate, iYear, iMonth, iDay); i := l_GetLunarHolDay(iYear, iMonth, iDay); case i of 1: result := '小 寒'; 2: result := '大 寒'; 3: result := '立 春'; 4: result := '雨 水'; 5: result := '惊 蛰'; 6: result := '春 分'; 7: result := '清 明'; 8: result := '谷 雨'; 9: result := '立 夏'; 10: result := '小 满'; 11: result := '芒 种'; 12: result := '夏 至'; 13: result := '小 暑'; 14: result := '大 暑'; 15: result := '立 秋'; 16: result := '处 暑'; 17: result := '白 露'; 18: result := '秋 分'; 19: result := '寒 露'; 20: result := '霜 降'; 21: result := '立 冬'; 22: result := '小 雪'; 23: result := '大 雪'; 24: result := '冬 至'; else l_CalcLunarDate(iYear, iMonth, iDay, CalcDateDiff(InDate, EncodeDate(START_YEAR, 1, 1))); result := trim(FormatMonth(iMonth) + FormatLunarDay(iDay)); end; end; function GetLunarHolDay(iYear, iMonth, iDay: word): string; begin result := GetLunarHolDay(EncodeDate(iYear, iMonth, iDay)); end; end.
{ Subroutine PICPRG_CLOSE (PR, STAT) * * Close this use of the PICPRG library. All system resources allocated * to the library use are released and the library use state PR will be * returned invalid. } module picprg_close; define picprg_close; %include 'picprg2.ins.pas'; procedure picprg_close ( {end a use of this library} in out pr: picprg_t; {library use state, returned invalid} out stat: sys_err_t); {completion status} val_param; var ev_thin: sys_sys_event_id_t; {signalled when input thread exits} cmd_p: picprg_cmd_p_t; {scratch command descriptor pointer} begin pr.quit := true; {indicate trying to shut down} file_close (pr.conn); {close the I/O connection} sys_thread_event_get (pr.thid_in, ev_thin, stat); if sys_error(stat) then return; discard( {wait for thread to exit or timeout} sys_event_wait_tout (ev_thin, 0.500, stat) ); if sys_error(stat) then return; sys_thread_release (pr.thid_in, stat); {release all thread state} if sys_error(stat) then return; sys_thread_lock_enter (pr.lock_cmd); {lock exclusive access to command pointers} cmd_p := pr.cmd_inq_p; {pointer to first command in input queue} while cmd_p <> nil do begin {once for each queued command} sys_event_notify_bool (cmd_p^.done); {signal this command has completed} cmd_p := cmd_p^.next_p; {advance to next queued command} end; sys_thread_lock_leave (pr.lock_cmd); {release exclusive lock on command pointers} sys_event_notify_bool (pr.ready); {release any thread waiting to send command} sys_thread_lock_delete (pr.lock_cmd, stat); {delete cmd pointers interlock}; if sys_error(stat) then return; sys_event_del_bool (pr.ready); {delete the OK to send command event} util_mem_context_del (pr.mem_p); {dealloc all dynamic memory and mem context} end;
unit InscricaoFiscal; interface type /// <summary> /// Classe base para validação da inscrição fiscal: CPF e CNPJ /// </summary> TInscricaoFiscal = class abstract(TObject) public function DocumentoValido(const ADocumento: string): Boolean; virtual; abstract; end; TCNPJ = class(TInscricaoFiscal) public function DocumentoValido(const ADocumento: string): Boolean; override; end; TCPF = class(TInscricaoFiscal) public function DocumentoValido(const ADocumento: string): Boolean; override; end; implementation { TCNPJ } function TCNPJ.DocumentoValido(const ADocumento: string): Boolean; begin Result := True; end; { TCPF } function TCPF.DocumentoValido(const ADocumento: string): Boolean; begin Result := True; end; end.
// ---------------------------------------------------------------------------// // // dgViewport2D // // Copyright © 2005-2009 DunconGames. All rights reserved. BSD License. Authors: simsmen // ---------------------------------------------------------------------------// // // ---------------------------------------------------------------------------// // History: // // 2009.01.08 simsmen // ---------------------------------------------------------------------------// // Bugs: // // ---------------------------------------------------------------------------// // Future: // // ---------------------------------------------------------------------------// unit dgViewport2D; {$DEFINE dgAssert} {$DEFINE dgTrace} interface procedure dgInitViewport2D; implementation uses windows, OpenGL, dgHeader, dgTraceCore, dgCore; const cnstUnitName = 'dgViewport2D'; type TdgNodeData = TdgDrawable; TdgNodeDataArray = array[0..(Maxint div sizeof(TdgNodeData)) - 1] of TdgNodeData; PdgNodeDataArray = ^TdgNodeDataArray; TdgNodeDataList = record rArray: PdgNodeDataArray; rCount: integer; rCapacity: integer; rIterator: integer; procedure Create; inline; procedure Free; inline; procedure StayBeforeFirst; inline; function StayOnNext: boolean; inline; function Data: TdgNodeData; inline; procedure Append(const aData: TdgNodeData); inline; procedure ExtractAll; inline; procedure Extract; inline; function StayOnData(const aData: TdgNodeData): boolean; inline; end; procedure TdgNodeDataList.Create; begin rArray := nil; rCount := 0; rCapacity := 0; rIterator := 0; dgAddCapacity(pointer(rArray), rCapacity, SizeOf(TdgNodeData)); end; procedure TdgNodeDataList.Free; var i: integer; begin for i := 0 to rCapacity - 1 do rArray[i] := nil; ReallocMem(rArray, 0); rArray := nil; end; procedure TdgNodeDataList.StayBeforeFirst; begin rIterator := -1; end; function TdgNodeDataList.StayOnNext: boolean; begin inc(rIterator); if rIterator >= rCount then begin rIterator := -1; result := false; end else result := true; end; function TdgNodeDataList.Data: TdgNodeData; begin {$IFDEF dgAssert} dgTrace.Assert(rIterator >= 0, '{9F287BDD-C11C-441E-9354-D4603D232E74}', cnstUnitName); {$ENDIF} Result := rArray^[rIterator]; end; procedure TdgNodeDataList.Append(const aData: TdgNodeData); begin inc(rCount); while rCount > rCapacity do dgAddCapacity(pointer(rArray), rCapacity, SizeOf(TdgNodeData)); rArray^[rCount - 1] := aData; end; procedure TdgNodeDataList.ExtractAll; var i: integer; begin for i := 0 to rCapacity - 1 do rArray[i] := nil; rIterator := -1; rCount := 0; end; procedure TdgNodeDataList.Extract; begin {$IFDEF dgAssert} dgTrace.Assert(rIterator >= 0, '{9F287BDD-C11C-441E-9354-D4603D232E74}', cnstUnitName); {$ENDIF} Dec(rCount); rArray^[rIterator] := rArray^[rCount]; rArray^[rCount] := nil; Dec(rIterator); end; function TdgNodeDataList.StayOnData(const aData: TdgNodeData): boolean; var i: integer; begin result := false; rIterator := -1; if aData <> nil then begin i := 0; while (i < rCount) and (rArray[i] <> aData) do inc(i); if rArray[i] = aData then begin result := true; rIterator := i; end; end; end; type TdgLightData = record rID: integer; rLightable: TdgLightable; end; TdgLightDataArray = array[0..(Maxint div sizeof(TdgLightData)) - 1] of TdgLightData; PdgLightDataArray = ^TdgLightDataArray; TdgLightDataList = record rArray: PdgLightDataArray; rCount: integer; rCapacity: integer; rIterator: integer; procedure Create; inline; procedure Free; inline; procedure StayBeforeFirst; inline; function StayOnNext: boolean; inline; function Data: TdgLightData; inline; procedure Append(const aData: TdgLightable); inline; procedure ExtractAll; inline; procedure Extract; inline; function StayOnData(const aData: TdgLightable): boolean; inline; end; procedure TdgLightDataList.Create; begin rArray := nil; rCount := 0; rCapacity := 0; rIterator := 0; dgAddCapacity(pointer(rArray), rCapacity, SizeOf(TdgLightData)); end; procedure TdgLightDataList.Free; var i: integer; begin for i := 0 to rCapacity - 1 do rArray[i].rLightable := nil; ReallocMem(rArray, 0); rArray := nil; end; procedure TdgLightDataList.StayBeforeFirst; begin rIterator := -1; end; function TdgLightDataList.StayOnNext: boolean; begin inc(rIterator); if rIterator >= rCount then begin rIterator := -1; result := false; end else result := true; end; function TdgLightDataList.Data: TdgLightData; begin {$IFDEF dgAssert} dgTrace.Assert(rIterator >= 0, '{9F287BDD-C11C-441E-9354-D4603D232E74}', cnstUnitName); {$ENDIF} Result := rArray^[rIterator]; end; procedure TdgLightDataList.Append(const aData: TdgLightable); begin inc(rCount); while rCount > rCapacity do dgAddCapacity(pointer(rArray), rCapacity, SizeOf(TdgLightData)); rArray^[rCount - 1].rID := aData.ID; rArray^[rCount - 1].rLightable := aData; end; procedure TdgLightDataList.ExtractAll; var i: integer; begin for i := 0 to rCapacity - 1 do rArray[i].rLightable := nil; rIterator := -1; rCount := 0; end; procedure TdgLightDataList.Extract; begin {$IFDEF dgAssert} dgTrace.Assert(rIterator >= 0, '{9F287BDD-C11C-441E-9354-D4603D232E74}', cnstUnitName); {$ENDIF} Dec(rCount); rArray^[rIterator].rID := rArray^[rCount].rID; rArray^[rIterator].rLightable := rArray^[rCount].rLightable; rArray^[rCount].rLightable := nil; Dec(rIterator); end; function TdgLightDataList.StayOnData(const aData: TdgLightable): boolean; var i: integer; begin result := false; rIterator := -1; if aData <> nil then begin i := 0; while (i < rCount) and (rArray[i].rLightable <> aData) do inc(i); if rArray[i].rLightable = aData then begin result := true; rIterator := i; end; end; end; type TdgViewport2D = class(Tdg2DDrawNotifier) constructor Create; destructor Destroy; override; private fRightTopFar: TdgVector3f; fLeftBottomNear: TdgVector3f; fAmbient: TdgVector4f; fLightableList: TdgLightDataList; fNodeableList: TdgNodeDataList; fDeltaTime: TdgFloat; procedure Enable; inline; procedure Disable; inline; public function pDeltaTime: PdgFloat; override; procedure Render; override; procedure Attach(const aNode: TdgDrawable); overload; override; procedure Detach(const aNode: TdgDrawable); overload; override; procedure Attach(const aNode: TdgLightable); overload; override; procedure Detach(const aNode: TdgLightable); overload; override; procedure SetRightTopFar(const aValue: TdgVector3f); override; function GetRightTopFar: TdgVector3f; override; procedure SetLeftBottomNear(const aValue: TdgVector3f); override; function GetLeftBottomNear: TdgVector3f; override; function GetAmbient: TdgVector4f; override; procedure SetAmbient(const aColor: TdgVector4f); override; procedure DetachAllDrawable; override; end; constructor TdgViewport2D.Create; begin inherited Create; fRightTopFar := dgVector3f(0.0, 0.0, 0.0); fLeftBottomNear := dgVector3f(0.0, 0.0, 0.0); fAmbient := dgVector4f(1.0, 1.0, 1.0, 1.0); fLightableList.Create; fNodeableList.Create; fDeltaTime := 0.0; {$IFDEF dgTrace} // dgTrace.Write.Info('Created ...', cnstUnitName); {$ENDIF} end; destructor TdgViewport2D.Destroy; begin fLightableList.Free; fNodeableList.Free; inherited Destroy; end; procedure TdgViewport2D.DetachAllDrawable; begin fNodeableList.ExtractAll; end; procedure TdgViewport2D.Attach(const aNode: TdgDrawable); begin fNodeableList.Append(aNode); end; procedure TdgViewport2D.Detach(const aNode: TdgDrawable); begin if fNodeableList.StayOnData(aNode) then fNodeableList.Extract; end; procedure TdgViewport2D.Attach(const aNode: TdgLightable); begin fLightableList.Append(aNode); end; procedure TdgViewport2D.Detach(const aNode: TdgLightable); begin if fLightableList.StayOnData(aNode) then fLightableList.Extract; end; function TdgViewport2D.pDeltaTime: PdgFloat; begin result := @fDeltaTime; end; procedure TdgViewport2D.Render; var T: LARGE_INTEGER; F: LARGE_INTEGER; Time: TdgFloat; begin QueryPerformanceFrequency(Int64(F)); QueryPerformanceCounter(Int64(T)); Time := T.QuadPart / F.QuadPart; Enable; fLightableList.StayBeforeFirst; while fLightableList.StayOnNext do glEnable(GL_LIGHT0 + fLightableList.Data.rID); fNodeableList.StayBeforeFirst; while fNodeableList.StayOnNext do fNodeableList.Data.Draw; fLightableList.StayBeforeFirst; while fLightableList.StayOnNext do glDisable(GL_LIGHT0 + fLightableList.Data.rID); Disable; QueryPerformanceCounter(Int64(T)); fDeltaTime := T.QuadPart / F.QuadPart - Time; end; // Idg3DRenderSet = interface procedure TdgViewport2D.Enable; begin glMatrixMode(GL_PROJECTION); glLoadIdentity; // glOrtho(0, 1000, 700, 0, -1, 1); glOrtho(FLeftBottomNear.X, FRightTopFar.X, FLeftBottomNear.Y, FRightTopFar.Y, FLeftBottomNear.Z, FRightTopFar.Z); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glDisable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, @fAmbient); glEnable(GL_CULL_FACE); end; procedure TdgViewport2D.Disable; begin glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); end; procedure TdgViewport2D.SetRightTopFar(const aValue: TdgVector3f); begin fRightTopFar := aValue; end; function TdgViewport2D.GetRightTopFar: TdgVector3f; begin result := fRightTopFar; end; procedure TdgViewport2D.SetLeftBottomNear(const aValue: TdgVector3f); begin fLeftBottomNear := aValue; end; function TdgViewport2D.GetLeftBottomNear: TdgVector3f; begin result := fLeftBottomNear; end; function TdgViewport2D.GetAmbient: TdgVector4f; begin result := fAmbient; end; procedure TdgViewport2D.SetAmbient(const aColor: TdgVector4f); begin fAmbient := aColor; end; function dgCreate2DRenderSet: TObject; begin result := TdgViewport2D.Create; end; procedure dgAssign2DRenderSet(const aSource: TObject; aObject: TObject); var cSource: Tdg2DDrawNotifier; cObject: Tdg2DDrawNotifier; begin {$IFDEF dgAssert} dgTrace.Assert((aSource <> nil) or (aObject <> nil), '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName); dgTrace.Assert((aSource is Tdg2DDrawNotifier) or (aObject is Tdg2DDrawNotifier), '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName); {$ENDIF} cSource := aSource as Tdg2DDrawNotifier; cObject := aObject as Tdg2DDrawNotifier; cObject.LeftBottomNear := cSource.LeftBottomNear; cObject.RightTopFar := cSource.RightTopFar; cObject.Ambient := cSource.Ambient; end; procedure dgLoad2DRenderSet(const aResource: TdgReadResource; aObject: TObject); var cObject: Tdg2DDrawNotifier; begin {$IFDEF dgAssert} dgTrace.Assert(aObject <> nil, '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName); dgTrace.Assert(aObject is Tdg2DDrawNotifier, '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName); {$ENDIF} cObject := aObject as Tdg2DDrawNotifier; aResource.ReadOpenTag('2DViewPort'); with cObject do begin aResource.ReadInteger('Version'); LeftBottomNear := aResource.ReadVector3f( 'LeftBottomNear'); RightTopFar := aResource.ReadVector3f( 'RightTopFar'); Ambient := aResource.ReadVector4f( 'Ambient'); end; aResource.ReadCloseTag('2DViewPort'); end; procedure dgSave2DRenderSet(const aResource: TdgWriteResource; aObject: TObject); var cObject: Tdg2DDrawNotifier; begin {$IFDEF dgAssert} dgTrace.Assert(aObject <> nil, '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName); dgTrace.Assert(aObject is Tdg2DDrawNotifier, '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName); {$ENDIF} cObject := aObject as Tdg2DDrawNotifier; aResource.WriteOpenTag('2DViewPort'); with cObject do begin aResource.WriteInteger(20080419, 'Version'); aResource.WriteVector3f(LeftBottomNear, 'LeftBottomNear'); aResource.WriteVector3f(RightTopFar, 'RightTopFar'); aResource.WriteVector4f(Ambient, 'Ambient'); end; aResource.WriteCloseTag( '2DViewPort'); end; procedure dgInitViewport2D; begin dg.DrawNotifier.Viewport2D:=dg.CreateOnly.ObjectFactory( @dgSave2DRenderSet, @dgLoad2DRenderSet, @dgCreate2DRenderSet, @dgAssign2DRenderSet); dg.DebugScreen.Renderable:= TdgViewport2D.Create; with Tdg2DDrawNotifier(dg.DebugScreen.Renderable) do begin LeftBottomNear := dgVector3f(0.0, dg.Window.Height, -1.0); RightTopFar := dgVector3f(dg.Window.Width, 0.0, 1.0); end; end; end.
unit RegExpTest; interface uses TestFramework, System.RegularExpressions; type TRegExpTest = class(TTestCase) private FRegExp: TRegEx; FPattern: string; FInput: string; public procedure SetUp; override; procedure TearDown; override; published procedure TestCharColumnMatch; procedure TestExtractGroupValueByNumber; procedure TestExtractGroupValueByName; procedure TestUniversalColumnMatch; procedure TestDelimiterMatch; procedure TestVersionMatch; procedure TestAttributesListMatchNoEmpty; procedure TestAttributesListMatchNoEmptyQuoted; procedure TestAttributesListMatchFirstEmpty; procedure TestAttributesListMatchLastEmpty; procedure TestAttributesListMatchOnlyOneField; procedure TestAttributesListMatchOnlyOneFieldEmptyFails; procedure TestAttributesListMatchTwoFieldsEmpty; procedure TestCharsetMatch; procedure TestColumnsNumberMatch; procedure TestPairOfXYCoords; procedure TestStartWithCoordSys; end; implementation uses System.SysUtils; { TRegExpTest } procedure TRegExpTest.SetUp; begin inherited; { for TestAttributes family only } { Kept as inspiration FPattern := '(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)'; FPattern := '(,|^)([^",]*|"(?:[^"]|"")*")?'; } FPattern := '(,|^)("(?:[^"]|"")*"|[^,]*)?'; end; procedure TRegExpTest.TearDown; begin inherited; end; procedure TRegExpTest.TestAttributesListMatchNoEmpty; begin FInput := '102631446,27701,RA_NO_202,20040128,350006747,20040128,0'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'NoEmpty fail'); Check(FRegExp.Matches(FInput).Count = 7, 'Count=' + IntToStr(FRegExp.Matches(FInput).Count)); Check(FRegExp.Matches(FInput).Item[0].Groups[1].Value = '', '[0][1]=' + FRegExp.Matches(FInput).Item[0].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[0].Groups[2].Value = '102631446', '[0][2]=' + FRegExp.Matches(FInput).Item[0].Groups[2].Value); Check(FRegExp.Matches(FInput).Item[1].Groups[1].Value = ',', '[1][1]=' + FRegExp.Matches(FInput).Item[1].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[1].Groups[2].Value = '27701', '[1][2]=' + FRegExp.Matches(FInput).Item[1].Groups[2].Value); Check(FRegExp.Matches(FInput).Item[5].Groups[1].Value = ',', '[5][1]=' + FRegExp.Matches(FInput).Item[5].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[5].Groups[2].Value = '20040128', '[5][2]=' + FRegExp.Matches(FInput).Item[5].Groups[2].Value); end; procedure TRegExpTest.TestAttributesListMatchNoEmptyQuoted; begin FInput := '"4","37","Äàíèëåâñêîãî","óë.","","3, ""×È×ÈÁÀÁÈÍÀ"" ÁÎÐÈÑÀ ÓË.","L"'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'NoEmptyQuoted fail'); Check(FRegExp.Matches(FInput).Item[0].Groups[1].Value = '', '[0][1]=' + FRegExp.Matches(FInput).Item[0].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[0].Groups[2].Value = '"4"', '[0][2]=' + FRegExp.Matches(FInput).Item[0].Groups[2].Value); Check(FRegExp.Matches(FInput).Item[2].Groups[1].Value = ',', '[2][1]=' + FRegExp.Matches(FInput).Item[1].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[2].Groups[2].Value = '"Äàíèëåâñêîãî"', '[2][2]=' + FRegExp.Matches(FInput).Item[1].Groups[2].Value); Check(FRegExp.Matches(FInput).Item[5].Groups[1].Value = ',', '[5][1]=' + FRegExp.Matches(FInput).Item[5].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[5].Groups[2].Value = '"3, ""×È×ÈÁÀÁÈÍÀ"" ÁÎÐÈÑÀ ÓË."', '[5][2]=' + FRegExp.Matches(FInput).Item[5].Groups[2].Value); end; procedure TRegExpTest.TestAttributesListMatchOnlyOneField; begin FInput := '0'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'IsMatch failed'); Check(FRegExp.Matches(FInput).Count = 1, 'Count=' + IntToStr(FRegExp.Matches(FInput).Count)); Check(FRegExp.Matches(FInput).Item[0].Groups[1].Value = '', '[0][1]=' + FRegExp.Matches(FInput).Item[0].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[0].Groups[2].Value = '0', '[0][2]=' + FRegExp.Matches(FInput).Item[0].Groups[2].Value); end; procedure TRegExpTest.TestAttributesListMatchOnlyOneFieldEmptyFails; begin FInput := ''; FRegExp.Create(FPattern); Check(not FRegExp.IsMatch(FInput), 'IsMatch should fail'); end; procedure TRegExpTest.TestAttributesListMatchTwoFieldsEmpty; begin FInput := ','; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'IsMatch failed'); Check(FRegExp.Matches(FInput).Count = 1, 'Count=' + IntToStr(FRegExp.Matches(FInput).Count)); Check(FRegExp.Matches(FInput).Item[0].Groups[1].Value = ',', '[0][1]=' + FRegExp.Matches(FInput).Item[0].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[0].Groups[2].Value = '', '[0][2]=' + FRegExp.Matches(FInput).Item[0].Groups[2].Value); end; procedure TRegExpTest.TestAttributesListMatchFirstEmpty; begin FInput := ',27701,RA_NO_202,20040128,350006747,20040128,'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'IsMatch failed'); Check(FRegExp.Matches(FInput).Count = 6, 'Count=' + IntToStr(FRegExp.Matches(FInput).Count)); Check(FRegExp.Matches(FInput).Item[0].Groups[1].Value = ',', '[0][1]=' + FRegExp.Matches(FInput).Item[0].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[0].Groups[2].Value = '27701', '[0][2]=' + FRegExp.Matches(FInput).Item[0].Groups[2].Value); Check(FRegExp.Matches(FInput).Item[1].Groups[1].Value = ',', '[1][1]=' + FRegExp.Matches(FInput).Item[1].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[1].Groups[2].Value = 'RA_NO_202', '[1][2]=' + FRegExp.Matches(FInput).Item[1].Groups[2].Value); Check(FRegExp.Matches(FInput).Item[5].Groups[1].Value = ',', '[5][1]=' + FRegExp.Matches(FInput).Item[5].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[5].Groups[2].Value = '', '[5][2]=' + FRegExp.Matches(FInput).Item[5].Groups[2].Value); end; procedure TRegExpTest.TestAttributesListMatchLastEmpty; begin FInput := '0,27701,RA_NO_202,20040128,350006747,20040128,'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'IsMatch failed'); Check(FRegExp.Matches(FInput).Count = 7, 'Count=' + IntToStr(FRegExp.Matches(FInput).Count)); Check(FRegExp.Matches(FInput).Item[0].Groups[1].Value = '', '[0][1]=' + FRegExp.Matches(FInput).Item[0].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[0].Groups[2].Value = '0', '[0][2]=' + FRegExp.Matches(FInput).Item[0].Groups[2].Value); Check(FRegExp.Matches(FInput).Item[2].Groups[1].Value = ',', '[2][1]=' + FRegExp.Matches(FInput).Item[2].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[2].Groups[2].Value = 'RA_NO_202', '[2][2]=' + FRegExp.Matches(FInput).Item[2].Groups[2].Value); Check(FRegExp.Matches(FInput).Item[6].Groups[1].Value = ',', '[6][1]=' + FRegExp.Matches(FInput).Item[6].Groups[1].Value); Check(FRegExp.Matches(FInput).Item[6].Groups[2].Value = '', '[6][2]=' + FRegExp.Matches(FInput).Item[6].Groups[2].Value); end; procedure TRegExpTest.TestCharColumnMatch; begin FPattern := '^\s*\w+\s+\w+\s*\(\d+\)'; FInput := ' NAME_UKR Char(64)'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput)); end; procedure TRegExpTest.TestCharsetMatch; begin FPattern := '^\s*CHARSET\s+"(?P<charset>\w+)"'; FInput := 'Charset "WindowsCyrillic"'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput)); Check(FRegExp.Match(FInput).Groups['charset'].Value = 'WindowsCyrillic'); end; procedure TRegExpTest.TestColumnsNumberMatch; begin FPattern := '^\s*COLUMNS\s+(?P<columns_number>\d+)'; FInput := 'COLUMNS 7'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput)); Check(FRegExp.Match(FInput).Groups['columns_number'].Value = '7'); end; procedure TRegExpTest.TestDelimiterMatch; begin FPattern := '^\s*DELIMITER\s+"(?P<delimiter>.)"'; FInput := 'DELIMITER ","'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput)); Check(FRegExp.Match(FInput).Groups['delimiter'].Value = ','); FInput := 'Delimiter ","'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput)); Check(FRegExp.Match(FInput).Groups['delimiter'].Value = ','); end; procedure TRegExpTest.TestUniversalColumnMatch; begin FPattern := '^\s*(?P<name>\w+)\s+(?P<type>\w+)(\s*\((?P<length>\d+)(,?(?P<precision>\d+)?)\))?'; FInput := ' PFI_CREATED date'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'date match fails'); Check(FRegExp.Match(FInput).Groups['name'].Value = 'PFI_CREATED'); Check(FRegExp.Match(FInput).Groups['type'].Value = 'date'); { Access to non-existent group doesn't allowed! Check(FRegExp.Match(FInput).Groups['length'].Value = '');} FInput := ' FEATURE_QUALITY_ID char(20)'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'char(20) match fails'); Check(FRegExp.Match(FInput).Groups['name'].Value = 'FEATURE_QUALITY_ID'); Check(FRegExp.Match(FInput).Groups['type'].Value = 'char'); Check(FRegExp.Match(FInput).Groups['length'].Value = '20'); FInput := ' UFI decimal(12,0)'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput), 'decimal(12,0) match fails'); Check(FRegExp.Match(FInput).Groups['name'].Value = 'UFI'); Check(FRegExp.Match(FInput).Groups['type'].Value = 'decimal'); Check(FRegExp.Match(FInput).Groups['length'].Value = '12'); Check(FRegExp.Match(FInput).Groups['precision'].Value = '0'); end; procedure TRegExpTest.TestVersionMatch; begin FPattern := '^\s*VERSION\s+(?P<version>\d{3})'; FInput := 'VERSION 300'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput)); Check(FRegExp.Match(FInput).Groups['version'].Value = '300'); FInput := 'Version 300'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput)); Check(FRegExp.Match(FInput).Groups['version'].Value = '300'); end; procedure TRegExpTest.TestExtractGroupValueByName; begin FPattern := '^\s*(?P<name>\w+)\s+(?P<type>\w+)\s*\((?P<length>\d+)\)'; FInput := ' NAME_UKR Char(64)'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput)); Check(FRegExp.Match(FInput).Groups['name'].Value = 'NAME_UKR'); Check(FRegExp.Match(FInput).Groups['type'].Value = 'Char'); Check(FRegExp.Match(FInput).Groups['length'].Value = '64'); end; procedure TRegExpTest.TestExtractGroupValueByNumber; begin FPattern := '^\s*(\w+)\s+(\w+)\s*\((\d+)\)'; FInput := ' NAME_UKR Char(64)'; FRegExp.Create(FPattern); Check(FRegExp.IsMatch(FInput)); Check(FRegExp.Match(FInput).Groups[1].Value = 'NAME_UKR'); Check(FRegExp.Match(FInput).Groups[2].Value = 'Char'); Check(FRegExp.Match(FInput).Groups[3].Value = '64'); end; procedure TRegExpTest.TestPairOfXYCoords; begin FPattern := '^\s*(?P<x>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))\s+(?P<y>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))'; FInput := '2467897.94083642 2450415.94219368'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput), '0.00 fail'); Check(FRegExp.Match(FInput).Groups['x'].Value = '2467897.94083642'); Check(FRegExp.Match(FInput).Groups['y'].Value = '2450415.94219368'); FInput := '24 94'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput), '0 fail'); Check(FRegExp.Match(FInput).Groups['x'].Value = '24'); Check(FRegExp.Match(FInput).Groups['y'].Value = '94'); FInput := '24. 94.'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput), '0. fail'); Check(FRegExp.Match(FInput).Groups['x'].Value = '24.'); Check(FRegExp.Match(FInput).Groups['y'].Value = '94.'); FInput := '.24 .94'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput), '.00 fail'); Check(FRegExp.Match(FInput).Groups['x'].Value = '.24'); Check(FRegExp.Match(FInput).Groups['y'].Value = '.94'); end; procedure TRegExpTest.TestStartWithCoordSys; begin FPattern := '^\s*COORDSYS'; FInput := ' CoordSys Earth Projection 3, 116, "m", 145, -37, -36, -38, 2500000, 2500000 Bounds (1500000,1500000) (3500000,3500000)'; FRegExp.Create(FPattern, [roIgnoreCase]); Check(FRegExp.IsMatch(FInput)); end; initialization RegisterTest(TRegExpTest.Suite); end.
// // Name: FlashPanel.pas // Desc: FlashPanel Component // A panel that flashes between 2 colors // // Author: David Verespey // // Revision History: // // 09/01/96 Start Program // // unit FlashPanel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, emptypanel, ThreadedPanel; type TFlashPanel = class(TThreadedPanel) private { Private declarations } fFlashColor: TColor; fColor: TColor; protected { Protected declarations } procedure SetFlashColor(value: TColor); procedure UpdateTimer; override; procedure Timer; override; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property FlashColor: TColor read fFlashColor write SetFlashColor; end; implementation constructor TFlashPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); FlashColor:=clRed; fColor:=Color; end; procedure TFlashPanel.SetFlashColor(value: TColor); begin fFlashColor:=value; end; procedure TFlashPanel.UpdateTimer; begin if fEnabled then begin fColor:=Color; end; Inherited UpdateTimer; if not fEnabled then begin // Reset back to original Color:=fColor; end; end; procedure TFlashPanel.Timer; begin if Color = fColor then begin Color:=fFlashColor; end else begin Color:=fColor; end; end; end.
program testord02(output); {tests chr() - note that the compiler_test has issues reading the unprintable characters} var i:integer; begin i := 32; repeat writeln(i,': ',chr(i)); i := i + 1; until i = 128; writeln('and this should fail with an error:'); writeln(chr(256)); end.
unit frmDataModule; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, Bde; type TDBModule = class(TDataModule) DSProgram: TDataSource; TableProgram: TTable; DSControl: TDataSource; TableControl: TTable; DSLookup: TDataSource; TableLookup: TTable; procedure DSProgramStateChange(Sender: TObject); procedure DSProgramUpdateData(Sender: TObject); procedure DSProgramDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } procedure DoReindex(Table: TTable); procedure PackTable(Table: TTable); end; var DBModule: TDBModule; implementation {$R *.DFM} uses ProgramVars; procedure TDBModule.DSProgramStateChange(Sender: TObject); begin case TableProgram.State of dsEdit: EditMode := TRUE; dsInsert: EditMode := TRUE; else EditMode := FALSE; end; end; procedure TDBModule.DSProgramUpdateData(Sender: TObject); begin FileModified := TRUE; end; { ReIndex a Paradox table } procedure TDBModule.DoReindex(Table: TTable); begin { Close our table } Table.Close; { Set exclusive so noone can edit while we reindex } Table.Exclusive := TRUE; { Open our table } Table.Open; { Make sure the table is open exclusively so we can get the db handle } if not Table.Active then raise EDatabaseError.Create('Table must be opened to pack'); if not Table.Exclusive then raise EDatabaseError.Create('Table must be opened exclusively to pack'); { Allow the BDE to regenerate our indexes } Check(DbiRegenIndexes(Table.Handle)); { Close our table } Table.Close; { Reset our exclusive mode } Table.Exclusive := FALSE; { Open our table } Table.Open; end; { Pack a Paradox or dBASE table } procedure TDBModule.PackTable(Table: TTable); var Props: CURProps; hDb: hDBIDb; TableDesc: CRTblDesc; begin { Close our table } Table.Close; { Set exclusive so noone can edit while we pack } Table.Exclusive := TRUE; { Open our table } Table.Open; { Make sure the table is open exclusively so we can get the db handle } if not Table.Active then raise EDatabaseError.Create('Table must be opened to pack'); if not Table.Exclusive then raise EDatabaseError.Create('Table must be opened exclusively to pack'); { Get the table properties to determine table type } Check(DbiGetCursorProps(Table.Handle, Props)); { If the table is a Paradox table, you must call DbiDoRestructure... } if (Props.szTableType = szPARADOX) then begin { Blank out the structure... } FillChar(TableDesc, sizeof(TableDesc), 0); { Get the database handle from the table's cursor handle... } Check(DbiGetObjFromObj(hDBIObj(Table.Handle), objDATABASE, hDBIObj(hDb))); { Put the table name in the table descriptor... } StrPCopy(TableDesc.szTblName, Table.TableName); { Put the table type in the table descriptor... } StrPCopy(TableDesc.szTblType, Props.szTableType); { Set the Pack option in the table descriptor to TRUE... } TableDesc.bPack := True; { Close the table so the restructure can complete... } Table.Close; { Call DbiDoRestructure... } Check(DbiDoRestructure(hDb, 1, @TableDesc, nil, nil, nil, False)); end else { If the table is a dBASE table, simply call DbiPackTable... } if (Props.szTableType = szDBASE) then Check(DbiPackTable(Table.DBHandle, Table.Handle, nil, szDBASE, True)) else { Pack only works on PAradox or dBASE; nothing else... } raise EDatabaseError.Create('Table must be either of Paradox or dBASE type to pack'); (* Neste momento não é usado aqui, devido ao facto de eu usar uma extensão diferente { Close our table } Table.Close; { Reset our exclusive mode } Table.Exclusive := FALSE; { Open our table } Table.Open; *) end; procedure TDBModule.DSProgramDataChange(Sender: TObject; Field: TField); begin DataAsChanged := TRUE; end; end.
unit ChangeLasFileFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, BaseObjects, Facade, LasFile, Well, ActnList, formReplacement; type TfrmChangeLasFile = class(TFrame) gbx1: TGroupBox; pgcMain: TPageControl; tsJoin: TTabSheet; tsChange: TTabSheet; lstBoxArea: TListBox; lstBoxWell: TListBox; btnJoinToWell: TButton; actlstChangeLasFile: TActionList; actJoinToWell: TAction; gbxVersion: TGroupBox; gbxWell: TGroupBox; gbxCurve: TGroupBox; gbxAscii: TGroupBox; lstVersion: TListBox; lstWell: TListBox; lstCurve: TListBox; lstAscii: TListBox; actChangeLasFile: TAction; actLstClick: TAction; actLstRowDblClick: TAction; procedure lstBoxAreaClick(Sender: TObject); procedure actJoinToWellUpdate(Sender: TObject); procedure actJoinToWellExecute(Sender: TObject); procedure actLstRowDblClickExecute(Sender: TObject); procedure lstCurveDblClick(Sender: TObject); private { Private declarations } FOnSelectedWellChanged: TNotifyEvent; FLasFiles: TLasFiles; FLasFileContents: TLasFileContents; FSelectedLasFile: TLasFile; function GetSelectedWell: TWell; procedure SetLasFiles(const Value: TLasFiles); procedure SetSelectedLasFile(const Value: TLasFile); procedure CreateContents; function GetCurrentContent: TLasFileContent; public { Public declarations } property OnWellSelected: TNotifyEvent read FOnSelectedWellChanged write FOnSelectedWellChanged; property SelectedWell: TWell read GetSelectedWell; property LasFiles: TLasFiles read FLasFiles write SetLasFiles; property SelectedLasFile: TLasFile read FSelectedLasFile write SetSelectedLasFile; property CurrentContent: TLasFileContent read GetCurrentContent; procedure ViewLasFileInLstBox(ALasFile : TLasFile); overload; // procedure ViewLasFileInLstBox(ALasFileContent : TLasFileContent); overload; {procedure MakeReplac(AReplacements: TReplacementList; ALasFile:TLasFile); } function RowReplac (inputString :string; repString:string) : string; // procedure ReplaceWellBlock (AWell: TWell); // function GetLasFileContent(ALasFile :TLasFile) : TLasFileContent; //function FindStringInContent (ALasFileContent :TLasFileContent; inputString : string) : string; end; implementation {$R *.dfm} function TfrmChangeLasFile.GetSelectedWell: TWell; begin if lstBoxWell.ItemIndex > -1 then Result := (lstBoxWell.Items.Objects [lstBoxWell.ItemIndex]) as TWell else Result := nil; end; procedure TfrmChangeLasFile.lstBoxAreaClick(Sender: TObject); var TmpArea : TIDObject; begin TmpArea := (lstBoxArea.Items.Objects [lstBoxArea.ItemIndex]) as TIDObject; TMainFacade.GetInstance.LasFilter:= 'AREA_ID = ' + IntToStr(TmpArea.ID); TMainFacade.GetInstance.SkipLasWells; TMainFacade.GetInstance.AllLasWells.MakeList(lstBoxWell.Items); end; procedure TfrmChangeLasFile.actJoinToWellUpdate(Sender: TObject); begin actJoinToWell.Enabled := Assigned(SelectedWell); end; procedure TfrmChangeLasFile.actJoinToWellExecute(Sender: TObject); begin // вот тут должна быть привязка, т.е вызов замены полей ласфайла которые содержать название площади, номер скв. и UWI if Assigned(SelectedLasFile) then if Assigned(FOnSelectedWellChanged) then begin if Assigned(FOnSelectedWellChanged) then FOnSelectedWellChanged(SelectedWell); //ReplaceWellBlock(SelectedWell); end; end; procedure TfrmChangeLasFile.SetLasFiles(const Value: TLasFiles); begin if FLasFiles <> Value then begin FLasFiles := Value; FSelectedLasFile := nil; CreateContents; end; end; procedure TfrmChangeLasFile.SetSelectedLasFile(const Value: TLasFile); begin FSelectedLasFile := Value; if Assigned(FSelectedLasFile) then ViewLasFileInLstBox(FSelectedLasFile); end; procedure TfrmChangeLasFile.ViewLasFileInLstBox(ALasFile: TLasFile); begin // ViewLasFileInLstBox(GetLasFileContent(ALasFile)); end; { procedure TfrmChangeLasFile.MakeReplac(AReplacements: TReplacementList; ALasFile:TLasFile); var ALasFileContent :TLasFileContent; begin ALasFileContent := TLasFileContent.Create(ALasFile); ALasFileContent.ReadFile; ALasFileContent.MakeReplacements(AReplacements); ALasFileContent.SaveFile(); ViewLasFileInLstBox(ALasFile); end; } function TfrmChangeLasFile.RowReplac(inputString, repString: string): string; var lab1, lab2, i : Integer; part1, part2 : string; begin lab1 := Pos(' ', inputString); lab2 := Pos(':', inputString); part1 := Copy(inputString, 1, lab1); part2 := Copy (inputString, lab2, Length(inputString)- lab2); Result:=part1; for i:=0 to lab2-lab1-Length(repString)-2 do Result:=Result+' '; Result:=Result+repString+part2; end; { procedure TfrmChangeLasFile.ReplaceWellBlock(AWell: TWell); var i: Integer; AReplacements :TReplacementList; str1, str2 : string; begin for i:=0 to AWell.LasFiles.Count-1 do if (AWell.LasFiles.Items[i].IsChanged) then begin AReplacements:= TReplacementList.Create(); str1:= FindStringInContent(CurrentContent, 'WELL'); str2:=RowReplac(str1, AWell.NumberWell); AReplacements.AddReplacement('~Well', 'WELL', str1, str2); str1:= FindStringInContent(CurrentContent, 'FLD'); str2:=RowReplac(str1, AWell.Area.Name); AReplacements.AddReplacement('~Well', 'FLD', str1, str2); str1:= FindStringInContent(CurrentContent, 'UWI'); str2:=RowReplac(str1, IntToStr(AWell.ID)); AReplacements.AddReplacement('~Well', 'UWI', str1, str2); MakeReplac(AReplacements, AWell.LasFiles.Items[i]); end; end; } { function TfrmChangeLasFile.GetLasFileContent(ALasFile: TLasFile): TLasFileContent; var ALasFileContent:TLasFileContent; s:string; begin ALasFileContent := TLasFileContent.Create(ALasFile); ALasFileContent.ReadFile; s:=ALasFileContent.Blocks.ItemByName['~Well'].RealContent.Strings[5]; Result:= ALasFileContent; Assert(Result <> nil, 'LasfileContent не создан'); end; } { function TfrmChangeLasFile.FindStringInContent(ALasFileContent: TLasFileContent; inputString: string): string; var i,j : Integer; begin Result:=''; for i:=0 to ALasFileContent.Blocks.Count-1 do for j:=0 to ALasFileContent.Blocks.Items[i].RealContent.Count-1 do if (Pos(inputString, ALasFileContent.Blocks.Items[i].RealContent.Strings[j])>0) then Result:= ALasFileContent.Blocks.Items[i].RealContent.Strings[j]; end; } procedure TfrmChangeLasFile.actLstRowDblClickExecute(Sender: TObject); var ListBox : TListBox; begin ListBox := Sender as TListBox; FreeAndNil(formReplac); formReplac := TformReplac.Create(Self); formReplac.FormType := rftSimple; //formReplac.InputString := FindStringInContent(CurrentContent, ListBox.Items[ListBox.ItemIndex]); if formReplac.ShowModal = mrOk then /// end; { procedure TfrmChangeLasFile.ViewLasFileInLstBox( ALasFileContent: TLasFileContent); begin lstVersion.Items.BeginUpdate; lstVersion.Clear; lstVersion.Items.AddStrings(ALasFileContent.Blocks.ItemByName['~Version'].RealContent); lstVersion.Items.EndUpdate; lstWell.Items.BeginUpdate; lstWell.Clear; lstWell.Items.AddStrings(ALasFileContent.Blocks.ItemByName['~Well'].RealContent); lstWell.Items.EndUpdate; lstCurve.Items.BeginUpdate; lstCurve.Clear; lstCurve.Items.AddStrings(ALasFileContent.Blocks.ItemByName['~Curve'].RealContent); lstCurve.Items.AddStrings(ALasFileContent.Blocks.ItemByName['~Parameter'].RealContent); lstCurve.Items.AddStrings(ALasFileContent.Blocks.ItemByName['~Parametr'].RealContent); lstCurve.Items.AddStrings(ALasFileContent.Blocks.ItemByName['~Other'].RealContent); lstCurve.Items.EndUpdate; lstAscii.Items.BeginUpdate; lstAscii.Clear; lstAscii.Items.AddStrings(ALasFileContent.Blocks.ItemByName['~A'].RealContent); lstAscii.Items.EndUpdate; end; } procedure TfrmChangeLasFile.CreateContents; var i: integer; lc: TLasFileContent; begin { TODO : Спрашивать о сохранении изменений в файле } // или спрашивать или по тихому сохранять все контенты FreeAndNil(FLasFileContents); FLasFileContents := TLasFileContents.Create; for i := 0 to LasFiles.Count - 1 do begin lc := TLasFileContent.Create(LasFiles.Items[i]); FLasFileContents.Add(lc); end; end; function TfrmChangeLasFile.GetCurrentContent: TLasFileContent; begin if Assigned(SelectedLasFile) then begin if not Assigned(FLasFileContents) then FLasFileContents:=TLasFileContents.Create; Result := FLasFileContents.GetContentByFile(SelectedLasFile) end else Result := nil; end; procedure TfrmChangeLasFile.lstCurveDblClick(Sender: TObject); var ListBox : TListBox; tempStr :String; i, j : integer; begin j:=0; ListBox := Sender as TListBox; tempStr:= Copy (ListBox.Items[ListBox.ItemIndex], pos('.',ListBox.Items[ListBox.ItemIndex]), Pos(':',ListBox.Items[ListBox.ItemIndex])-Pos('.',ListBox.Items[ListBox.ItemIndex])); for i:=1 to Length(tempStr) do if tempStr[i]=' ' then Inc(j); tempStr:= Copy(tempStr, j+2, Length(tempStr)-j); FreeAndNil(formReplac); formReplac := TformReplac.Create(Self); formReplac.FormType := rftCurves; formReplac.InputString := tempStr; if formReplac.ShowModal = mrOk then end; end.
unit ReasonChange; interface uses Registrator, BaseObjects, Employee, Classes; type TReasonChange = class (TRegisteredIDObject) private FDtmChange: TDateTime; FEmployee: TEmployee; protected procedure AssignTo(Dest: TPersistent); override; public // дата изменений property DtmChange: TDateTime read FDtmChange write FDtmChange; // сотрудник, внесший последние изменения property Employee: TEmployee read FEmployee write FEmployee; constructor Create (ACollection: TIDObjects); override; end; TReasonChanges = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TReasonChange; public property Items[Index: Integer]: TReasonChange read GetItems; Constructor Create; override; end; implementation uses ReasonChangePoster, Facade; { TReasonChange } procedure TReasonChange.AssignTo(Dest: TPersistent); var o: TReasonChange; begin inherited; o := Dest as TReasonChange; o.DtmChange := DtmChange; o.Employee := Employee; end; constructor TReasonChange.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Причина изменений'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TReasonChangeDataPoster]; end; { TReasonChanges } constructor TReasonChanges.Create; begin inherited; FObjectClass := TReasonChange; Poster := TMainFacade.GetInstance.DataPosterByClassType[TReasonChangeDataPoster]; end; function TReasonChanges.GetItems(Index: Integer): TReasonChange; begin Result := inherited Items[Index] as TReasonChange; end; end.
unit f2h; {*******************************************************} { } { Form to HTML converter "F2H" } { } { Copyright (c) 1998-2018 HREF Tools Corp. } { http://www.href.com/f2h } { } { This file is licensed under a Creative Commons } { Share-Alike 3.0 License. } { http://creativecommons.org/licenses/by-sa/3.0/ } { If you use this file, please keep this notice } { intact. } { } { Developed by HREF Tools Corp. 1998-2012 } { First author: Philippe Maquet } { } {*******************************************************} interface {$DEFINE IN_WEB_APPLICATION} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, tpIntegerTypes; type THBrowserFamily = (bfDefault, bfIE3, bfIE4, bfNS3, bfNS4); THBrowserRunFamily = (brfIE3, brfIE4, brfNS3, brfNS4); THAttrType = (atString, atBoolean, atInteger, atList); THAttrOption = (aoEditable, aoHTML, aoIgnore, aoWebHub, aoDialog, aoNoName); THAttrOptions = set of THAttrOption; THAttribute = class; THADialogProc = procedure (attr : THAttribute; var bEdited : Boolean) of object; THAGetDefaultProc = procedure (var defaultString : string) of object; THAValidateProc = procedure (var aValue : string; var bOK : Boolean) of object; THAValueChangedProc = procedure (changedAttr : THAttribute) of object; THAttribute = class(TObject) // an HTML attribute private _attrType : THAttrType; _bChanged : Boolean; _bIsDefault : Boolean; _defValue : string; _dialogProc : THADialogProc; _getDefaultProc : THAGetDefaultProc; _hint : string; _name : string; _options : THAttrOptions; _savedValue : string; _stdAttrName : string; _validateProc : THAValidateProc; _value : string; _valueChangedProc : THAValueChangedProc; _valuesList : TStringList; function ValueEquals(compObj : THAttribute) : Boolean; function getBChanged : Boolean; function getBooleanValue : Boolean; function getDefValue : string; function getHTML : string; function getNextValue : string; function getValue : string; procedure setBooleanValue(b : Boolean); procedure setDefValue(const aValue : string); procedure setOptions(options : THAttrOptions); procedure setValue(const aValue : string); procedure writeData(writer: TWriter); public constructor create(const aName : string; aType : THAttrType; const aHint : string); destructor Destroy; override; class function boolean2String(b : Boolean) : string; function isValid(var aValue : string) : Boolean; procedure restore; procedure save; class function string2Boolean(const s : string) : Boolean; //properties property AttrType : THAttrType read _attrType; property BooleanValue : Boolean read getBooleanValue write setBooleanValue; property Changed : Boolean read getBChanged; // information for the editor property DefValue : string read getDefValue write setDefValue; property DialogProc : THADialogProc read _dialogProc write _dialogProc; property GetDefaultProc : THAGetDefaultProc read _GetDefaultProc write _GetDefaultProc; property Hint : string read _hint; property HTML : string read getHTML; property Name : string read _name; property NextValue : string read getNextValue; property Options : THAttrOptions read _options write setOptions; property StdAttrName : string read _stdAttrName write _stdAttrName; property ValidateProc : THAValidateProc read _validateProc write _validateProc; property Value : string read getValue write setValue; property ValueChangedProc : THAValueChangedProc read _valueChangedProc write _valueChangedProc; property ValuesList : TStringList read _valuesList; end; THAttributes = class(TObject) // an HTML object's attributes list private _attributes : TList; _optionsFilter : THAttrOptions; function ValueEquals(compObj : THAttributes) : Boolean; function getAttribute(const attrName : string) : THAttribute; function getAttributeN(index : integer) : THAttribute; function getCount : integer; function getHTML : string; procedure writeData(writer: TWriter); public destructor Destroy; override; procedure add(anAttr : THAttribute); procedure remove(const attrName : string); procedure save; procedure restore; // Properties property Attribute[const attrName : string] : THAttribute read getAttribute; default; property AttributeN[index : integer] : THAttribute read getAttributeN; property Count : integer read getCount; property HTML : string read getHTML; property OptionsFilter : THAttrOptions read _optionsFilter write _optionsFilter; end; TWHForm2HTML = class; THAttrObject = class(TObject) private _attributes : THAttributes; _form2HTML : TWHForm2HTML; procedure copyAttributesFrom(fromAO : THAttrObject); function ValueEquals(compObj : THAttrObject) : Boolean; virtual; function getName : string; virtual; abstract; procedure setOptionsFilter(optionsFilter : THAttrOptions); virtual; procedure setWebHubMode(b : Boolean); virtual; procedure writeData(writer: TWriter); virtual; public constructor createHAttrObject; virtual; destructor Destroy; override; property Attributes : THAttributes read _attributes; property Form2HTML : TWHForm2HTML read _form2HTML write _form2HTML; property Name : string read getName; property OptionsFilter : THAttrOptions write setOptionsFilter; property WebHubMode : Boolean write setWebHubMode; end; THContainer = class; THElement = class(THAttrObject) // Any element. Owns the BeforeElement/After attributes private procedure addBeforeAndAfterElements(var toS : string); function getAfterElement : string; function getBeforeElement : string; public constructor createHAttrObject; override; end; THControl = class(THElement) // An abstract HTML control, container or not private _bRightAligned : Boolean; _bRendered : Boolean; _bSynch : Boolean; _control : TControl; _col, _colspan, _row, _rowspan : integer; _hContainer : THContainer; procedure addAnchorsAttributes; procedure asAnchorChanged(attr : THAttribute); procedure asWHAnchorChanged(attr : THAttribute); procedure getDefaultWHAnchorMacro(var defWHAnchorMacro : string); function getEnabled : Boolean; function getHTML : string; virtual; function getHTMLBeginTag : string; virtual; function getHTMLEndTag : string; virtual; function getHTMLText: string; virtual; function getName : string; override; function getNamePath : string; function getVisible : Boolean; function getWHResetToDefaultMacro(clearList : TStringList) : string; virtual; procedure setSynchronized(bOnOff : Boolean); virtual; public constructor create(aControl : TControl); virtual; function getHDims(var hWidth, hHeight : integer) : Boolean; virtual; property Control : TControl read _control; property Enabled : Boolean read getEnabled; property HTML : string read getHTML; property RightAligned : Boolean read _bRightAligned write _bRightAligned; property Synchronized : Boolean read _bSynch write setSynchronized; property Visible : Boolean read getVisible; end; THControlClass = class of THControl; THLabel = class(THControl) // A label private function getHTML: string; override; function getHTMLText: string; override; public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THWinControl = class(THControl) private function getHTML : string; override; function getHTMLText : string; override; public function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THNamed = class(THWinControl) // Any control with a "name" attribute private procedure getDefaultName (var defaultName : string); virtual; public constructor create(aControl : TControl); override; end; THMemo = class(THNamed) // Any control of type <TEXTAREA> private procedure getDefaultCols(var defCols : string); procedure getDefaultText(var defText : string); procedure getDefaultRows(var defRows : string); function getHTMLBeginTag : string; override; function getHTMLText : string; override; function getHTMLEndTag : string; override; function getHTML : string; override; function getWHResetToDefaultMacro(clearList : TStringList) : string; override; public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THInput = class(THNamed) // Any control of type <INPUT> private function getHTMLBeginTag : string; override; end; THButton = class(THInput) private procedure asImageChanged(attr : THAttribute); procedure getDefaultAlt(var defAlt : string); procedure getDefaultValue(var defValue : string); function getHTML : string; override; function getHWidth(const sCaption : string) : integer; function getPureCaption : string; procedure validateType(var sType : string; var bOK : Boolean); public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THImage = class(THNamed) private procedure asButtonChanged(attr : THAttribute); procedure getDefaultAlt(var defAlt : string); procedure getDefaultHeight(var defHeight : string); procedure getDefaultWidth(var defWidth : string); function getHTMLBeginTag : string; override; function getHTMLEndTag : string; override; function getHTML : string; override; public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THEdit = class(THInput) // <INPUT type="text"> private procedure getDefaultMaxLength(var defMaxLength : string); procedure getDefaultSize(var defSize : string); procedure getDefaultType(var defType : string); procedure getDefaultValue(var defValue : string); function getHTML : string; override; function getWHResetToDefaultMacro(clearList : TStringList) : string; override; procedure validateMaxLength(var sMaxLength : string; var bOK : Boolean); public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THCheck = class(THInput) // Any <INPUT> control with a "Checked" attribute private procedure getDefaultChecked(var defChecked : string); procedure getDefaultName (var defaultName : string); override; function getHTMLText: string; override; function isRadio : Boolean; public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THCheckBox = class(THCheck) // <INPUT type="checkbox"> private function getHTML : string; override; function getWHResetToDefaultMacro(clearList : TStringList) : string; override; public constructor create(aControl : TControl); override; end; THRadio = class(THCheck) // <INPUT type="radio"> private procedure getDefaultValue(var defValue : string); function getHTML : string; override; function getWHResetToDefaultMacro(clearList : TStringList) : string; override; public constructor create(aControl : TControl); override; end; THList = class(THNamed) private function getHTML : string; override; function getHTMLBeginTag : string; override; function getHTMLEndTag : string; override; function getHTMLText : string; override; function getItemsMaxLength(var index : integer) : integer; function getItemText(index : integer) : string; function getItemValue(index : integer) : string; function getStdHWidth : integer; function getWHResetToDefaultMacro(clearList : TStringList) : string; override; public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THComboBox = class(THList) public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THListBox = class(THList) private procedure getDefaultMultiple(var defMultiple : string); procedure getDefaultSize(var defSize : string); public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THPlacer = class(TObject) private _hContainer : THContainer; _form2HTML : TWHForm2HTML; _rows : TList; _xPrec, _yPrec : integer; procedure addRows(nRows : integer); procedure addCols(nCols : integer); function colCount : integer; function getCell(col, row : integer) : THControl; function getHTML : string; function rowCount : integer; procedure setCell(col, row : integer; hControl : THControl); property Cell[col, row : integer] : THControl read getCell write setCell; public constructor create(hControl : THControl; width, height, xPrec, yPrec : integer); destructor Destroy; override; procedure getHDims(var hWidth, hHeight : integer); procedure placeControl(hControl : THControl); property HTML : string read getHTML; end; THContainer = class(THWinControl) private _children : TList; _hPlacer : THPlacer; procedure createPlacer; function ValueEquals(compObj : THAttrObject) : Boolean; override; procedure freePlacer; function getChild(index : integer) : THControl; function getCount : integer; function getHTMLText: string; override; function getWHResetToDefaultMacro(clearList : TStringList) : string; override; procedure setChild(index : integer; anHControl : THControl); procedure setOptionsFilter(optionsFilter : THAttrOptions); override; procedure setSynchronized(bOnOff : Boolean); override; procedure setWebHubMode(b : Boolean); override; procedure writeData(writer: TWriter); override; public constructor create(aControl : TControl); override; destructor Destroy; override; function createNewChild(fromCtl : TControl) : THControl; function FindHObjectByName(const objName : string) : THAttrObject; function getHDims(var hWidth, hHeight : integer) : Boolean; override; procedure synchronize; procedure synchronizeDone; property Children[index : integer] : THControl read getChild write setChild; property Count : integer read getCount; end; THFormElement = class(THElement) // <FORM>..</FORM> element private function getName : string; override; procedure getDefaultWHAction(var defWHAction : string); procedure getDefaultWHTargetPageID(var defWHTargetPageID : string); procedure updateWHAction(attr : THAttribute); public constructor create; end; THForm = class(THContainer) // A form container private procedure CaptionColorDlg(attr : THAttribute; var bEdited : Boolean); function getHTMLText: string; override; procedure ShowCaptionChanged(attr : THAttribute); public constructor create(aControl : TControl); override; end; THPanel = class(THContainer) // A panel container private procedure getDefaultBorder(var defBorder : string); function getHTMLText: string; override; procedure validateBorder(var sBorder : string; var bOK : Boolean); public constructor create(aControl : TControl); override; function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THGroupBox = class(THContainer) private function getHTMLText: string; override; public function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THRadioGroup = class(THNamed) private function getHTMLText: string; override; function getHTML : string; override; function itemsHTML : string; function getWHResetToDefaultMacro(clearList : TStringList) : string; override; public function getHDims(var hWidth, hHeight : integer) : Boolean; override; end; THExtStored = class(TObject) private _bIsAttr : Boolean; _name : string; _value : string; public constructor create(bIsAttr : Boolean); procedure readData(Reader : TReader); property IsAttr : Boolean read _bIsAttr; property Name : string read _name; property Value : string read _value; end; THExtStoredList = class(TObject) private _list : TList; public constructor create; destructor Destroy; override; procedure readData(Reader : TReader); property List : TList read _list; end; TWHChunkOutputScope = (cosAll, cosForm, cosReset); TBARenderingEvent = procedure (ctl : TControl; hctl : THControl) of object; TRenderingEvent = procedure (ctl : TControl; hctl : THControl; var output : string) of object; TWHForm2HTML = class(TComponent) private _alternateFonts : string; _bChunkOnly : Boolean; _bmp : TBitmap; _bSetFonts : Boolean; _BGColor : string; _browserFamily : THBrowserFamily; _bQualifiedNames : Boolean; _bWHChunkDeclaration : Boolean; _exportFName : TFileName; _exportWHChunkFName : TFileName; _extStoredList : THExtStoredList; _mainContainer : TWinControl; _hForm : THFormElement; _hMainContainer : THContainer; _WHChunkOutputScope : TWHChunkOutputScope; // Events _onAfterRendering : TBARenderingEvent; _onBeforeRendering : TBARenderingEvent; _onRendering : TRenderingEvent; {_onAfterRenderingControl : TNotifyEvent; _onBeforeRenderingControl : TNotifyEvent;} procedure doBrowse(bWH : Boolean); function ValueEquals(compObj : TWHForm2HTML) : Boolean; function fontSize2HFontSize(fSize : integer) : integer; function getBrowseIt : Boolean; function getFontAttr(hctl : THControl; const sColor : string) : string; function getFontOfHCtl(hctl : THControl) : TFont; function getFormBeginTag : string; function getFormEndTag : string; function getHDimsOfText(hctl : THControl; const s : string; var hWidth, hHeight : integer) : Boolean; function getHTML : string; function getHTMLString : string; function getVersion : string; function getWHChunk : string; function hFontSize2FontSize(hfSize : integer) : integer; procedure ReadData(Reader: TReader); procedure setBrowseIt(b : Boolean); procedure setBrowseWHChunk(b : Boolean); procedure setCGIUserAgent(const cua : string); procedure setMainContainer(mainContainer : TWinControl); procedure setVersion(const s : string); procedure writeData(Writer: TWriter); protected _bWebHubMode : Boolean; procedure DefineProperties(Filer: TFiler); override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; //For TWHForm2HTMLHack function edit : Boolean; function doExport : Boolean; function editExport : Boolean; public constructor Create(owner : TComponent); override; destructor Destroy; override; function BGColorAttr : string; procedure browseHTMLDialog; procedure browseWHChunkDialog; function exportHTML : Boolean; function exportHTMLDialog : Boolean; function exportWHChunk : Boolean; function exportWHChunkDialog : Boolean; function getHControlClass(fromCtl : TControl) : THControlClass; class function getHContainerClass(fromCtl : TControl) : THControlClass; procedure Synchronize; property CGIUserAgent : string write setCGIUserAgent; property HForm : THFormElement read _hForm; property HTML : string read getHTML; property HMainContainer : THContainer read _hMainContainer; property WebHubMode : Boolean read _bWebHubMode; property WHChunk : string read getWHChunk; published property AlternateFonts : string read _alternateFonts write _alternateFonts; property Attributes : THFormElement read _hForm; // or any other type ! property BGColor : string read _BGColor write _BGColor; property BrowseIt : Boolean read getBrowseIt write setBrowseIt stored false; property BrowseWHChunk : Boolean read getBrowseIt write setBrowseWHChunk stored false; property BrowserFamily : THBrowserFamily read _BrowserFamily write _BrowserFamily; property ChunkOnly : Boolean read _bChunkOnly write _bChunkOnly; property ExportFName : TFileName read _exportFName write _exportFName; property ExportWHChunkFName : TFileName read _exportWHChunkFName write _exportWHChunkFName; property MainContainer : TWinControl read _mainContainer write setMainContainer; property SetFonts : Boolean read _bSetFonts write _bSetFonts; property QualifiedNames : Boolean read _bQualifiedNames write _bQualifiedNames default False; property Version : string read getVersion write setVersion; property WHChunkDeclaration : Boolean read _bWHChunkDeclaration write _bWHChunkDeclaration default true; property WHChunkOutputScope : TWHChunkOutputScope read _WHChunkOutputScope write _WHChunkOutputScope; // Events property OnAfterRendering : TBARenderingEvent read _OnAfterRendering write _OnAfterRendering; property OnBeforeRendering : TBARenderingEvent read _OnBeforeRendering write _OnBeforeRendering; property OnRendering : TRenderingEvent read _OnRendering write _OnRendering; {property OnAfterRenderingControl : TNotifyEvent read _OnAfterRenderingControl write _OnAfterRenderingControl; property OnBeforeRenderingControl : TNotifyEvent read _OnBeforeRenderingControl write _OnBeforeRenderingControl;} end; function editBGColor(var sColor : string) : Boolean; // See regf2h.pas for registration of component onto Delphi palette. implementation uses {$IFDEF CodeSite}CodeSiteLogging,{$ENDIF} StdCtrls, shellapi, TypInfo, ExtCtrls, {$IFDEF IN_WEB_APPLICATION}ZM_CodeSiteInterface,{$ENDIF} f2hf; var MacroStart: string = '(~'; {signals beginning of dynamic WebHub content} MacroEnd: string = '~)'; {signals end of dynamic content} const VERSION_NUMBER = '1.10'; DEF_BRF : THBrowserRunFamily = brfIE4; EDIT_HEIGHT : array[THBrowserRunFamily] of integer = (23, 24, 24, 24); EDIT_MIN_WIDTH : array[THBrowserRunFamily] of integer = (25, 20, 16, 16); EDIT_MIN_WIDTH_CHARS : array[THBrowserRunFamily] of integer = (1, 1, 1, 1); EDIT_WIDTH_PER_CHAR : array[THBrowserRunFamily] of integer = (5, 7, 8, 8); BUT_HEIGHT : array[THBrowserRunFamily] of integer = (23, 24, 24, 24); BUT_MIN_TW : array[THBrowserRunFamily] of integer = (61, 0, 0, 0); BUT_ADD_WPCT : array[THBrowserRunFamily] of double = (0.0, 0.5, 0.5, 0.5); BUT_ADD_W : array[THBrowserRunFamily] of integer = (11, 4, 4, 4); BUT_FNT_MOD_SIZE : array[THBrowserRunFamily] of integer = (9, 12, 11, 11); CHECK_MIN_HEIGHT : array[THBrowserRunFamily] of integer = (19, 19, 19, 19); CHECK_MIN_WIDTH : array[THBrowserRunFamily] of integer = (19, 19, 19, 19); COMBO_HEIGHT : array[THBrowserRunFamily] of integer = (21, 22, 22, 22); LIST_MIN_WIDTH : array[THBrowserRunFamily] of integer = (75, 34, 41, 41); LIST_MIN_WIDTH_CHARS : array[THBrowserRunFamily] of integer = (10, 1, 1, 1); LIST_WIDTH_PER_CHARS : array[THBrowserRunFamily] of double = (5, 6.7, 6, 6); LIST_BASE_HEIGHT : array[THBrowserRunFamily] of integer = (6, 6, 6, 6); LIST_ITEM_HEIGHT : array[THBrowserRunFamily] of integer = (13, 16, 16, 16); MEMO_BASE_HEIGHT : array[THBrowserRunFamily] of integer = (26, 8, 32, 32); MEMO_ITEM_HEIGHT : array[THBrowserRunFamily] of integer = (13, 16, 16, 16); MEMO_BASE_WIDTH : array[THBrowserRunFamily] of integer = (0, 22, 16, 16); MEMO_COL_WIDTH : array[THBrowserRunFamily] of integer = (5, 8, 8, 8); {$R *.RES} // Utilities function HColor2Color(const sColor : string; var color : TColor) : Boolean; var s : string; begin s := UpperCase(sColor); if s = 'LTGRAY' then s := 'SILVER' else if s = 'DKGRAY' then s := 'GRAY'; s := 'cl' + s; if IdentToColor(s, Int32(Color)) then result := True else if (copy(sColor, 1, 1) <> '#') or (length(sColor) <> 7) then result := false else begin s := '$00' + copy(sColor, 6, 2) + copy(sColor, 4, 2) + copy(sColor, 2, 2); try color := integer(strToInt(s)); result := true; except result := false; end; end; end; function Color2HColor(color : TColor) : string; var s : string; begin s := intToHex(ColorToRGB(color), 8); result := '#'+ copy(s, 7, 2) + copy(s, 5, 2) + copy(s, 3, 2); end; function editBGColor(var sColor : string) : Boolean; var colorDlg : TColorDialog; col : TColor; begin colorDlg := nil; result := false; try colorDlg := TColorDialog.create(application); with colorDlg do begin options := [cdSolidColor]; if HColor2Color(sColor, col) then Color := col; if execute then begin sColor := Color2HColor(color); result := true; end; end; finally colorDlg.free; end; end; function left(const s : string; n : integer) : string; begin result := copy(s, 1, n); end; function right(const s : string; n : integer) : string; begin result := copy(s, length(s) - 1, n); end; function bf2brf(bf : THBrowserFamily) : THBrowserRunFamily; begin if bf = bfDefault then result := DEF_BRF else result := THBrowserRunFamily(integer(bf) - 1); end; function removeChars(const s, cars : string) : string; var i: integer; begin Result := ''; for i := 1 to length(s) do if pos(s[i],cars) = 0 then Result := Result + s[i]; end; function LTrim(const aString : string) : string; var i, len : integer; testCar : char; begin result := ''; len := length(aString); for i := 1 to len do begin testCar := aString[i]; if testCar <> ' ' then begin result := copy(aString, i , len - i + 1); exit; end; end; end; function RTrim(const aString : string) : string; var i, nSpaces, len : integer; testCar : char; begin result := ''; nSpaces := 0; len := length(aString); for i := len downto 1 do begin testCar := aString[i]; if testCar <> ' ' then begin result := copy(aString, 1 , len - nSpaces); exit; end; inc(nSpaces); end; end; function AllTrim(const aString : string) : string; begin result := RTrim(LTrim(aString)); end; // End of utilities // Hacker classes type THackLabel = class(TCustomLabel) end; THackEdit = class(TCustomEdit) end; THackCheckBox = class(TCustomCheckBox) end; THackListBox = class(TCustomListBox) end; THackRadioGroup = class(TCustomRadioGroup) end; THackGroupBox = class(TCustomGroupBox) end; THackPanel = class(TCustomPanel) end; constructor THMemo.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Cols', atInteger, 'HTML <TEXTAREA> Cols. Sets the element''s width in characters.'); with tmpAttr do begin GetDefaultProc := getDefaultCols; Options := Options - [aoEditable]; end; add(tmpAttr); tmpAttr := THAttribute.create('Rows', atInteger, 'HTML <TEXTAREA> Rows. Sets the number of rows that will be displayed.'); with tmpAttr do begin GetDefaultProc := getDefaultRows; Options := Options - [aoEditable]; end; add(tmpAttr); tmpAttr := THAttribute.create('Text', atString, 'HTML <TEXTAREA> initially displayed text.'); with tmpAttr do begin GetDefaultProc := getDefaultText; Options := Options - [aoHTML]; end; add(tmpAttr); tmpAttr := THAttribute.create('Wrap', atList, 'HTML <TEXTAREA> Wrap attribute. The possible values are "Off", "Virtual" and "Physical".'); with tmpAttr.ValuesList do begin add('Off'); add('Virtual'); add('Physical'); end; with tmpAttr do begin DefValue := 'Physical'; Value := DefValue; end; add(tmpAttr); end; end; // Ann also changed this function to make the textareas work. function THMemo.getHTML : string; var s : string; aName, aText : string; aWrap : string; begin if (not Form2HTML.WebHubMode) or (not enabled) then result := inherited getHTML else begin // aName:=Attributes['Name'].Value; aText:=Attributes['Text'].Value; aWrap:=Attributes['Wrap'].Value; // if aText<>aName then begin result:='<textarea rows='+Attributes['Rows'].Value+ ' cols='+Attributes['Cols'].Value+ ' name='+aName; // not sure where the extra attributes go. -ann if aWrap<>'' then result:=result+' wrap='+aWrap; result:=result+'>'+aText+'</textarea>'; end else begin result := string(MacroStart) + 'INPUTTEXTAREA|' + Attributes['Name'].Value + ',' + Attributes['Rows'].Value + ',' + Attributes['Cols'].Value; result := result + '|Wrap=' + Attributes['Wrap'].Value; s := Attributes['ExtraAttributes'].Value; if s <> '' then result := result + ' ' + s; result := result + string(MacroEnd); end; addBeforeAndAfterElements(result); with _form2HTML do begin if assigned(_OnAfterRendering) then _OnAfterRendering(_control, self); end; end; end; function THMemo.getHTMLText : string; begin result := Attributes['Text'].Value; end; procedure THMemo.getDefaultText(var defText : string); begin defText := TCustomMemo(_control).Lines.Text; end; procedure THMemo.getDefaultCols(var defCols : string); var nWidth, nCols : integer; brf : THBrowserRunFamily; begin nWidth := _control.Width; brf := bf2brf(Form2HTML.BrowserFamily); if nWidth < MEMO_BASE_WIDTH[brf] then nWidth := MEMO_BASE_WIDTH[brf]; // minimum width nCols := (nWidth - MEMO_BASE_WIDTH[brf]) div MEMO_COL_WIDTH[brf]; if ((nWidth - MEMO_BASE_WIDTH[brf]) mod MEMO_COL_WIDTH[brf]) <> 0 then inc(nCols); defCols := intToStr(nCols); end; procedure THMemo.getDefaultRows(var defRows : string); var nHeight, nRows : integer; brf : THBrowserRunFamily; begin nHeight := _control.height; brf := bf2brf(Form2HTML.BrowserFamily); if nHeight < MEMO_BASE_HEIGHT[brf] then nHeight := MEMO_BASE_HEIGHT[brf]; // minimum height nRows := (nHeight - MEMO_BASE_HEIGHT[brf]) div MEMO_ITEM_HEIGHT[brf]; if ((nHeight - MEMO_BASE_HEIGHT[brf]) mod MEMO_ITEM_HEIGHT[brf]) <> 0 then inc(nRows); defRows := intToStr(nRows); end; function THMemo.getHTMLBeginTag : string; begin result := '<TEXTAREA'; end; function THMemo.getHTMLEndTag : string; begin result := '</TEXTAREA>'; end; function THMemo.getHDims(var hWidth, hHeight : integer) : Boolean; var nCols, nRows : integer; brf : THBrowserRunFamily; begin result := true; if inherited getHDims(hWidth, hHeight) then exit; brf := bf2brf(Form2HTML.BrowserFamily); nRows := StrToInt(_attributes['Rows'].Value); hHeight := MEMO_BASE_HEIGHT[brf] + nRows * MEMO_ITEM_HEIGHT[brf]; nCols := StrToInt(_attributes['Cols'].Value); hWidth := MEMO_BASE_WIDTH[brf] + nCols * MEMO_COL_WIDTH[brf]; end; constructor THEdit.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Maxlength', atInteger, 'HTML <INPUT> Maxlength. Sets the number of characters which may be typed. Unlimited if empty.'); with tmpAttr do begin GetDefaultProc := getDefaultMaxLength; ValidateProc := validateMaxLength; end; add(tmpAttr); tmpAttr := THAttribute.create('Size', atInteger, 'HTML <INPUT> Size. Sets the element''s width in characters.'); with tmpAttr do begin GetDefaultProc := getDefaultSize; Options := Options - [aoEditable]; end; add(tmpAttr); tmpAttr := THAttribute.create('Type', atString, 'HTML <INPUT> Type, "text" or "password" depending on property ''PasswordChar''.'); with tmpAttr do begin GetDefaultProc := getDefaultType; options := options - [aoEditable]; end; add(tmpAttr); tmpAttr := THAttribute.create('Value', atString, 'HTML <INPUT> Value. Sets the initial displayed value.'); with tmpAttr do GetDefaultProc := getDefaultValue; add(tmpAttr); end; end; function THEdit.getHTML : string; var s : string; aName, aValue : string; aMaxLength : string; begin if (not Form2HTML.WebHubMode) or (not enabled) then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} aName:=Attributes['Name'].Value; aValue:=Attributes['Value'].Value; aMaxLength:=Attributes['MaxLength'].value; if aValue<>aName then begin result:='<input type=text '+ ' name='+aName+ ' size='+Attributes['Size'].Value; if aMaxLength<>'' then result:=result+' maxlength='+aMaxLength; result:=result+' value="'+aValue+'">'; end else begin if Attributes['Type'].Value = 'text' then result := MacroStart + 'INPUTTEXT|' else result := MacroStart + 'INPUTPASSWORD|'; result := result + aName + ',' + Attributes['Size'].Value; //s := Attributes['Maxlength'].Value; if aMaxLength <> '' then result := result + ',' + aMaxLength; s := Attributes['ExtraAttributes'].Value; if s <> '' then result := result + '|' + s; result := result + MacroEnd; end; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; end; procedure THEdit.getDefaultType(var defType : string); begin if THackEdit(_control).PasswordChar = #0 then defType := 'text' else defType := 'password'; end; function THEdit.getHDims(var hWidth, hHeight : integer) : Boolean; var nSize : integer; brf : THBrowserRunFamily; begin result := true; if inherited getHDims(hWidth, hHeight) then exit; brf := bf2brf(Form2HTML.BrowserFamily); hHeight := EDIT_HEIGHT[brf]; nSize := StrToInt(_attributes['Size'].Value); if nSize < EDIT_MIN_WIDTH_CHARS[brf] then nSize := EDIT_MIN_WIDTH_CHARS[brf]; hWidth := EDIT_MIN_WIDTH[brf] + EDIT_WIDTH_PER_CHAR[brf] * (nSize - EDIT_MIN_WIDTH_CHARS[brf]); end; procedure THEdit.getDefaultSize(var defSize : string); var nSize : integer; brf : THBrowserRunFamily; w : integer; begin brf := bf2brf(Form2HTML.BrowserFamily); nSize := EDIT_MIN_WIDTH_CHARS[brf]; w := TCustomEdit(_control).width - EDIT_MIN_WIDTH[brf]; if w > 0 then inc(nSize, w div EDIT_WIDTH_PER_CHAR[brf]); if (w mod EDIT_WIDTH_PER_CHAR[brf]) <> 0 then inc(nSize); defSize := intToStr(nSize); end; procedure THEdit.getDefaultMaxLength(var defMaxLength : string); begin with THackEdit(_control) do begin if MaxLength <> 0 then defMaxLength := intToStr(MaxLength) else defMaxLength := ''; end; end; procedure THEdit.validateMaxLength(var sMaxLength : string; var bOK : Boolean); var n : integer; begin if sMaxLength <> '' then begin try n := strToInt(sMaxLength); if n <= 0 then bOK := false; except bOK := false; end; end; end; procedure THEdit.getDefaultValue(var defValue : string); begin defValue := TCustomEdit(_control).text; end; constructor THList.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Size', atInteger, 'HTML <SELECT> Size. Specifies the number of visible items.'); with tmpAttr do Options := Options - [aoEditable]; add(tmpAttr); end; end; function THList.getHTMLBeginTag : string; begin if Form2HTML.WebHubMode then result := sLineBreak + MacroStart else result := ''; result := result + '<SELECT'; end; function THList.getHTMLEndTag : string; begin result := '</SELECT>'; end; function THList.getHTMLText : string; var i, j : integer; nIncreaseHWidth, iLongestItem, nCarsToAdd : integer; brf : THBrowserRunFamily; tmpDouble : double; sText, sValue : string; begin getItemsMaxLength(iLongestItem); nIncreaseHWidth := _control.Width - getStdHWidth; if nIncreaseHWidth > 0 then begin brf := bf2brf(Form2HTML.BrowserFamily); tmpDouble := nIncreaseHWidth; tmpDouble := tmpDouble / LIST_WIDTH_PER_CHARS[brf]; nCarsToAdd := round(tmpDouble) + 1; end else nCarsToAdd := 0; // Just to avoid a compiler warning if not Form2HTML.WebHubMode then result := sLineBreak; if (_control is TCustomComboBox) then begin with TCustomComboBox(_control) do begin for i := 0 to items.count - 1 do begin if not Form2HTML.WebHubMode then begin result := result + '<OPTION'; if i = itemIndex then result := result + ' Selected'; result := result + ' Value="' + getItemValue(i) + '"'; result := result + '>' + getItemText(i); end else begin if i > 0 then result := result + ','; sValue := getItemValue(i); sText := getItemText(i); if sText = sValue then result := result + sText else result := result + sValue + '-' + sText; end; if (nIncreaseHWidth > 0) and (i = iLongestItem) then begin for j := 1 to round(1.2 * nCarsToAdd) do result := result + '&nbsp;'; end; if not Form2HTML.WebHubMode then result := result + sLineBreak; end; end; end; end; function THList.getHTML : string; var s : string; begin if (not Form2HTML.WebHubMode) or (not enabled) then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} //INPUTSELECT|name,valuename,size[,MULTIPLE][|other tags] result:= MacroStart + 'SET|list.dyn0='+getHTMLText+MacroEnd+sLineBreak +MacroStart + 'INPUTSELECT|' + Attributes['Name'].Value +',dyn0,' + Attributes['Size'].Value; if (self is THListBox) then begin if Attributes['Multiple'].BooleanValue then //result := result + ',MULTIPLE'; result := result + ',YES'; end; s := Attributes['ExtraAttributes'].Value; if s <> '' then result := result + '|' + s; result := result + MacroEnd+sLineBreak+MacroStart + 'CLEAR|dyn0' + MacroEnd; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; end; constructor THComboBox.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); tmpAttr := _attributes['Size']; with tmpAttr do begin DefValue := '1'; Value := DefValue; end; end; function THList.getItemText(index : integer) : string; var s : string; i : integer; begin if (_control is TCustomComboBox) then s := TCustomComboBox(_control).items[index] else if (_control is TListBox) then s := TListBox(_control).items[index]; i := Pos('=', s); if i = 0 then Result := s else Result := AllTrim(Copy(s, 1, i - 1)); end; function THList.getItemValue(index : integer) : string; var s : string; i : integer; begin if (_control is TCustomComboBox) then s := TCustomComboBox(_control).items[index] else if (_control is TListBox) then s := TListBox(_control).items[index]; i := Pos('=', s); if i = 0 then result := s else result := AllTrim(Copy(s, i + 1, MAXINT)); end; function THList.getItemsMaxLength(var index : integer) : integer; var i, l : integer; begin result := 0; index := -1; if (_control is TListBox) then begin with TListBox(_control) do begin for i := 0 to items.count - 1 do begin l := length(getItemText(i)); if l > result then begin result := l; index := i; end; end; end; end else if (_control is TCustomComboBox) then begin with TCustomComboBox(_control) do begin for i := 0 to items.count - 1 do begin l := length(getItemText(i)); if l > result then begin result := l; index := i; end; end; end; end; end; function THList.getStdHWidth : integer; var brf : THBrowserRunFamily; nMax, dummy : integer; tmpDouble : double; begin nMax := getItemsMaxLength(dummy); brf := bf2brf(Form2HTML.BrowserFamily); result := LIST_MIN_WIDTH[brf]; if nMax > LIST_MIN_WIDTH_CHARS[brf] then begin tmpDouble := LIST_WIDTH_PER_CHARS[brf]; inc(result, round(tmpDouble * (nMax - LIST_MIN_WIDTH_CHARS[brf]))); end; end; function THList.getHDims(var hWidth, hHeight : integer) : Boolean; begin result := true; if inherited getHDims(hWidth, hHeight) then exit; // hWidth only (common to THComboBox and THListBox) hWidth := getStdHWidth; with _control do begin if hWidth < Width then hWidth := Width; end; end; function THComboBox.getHDims(var hWidth, hHeight : integer) : Boolean; var brf : THBrowserRunFamily; begin result := inherited getHDims(hWidth, hHeight); // hWidth computed in THList if Enabled then begin brf := bf2brf(Form2HTML.BrowserFamily); hHeight := COMBO_HEIGHT[brf]; end; end; constructor THListBox.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Multiple', atBoolean, 'HTML <SELECT> Multiple. If True, the user can select more than one option.'); tmpAttr.GetDefaultProc := getDefaultMultiple; add(tmpAttr); tmpAttr := Attribute['Size']; with tmpAttr do GetDefaultProc := getDefaultSize; end; end; procedure THListBox.getDefaultMultiple(var defMultiple : string); var bMultiple : Boolean; begin bMultiple := THackListBox(_control).MultiSelect; defMultiple := THAttribute.boolean2String(bMultiple); end; procedure THListBox.getDefaultSize(var defSize : string); var nItems, hi : integer; brf : THBrowserRunFamily; begin brf := bf2brf(Form2HTML.BrowserFamily); hi := _control.Height - LIST_BASE_HEIGHT[brf]; nItems := hi div LIST_ITEM_HEIGHT[brf]; if (hi mod LIST_ITEM_HEIGHT[brf]) <> 0 then inc(nItems); defSize := intToStr(nItems); end; function THListBox.getHDims(var hWidth, hHeight : integer) : Boolean; var nSize : integer; brf : THBrowserRunFamily; begin result := inherited getHDims(hWidth, hHeight); // hWidth computed in THList if not enabled then exit; brf := bf2brf(Form2HTML.BrowserFamily); nSize := strToInt(_attributes['Size'].Value); hHeight := LIST_BASE_HEIGHT[brf] + LIST_ITEM_HEIGHT[brf] * nSize; end; function THInput.getHTMLBeginTag : string; begin result := '<INPUT'; end; constructor THCheck.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Checked', atBoolean, 'HTML <INPUT> Checked. Determines the initial state of the checkbox or radio button.'); tmpAttr.GetDefaultProc := getDefaultChecked; add(tmpAttr); end; addAnchorsAttributes; // In THControl end; procedure THCheck.getDefaultName (var defaultName : string); begin if isRadio then begin if _form2HTML.QualifiedNames then defaultName := _hContainer.getNamePath + '_Radio' else defaultName := 'Radio'; end else inherited getDefaultName(defaultName); end; function THCheck.isRadio : Boolean; begin result := (_control is TRadioButton); end; procedure THCheck.getDefaultChecked(var defChecked : string); var bChecked : Boolean; begin if (_control is TCustomCheckBox) then bChecked := THackCheckBox(_control).checked else bChecked := TRadioButton(_control).checked; defChecked := THAttribute.boolean2String(bChecked); end; constructor THCheckBox.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Type', atString, 'HTML <INPUT> Type.'); with tmpAttr do begin options := options - [aoEditable]; DefValue := 'checkbox'; Value := DefValue; end; add(tmpAttr); tmpAttr := THAttribute.create('Value', atString, 'HTML <INPUT> Value.'); with tmpAttr do begin DefValue := 'YES'; Value := DefValue; end; add(tmpAttr); end; end; function THCheckBox.getHTML : string; var s : string; begin if (not Form2HTML.WebHubMode) or (not enabled) then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} result := MacroStart + 'INPUTCHECKBOX|' + Attributes['Name'].Value; s := Attributes['ExtraAttributes'].Value; if s <> '' then result := result + '|' + s; result := result + MacroEnd; result := result + getHTMLText; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; end; constructor THRadio.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Type', atString, 'HTML <INPUT> Type.'); with tmpAttr do begin options := options - [aoEditable]; DefValue := 'radio'; Value := DefValue; end; add(tmpAttr); tmpAttr := THAttribute.create('Value', atString, 'HTML <INPUT> Value.'); with tmpAttr do GetDefaultProc := getDefaultValue; add(tmpAttr); end; end; procedure THRadio.getDefaultValue(var defValue : string); begin defValue := _control.Name; end; function THRadio.getHTML : string; var s : string; begin if (not Form2HTML.WebHubMode) or (not enabled) then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} result := MacroStart + 'INPUTRADIO|' + Attributes['Name'].Value + ',' + Attributes['Value'].Value; s := Attributes['ExtraAttributes'].Value; if s <> '' then result := result + '|' + s; result := result + MacroEnd; result := result + getHTMLText; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; end; function THCheck.getHDims(var hWidth, hHeight : integer) : Boolean; var brf : THBrowserRunFamily; tw, th : integer; begin result := true; if inherited getHDims(hWidth, hHeight) then exit; brf := bf2brf(Form2HTML.BrowserFamily); hHeight := CHECK_MIN_HEIGHT[brf]; hWidth := CHECK_MIN_WIDTH[brf]; _form2HTML.getHDimsOfText(self, THackCheckBox(_control).caption, tw, th); inc(hWidth, tw); if hHeight < th then hHeight := th; end; function THCheck.getHTMLText: string; var sCaption, sFont : string; begin sCaption := removeChars(THackCheckBox(_control).caption, '&'); sFont := _form2HTML.getFontAttr(self, ''); if _attributes['AsAnchor'].BooleanValue then begin if _form2HTML.WebHubMode then result := _attributes['WHAnchorMacro'].DefValue else result := sFont + '<A Href="' + _attributes['Href'].Value + '">' + sCaption + '</A>'; end else result := sFont + sCaption; end; constructor TWHForm2HTML.create(owner : TComponent); begin inherited create(owner); _bmp := TBitmap.create; _hForm := THFormElement.create; _hForm.Form2HTML := self; _bChunkOnly := False; _BGColor := '[None]'; _bSetFonts := True; _bWHChunkDeclaration := True; MainContainer := nil; // needed for initialization through setMainContainer ! end; destructor TWHForm2HTML.destroy; begin _bmp.free; _hForm.free; _hMainContainer.free; inherited destroy; end; function TWHForm2HTML.getVersion : string; begin result := VERSION_NUMBER; end; procedure TWHForm2HTML.setVersion(const s : string); begin end; function TWHForm2HTML.getFontOfHCtl(hctl : THControl) : TFont; begin if hctl is THLabel then result := THackLabel(hctl.Control).Font else if hctl is THCheckBox then result := THackCheckBox(hctl.Control).Font else if hctl is THRadio then result := TRadioButton(hctl.Control).Font else result := TForm(owner).Font; end; function TWHForm2HTML.hFontSize2FontSize(hfSize : integer) : integer; begin case hfSize of 1: result := 8; 2: result := 10; 3: result := 12; 4: result := 14; 5: result := 18; 6: result := 24; else // 7 result := 36; end; end; function TWHForm2HTML.fontSize2HFontSize(fSize : integer) : integer; begin if fSize < 10 then result := 1 else if fSize < 12 then result := 2 else if fSize < 14 then result := 3 else if fSize < 18 then result := 4 else if fSize < 24 then result := 5 else if fSize < 36 then result := 6 else result := 7; end; function TWHForm2HTML.getFontAttr(hctl : THControl; const sColor : string) : string; var font : TFont; sRealColor : string; function getNames : string; var s : string; begin result := font.Name; s := allTrim(_alternateFonts); if s <> '' then begin if copy(s, 1, 1) <> ',' then result := result + ','; result := result + s; end; end; begin if not _bSetFonts then begin if sColor = '' then result := '' else result := '<FONT Color="' + sColor + '">'; end else begin font := getFontOfHCtl(hctl); if sColor = '' then sRealColor := Color2HColor(font.Color) else sRealColor := sColor; result := '<FONT Face="' + getNames + '" Size="' + intToStr(fontSize2HFontSize(font.size)) + '" Color="' + sRealColor + '">'; with font do begin if fsBold in Style then result := result + '<B>'; if fsItalic in Style then result := result + '<I>'; if fsUnderline in Style then result := result + '<U>'; end; end; end; function TWHForm2HTML.getHDimsOfText(hctl : THControl; const s : string; var hWidth, hHeight : integer) : Boolean; var hfSize : integer; begin result := True; with _bmp.canvas do begin if _bSetFonts then begin with font do begin assign(getFontOfHCtl(hctl)); hfSize := fontSize2HFontSize(Size); Size := hFontSize2FontSize(hfSize); end; end else begin with font do begin // Reference browser default font name := 'Times New Roman'; size := 12; end; end; hWidth := TextWidth(s); hHeight := TextHeight(s); end; end; function TWHForm2HTML.BGColorAttr : string; begin if CompareText(_BGColor, '[None]') = 0 then result := '' else if CompareText(_BGColor, '[Same]') = 0 then result := Color2HColor(TForm(owner).color) else result := _BGColor; if result <> '' then result := ' BGColor="' + result + '"'; end; procedure TWHForm2HTML.setCGIUserAgent(const cua : string); var s : string; begin s := upperCase(cua); if copy(s, 1, 9) = 'MOZILLA/4' then begin if pos('MSIE 4', s) > 0 then _browserFamily := bfIE4 else _browserFamily := bfNS4; end else if copy(s, 1, 8) = 'MOZILLA/' then begin if pos('MSIE 3', s) > 0 then _browserFamily := bfIE3 else _browserFamily := bfNS3; end else _browserFamily := bfDefault; // same as bfIE4 end; procedure TWHForm2HTML.setMainContainer(mainContainer : TWinControl); var hCtlClass : THControlClass; savedHMainContainer : THContainer; procedure restoreAttributesFrom(fromObj : THContainer); var i : integer; hObj, hOldObj : THAttrObject; begin if _hMainContainer.Name = fromObj.Name then _hMainContainer.copyAttributesFrom(fromObj); with fromObj do begin for i := 0 to count - 1 do begin hOldObj := Children[i]; hObj := _hMainContainer.FindHObjectByName(hOldObj.Name); if hObj <> nil then hObj.copyAttributesFrom(hOldObj); if hOldObj is THContainer then restoreAttributesFrom(THContainer(hOldObj)); end; end; end; begin if (mainContainer = _mainContainer) and (mainContainer <> nil) then exit; savedHMainContainer := nil; try savedHMainContainer := _hMainContainer; if mainContainer = nil then mainContainer := TForm(owner); _mainContainer := mainContainer; hCtlClass := getHContainerClass(mainContainer); if hCtlClass <> nil then begin _hMainContainer := THContainer(hCtlClass.create(mainContainer)); _hMainContainer.Form2HTML := self; synchronize; end; if savedHMainContainer <> nil then restoreAttributesFrom(savedHMainContainer); finally savedHMainContainer.free; end; end; procedure TWHForm2HTML.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = _mainContainer) then MainContainer := nil; inherited Notification(AComponent, Operation); end; procedure THAttribute.writeData(writer : TWriter); begin with writer do begin WriteString(Name); WriteString(Value); end; end; procedure THAttributes.writeData(writer : TWriter); var i : integer; begin writer.WriteListBegin; for i := 0 to count - 1 do AttributeN[i].writeData(writer); writer.WriteListEnd; end; procedure THContainer.writeData(writer: TWriter); var i : integer; begin inherited writeData(writer); for i := 0 to count - 1 do Children[i].writeData(writer); end; constructor THExtStoredList.create; begin inherited create; _list := TList.create; end; destructor THExtStoredList.destroy; var i : integer; begin with _list do begin for i := 0 to count - 1 do THExtStored(items[i]).free; free; end; inherited destroy; end; constructor THExtStored.create(bIsAttr : Boolean); begin inherited create; _bIsAttr := bIsAttr; end; procedure THExtStored.readData(Reader : TReader); begin with Reader do begin _name := readString; if _bIsAttr then _value := readString; end; end; procedure THExtStoredList.readData(Reader : TReader); var extStored : THExtStored; begin with Reader do begin ReadListBegin; while not EndOfList do begin extStored := THExtStored.create(False); // an object extStored.readData(Reader); _list.add(extStored); ReadListBegin; while not EndOfList do begin // attributes extStored := THExtStored.create(True); // an attribute extStored.readData(Reader); _list.add(extStored); end; ReadListEnd; end; ReadListEnd; end; end; procedure TWHForm2HTML.readData(reader: TReader); begin if _extStoredList <> nil then exit; _extStoredList := THExtStoredList.create; _extStoredList.readData(reader); end; procedure TWHForm2HTML.loaded; var i : integer; extStored : THExtStored; attrObject : THAttrObject; attr : THAttribute; begin inherited loaded; if _extStoredList = nil then exit; synchronize; try attrObject := _hForm; with _extStoredList.List do begin // First item (0) is _hForm for i := 1 to count - 1 do begin extStored := THExtStored(items[i]); if extStored.IsAttr then begin if attrObject <> nil then begin with attrObject do begin attr := Attributes[extStored.Name]; if attr <> nil then attr.Value := extStored.Value; end; end; end else attrObject := HMainContainer.FindHObjectByName(extStored.Name); end; end; finally _extStoredList.free; _extStoredList := nil; end; end; procedure TWHForm2HTML.writeData(writer: TWriter); begin synchronize; writer.WriteListBegin; _hForm.writeData(writer); _hMainContainer.writeData(writer); writer.WriteListEnd; end; function THAttribute.ValueEquals(compObj : THAttribute) : Boolean; begin result := (Value = compObj.Value); end; function THAttributes.ValueEquals(compObj : THAttributes) : Boolean; var i : integer; begin result := (count = compObj.count); if result then begin for i := 0 to count - 1 do begin result := AttributeN[i].ValueEquals(compObj.AttributeN[i]); if not result then break; end; end; end; constructor THElement.createHAttrObject; var tmpAttr : THAttribute; begin inherited createHAttrObject; with _attributes do begin tmpAttr := THAttribute.create('BeforeElement', atString, 'TWHForm2HTML option. Let''s you insert some HTML code before the element.'); with tmpAttr do options := options - [aoHTML]; add(tmpAttr); tmpAttr := THAttribute.create('AfterElement', atString, 'TWHForm2HTML option. Let''s you insert some HTML code after the element.'); with tmpAttr do options := options - [aoHTML]; add(tmpAttr); tmpAttr := THAttribute.create('ExtraAttributes', atString, 'Let''s you insert additional HTML attributes such as JavaScript handlers.'); with tmpAttr do options := options + [aoNoName]; add(tmpAttr); end; end; function THElement.getAfterElement : string; begin result := Attributes['AfterElement'].Value; end; procedure THElement.addBeforeAndAfterElements(var toS : string); var s : string; begin toS := getBeforeElement + toS; s := getAfterElement; if s <> '' then s := sLineBreak + s; toS := toS + s; end; function THElement.getBeforeElement : string; begin result := Attributes['BeforeElement'].Value; if result <> '' then result := result + sLineBreak; end; function THAttrObject.ValueEquals(compObj : THAttrObject) : Boolean; begin result := _attributes.ValueEquals(compObj.Attributes); end; function THContainer.ValueEquals(compObj : THAttrObject) : Boolean; var i : integer; begin result := inherited ValueEquals(compObj); if result then result := (count = THContainer(compObj).count); if result then begin for i := 0 to count - 1 do begin result := Children[i].ValueEquals(THContainer(compObj).Children[i]); if not result then break; end; end; end; function TWHForm2HTML.ValueEquals(compObj : TWHForm2HTML) : Boolean; begin result := _hForm.ValueEquals(compObj.HForm); // <FORM> element : is a THAttrObject if result then result := _hMainContainer.ValueEquals(compObj.HMainContainer); // is a THContainer end; procedure TWHForm2HTML.DefineProperties(Filer: TFiler); function DoFile: Boolean; begin if Filer.Ancestor <> nil then result := not ValueEquals(TWHForm2HTML(Filer.Ancestor)) else result := true; end; begin inherited DefineProperties(Filer); with Filer do DefineProperty('Links', readData, writeData, DoFile); end; function TWHForm2HTML.getBrowseIt : Boolean; begin result := false; end; procedure TWHForm2HTML.setBrowseIt(b : Boolean); begin browseHTMLDialog; end; procedure TWHForm2HTML.setBrowseWHChunk(b : Boolean); begin browseWHChunkDialog; end; function TWHForm2HTML.editExport : Boolean; var saveDlg : TSaveDialog; testExt : string; begin result := false; saveDlg := nil; try saveDlg := TSaveDialog.create(application); with saveDlg do begin if _bWebHubMode then begin Title := ' Export WebHub chunk'; FileName := ExportWHChunkFName; Filter := 'Text files (*.txt)|*.txt|HTML files (*.HTML)|*.HTML|All files (*.*)|*.*'; DefaultExt := 'txt'; end else begin Title := ' Export HTML'; FileName := ExportFName; Filter := 'HTML files (*.HTML)|*.HTML|All files (*.*)|*.*'; DefaultExt := 'HTML'; end; Options := [ofHideReadOnly, ofNoReadOnlyReturn, ofOverwritePrompt, ofPathMustExist]; if execute then begin if _bWebHubMode then ExportWHChunkFName := FileName else ExportFName := FileName; //<TSaveDialog.bug> // on extensions with more than 3 char's testExt := extractFileExt(FileName); if upperCase(testExt) = '.HTM' then begin if copy(testExt, 4, 1) = 'M' then ExportFName := ExportFName + 'L' else ExportFName := ExportFName + 'l'; end; //</TSaveDialog.bug> result := doExport; end; end; finally saveDlg.free; end; end; function TWHForm2HTML.getHTMLString : string; var bForm : Boolean; begin try synchronize; if _bWebHubMode then begin _hForm.WebHubMode := True; _hMainContainer.WebHubMode := True; end; if assigned(_OnBeforeRendering) then _OnBeforeRendering(_hMainContainer._control, _hMainContainer); result := getFormBeginTag; bForm := (not _bWebHubMode) or (_WHChunkOutputScope in [cosAll, cosForm]); if bForm then result := result + _hMainContainer.HTML; result := result + getFormEndTag; finally if _bWebHubMode then begin _hForm.WebHubMode := False; _hMainContainer.WebHubMode := False; _bWebHubMode := False; end; if assigned(_OnRendering) then _OnRendering(_hMainContainer._control, _hMainContainer, result); if assigned(_OnAfterRendering) then _OnAfterRendering(_hMainContainer._control, _hMainContainer); end; end; function TWHForm2HTML.getHTML : string; begin _bWebHubMode := False; result := getHTMLString; end; function TWHForm2HTML.getWHChunk : string; begin _bWebHubMode := True; result := getHTMLString; end; function TWHForm2HTML.doExport : Boolean; var sh : AnsiString; hf : THandle; expFName: string; msgTitle : string; begin result := false; if _bWebHubMode then begin expFName := _exportWHChunkFName; msgTitle := 'Export WebHub chunck'; end else begin expFName := _exportFName; msgTitle := 'Export HTML'; end; if expFName = '' then exit; hf := INVALID_HANDLE_VALUE; try screen.cursor := crHourglass; sh := AnsiString(getHTMLString); hf := CreateFile( pChar(expFName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if hf <> INVALID_HANDLE_VALUE then begin if integer(_lWrite(hf, pAnsiChar(sh), length(sh))) = length(sh) then result := true; end; finally CloseHandle(hf); screen.cursor := crDefault; if not result then begin Forms.Application.MessageBox( pChar('Cannot create file ''' + expFName + ''' !'), pChar(msgTitle), MB_APPLMODAL or MB_ICONERROR or MB_OK); end; end; end; function TWHForm2HTML.edit : Boolean; begin try screen.cursor := crHourglass; synchronize; f2hFrm := Tf2hFrm.create(application); with f2hFrm do begin Form2HTML := self; screen.cursor := crDefault; result := (showModal = mrOK); end; finally f2hFrm.free; f2hFrm := nil; screen.cursor := crDefault; end; end; procedure TWHForm2HTML.doBrowse(bWH : Boolean); var bCanBrowse : Boolean; expFName : string; begin _bWebHubMode := bWH; if bWH then expFName := _exportWHChunkFName else expFName := _exportFName; if expFName = '' then bCanBrowse := editExport else bCanBrowse := doExport; if bCanBrowse then begin if ShellExecute( 0, // hwnd nil, // operation pChar(expFName), nil, // parameters nil, // default directory SW_SHOWDEFAULT // nShowCmd ) <= 32 then Forms.Application.MessageBox( pChar('Cannot open file ''' + expFName + ''' !'), 'Browse', MB_APPLMODAL or MB_ICONERROR or MB_OK); end; end; procedure TWHForm2HTML.browseHTMLDialog; begin doBrowse(False); end; procedure TWHForm2HTML.browseWHChunkDialog; begin doBrowse(True); end; function TWHForm2HTML.exportHTMLDialog : Boolean; begin _bWebHubMode := False; result := editExport; end; function TWHForm2HTML.exportHTML : Boolean; begin _bWebHubMode := False; result := doExport; end; function TWHForm2HTML.exportWHChunk : Boolean; begin _bWebHubMode := True; result := doExport; end; function TWHForm2HTML.exportWHChunkDialog : Boolean; begin _bWebHubMode := True; result := editExport; _bWebHubMode := False; end; procedure TWHForm2HTML.synchronize; begin if _hMainContainer = nil then exit; with _hMainContainer do begin synchronized := false; synchronize; synchronizeDone; end; end; constructor THPlacer.create(hControl : THControl; width, height, xPrec, yPrec : integer); var n : integer; begin inherited create; _hContainer := THContainer(hControl); if _hContainer is THGroupBox then dec(height, 10); _form2HTML := hControl.form2HTML; _xPrec := xPrec; _yPrec := yPrec; _rows := TList.create; n := height div _yPrec; if (height mod _yPrec) <> 0 then inc(n); addRows(n); n := width div _xPrec; if (width mod _xPrec) <> 0 then inc(n); addCols(n); end; destructor THPlacer.destroy; var i : integer; begin for i := 0 to rowCount - 1 do TList(_rows[i]).free; _rows.free; inherited destroy; end; function THPlacer.colCount : integer; begin if rowCount = 0 then result := 0 else result := TList(_rows[0]).count; end; function THPlacer.rowCount : integer; begin result := _rows.count; end; procedure THPlacer.addRows(nRows : integer); var i, j, nRow : integer; begin for i := 1 to nRows do begin nRow := _rows.Add(TList.create); for j := 1 to colCount do TList(_rows[nRow]).add(nil); end; end; procedure THPlacer.addCols(nCols : integer); var i, j : integer; begin for i := 0 to rowCount - 1 do begin for j := 1 to nCols do TList(_rows[i]).Add(nil); end; end; function THPlacer.getCell(col, row : integer) : THControl; begin result := nil; if (row > rowCount - 1) or (col > colCount -1) then exit; result := THControl(TList(_rows[row])[col]); end; procedure THPlacer.setCell(col, row : integer; hControl : THControl); begin if (row > rowCount - 1) then addRows(row - (rowCount - 1)); if (col > colCount - 1) then addCols(col - (colCount -1)); TList(_rows[row])[col] := hControl; end; function THPlacer.getHTML : string; var r, c, n, nt, cur, i : integer; b : Boolean; hCtls, tmpHCtls, hCols, hRows : TList; hControl, hc : THControl; ret, s : string; procedure writeTable; var cellsDone, tmpList, notRenderedList : TList; i, j, k, r, c, nEmpty : integer; procedure newCell(bNewLine : Boolean); begin if (bNewLine and (c > 0)) or (r = 0) then ret := ret + sLineBreak; ret := ret + '<TD'; if c = 0 then ret := ret + ' Height="' + intToStr(integer(hRows[r])) + '"'; if r = 0 then ret := ret + ' Width="' + intToStr(integer(hCols[c])) + '"'; end; begin cellsDone := nil; notRenderedList := nil; try cellsDone := TList.create; for i := 0 to hRows.count - 1 do begin tmpList := TList.create; for j := 0 to hCols.count - 1 do tmpList.add(nil); cellsDone.add(tmpList); end; ret := '<TABLE' + _form2HTML.BGColorAttr + ' Cellspacing="0" Cellpadding="0">'; with hCtls do for i := 0 to count - 1 do THControl(items[i])._bRendered := false; for r := 0 to hRows.count - 1 do begin ret := ret + sLineBreak + '<TR>'; nEmpty := 0; for c := 0 to hCols.count - 1 do begin if TList(cellsDone[r])[c] <> nil then continue; with hCtls do begin b := True; for i := 0 to count - 1 do begin hc := THControl(items[i]); with hc do begin if (_row = r) and (_col = c) then begin _bRendered := true; b := False; if nEmpty > 0 then begin for k := 1 to nEmpty do begin newCell(False); ret := ret + '></TD>'; end; nEmpty := 0; end; newCell(True); if _colspan > 1 then ret := ret + ' Colspan="' + intToStr(_colspan) + '"'; if _rowspan > 1 then ret := ret + ' Rowspan="' + intToStr(_rowspan) + '"'; if RightAligned then // labels placed on the left side ret := ret + ' Align="right" VAlign="top"' else if hControl is THLabel then // labels placed on the top side ret := ret + ' Align="left" VAlign="bottom"' else ret := ret + ' Align="left" VAlign="top"'; ret := ret + '>'; with _form2HTML do begin if assigned(_OnBeforeRendering) then _OnBeforeRendering(hc._control, hc); s := hc.HTML; if assigned(_OnRendering) then _OnRendering(hc._control, hc, s); ret := ret + s; if assigned(_OnAfterRendering) then _OnAfterRendering(hc._control, hc); end; for j := 0 to _rowspan - 1 do begin for k := 0 to _colspan - 1 do TList(cellsDone[r + j])[c + k] := pointer(1); end; break; end; end; end; if b then // Empty cell begin if (r = 0) or (c = 0) then begin newCell(False); ret := ret + '></TD>'; end else inc(nEmpty); end else ret := ret + '</TD>'; end; end; ret := ret + '</TR>'; end; notRenderedList := TList.create; finally ret := ret + sLineBreak + '</TABLE>' + sLineBreak; with cellsDone do begin for i := 0 to count - 1 do TList(items[i]).free; free; end; with hCtls do for i := 0 to count - 1 do if not THControl(items[i])._bRendered then notRenderedList.add(THControl(items[i])); with notRenderedList do begin if count > 0 then begin s := 'The following controls could not be rendered' + sLineBreak + 'because overlapped in the target form :' + sLineBreak; for i := 0 to count - 1 do s := s + '- ' + THControl(items[i]).name + sLineBreak; s := s + 'Some controls are too close together in the source form.' + sLineBreak + 'Spread them and try again...'; {$IFDEF CodeSite} CodeSite.SendWarning(S); {$ENDIF} {$IFDEF IN_WEB_APPLICATION} LogSendWarning(S, 'getHTML'); {$ELSE} Forms.Application.messageBox(pChar(s), 'Lost controls', MB_ICONWARNING or MB_OK); {$ENDIF} end; free; end; end; end; begin hCols := nil; hRows := nil; hCtls := nil; tmpHCtls := nil; ret := ''; try hCols := TList.create; hRows := TList.create; hCtls := TList.create; tmpHCtls := TList.create; // First step : optimizing columns widths cur := 0; nt := 0; while cur < colCount do begin n := colCount; if cur > 0 then begin b := False; for r := 0 to rowCount - 1 do begin hControl := Cell[cur - 1, r]; if (hControl <> nil) and (hControl <> Cell[cur, r]) then begin with tmpHCtls do begin i := indexOf(hControl); if i <> -1 then begin tmpHCtls[i] := nil; b := true; end end; end; end; if b then tmpHCtls.pack; end; for r := 0 to rowCount - 1 do begin hControl := Cell[cur, r]; if hControl <> nil then begin with tmpHCtls do begin if indexOf(hControl) = -1 then begin add(hControl); hControl._col := hCols.count; end; end; with hCtls do begin if indexOf(hControl) = -1 then add(hControl); end; end; i := 0; for c := cur to colCount - 1 do begin hc := Cell[c, r]; if (hc = hControl) or (hc = nil) then inc(i) else begin if i < n then n := i; break; end; end; end; if nt + n < colCount then inc(nt, n) else n := colCount - nt; hCols.add(pointer(n * _xPrec)); inc(cur, n); with tmpHCtls do begin for i := 0 to count - 1 do inc(THControl(items[i])._colspan); end; end; // Second step : optimizing rows heights cur := 0; nt := 0; tmpHCtls.clear; while cur < rowCount do begin n := rowCount; if cur > 0 then begin b := False; for c := 0 to colCount - 1 do begin hControl := Cell[c, cur - 1]; if (hControl <> nil) and (hControl <> Cell[c, cur]) then begin with tmpHCtls do begin i := indexOf(hControl); if i <> -1 then begin tmpHCtls[i] := nil; b := true; end end; end; end; if b then tmpHCtls.pack; end; for c := 0 to colCount - 1 do begin hControl := Cell[c, cur]; if hControl <> nil then begin with tmpHCtls do begin if indexOf(hControl) = -1 then begin add(hControl); hControl._row := hRows.count; end; end; end; i := 0; for r := cur to rowCount - 1 do begin hc := Cell[c, r]; if (hc = hControl) or (hc = nil) then inc(i) else begin if i < n then n := i; break; end; end; end; if nt + n < rowCount then inc(nt, n) else n := rowCount - nt; hRows.add(pointer(n * _yPrec)); inc(cur, n); with tmpHCtls do begin for i := 0 to count - 1 do inc(THControl(items[i])._rowspan); end; end; // Colspan's / Rowspan's computing with hCtls do begin for i := 0 to count - 1 do begin hc := THControl(items[i]); with hc do begin getHDims(c, r); n := _col; _colspan := 0; while (c > 0) and (n < hCols.count) do begin inc(_colspan); dec(c, integer(hCols[n])); inc(n); end; n := _row; _rowspan := 0; while (r > 0) and (n < hRows.count) do begin inc(_rowspan); dec(r, integer(hRows[n])); inc(n); end; end; end; end; FreeAndNil(tmpHCtls); writeTable; finally result := ret; FreeAndNil(hCols); FreeAndNil(hRows); FreeAndNil(hCtls); FreeAndNil(tmpHCtls); end; end; procedure THPlacer.placeControl(hControl : THControl); var left, top : integer; hWidth, hHeight : integer; cLeft, cWidth, cTop, cHeight : integer; i, j : integer; bRightAligned : Boolean; begin if not hControl.Visible then exit; bRightAligned := false; hControl.getHDims(hWidth, hHeight); if (not _form2HTML.setFonts) and (hControl.control is TCustomLabel) then begin with THackLabel(hControl.control) do begin if focusControl <> nil then if focusControl.left >= left + width then bRightAligned := true; end; end; hControl.RightAligned := bRightAligned; left := hControl.control.left; top := hControl.control.top; if _hContainer is THGroupBox then dec(top, 10); if (hControl is THEdit) and (not hControl.enabled) then begin inc(top, 4); inc(left, 4); end; if bRightAligned then inc(left, hControl.control.width); cLeft := left div _xPrec; cTop := top div _yPrec; cWidth := hWidth div _xPrec; if (hWidth mod _xPrec) <> 0 then inc(cWidth); cHeight := hHeight div _yPrec; if (hHeight mod _yPrec) <> 0 then inc(cHeight); if bRightAligned then begin dec(cLeft, cWidth); if cLeft < 0 then cLeft := 0; end; for i := 0 to cWidth - 1 do begin for j := 0 to cHeight - 1 do Cell[cLeft + i, cTop + j] := hControl; end; end; procedure THPlacer.getHDims(var hWidth, hHeight : integer); begin hWidth := colCount * _xPrec; hHeight := rowCount * _yPrec; end; constructor THFormElement.create; var tmpAttr : THAttribute; begin inherited createHAttrObject; with _attributes do begin add(THAttribute.create('Action', atString, 'HTML <FORM> Action tag. Enter URL or WebHub PageID.')); add(THAttribute.create('Enctype', atString, 'HTML <FORM> Enctype.')); tmpAttr := THAttribute.create('Method', atList, 'HTML <FORM> Method. The possible values are "get" and "post".'); with tmpAttr.ValuesList do begin add('post'); add('get'); end; add(tmpAttr); tmpAttr := THAttribute.create('WHAction', atString, 'HTML <FORM> Action tag, used when exporting as a WebHub chunk.'); with tmpAttr do begin Options := Options - [aoHTML] - [aoEditable] + [aoWebHub]; StdAttrName := 'Action'; GetDefaultProc := getDefaultWHAction; end; add(tmpAttr); tmpAttr := THAttribute.create('WHTargetPageID', atString, 'The destination page ID, using WebHub syntax of [AppID:]PageID[(ServerID)].'); with tmpAttr do begin Options := Options - [aoHTML]; GetDefaultProc := getDefaultWHTargetPageID; ValueChangedProc := updateWHAction; end; add(tmpAttr); tmpAttr := THAttribute.create('WHCbk', atBoolean, 'Sets the .CKB command, which is used to enable save-state with checkboxes in WebHub.'); with tmpAttr do begin Options := Options - [aoHTML]; DefValue := boolean2String(False); Value := DefValue; ValueChangedProc := updateWHAction; end; add(tmpAttr); end; end; procedure THFormElement.getDefaultWHTargetPageID(var defWHTargetPageID : string); begin defWHTargetPageID := 'pg' + Form2HTML.MainContainer.Name; end; procedure THFormElement.getDefaultWHAction(var defWHAction : string); var s : string; begin with _attributes do begin s := MacroStart + 'ACTION|' + alltrim(Attribute['WHTargetPageID'].Value); if Attribute['WHCbk'].BooleanValue then s := s + ',.CKB'; s := s + MacroEnd; defWHAction := s; end; end; procedure THFormElement.updateWHAction(attr : THAttribute); begin with _attributes['WHAction'] do Value := DefValue; end; function THFormElement.getName : string; begin result := '<FORM>..</FORM>'; end; constructor THForm.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Border', atBoolean, 'TWHForm2HTML option. If True, the form is rendered with a border around it.'); with tmpAttr do options := options - [aoHTML]; add(tmpAttr); tmpAttr := THAttribute.create('CaptionBGColor', atString, 'TWHForm2HTML option. Let''s you specify the background color of the title bar.'); with tmpAttr do begin options := options - [aoHTML] + [aoDialog]; DialogProc := CaptionColorDlg; Value := 'Navy'; DefValue := Value; end; add(tmpAttr); tmpAttr := THAttribute.create('CaptionColor', atString, 'TWHForm2HTML option. Let''s you specify the text color of the caption.'); with tmpAttr do begin options := options - [aoHTML] + [aoDialog]; DialogProc := CaptionColorDlg; Value := 'White'; DefValue := Value; end; add(tmpAttr); tmpAttr := THAttribute.create('ShowCaption', atBoolean, // Must be the last one ! 'TWHForm2HTML option. If True, the form is rendered with a title bar and a border around it.'); with tmpAttr do begin options := options - [aoHTML]; ValueChangedProc := ShowCaptionChanged; ShowCaptionChanged(tmpAttr); end; add(tmpAttr); end; end; procedure THForm.CaptionColorDlg(attr : THAttribute; var bEdited : Boolean); var sColor : string; begin with attr do begin sColor := Value; bEdited := editBGColor(sColor); if bEdited then Value := sColor; end; end; procedure THForm.ShowCaptionChanged(attr : THAttribute); begin with _attributes do begin if attr.BooleanValue then // ShowCaption begin with Attribute['CaptionBGColor'] do Options := Options + [aoEditable]; with Attribute['CaptionColor'] do Options := Options + [aoEditable]; end else begin with Attribute['CaptionBGColor'] do Options := Options - [aoEditable]; with Attribute['CaptionColor'] do Options := Options - [aoEditable]; end; end; end; function TWHForm2HTML.getFormBeginTag : string; begin result := ''; if _bWebHubMode then begin if not (_WHChunkOutputScope in [cosAll, cosForm]) then // cosReset only exit; if _bWHChunkDeclaration then result := '<H1>-Chunk:ch' + MainContainer.Name + '</H1>' + sLineBreak; end else if ChunkOnly then result := '' else begin result := '<HTML>' + sLineBreak + '<HEAD>' + sLineBreak + '<TITLE>'; result := result + TForm(owner).caption + '</TITLE>' + sLineBreak; result := result + '<BODY>' + sLineBreak + sLineBreak; end; result := result + '<!-- Generated on ' + DateTimeToStr(Now) + ' by TWHForm2HTML,' + sLineBreak; result := result + 'the VCL FORM to HTML converter component.' + sLineBreak; result := result + 'Author: Philippe Maquet.' + sLineBreak; result := result + 'Copyright (c) 1998 HREF Tools Corp. All Rights Reserved.'; result := result + ' -->' + sLineBreak; if not _bWebHubMode then result := result + sLineBreak; result := result + _hForm.getBeforeElement + '<FORM' + _hForm.Attributes.HTML + '>'; end; function TWHForm2HTML.getFormEndTag : string; var clearList : TStringList; i : integer; bForm, bResetChunk : Boolean; begin bForm := (not _bWebHubMode) or (_WHChunkOutputScope in [cosAll, cosForm]); bResetChunk := _bWebHubMode and (_WHChunkOutputScope in [cosAll, cosReset]); if bForm then begin result := '</FORM>' + sLineBreak; result := result + _hForm.getAfterElement; end; if not (ChunkOnly or _bWebHubMode) then result := result + '</BODY>' + sLineBreak + '</HTML>' + sLineBreak else if bResetChunk then begin if _bWHChunkDeclaration then begin if bForm then result := result + sLineBreak; result := result + '<H1>-Chunk:ch' + MainContainer.Name + 'Reset</H1>' + sLineBreak; end; clearList := nil; try clearList := TStringList.create; result := result + _hMainContainer.getWHResetToDefaultMacro(clearList); with clearList do begin if count > 0 then begin sort; result := result + MacroStart + 'CLEAR|'; for i := 0 to count - 1 do begin if i > 0 then result := result + ','; result := result + strings[i]; end; result := result + MacroEnd + sLineBreak; end; end; finally clearlist.free; end; end; end; function THGroupBox.getHDims(var hWidth, hHeight : integer) : Boolean; begin hHeight := THackGroupBox(_control).clientHeight; hWidth := THackGroupBox(_control).clientWidth; result := true; end; function THGroupBox.getHTMLText: string; var hw, hh : integer; begin _form2HTML.getHDimsOfText(self, THackGroupBox(_control).caption, hw, hh); inc(hh,2); result := '<TABLE' + _form2HTML.BGColorAttr + ' Border="1" Cellspacing="0" Cellpadding="0">' + sLineBreak; result := result + '<TR><TD Height="' + intToStr(hh) + '" Valign="middle">' + _form2HTML.getFontAttr(self, '') + '&nbsp;' + removeChars(THackGroupBox(_control).caption, '&') + '</TD>' + sLineBreak + '<TR><TD>'; result := result + inherited getHTMLText; result := result + '</TD></TR></TABLE>'; end; function THRadioGroup.getHDims(var hWidth, hHeight : integer) : Boolean; begin hHeight := THackRadioGroup(_control).clientHeight; hWidth := THackRadioGroup(_control).clientWidth; result := true; end; function THRadioGroup.getHTML : string; begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} result := getHTMLText; {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; function THRadioGroup.itemsHTML : string; var ret : string; nr, nc, ni, n, r, c : integer; srh, scw : string; hw, hh : integer; function HTMLOfItem(r, c : integer) : string; var ret, s : string; i : integer; begin i := (r - 1) + (c - 1) * nr; if Form2HTML.WebHubMode then begin ret := MacroStart + 'INPUTRADIO|' + Attributes['Name'].Value + ',' + intToStr(i); s := Attributes['ExtraAttributes'].Value; if s <> '' then ret := ret + '|' + s; ret := ret + MacroEnd; end else begin ret := '<INPUT Type="radio"'; if THackRadioGroup(_control).itemIndex = i then ret := ret + ' Checked'; ret := ret + Attributes.HTML + ' Value="' + THackRadioGroup(_control).items[i] + '">'; end; ret := ret + _form2HTML.getFontAttr(self, '') + THackRadioGroup(_control).items[i]; result := ret; end; begin _form2HTML.getHDimsOfText(self, THackRadioGroup(_control).caption, hw, hh); inc(hh,2); ret := '<TABLE' + _form2HTML.BGColorAttr + ' Cellspacing="0" Cellpadding="0">' + sLineBreak; nc := THackRadioGroup(_control).columns; ni := THackRadioGroup(_control).items.count; nr := ni div nc; if (ni mod nc) <> 0 then inc(nr); if nr > 0 then begin srh := intToStr((THackRadioGroup(_control).clientHeight - hh) div nr); // row height scw := intToStr((THackRadioGroup(_control).clientWidth - 4) div nc); // columns width n := 0; for r := 1 to nr do begin if n = ni then break; ret := ret + '<TR><TD Height="' + srh + '" Width="' + scw + '">'; ret := ret + HTMLOfItem(r, 1) + '</TD>'; inc(n); for c := 2 to nc do begin if n = ni then break; ret := ret + sLineBreak + '<TD Width="' + scw + '">'; ret := ret + HTMLOfItem(r, c) + '</TD>'; inc(n); end; ret := ret + '</TR>' + sLineBreak; end; end; ret := ret + '</TABLE>' + sLineBreak; result := ret; end; function THRadioGroup.getHTMLText: string; var hw, hh : integer; begin _form2HTML.getHDimsOfText(self, THackRadioGroup(_control).caption, hw, hh); inc(hh,2); result := '<TABLE' + _form2HTML.BGColorAttr + ' Border="1" Cellspacing="0" Cellpadding="0">' + sLineBreak; result := result + '<TR><TD Height="' + intToStr(hh) + '" Valign="middle">' + _form2HTML.getFontAttr(self, '') + '&nbsp;' + removeChars(THackGroupBox(_control).caption, '&') + '</TD>' + sLineBreak + '<TR><TD>'; result := result + itemsHTML; result := result + '</TD></TR></TABLE>'; addBeforeAndAfterElements(result); end; function THForm.getHTMLText: string; var bShowCaption, bBorder : Boolean; th, tw : integer; s : string; brf : THBrowserRunFamily; function getOuterTableBGColorAttr : string; var sCaptionBGColor : string; begin if not bShowCaption then result := _form2HTML.BGColorAttr else begin sCaptionBGColor := _attributes['CaptionBGColor'].Value; if sCaptionBGColor = '' then result := _form2HTML.BGColorAttr else result := ' BGColor="' + sCaptionBGColor + '"'; end; end; begin result := ''; with _attributes do begin bShowCaption := Attribute['ShowCaption'].BooleanValue; if bShowCaption then bBorder := true else bBorder := Attribute['Border'].BooleanValue; end; if bBorder then result := result + '<TABLE' + getOuterTableBGColorAttr + ' Border="3" Cellspacing="0" Cellpadding="0">' + sLineBreak; if bShowCaption then begin _form2HTML.getHDimsOfText(self, TForm(_control).caption, tw, th); result := result + '<TR><TD Height="' + intToStr(th + 7) + '" VAlign="middle">' + _form2HTML.getFontAttr(self, _attributes['CaptionColor'].Value) + '<B>&nbsp;' + TForm(_control).caption + '</TD>' + sLineBreak; end; if bBorder then begin result := result + '<TR><TD>' + sLineBreak; s := _form2HTML.BGColorAttr; if bShowCaption then begin // Netscape bug (the whole table gets the caption backColor if the // inner backColor is empty) brf := bf2brf(Form2HTML.BrowserFamily); if (s = '') and (brf in [brfNS3, brfNS4]) then s := ' BGColor="White"'; end; result := result + '<TABLE' + s + ' Cellspacing="0" Cellpadding="0"> <TR><TD>' + sLineBreak; end; result := result + inherited getHTMLText; if bBorder then begin result := result + '</TD></TR></TABLE>'; result := result + '</TD></TR></TABLE>' + sLineBreak; end; end; constructor THPanel.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Border', atInteger, 'TWHForm2HTML option. If greater then 0, the panel is rendered with a border around it.'); with tmpAttr do begin options := options - [aoHTML]; GetDefaultProc := getDefaultBorder; ValidateProc := validateBorder; end; add(tmpAttr); end; end; procedure THPanel.getDefaultBorder(var defBorder : string); var nBorder : integer; begin with THackPanel(_control) do begin nBorder := 0; if BevelOuter <> bvNone then nBorder := BevelWidth; if BevelInner <> bvNone then inc(nBorder,BevelWidth); end; defBorder := intToStr(nBorder); end; procedure THPanel.validateBorder(var sBorder : string; var bOK : Boolean); var n : integer; s : string; begin if sBorder = '' then s := '0' else s := sBorder; try n := strToInt(sBorder); if (n < 0) or (n > 8) then bOK := false; except bOK := false; end; end; function THPanel.getHDims(var hWidth, hHeight : integer) : Boolean; var nBorder : integer; begin result := inherited getHDims(hWidth, hHeight); nBorder := strToInt(_attributes['Border'].Value); inc(hWidth, 2 * nBorder); inc(hHeight, 2 * nBorder); end; function THPanel.getHTMLText: string; var nBorder : integer; brf : THBrowserRunFamily; begin result := ''; with _attributes do nBorder := strToInt(Attribute['Border'].Value); if nBorder > 0 then begin brf := bf2brf(Form2HTML.BrowserFamily); if brf in [brfNS3, brfNS4] then inc(nBorder); result := result + '<TABLE' + _form2HTML.BGColorAttr + ' Border="' + intToStr(nBorder) + '" Cellspacing="0" Cellpadding="0">' + sLineBreak; result := result + '<TR><TD>' + sLineBreak; end; result := result + inherited getHTMLText; if nBorder > 0 then result := result + '</TD></TR></TABLE>'; end; constructor THLabel.create(aControl : TControl); begin inherited create(aControl); with _attributes do remove('ExtraAttributes'); addAnchorsAttributes; // In THControl end; function THLabel.getHTML: string; begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} result := getHTMLText; {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; function THLabel.getHTMLText: string; var sCaption, sFont : string; begin sCaption := removeChars(THackLabel(_control).caption, '&'); sFont := _form2HTML.getFontAttr(self, ''); if _attributes['AsAnchor'].BooleanValue then begin if _form2HTML.WebHubMode then result := _attributes['WHAnchorMacro'].DefValue else result := sFont + '<A Href="' + _attributes['Href'].Value + '">' + sCaption + '</A>'; end else result := sFont + sCaption; end; function THLabel.getHDims(var hWidth, hHeight : integer) : Boolean; begin result := _form2HTML.getHDimsOfText(self, THackLabel(_control).caption, hWidth, hHeight); end; function THWinControl.getHDims(var hWidth, hHeight : integer) : Boolean; begin if Enabled then result := False // job is to be done by the descendant else result := _form2HTML.getHDimsOfText(self, getHTMLText, hWidth, hHeight); end; function THWinControl.getHTMLText : string; var pBuf : pChar; begin if Enabled then begin if _Form2HTML.WebHubMode then result := inherited getHTML else result := inherited getHTMLText; end else begin pBuf := nil; try getMem(pBuf, 512); GetWindowText( TWinControl(_control).handle, pBuf, 512); result := strpas(pBuf); finally freeMem(pBuf); end; end; end; function THWinControl.getHTML : string; begin if Enabled then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} result := getBeforeElement + _form2HTML.getFontAttr(self, '') + getHTMLText + getAfterElement; {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; end; constructor THControl.create(aControl : TControl); begin inherited createHAttrObject; _control := aControl; end; procedure THControl.addAnchorsAttributes; var tmpAttr : THAttribute; begin with _attributes do begin tmpAttr := THAttribute.create('Href', atString, 'HTML Href attribute, used when AsAnchor is true. Specify the URL or WebHub pageID.'); with tmpAttr do begin ValueChangedProc := asWHAnchorChanged; Options := Options - [aoHTML]; end; add(tmpAttr); tmpAttr := THAttribute.create('WHAnchorType', atList, 'TWHForm2HTML option. Based on WHAnchorType, this defines the string to be used when exporting as a WebHub chunk.'); with tmpAttr do begin Options := Options - [aoHTML]; ValueChangedProc := asWHAnchorChanged; with ValuesList do begin add('GO'); add('GOR'); add('HIDE'); add('HIDER'); add('HREF'); add('JUMP'); add('JUMPR'); end; end; add(tmpAttr); tmpAttr := THAttribute.create('WHAnchorMacro', atString, 'TWHForm2HTML option. Defines the type of WebHub anchor macro to be used. Double-click to see choices.'); with tmpAttr do begin Options := Options - [aoHTML, aoEditable]; GetDefaultProc := getDefaultWHAnchorMacro; end; add(tmpAttr); tmpAttr := THAttribute.create('AsAnchor', atBoolean, 'TWHForm2HTML option. Specifies whether the element will create an HTML anchor or not.'); with tmpAttr do begin ValueChangedProc := asAnchorChanged; Value := boolean2String(False); DefValue := Value; Options := Options - [aoHTML]; end; add(tmpAttr); end; end; procedure THControl.asAnchorChanged(attr : THAttribute); begin with _attributes do begin if attr.BooleanValue then // AsAnchor begin with Attribute['Href'] do Options := Options + [aoEditable] - [aoIgnore]; with Attribute['WHAnchorType'] do Options := Options + [aoEditable]; end else begin with Attribute['Href'] do Options := Options - [aoEditable] + [aoIgnore]; with Attribute['WHAnchorType'] do Options := Options - [aoEditable]; end; Attribute['WHAnchorMacro']._bChanged := True; end; end; procedure THControl.getDefaultWHAnchorMacro(var defWHAnchorMacro : string); var s, s2 : string; begin if not _attributes['AsAnchor'].BooleanValue then defWHAnchorMacro := '' else begin if not (self is THImage) then s := _form2HTML.getFontAttr(self, '') else s := ''; s := s + MacroStart + _attributes['WHAnchorType'].Value + '|' + _attributes['Href'].Value; if self is THImage then begin s := s + '|<IMG '; s2 := _attributes['Alt'].Value; if s2 <> '' then s := s + 'Alt="' + s2 + '" '; s := s + 'Height="' + _attributes['Height'].Value + '" Src="' + _attributes['Src'].Value + '" Width="' + _attributes['Width'].Value + '">' + MacroEnd; end else begin if self is THLabel then s := s + '|' + removeChars(THackLabel(_control).caption, '&') + MacroEnd else s := s + '|' + removeChars(THackCheckBox(_control).caption, '&') + MacroEnd end; defWHAnchorMacro := s; end; end; procedure THControl.asWHAnchorChanged(attr : THAttribute); begin _attributes['WHAnchorMacro']._bChanged := True; end; function THControl.getNamePath : string; begin result := getName; if _hContainer <> nil then result := _hContainer.getNamePath + '_' + result; end; function THControl.getName : string; begin result := _control.name; end; function THControl.getVisible : Boolean; begin result := _control.Visible; end; function THControl.getEnabled : Boolean; begin with _control do result := (csAcceptsControls in _control.ControlStyle) or Enabled; end; constructor THAttrObject.createHAttrObject; begin inherited create; _attributes := THAttributes.create; end; destructor THAttrObject.destroy; begin _attributes.free; inherited destroy; end; procedure THAttrObject.copyAttributesFrom(fromAO : THAttrObject); var i : integer; begin for i := 0 to fromAO.Attributes.count - 1 do self.Attributes.AttributeN[i].Value := fromAO.Attributes.AttributeN[i].Value; end; procedure THAttrObject.writeData(writer : TWriter); begin writer.WriteString(Name); _attributes.writeData(writer); end; procedure THAttrObject.setOptionsFilter(optionsFilter : THAttrOptions); begin Attributes.OptionsFilter := optionsFilter; end; function THControl.getWHResetToDefaultMacro(clearList : TStringList) : string; begin result := ''; end; function THEdit.getWHResetToDefaultMacro(clearList : TStringList) : string; var sValue : string; begin sValue := _attributes['Value'].Value; if sValue <> '' then result := MacroStart + 'SET|' + _attributes['Name'].Value + '=' + sValue + MacroEnd + sLineBreak else begin result := ''; clearList.add(_attributes['Name'].Value); end; end; function THMemo.getWHResetToDefaultMacro(clearList : TStringList) : string; var sValue : string; begin sValue := _attributes['Text'].Value; if sValue <> '' then result := MacroStart + 'SET|textarea.' + _attributes['Name'].Value + '=' + sValue + MacroEnd + sLineBreak else begin result := ''; clearList.add('textarea.' + _attributes['Name'].Value); end; end; function THCheckBox.getWHResetToDefaultMacro(clearList : TStringList) : string; var bChecked : Boolean; begin bChecked := _attributes['Checked'].BooleanValue; if bChecked then result := MacroStart + 'CHECK|' + _attributes['Name'].Value + MacroEnd + sLineBreak else begin result := ''; clearList.add(_attributes['Name'].Value); end; end; function THRadio.getWHResetToDefaultMacro(clearList : TStringList) : string; var bChecked : Boolean; begin bChecked := _attributes['Checked'].BooleanValue; if bChecked then result := MacroStart + 'SET|' + _attributes['Name'].Value + '=' + _attributes['Value'].Value + MacroEnd + sLineBreak else result := ''; end; function THList.getWHResetToDefaultMacro(clearList : TStringList) : string; var i : integer; begin i := TCustomComboBox(_control).itemIndex; if i = -1 then begin result := ''; clearList.add(_attributes['Name'].Value); end else result := MacroStart + 'SET|' + _attributes['Name'].Value + '=' + getItemValue(i) + MacroEnd + sLineBreak; end; function THRadioGroup.getWHResetToDefaultMacro(clearList : TStringList) : string; var i : integer; begin i := THackRadioGroup(_control).itemIndex; if i = -1 then begin result := ''; clearList.add(_attributes['Name'].Value); end else result := MacroStart + 'SET|' + _attributes['Name'].Value + '=' + intToStr(i) + MacroEnd + sLineBreak; end; function THContainer.getWHResetToDefaultMacro(clearList : TStringList) : string; var i : integer; begin result := ''; for i := 0 to count - 1 do result := result + Children[i].getWHResetToDefaultMacro(clearList); end; procedure THNamed.getDefaultName (var defaultName : string); begin if _form2HTML.QualifiedNames then defaultName := getNamePath else defaultName := _control.name end; constructor THNamed.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Name', atString, 'HTML element''s name. Symbolic name used in transferring the output.'); tmpAttr.GetDefaultProc := getDefaultName; add(tmpAttr); end; end; function THControl.getHDims(var hWidth, hHeight : integer) : Boolean; begin result := false; hWidth := 0; hHeight := 0; end; function THControl.getHTML : string; var s : string; begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} s := getHTMLBeginTag; result := s; result := result + attributes.HTML; if s <> '' then result := result + '>'; result := result + getHTMLText; result := result + getHTMLEndTag; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; function THControl.getHTMLBeginTag : string; begin result := ''; end; function THControl.getHTMLEndTag : string; begin result := ''; end; function THControl.getHTMLText: string; begin result := ''; end; procedure THControl.setSynchronized(bOnOff : Boolean); begin _bSynch := bOnOff; end; constructor THContainer.create(aControl : TControl); begin inherited create(aControl); with _attributes do remove('ExtraAttributes'); _children := TList.create; end; destructor THContainer.destroy; var i : integer; begin for i := 0 to count - 1 do Children[i].free; _children.free; freePlacer; inherited destroy; end; function THContainer.FindHObjectByName(const objName : string) : THAttrObject; var i : integer; testName : string; begin testName := UpperCase(objName); if testName = UpperCase(self.Name) then begin result := self; exit; end; result := nil; for i := 0 to count - 1 do begin if UpperCase(Children[i].Name) = testName then begin result := Children[i]; break; end else if Children[i] is THContainer then begin result := THContainer(Children[i]).FindHObjectByName(objName); if result <> nil then break; end; end; end; procedure THContainer.setOptionsFilter(optionsFilter : THAttrOptions); var i : integer; begin inherited setOptionsFilter(optionsFilter); for i := 0 to count - 1 do Children[i].OptionsFilter := optionsFilter; end; procedure THContainer.createPlacer; var i : integer; begin if _hPlacer <> nil then exit; // already created with _control do _hPlacer := THPlacer.create(self, clientWidth, clientHeight, 4, 4); with _hPlacer do begin for i := 0 to count - 1 do placeControl(Children[i]); end; end; procedure THContainer.freePlacer; begin _hPlacer.free; _hPlacer := nil; end; function THContainer.getHTMLText: string; begin createPlacer; result := _hPlacer.HTML; end; function THContainer.getHDims(var hWidth, hHeight : integer) : Boolean; begin result := true; createPlacer; _hPlacer.getHDims(hWidth, hHeight); end; function THContainer.getChild(index : integer) : THControl; begin result := THControl(_children[index]); end; procedure THContainer.setChild(index : integer; anHControl : THControl); begin _children[index] := anHControl; end; function THContainer.getCount : integer; begin result := _children.count; end; procedure THContainer.setSynchronized(bOnOff : Boolean); var i : integer; begin inherited setSynchronized(bOnOff); if not bOnOff then begin for i := 0 to count - 1 do Children[i].synchronized := false; end; end; procedure THContainer.synchronize; var i,j : integer; ctl, testCtl : TControl; hControl : THControl; bIn : Boolean; hCtlClass : THControlClass; winContainer : TWinControl; begin freePlacer; winContainer := TWinControl(_control); synchronized := True; with winContainer do begin for i := 0 to controlCount - 1 do begin ctl := controls[i]; hCtlClass := Form2HTML.getHControlClass(ctl); if hCtlClass <> nil then begin // ctl's type is supported bIn := false; hControl := nil; // just to avoid a compile warning ! with self do begin for j := 0 to count - 1 do begin hControl := Children[j]; testCtl := hControl.control; if (ctl = testCtl) and (ctl.classType = testCtl.classType) then begin bIn := true; break; end; end; if not bIn then hControl := createNewChild(ctl); with hControl do begin synchronized := True; _hContainer := self; end; end; if hControl is THContainer then THContainer(hControl).synchronize; end; end; end; end; procedure THContainer.synchronizeDone; var i : integer; hControl : THControl; bPack : Boolean; begin bPack := false; for i := 0 to count - 1 do begin hControl := Children[i]; if not hControl.synchronized then begin hControl.free; Children[i] := nil; bPack := true; end else if hControl is THContainer then THContainer(hControl).synchronizeDone; end; if bPack then _children.pack; end; class function TWHForm2HTML.getHContainerClass(fromCtl : TControl) : THControlClass; begin result := nil; if not (csAcceptsControls in fromCtl.ControlStyle) then exit; if fromCtl is TForm then // TCustomForm doesn't exist in Delphi2 result := THForm else if (fromCtl is TCustomGroupBox) and (not (fromCtl is TCustomRadioGroup)) then result := THGroupBox else if fromCtl is TCustomPanel then result := THPanel else result := THContainer; end; function TWHForm2HTML.getHControlClass(fromCtl : TControl) : THControlClass; begin result := getHContainerClass(fromCtl); if result <> nil then exit; if fromCtl is TCustomLabel then result := THLabel else if fromCtl is TCustomMemo then // must stay *before* TCustomEdit ! result := THMemo else if fromCtl is TCustomEdit then result := THEdit else if fromCtl is TCustomCheckBox then result := THCheckBox else if fromCtl is TRadioButton then result := THRadio else if fromCtl is TCustomComboBox then result := THComboBox else if fromCtl is TCustomListBox then result := THListBox else if fromCtl is TButton then result := THButton else if fromCtl is TImage then result := THImage else if fromCtl is TCustomRadioGroup then result := THRadioGroup else result := nil; end; function THContainer.createNewChild(fromCtl : TControl) : THControl; var hCtlClass : THControlClass; begin hCtlClass := Form2HTML.getHControlClass(fromCtl); if hCtlClass <> nil then begin result := hCtlClass.create(fromCtl); result.Form2HTML := _form2HTML; _children.add(result); end else result := nil; end; constructor THAttribute.create(const aName : string; aType : THAttrType; const aHint : string); begin inherited create; _bIsDefault := true; _name := aName; _hint := aHint; _attrType := aType; _options := [aoEditable, aoHTML]; case _attrType of atBoolean: _defValue := boolean2String(False); atList: _valuesList := TStringList.create; end; end; destructor THAttribute.destroy; begin _valuesList.free; inherited destroy; end; procedure THAttribute.setOptions(options : THAttrOptions); begin _options := options; _bChanged := True; end; procedure THAttribute.setValue(const aValue : string); begin _value := aValue; _bIsDefault := (_value = DefValue); _bChanged := True; if assigned(_valueChangedProc) then _valueChangedProc(self); end; procedure THAttribute.setDefValue(const aValue : string); begin _defValue := aValue; _bIsDefault := (_defValue = _value); end; function THAttribute.getValue : string; begin if _bIsDefault then result := DefValue else result := _value; end; function THAttribute.getBooleanValue : Boolean; begin result := string2Boolean(Value); end; procedure THAttribute.setBooleanValue(b : Boolean); begin Value := boolean2String(b); end; procedure THAttribute.restore; begin _value := _savedValue; end; procedure THAttribute.save; begin _savedValue := _value; _bChanged := False; end; function THAttribute.getBChanged : Boolean; begin result := _bChanged; _bChanged := False; end; function THAttribute.getDefValue : string; begin result := _defValue; if (result = '') and (_attrType = atList) then begin if _valuesList.count > 0 then result := _valuesList.strings[0]; end; if assigned(_getDefaultProc) then _getDefaultProc(result); end; function THAttribute.getNextValue : string; var i : integer; begin result := ''; if _attrType = atList then begin with _valuesList do begin if count = 0 then exit; i := indexOf(Value); if (i = count - 1) then result := strings[0] else result := strings[i+1]; end; end; end; class function THAttribute.boolean2String(b : Boolean) : string; begin if b then result := 'True' else result := 'False'; end; class function THAttribute.string2Boolean(const s : string) : Boolean; begin result := (s = 'True') end; function THAttribute.getHTML : string; begin result := ''; if (aoHTML in _options) then begin if _attrType = atBoolean then begin if BooleanValue then result := ' ' + _name; end else if Value <> '' then begin if (aoNoName in _options) then result := ' ' + Value // Used by ExtraAttributes else result := ' ' + _name + '="' + Value + '"'; end; end; end; function THAttribute.isValid(var aValue : string) : Boolean; begin if _attrType = atList then result := (_valuesList.IndexOf(aValue) <> -1) else result := true; if result and assigned(_validateProc) then _validateProc(aValue, result); end; destructor THAttributes.destroy; var i : integer; begin if _attributes <> nil then begin for i := 0 to count - 1 do AttributeN[i].free; end; _attributes.Free; inherited destroy; end; procedure THAttributes.save; var i : integer; begin for i := 0 to count -1 do AttributeN[i].save; end; procedure THAttrObject.setWebHubMode(b : Boolean); var i : integer; stdAttr, attr : THAttribute; begin with _attributes do begin for i := 0 to count - 1 do begin attr := AttributeN[i]; with attr do begin if aoWebHub in Options then begin stdAttr := Attribute[StdAttrName]; if b then begin stdAttr.save; stdAttr.Value := Value; end else stdAttr.restore; end; end; end; end; end; procedure THContainer.setWebHubMode(b : Boolean); var i : integer; begin inherited setWebHubMode(b); for i := 0 to count - 1 do Children[i].WebHubMode := b; end; procedure THAttributes.restore; var i : integer; begin for i := 0 to count -1 do AttributeN[i].restore; end; procedure THAttributes.add(anAttr : THAttribute); var i : integer; insertPos : integer; begin if _attributes = nil then _attributes := TList.create; insertPos := -1; for i := 0 to count - 1 do begin if AttributeN[i].name >= anAttr.name then begin insertPos := i; break; end; end; if insertPos = -1 then _attributes.add(anAttr) else _attributes.insert(insertPos, anAttr); end; procedure THAttributes.remove(const attrName : string); var attr : THAttribute; begin attr := Attribute[attrName]; if attr <> nil then begin _attributes.remove(attr); attr.free; end; end; function THAttributes.getAttributeN(index : integer) : THAttribute; var i, n : integer; testAttr : THAttribute; begin if count = 0 then result := nil else if _optionsFilter = [] then result := THAttribute(_attributes.items[index]) else begin result := nil; n := -1; with _attributes do begin for i := 0 to count - 1 do begin testAttr := THAttribute(items[i]); if (testAttr.Options * _optionsFilter) <> [] then begin inc(n); if n = index then begin result := testAttr; exit; end; end; end; end; end; end; function THAttributes.getAttribute(const attrName : string) : THAttribute; var i : integer; s1, s2 : string; begin s1 := UpperCase(attrName); for i := 0 to count - 1 do begin result := AttributeN[i]; s2 := UpperCase(result.Name); if s2 = s1 then exit else if s2 > s1 then break; end; result := nil; end; function THAttributes.getCount : integer; var i : integer; begin if _attributes = nil then result := 0 else if _optionsFilter = [] then result := _attributes.count else begin result := 0; with _attributes do begin for i := 0 to count - 1 do begin if (THAttribute(items[i]).Options * _optionsFilter) <> [] then inc(result); end; end; end; end; function THAttributes.getHTML : string; var i : integer; attr : THAttribute; begin result := ''; if _attributes <> nil then begin for i := 0 to count - 1 do begin attr := AttributeN[i]; if not (aoIgnore in attr.Options) then result := result + attr.HTML; end; end; end; constructor THButton.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Type', atList, 'HTML <INPUT> Type. If AsImage is true, use "image". Otherwise, use "submit" or "reset".'); with tmpAttr do ValidateProc := validateType; add(tmpAttr); tmpAttr := THAttribute.create('Value', atString, 'HTML <INPUT> Value. Specifies the button''s caption.'); with tmpAttr do GetDefaultProc := getDefaultValue; add(tmpAttr); add(THAttribute.create('Src', atString, 'HTML <INPUT> Src. Defines the source file for the image when the attribute Type is set to "image".')); tmpAttr := THAttribute.create('Alt', atString, 'HTML Alt tag. This is defaulted based on the Hint property.'); with tmpAttr do GetDefaultProc := getDefaultAlt; add(tmpAttr); tmpAttr := THAttribute.create('AsImage', atBoolean, // must stay the last one ! 'TWHForm2HTML option. Specifies whether the button is to be rendered as an image.'); with tmpAttr do begin ValueChangedProc := asImageChanged; Value := boolean2String(False); DefValue := Value; Options := Options - [aoHTML]; end; add(tmpAttr); end; end; procedure THButton.getDefaultAlt(var defAlt : string); begin defAlt := TButton(_control).hint; end; procedure THButton.asImageChanged(attr : THAttribute); begin with _attributes do begin if attr.BooleanValue then // AsImage begin with Attribute['Type'] do begin DefValue := 'image'; Options := Options - [aoEditable]; with ValuesList do begin clear; add('image'); end; end; with Attribute['Src'] do Options := Options + [aoEditable] - [aoIgnore]; with Attribute['Alt'] do Options := Options + [aoEditable] - [aoIgnore]; with Attribute['Value'] do Options := Options - [aoEditable] + [aoIgnore]; end else begin with Attribute['Type'] do begin DefValue := 'submit'; Options := Options + [aoEditable]; with ValuesList do begin clear; add('submit'); add('reset'); end; end; with Attribute['Src'] do Options := Options - [aoEditable] + [aoIgnore]; with Attribute['Alt'] do Options := Options - [aoEditable] + [aoIgnore]; with Attribute['Value'] do Options := Options + [aoEditable] - [aoIgnore]; end; with Attribute['Type'] do Value := DefValue; end; end; procedure THButton.getDefaultValue(var defValue : string); begin defValue := removeChars(TButton(_control).Caption, '&'); end; procedure THButton.validateType(var sType : string; var bOK : Boolean); var s : string; begin s := upperCase(sType); if _attributes['AsImage'].booleanValue then bOK := (s = 'IMAGE') else bOK := (s = 'SUBMIT') or (s = 'RESET'); end; function THButton.getPureCaption : string; begin result := removeChars(Attributes['Value'].Value, '&'); if result = '' then result := removeChars(Attributes['Value'].defValue, '&'); end; function THButton.getHWidth(const sCaption : string) : integer; var brf : THBrowserRunFamily; tmpDouble : double; w : integer; begin brf := bf2brf(Form2HTML.BrowserFamily); with _form2HTML._bmp.canvas do begin with font do begin name := 'Times New Roman'; size := BUT_FNT_MOD_SIZE[brf]; style := []; end; w := textWidth(sCaption); if w < BUT_MIN_TW[brf] then w := BUT_MIN_TW[brf]; tmpDouble := w; tmpDouble := tmpDouble * BUT_ADD_WPCT[brf]; inc(w, round(tmpDouble)); inc(w, BUT_ADD_W[brf]); result := w; end; end; function THButton.getHTML : string; var s, s1, s2 : string; valueAttr : THAttribute; n : integer; begin if Attributes['AsImage'].booleanValue then begin if not Form2HTML.WebHubMode then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} result := MacroStart + 'INPUTIMAGE|' + Attributes['Name'].Value + ',' + Attributes['Src'].Value; s1 := Attributes['Alt'].Value; s2 := Attributes['ExtraAttributes'].Value; if (s1 <> '') or (s2 <> '') then result := result + '|'; if (s1 <> '') then result := result + 'Alt="' + s1 + '"'; if (s2 <> '') then begin if (s1 <> '') then result := result + ' '; result := result + s2; end; result := result + MacroEnd; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; end else begin s := getPureCaption; n := 0; while getHWidth(s) < _control.Width do begin if (n mod 2) = 0 then s := ' ' + s else s := s + ' '; inc(n); end; valueAttr := Attributes['Value']; with valueAttr do begin save; // Save attribute's Value Value := s; if not Form2HTML.WebHubMode then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} if Attributes['Type'].Value = 'submit' then result := MacroStart + 'INPUTSUBMIT|' else result := MacroStart + 'INPUTRESET|'; result := result + Attributes['Name'].Value + ',' + Attributes['Value'].Value; s := Attributes['ExtraAttributes'].Value; if s <> '' then result := result + '|' + s; result := result + MacroEnd; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; restore; // restore attribute's Value end; end; end; function THButton.getHDims(var hWidth, hHeight : integer) : Boolean; var brf : THBrowserRunFamily; begin result := true; if inherited getHDims(hWidth, hHeight) then exit; with TButton(_control) do begin if Attributes['AsImage'].booleanValue then begin hWidth := Width; hHeight := Height; end else begin brf := bf2brf(Form2HTML.BrowserFamily); hHeight := BUT_HEIGHT[brf]; hWidth := getHWidth(getPureCaption); if hWidth < Width then hWidth := Width; end; end; end; constructor THImage.create(aControl : TControl); var tmpAttr : THAttribute; begin inherited create(aControl); with _attributes do begin tmpAttr := THAttribute.create('Type', atString, 'HTML <INPUT> Type. Only used if AsButton is False.'); with tmpAttr do begin Value := 'image'; DefValue := Value; Options := Options - [aoEditable]; end; add(tmpAttr); tmpAttr := THAttribute.create('Alt', atString, 'HTML Alt Value. Specifies the alternate string for the image.'); with tmpAttr do begin GetDefaultProc := getDefaultAlt; ValueChangedProc := asWHAnchorChanged; end; add(tmpAttr); tmpAttr := THAttribute.create('Height', atInteger, 'HTML Height attribute. Sets the height of the image in pixels.'); with tmpAttr do begin GetDefaultProc := getDefaultHeight; Options := Options - [aoEditable]; end; add(tmpAttr); tmpAttr := THAttribute.create('Width', atInteger, 'HTML Width attribute. Sets the width of the image in pixels.'); with tmpAttr do begin GetDefaultProc := getDefaultWidth; Options := Options - [aoEditable]; end; add(tmpAttr); tmpAttr := THAttribute.create('Src', atString, 'HTML <INPUT> or <IMG> Src. Defines the source file for the image.'); with tmpAttr do ValueChangedProc := asWHAnchorChanged; add(tmpAttr); addAnchorsAttributes; // In THControl tmpAttr := THAttribute.create('AsButton', atBoolean, // must remain the last one 'TWHForm2HTML option. Specifies whether the image will act as a button (<INPUT Type="image">).'); with tmpAttr do begin ValueChangedProc := asButtonChanged; Value := boolean2String(True); DefValue := Value; Options := Options - [aoHTML]; end; add(tmpAttr); end; end; procedure THImage.getDefaultAlt(var defAlt : string); begin defAlt := TImage(_control).hint; end; procedure THImage.getDefaultHeight(var defHeight : string); begin defHeight := intToStr(TImage(_control).height); end; procedure THImage.getDefaultWidth(var defWidth : string); begin defWidth := intToStr(TImage(_control).Width); end; procedure THImage.asButtonChanged(attr : THAttribute); begin with _attributes do begin if attr.BooleanValue then // AsButton begin with Attribute['Type'] do Options := Options - [aoIgnore]; with Attribute['AsAnchor'] do begin Options := Options - [aoEditable]; Value := boolean2String(False); end; with Attribute['Name'] do Options := Options - [aoIgnore] + [aoEditable]; end else begin with Attribute['Type'] do Options := Options + [aoIgnore]; Attribute['AsAnchor'].Options := Attribute['AsAnchor'].Options + [aoEditable]; Attribute['AsAnchor'].Value := Value; with Attribute['Name'] do Options := Options + [aoIgnore] - [aoEditable]; end; end; end; function THImage.getHTMLBeginTag : string; begin if _attributes['AsButton'].BooleanValue then result := '<INPUT' else begin if _attributes['AsAnchor'].BooleanValue then begin with Attributes['Href'] do begin Options := Options + [aoHTML]; result := '<A' + HTML + '><IMG'; Options := Options - [aoHTML]; end; end else result := '<IMG'; end; end; function THImage.getHTMLEndTag : string; begin if _attributes['AsButton'].BooleanValue then result := '' else begin if _attributes['AsAnchor'].BooleanValue then begin result := '</A>'; Attributes['Href'].Options := Attributes['Href'].Options - [aoIgnore]; end else result := ''; end; end; function THImage.getHTML : string; var s1, s2 : string; begin if _attributes['AsAnchor'].BooleanValue then begin if not Form2HTML.WebHubMode then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} result := _attributes['WHAnchorMacro'].DefValue; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; end else if not _attributes['AsButton'].BooleanValue then result := inherited getHTML else begin if not Form2HTML.WebHubMode then result := inherited getHTML else begin {if assigned(_form2HTML.OnBeforeRenderingControl) then _form2HTML.OnBeforeRenderingControl(self);} result := MacroStart + 'INPUTIMAGE|' + Attributes['Name'].Value + ',' + Attributes['Src'].Value; s1 := Attributes['Alt'].Value; s2 := Attributes['ExtraAttributes'].Value; if (s1 <> '') or (s2 <> '') then result := result + '|'; if (s1 <> '') then result := result + 'Alt="' + s1 + '"'; if (s2 <> '') then begin if (s1 <> '') then result := result + ' '; result := result + s2; end; result := result + MacroEnd; addBeforeAndAfterElements(result); {if assigned(_form2HTML.OnAfterRenderingControl) then _form2HTML.OnAfterRenderingControl(self);} end; end; end; function THImage.getHDims(var hWidth, hHeight : integer) : Boolean; begin result := True; hWidth := _control.Width; hHeight := _control.Height; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ToolWin, ComCtrls, StdCtrls, Buttons; type TForm1 = class(TForm) RichEdit1: TRichEdit; ToolBar1: TToolBar; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; BitBtn1: TBitBtn; BitBtn2: TBitBtn; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; ToolButton9: TToolButton; procedure BitBtn1Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure ToolButton3Click(Sender: TObject); procedure ToolButton4Click(Sender: TObject); procedure ToolButton5Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.BitBtn1Click(Sender: TObject); begin if OpenDialog1.Execute then RichEdit1.Lines.LoadFromFile(OpenDialog1.FileName); end; procedure TForm1.BitBtn2Click(Sender: TObject); begin if SaveDialog1.Execute then RichEdit1.Lines.SaveToFile(SaveDialog1.FileName); end; procedure TForm1.ToolButton3Click(Sender: TObject); begin RichEdit1.SelAttributes.Style:=[fsBold]; end; procedure TForm1.ToolButton4Click(Sender: TObject); begin RichEdit1.SelAttributes.Style:=[fsItalic]; end; procedure TForm1.ToolButton5Click(Sender: TObject); begin RichEdit1.SelAttributes.Style:=[fsUnderline]; end; end.
unit images; interface uses windows, sysutils, graphics, strutils, controls, classes, ImgList, TSImageList; type TImages = class(TObject) private imageHash16 :tstrings; public il16 : TImageList; tsIl16 : TtsImageList; constructor create; destructor destroy; override; function GetImageIndex(imageName: string): integer; procedure assignImage(const imageName:string;var aBitmap:TBitmap); end; var allImages : TImages; implementation //------------------------------------------------------------------------------ function TImages.GetImageIndex(imageName: string): integer; begin imageName := upperCase(imageName); result := imageHash16.indexOf(imageName); //if(result = -1) then // result := imageHash32.indexOf(imageName); end; //------------------------------------------------------------------------------ procedure TImages.assignImage(const imageName:string;var aBitmap:TBitmap); begin il16.GetBitmap(GetImageIndex(imageName), aBitmap); end; //------------------------------------------------------------------------------ function enumResNamesProc( module: HMODULE; restype, resname: PChar; aI:TImages): Integer; stdcall; var r : string; b : tbitmap; i : TtsImage; begin if HiWord( Cardinal(resname) ) <> 0 then r := resname else r := format('#%d',[loword(cardinal(resname))]); if(length(r) > 5) and (leftstr(r,5) = 'JSCP_') then begin // both il.ResourceLoad and il.GetResource seem to not support 256 color palletes // the work around is to add it to a bitmap first b := tbitmap.Create(); try b.Width := 16; b.Height := 16; b.LoadFromResourceName(HInstance, r); aI.il16.AddMasked(b, clFuchsia); i := aI.tsIl16.Images.Add(); i.Bitmap.Assign(b); i.Name := rightstr(r, length(r)-5); i.Transparent := true; i.TransparentColor := clFuchsia; finally b.free(); end; aI.imageHash16.add(rightstr(r, length(r)-5)); end; result := 1; end; //------------------------------------------------------------------------------ constructor TImages.create; begin inherited; imageHash16 := tstringlist.create(); il16 := TImageList.create(nil); tsIl16 := TtsImageList.Create(nil); EnumResourceNames( hinstance, RT_BITMAP, @enumResNamesProc, integer(self)); end; //------------------------------------------------------------------------------ destructor TImages.destroy; begin imageHash16.Free(); il16 .free(); tsIl16 .free(); inherited; end; //------------------------------------------------------------------------------ initialization allImages := TImages.create(); finalization allImages.free(); end.
{*======================================================================* | unitRTF2HTML | | | | RTF to HTML converter. | | | | Limitations | | ----------- | | This is designed to convert XanaNews messages only, so its scope is | | limited. It doesn't do tables, embedded images, etc. etc. etc. | | | Handling of out-of-order tags is limited - eg. | | | 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. | | | | Copyright © Colin Wilson 2004 All Rights Reserved | | | Version Date By Description | | ------- ---------- ---- ------------------------------------------| | 1.0 07/03/2005 CPWW Original | *======================================================================*} unit unitRTF2HTML; interface uses Windows, Classes, SysUtils; function RTF2HTML (const rtf : string; rawFragment : boolean = false) : string; implementation type // nb. The token strings below *must* be in alphabetical order TRTFTokens = (rtAnsi, rtAnsiCPG, rtBold, rtBoldNone, rtCf, rtColorTbl, rtDeff, rtDefLang, rtF, rtFontTbl, rtFs, rtItalic, rtItalicNone, rtPar, rtPard, rtPlain, rtRtf, rtUc, rtUnderline, rtUnderlineNone, rtViewkind, rtUnknown); var RTFTokens : array [Low (TRTFTokens)..Pred (rtUnknown)] of string = ('ansi', 'ansicpg', 'b', 'bnone', 'cf', 'colortbl', 'deff', 'deflang', 'f', 'fonttbl', 'fs', 'i', 'inone', 'par', 'pard', 'plain', 'rtf', 'uc', 'ul', 'ulnone', 'viewkind'); {*----------------------------------------------------------------------* | function FindToken | | | | Convert a token string to a token | *----------------------------------------------------------------------*} function FindToken (const token : string) : TRTFTokens; function bsearch (s, e : TRTFTokens) : TRTFTokens; var m : TRTFTokens; c : Integer; si, ei : Integer; begin si := Integer (s); ei := Integer (e); if ei = 255 then ei := -1; if si <= ei then begin m := TRTFTokens (si + (ei - si) div 2); c := AnsiCompareText (token, RTFTokens [m]); if c > 0 then result := bsearch (Succ (m), e) else if c < 0 then result := bsearch (s, Pred (m)) else result := m end else result := rtUnknown; end; begin result := bsearch (Low (TRTFTokens), Pred (rtUnknown)) end; {*----------------------------------------------------------------------* | function RTF2HTML | | | | Convert an RTF string to an HTML string | *----------------------------------------------------------------------*} function RTF2HTML (const rtf : string; rawFragment : boolean = false) : string; var p : PChar; ch : char; value : string; token : TRTFTokens; HTMLTagStack : TStringList; inBody : boolean; colors : TList; inTags : boolean; procedure Error (const st : string); begin raise Exception.Create(st); end; procedure CheckInBody; forward; // ------ Basic HTML generation routines... procedure EmitChar (ch : char); begin CheckInBody; result := result + ch; end; procedure EmitStr (const st : string); begin CheckInBody; result := result + st end; procedure EmitText (const st : string); begin if inTags then begin inTags := False; EmitStr (#13#10) end; EmitStr (st) end; procedure EmitTextChar (ch : char); begin if inTags then begin inTags := False; EmitStr (#13#10) end; case ch of '>' : EmitStr ('&gt;'); '<' : EmitStr ('&lt;'); '"' : EmitStr ('&quot;'); '&' : EmitStr ('&amp;'); else EmitChar (ch) end end; // // Emit an HTML tag and push it onto the HTML tag stack so that it will // automatically get closed. // procedure EmitTag (const tag, params : string); begin // Optimization - don't do <BODY><P>. Just <BODY> will do if not inBody and (tag = 'P') and (params = '') then begin CheckInBody; exit end; // Emit the tag and parameters EmitChar ('<'); EmitStr (tag); if params <> '' then begin EmitChar (' '); EmitStr (params) end; EmitChar ('>'); // Add the tag to the HTML tag stack if Copy (tag, 1, 1) <> '/' then begin HTMLTagStack.Insert(0, tag); inTags := True end end; // // *only* if the tag is on the stack, pop and emit all tags up to and // including the tag. // procedure PopTag (const tag : string); var st : string; begin if HTMLTagStack.IndexOf(tag) >= 0 then while (HTMLTagStack.Count > 0) do begin st := HTMLTagStack [0]; HTMLTagStack.Delete(0); if st <> '{' then begin EmitTag ('/' + st, ''); EmitStr (#13#10) end; if st = tag then break end end; procedure CheckInBody; begin if not inBody then begin inBody := True; if not rawFragment then EmitTag ('BODY', ''); end end; // ----- Basic parsing routines function GetChar : char; begin ch := p^; result := ch; Inc (p) end; function GetValue : string; begin value := ''; while not (GetChar in [' ', '\', '{', ';', #13, #10]) do value := value + ch; if ch <> ' ' then Dec (p); result := value end; function GetToken : TRTFTokens; var st : string; begin st := ''; while GetChar in ['A'..'Z', 'a'..'z'] do st := st + ch; Dec (p); token := FindToken (st); result := token end; function GetTokenValue : string; begin value := ''; while GetChar in ['A'..'Z', 'a'..'z'] do value := value + ch; Dec (p); result := value; end; //----- Parse a font group structure procedure GetFontGroup; procedure GetFontNameValue; begin Value := ''; while not (GetChar in [';', '\']) do Value := Value + ch; Dec (p); end; begin while not (GetChar in [#0, '}']) do case ch of '\' : begin GetToken; GetValue; end; ' ' : GetFontNameValue; ';' : if GetChar <> '}' then Error ('} expected after ; in font table') else break; '{' : Error ('Unexpected { in font table'); end end; //----- Parse a colour group procedure GetColorGroup; var st : string; rVal, gVal, bVal : byte; begin rVal := 0; gVal := 0; bVal := 0; while ch <> #0 do case ch of '\' : begin st := GetTokenValue; GetValue; if SameText (st, 'red') then rVal := StrToIntDef (value, 0) else if SameText (st, 'green') then gVal := StrToIntDef (value, 0) else if SameText (st, 'blue') then bVal := StrToIntDef (value, 0); while GetChar = ' ' do; end; ';' : begin if colors = Nil then colors := TList.Create; colors.Add(Pointer (RGB (rVal, gVal, bVal))); GetChar; break end; ' ' : GetChar (); else Error ('\ expected in color table'); end end; // ----- Parse a group (between '{' and '}'). Does most of the work procedure GetGroup; var intVal : Integer; procedure ProcessFontTable; begin while GetChar = '{' do GetFontGroup; if ch <> '}' then Error ('} expected in Font Table') else Dec (p) end; procedure ProcessColorTable; begin while not (ch in ['}', #0]) do GetColorGroup; Dec (p) end; procedure ProcessToken; begin GetToken; GetValue; case Token of rtFontTbl : ProcessFontTable; rtColorTbl : ProcessColorTable; rtBold : if value = '0' then PopTag ('B') else EmitTag ('B', ''); rtBoldNone : PopTag ('B'); rtItalic : if value = '0' then PopTag ('I') else EmitTag ('I', ''); rtItalicNone : PopTag ('I'); rtUnderline : if value = '0' then PopTag ('U') else EmitTag ('U', ''); rtUnderlineNone : PopTag ('U'); rtPard : begin PopTag ('P'); EmitTag ('P', ''); end; rtPar : EmitText ('<BR>'+#13#10); rtPlain : begin PopTag ('B'); PopTag ('U'); PopTag ('I'); PopTag ('FONT') end; rtCf : begin intVal := StrToIntDef (value, -1); if (intVal >= 0) and (colors <> Nil) and (intVal < colors.Count) then begin intVal := Integer (colors [intVal]); PopTag ('FONT'); EmitTag ('FONT', Format ('Color=#%2.2x%2.2x%2.2x', [ getRValue (intVal), getGValue (intVal), getBValue (intVal)])); end end end end; begin { GetGroup } HTMLTagStack.Insert(0, '{'); while not (GetChar in [#0, '}']) do case ch of #10, #13 :; '\' : case p [0] of '''' : begin // Hex literal Value := p [1] + p [2]; Inc (p, 3); EmitTextChar (Char (StrToInt ('$' + Value))); end; '{', '}', '/' : EmitTextChar (GetChar); else ProcessToken end; '{' : GetGroup else if (ch = ' ') and (p [0] = ' ') then EmitTextChar (#$a0) else EmitTextChar (ch) end; PopTag ('{'); end; begin { RTF2HTML } inBody := False; // Initialize globals result := ''; colors := Nil; inTags := False; p := @rtf [1]; HTMLTagStack := TStringList.Create; try HTMLTagStack.CaseSensitive := False; while GetChar <> #0 do case ch of #0 : break; '{' : GetGroup; '}' : Error ('Mismatched curly brackets') end finally // The HTML tag stack should be empty - but // make sure... while HTMLTagStack.Count > 0 do PopTag (HTMLTagStack [HTMLTagStack.Count - 1]); HTMLTagStack.Free; colors.Free end end; end.
unit FileUtils; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} interface uses Classes, SysUtils; { Appends the passed file (FileName) to the Stream, uses the current stream position if DontSeek is false (which may lead to overwrites), the end of the steam otherwise } procedure AppendDataToFileStream(Stream : TFileStream; const FileName : String; const DontSeek : Boolean = false); { Searches for a Data string in the passed byte-stream (will convert the string to a byte array), will always seek in the passed stream, so pass Stream.Position as StartPos to work "around" that StartPos is the postition to start searching from, pass negative values for a offset from the end of the stream (passing 0 and Backwards=true will start at the end) Backwards specifies the direction in which to search, independant of StartPos You can pass an optional OutputStream in which all data from StartPos to the final end of the String to find will be written (only when Backwards is false) Uses a "rolling" buffer to eliminate the problem of the string to be split into two Because of that only the first 512 bytes of Data are used for comparison } function FindStringDataInStream(const Data : String; Stream : TFileStream; const StartPos : Int64 = 0; const Backwards : Boolean = false; OutputStream : TFileStream = nil) : Int64; implementation uses Math, Forms; procedure AppendDataToFileStream(Stream : TFileStream; const FileName : String; const DontSeek : Boolean = false); var Buffer : Array [Word] of Byte; //64KB NumRead, NumWrite : Integer; Other : TFileStream; begin if NOT DontSeek then Stream.Seek(0,soFromEnd); Other := TFileStream.Create(FileName,fmOpenRead); try repeat NumRead := Other.Read(Buffer,SizeOf(Buffer)); NumWrite := Stream.Write(Buffer,NumRead); until (NumRead = 0) OR (NumWrite <> NumRead); finally Other.Free; end; end; function FindStringDataInStream(const Data : String; Stream : TFileStream; const StartPos : Int64 = 0; const Backwards : Boolean = false; OutputStream : TFileStream = nil) : Int64; var NumRead : Word; DataArray : Array [0..511] of Byte; Buffer : Array [0..1023] of Byte; // 1KB I,K : Word; Size : Word; Found : Boolean; Pos : Int64; begin // convert string to byte array for comparison Size := Min(Length(Data) * SizeOf(Char),SizeOf(DataArray)); Move(Data[1],DataArray,Size); // set-up stream correctly if StartPos < 0 then Stream.Seek(StartPos,soFromEnd) else if StartPos > 0 then Stream.Seek(StartPos,soFromBeginning) else begin if Backwards then Stream.Seek(0,soFromEnd) else Stream.Seek(0,soFromBeginning); end; if Backwards then begin // first seek here as we begin with a read operation Stream.Seek(-SizeOf(Buffer),soFromEnd); // stream output only supported in forwards mode OutputStream := nil; end; Result := -1; repeat // save current position for loop check Pos := Stream.Position; NumRead := Stream.Read(Buffer,SizeOf(Buffer)); // check buffer against data for I := 0 to SizeOf(Buffer) - Size - 1 do begin if Buffer[I] = DataArray[0] then begin Found := true; for K := 0 to Size - 1 do begin if Buffer[I+K] <> DataArray[K] then begin Found := false; Break; end; end; if Found then begin Result := Stream.Position - NumRead + I; Break; end; end; end; // save buffer to output stream if OutputStream <> nil then begin if Result = -1 then // not found yet begin if NumRead < SizeOf(Buffer) then OutputStream.Write(Buffer,NumRead) else OutputStream.Write(Buffer,SizeOf(Buffer) div 2); end else OutputStream.Write(Buffer,Result + Size + NumRead - Stream.Position); // I + Size end; // position found -> exit if Result <> -1 then Exit; // use a "rolling" buffer to work around data beeing split on two buffers // this also is the reason the data array is half the size of the buffer if Backwards then Stream.Seek(Max(-SizeOf(Buffer) * 3 div 2,-Stream.Position),soFromCurrent) else Stream.Seek(-SizeOf(Buffer) div 2,soFromCurrent); // forward: read less bytes than buffer means end of file // backward: seeking does not change position means beginning of file until (NumRead < SizeOf(Buffer)) OR (Stream.Position = Pos); end; end.
{ Implémentation de l'algorithme de hachage LEA-128 Algorithme LEA-128 (Lossy Elimination Algorithm - Algorithme de perte de données par élimination). Auteur : Bacterius. Algorithme de perte de données par élimination : on élimine la donnée et on en tire son empreinte. Effectivement, cet algorithme va réduire une donnée de taille variable (de 1 octet, 12 mégas, ou même 1 gigaoctet) en sa représentation unique (de taille fixe : 32 octets). Chaque donnée aura une représentation unique (théoriquement : mais en pratique, il y aura toujours des collisions, car il y a plus de possibilités de messages que de possibilités de hash : d'après le principe des tiroirs). Mathématiquement, si Hash(x) est la fonction par laquelle passe la donnée x, et H le hash de cette donnée x, on a : y <> x Hash(x) = H Hash(y) <> H Cet algorithme de hachage est basé sur un hachage octet par octet, c'est à dire que chaque octet (caractère) du message va changer le hachage. Voici un schéma : ________________________________________________________________________________ VALEURS DE DEPART | MESSAGE | A B C D | | | | | | ? ? ? ? <---- OCTET 1 DU MESSAGE (altération de A, B, C, D) | | | | | ? ? ? ? <---- OCTET 2 DU MESSAGE (altération de A, B, C, D) | | | | | ? ? ? ? <---- OCTET 3 DU MESSAGE (altération de A, B, C, D) | | | | | ................. etc ... | | | | | W X Y Z <---- HACHAGES (altérés) \ | | / | Hachage <---- de 128 bits, c'est la réunion de W, X, Y et Z (32 bits chacun) ________________________________________________________________________________ L'algorithme de hachage tient surtout à la façon dont sont altérées les valeurs A, B, C et D à chaque octet du message. HashTable contient les 4 valeurs de départ. Elles représentent la "signature" de l'algorithme. Si vous changez ces valeurs, les hachages changeront également. HashTransform associe à chaque valeur d'un octet (0..255) une valeur d'un double mot. Si vous changez une ou plusieurs de ces valeurs, certains hachages risquent d'être différents. Cet algorithme n'est pas spécialement rapide (environ 0.05 millisecondes le hachage d'un message de 255 octets), et le test de collisions n'est pas terminé. Comme pour tous les algorithmes de hash, on s'efforce de faire des hachages les moins similaires possibles pour des petits changements. Essayez avec "a", puis "A", puis "b", vous verrez ! ¤ Les fonctions - Hash : cette fonction effectue le hachage d'une donnée Buffer, de taille Size. Il s'agit de la fonction de base pour hacher un message. - HashToString : cette fonction convertit un hachage en une chaîne lisible. - StringToHash : cette fonction convertit une chaîne lisible en hash, si celle-ci peut correspondre à un hash. En cas d'erreur, toutes les valeurs du hash sont nulles. - SameHash : cette fonction compare deux hachages et dit si celles-ci sont identiques. Renvoie True le cas échéant, False sinon. - HashCrypt : cette fonction crypte un hachage tout en conservant son aspect. - HashUncrypt : cette fonction décrypte un hachage crypté avec la bonne clef. - IsHash : cette fonction vérifie si la chaîne passée peut être ou est un hachage. - HashStr : cette fonction effectue le hachage d'une chaîne de caractères. - HashInt : cette fonction effectue le hachage d'un entier sur 32 bits. Attention : la fonction effectue le hachage de l'entier directement, elle ne convertit absolument pas l'entier en texte ! - HashFile : cette fonction effectue le hachage du contenu d'un fichier. ¤ Collisions. Dans tout algorithme de hachage existent des collisions. Cela découle logiquement de l'affirmation suivante : Il y a un nombre limité de hachages possibles (2^128). Mais il existe une infinité de messages possibles, si l'on ne limite pas les caractères. Cependant, l'algorithme peut réduire le nombre de collisions, qui, théoriquement infini, ne l'est pas à l'échelle humaine. Si l'on suppose qu'à l'échelle humaine, nous ne tenons compte, schématiquement, de messages de 10 octets maximum (c'est un exemple), l'on a une possibilité de combinaisons de 255^10 octets, sur une possibilité de 2^128 hachages. Il est donc possible de n'avoir aucune collision, puisqu'il y a plus de possibilités de hachages que de possibilités de combinaisons. ¤ Protection additionnelle Un hash est déjà théoriquement impossible à inverser. Cependant, cela est possible à l'échelle mondiale avec un réseau de super-calculateurs, moyennant tout de même une quantité de temps impressionnante (avec les 80 et quelques supercalculateurs de IBM, l'on ne met que 84 ans à trouver le message (de 10 caractères) correspondant au hachage). Vous pouvez donc ajouter des protections supplémentaires : - Le salage : cela consiste à ajouter une donnée supplémentaire au message avant hachage. Cela rend le hachage moins vulnérable aux attaques par dictionnaire. Par exemple, si vous avez un mot de passe "chat", quand quelqu'un va attaquer le hachage de "chat", il va rapidement le trouver dans le dictionnaire, va s'apercevoir que le hachage est le même, et va déduire qu'il s'agit de votre mot de passe. Pour éviter ça, vous allez ajouter une donnée moins évidente au message, disons "QS77". Vous allez donc hacher le mot de passe "QS77chat" ( ou "chatQS77"). Ce mot ne figure evidemment pas dans le dictionnaire. Le pirate va donc avoir un problème, et va alors eventuellement laisser tomber, ou bien changer de technique, et attaquer par force brute (tester toutes les combinaisons possibles). Si vous avez un mot de passe de 5 caractères ASCII, cela lui prendra au plus 5 jours. Si vous avez un mot de passe de 10 caractères, cela mettra 70 milliards d'années. Donc, optez pour un mot de passe d'au moins 6 caractères (et eventuellement, rajoutez un caractère spécial, comme un guillemet, pour forcer le pirate à attaquer en ASCII et non pas en alphanumérique (il lui faudrait plus de temps de tester les 255 caractères ASCII que seulement les 26 lettres de l'alphabet et les nombres ...)). - Le cryptage : cela consiste à crypter le hachage par-dessus (tout en lui faisant garder son aspect de hachage ! Par exemple, si vous avez un hachage "A47F", n'allez pas le crypter en "%E#!", il apparaîtrait evident qu'il est crypté !). Cela a pour effet de compliquer encore plus le travail du pirate, qui, inconsciemment, sera en train d'essayer de percer un mauvais hachage ! Si le cryptage est bien réalisé, il peut s'avérer plus qu'efficace. Cependant, pensez à conserver la clef de cryptage/décryptage, sans quoi, si pour une raison ou pour une autre vous aviez à récupérer le hash d'origine (cela peut arriver parfois), vous devriez tester toutes les clefs ... Une fonction de cryptage et une de décryptage est fournie dans cette unité. - Le byteswap : cela consiste à "swapper" les octets du hachage. Cela revient à crypter le hachage puisque cette opération est réversible "permutative" (la fonction de cryptage joue également le rôle de la fonction de décryptage). Ajouter une petite protection ne coûte rien de votre côté, et permet de se protéger plus qu'efficacement contre des attaques. Même si un hash en lui-même est déjà pas mal, mieux vaut trop que pas assez ! } unit LEA_Hash; interface uses Windows, SysUtils, Dialogs; const { Ces valeurs sont pseudo-aléatoires (voir plus bas) et sont distinctes (pas de doublon) } { Notez que le hachage d'une donnée nulle (de taille 0) renverra HashTable (aucune altération) } HashTable: array [0..3] of Longword = ($CF306227, $4FCE8AC8, $ACE059ED, $4E3079A6); { MODIFIER CES VALEURS ENTRAINERA UNE MODIFICATION DE TOUS LES HACHAGES } const { Ces valeurs sont précalculées sur la base du polynome du nombre $3E8A42F7 } HashTransform: array [0..255] of Longword = ( $3E8A42F7,$181354AB,$3026A956,$2835FDFD,$1D59D743,$054A83E8,$2D7F7E15,$356C2ABE, $3AB3AE86,$22A0FA2D,$0A9507D0,$1286537B,$27EA79C5,$3FF92D6E,$17CCD093,$0FDF8438, $0873D8E3,$10608C48,$385571B5,$2046251E,$152A0FA0,$0D395B0B,$250CA6F6,$3D1FF25D, $32C07665,$2AD322CE,$02E6DF33,$1AF58B98,$2F99A126,$378AF58D,$1FBF0870,$07AC5CDB, $10E7B1C6,$08F4E56D,$20C11890,$38D24C3B,$0DBE6685,$15AD322E,$3D98CFD3,$258B9B78, $2A541F40,$32474BEB,$1A72B616,$0261E2BD,$370DC803,$2F1E9CA8,$072B6155,$1F3835FE, $18946925,$00873D8E,$28B2C073,$30A194D8,$05CDBE66,$1DDEEACD,$35EB1730,$2DF8439B, $2227C7A3,$3A349308,$12016EF5,$0A123A5E,$3F7E10E0,$276D444B,$0F58B9B6,$174BED1D, $21CF638C,$39DC3727,$11E9CADA,$09FA9E71,$3C96B4CF,$2485E064,$0CB01D99,$14A34932, $1B7CCD0A,$036F99A1,$2B5A645C,$334930F7,$06251A49,$1E364EE2,$3603B31F,$2E10E7B4, $29BCBB6F,$31AFEFC4,$199A1239,$01894692,$34E56C2C,$2CF63887,$04C3C57A,$1CD091D1, $130F15E9,$0B1C4142,$2329BCBF,$3B3AE814,$0E56C2AA,$16459601,$3E706BFC,$26633F57, $3128D24A,$293B86E1,$010E7B1C,$191D2FB7,$2C710509,$346251A2,$1C57AC5F,$0444F8F4, $0B9B7CCC,$13882867,$3BBDD59A,$23AE8131,$16C2AB8F,$0ED1FF24,$26E402D9,$3EF75672, $395B0AA9,$21485E02,$097DA3FF,$116EF754,$2402DDEA,$3C118941,$142474BC,$0C372017, $03E8A42F,$1BFBF084,$33CE0D79,$2BDD59D2,$1EB1736C,$06A227C7,$2E97DA3A,$36848E91, $3E8A42F7,$2699165C,$0EACEBA1,$16BFBF0A,$23D395B4,$3BC0C11F,$13F53CE2,$0BE66849, $0439EC71,$1C2AB8DA,$341F4527,$2C0C118C,$19603B32,$01736F99,$29469264,$3155C6CF, $36F99A14,$2EEACEBF,$06DF3342,$1ECC67E9,$2BA04D57,$33B319FC,$1B86E401,$0395B0AA, $0C4A3492,$14596039,$3C6C9DC4,$247FC96F,$1113E3D1,$0900B77A,$21354A87,$39261E2C, $2E6DF331,$367EA79A,$1E4B5A67,$06580ECC,$33342472,$2B2770D9,$03128D24,$1B01D98F, $14DE5DB7,$0CCD091C,$24F8F4E1,$3CEBA04A,$09878AF4,$1194DE5F,$39A123A2,$21B27709, $261E2BD2,$3E0D7F79,$16388284,$0E2BD62F,$3B47FC91,$2354A83A,$0B6155C7,$1372016C, $1CAD8554,$04BED1FF,$2C8B2C02,$349878A9,$01F45217,$19E706BC,$31D2FB41,$29C1AFEA, $1F45217B,$075675D0,$2F63882D,$3770DC86,$021CF638,$1A0FA293,$323A5F6E,$2A290BC5, $25F68FFD,$3DE5DB56,$15D026AB,$0DC37200,$38AF58BE,$20BC0C15,$0889F1E8,$109AA543, $1736F998,$0F25AD33,$271050CE,$3F030465,$0A6F2EDB,$127C7A70,$3A49878D,$225AD326, $2D85571E,$359603B5,$1DA3FE48,$05B0AAE3,$30DC805D,$28CFD4F6,$00FA290B,$18E97DA0, $0FA290BD,$17B1C416,$3F8439EB,$27976D40,$12FB47FE,$0AE81355,$22DDEEA8,$3ACEBA03, $35113E3B,$2D026A90,$0537976D,$1D24C3C6,$2848E978,$305BBDD3,$186E402E,$007D1485, $07D1485E,$1FC21CF5,$37F7E108,$2FE4B5A3,$1A889F1D,$029BCBB6,$2AAE364B,$32BD62E0, $3D62E6D8,$2571B273,$0D444F8E,$15571B25,$203B319B,$38286530,$101D98CD,$080ECC66); { MODIFIER CES VALEURS PEUT ENTRAINER UNE MODIFICATION DE CERTAINS HACHAGES } type THash = record { La structure d'un hash LEA sur 128 bits } A, B, C, D: Longword; { Les quatre double mots } end; function Hash (const Buffer; const Size: Longword): THash; function HashStr (const Str : String ): THash; function HashInt (const Int : Integer ): THash; function HashFile (const FilePath: String ): THash; function HashToString (const Hash : THash ): String; function StringToHash (const Str : String ): THash; function SameHash (const A, B : THash ): Boolean; function HashCrypt (const Hash : String; Key: Integer): String; function HashUncrypt (const Hash : String; Key: Integer): String; function IsHash (const Hash : String ): Boolean; implementation function Hash(const Buffer; const Size: Longword): THash; Var V: PByte; E: Pointer; begin { Etapes du hachage : on va récupérer 4 valeurs de départ A, B, C, D de 32 bits provenant du tableau HashTable. Ce sont les "vecteurs d'initialisation". On va alors altérer ces valeurs à l'aide du message contenu dans Buffer. Plusieurs altérations sont nécessaires. Ensuite, on reconstitue l'empreinte en mettant bout à bout les 4 valeurs de 32 bits obtenues. } { On récupère les valeurs du tableau } Move(HashTable, Result, 16); { Si buffer vide, on a les valeurs initiales } if Size = 0 then Exit; { On prend le premier octet du buffer } V := @Buffer; { On calcule le dernier octet du buffer } E := Ptr(Longword(@Buffer) + Size); with Result do repeat { Pour chaque octet, tant qu'on est pas arrivé à la fin ... } begin { On effectue une altération complexe } A := (A shl 5) xor (D shr 2) and V^ + B; B := (B shl 2) xor (C shr 11) and V^ + A; C := (C shl 7) xor (A shr 4) and V^ + D; D := (D shl 8) xor (B shr 14) and V^ + C; Inc(A, (HashTransform[V^] xor D) + (C xor (D or (not B)))); Inc(B, (HashTransform[V^] xor C) + (D xor (B or (not A)))); Inc(C, (HashTransform[V^] xor B) + (A xor (C or (not D)))); Inc(D, (HashTransform[V^] xor A) + (B xor (A or (not C)))); Inc(V); { On passe à l'octet suivant ! } { Ne pas modifier les 8 lignes de calcul, sinon cela peut ne plus marcher } end until V = E; end; function HashStr(const Str: String): THash; Var S: array of Char; I: Integer; begin { On va stocker la chaîne Delphi dans un tableau de caractères, et envoyer ça à la fonction Hash. } SetLength(S, Length(Str)); for I := 1 to Length(Str) do S[I - 1] := Str[I]; Result := Hash(S[0], Length(Str)); end; function HashInt(const Int: Integer): THash; begin { On envoie directement le nombre dans le buffer. } Result := Hash(Int, SizeOf(Integer)); end; function HashFile(const FilePath: String): THash; Var H, M: Longword; P: Pointer; begin { On va mettre à 0 pour cette fonction, car autant il n'était pas possible que les fonctions précédentes n'échouent, celle-ci peut échouer pour diverses raisons. } ZeroMemory(@Result, 16); { On ouvre le fichier } H := CreateFile(PChar(FilePath), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); { Si erreur d'ouverture, on s'en va } if H = INVALID_HANDLE_VALUE then Exit; { CreateFileMapping rejette les fichiers de taille 0 : ainsi, on doit les tester avant } if GetFileSize(H, nil) = 0 then begin Result := Hash('', 0); { On récupère un hash nul } CloseHandle(H); { On libère le handle } Exit; end; { On crée une image mémoire du fichier } try M := CreateFileMapping(H, nil, PAGE_READONLY, 0, 0, nil); try { On récupère un pointeur sur l'image du fichier en mémoire } if M = 0 then Exit; P := MapViewOfFile(M, FILE_MAP_READ, 0, 0, 0); try { On envoie le pointeur au hash, avec comme taille de buffer la taille du fichier } if P = nil then Exit; Result := Hash(P^, GetFileSize(H, nil)); finally { On libère tout ... } UnmapViewOfFile(P); end; finally CloseHandle(M); end; finally CloseHandle(H); end; end; function HashToString(const Hash: THash): String; begin { On ajoute les quatre entiers l'un après l'autre sous forme héxadécimale ... } Result := Format('%.8x%.8x%.8x%.8x', [Hash.A, Hash.B, Hash.C, Hash.D]); end; function StringToHash(const Str: String): THash; begin if IsHash(Str) then with Result do begin { Astuce de Delphi : un HexToInt sans trop de problèmes ! Rajouter un "$" devant le nombre et appeller StrToInt. Cette astuce accepte un maximum de 8 caractères après le signe "$". } A := StrToInt(Format('$%s', [Copy(Str, 1, 8)])); B := StrToInt(Format('$%s', [Copy(Str, 9, 8)])); C := StrToInt(Format('$%s', [Copy(Str, 17, 8)])); D := StrToInt(Format('$%s', [Copy(Str, 25, 8)])); end else ZeroMemory(@Result, 16); { Si Str n'est pas un hash, on met tout à 0 } end; function SameHash(const A, B: THash): Boolean; begin { On compare les deux hashs ... } Result := (A.A = B.A) and (A.B = B.B) and (A.C = B.C) and (A.D = B.D); end; const Z = #0; // Le caractère nul, plus pratique de l'appeller Z que de faire chr(0) ou #0 function hxinc(X: Char): Char; { Incrémentation héxadécimale } const XInc: array [48..70] of Char = ('1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', Z, Z, Z, Z, Z, Z, Z, 'B', 'C', 'D', 'E', 'F', '0'); begin if ord(X) in [48..57, 65..70] then Result := XInc[ord(X)] else Result := Z; end; function hxdec(X: Char): Char; { Décrémentation héxadécimale ... } const XDec: array [48..70] of Char = ('F', '0', '1', '2', '3', '4', '5', '6', '7', '8', Z, Z, Z, Z, Z, Z, Z, '9', 'A', 'B', 'C', 'D', 'E'); begin if ord(X) in [48..57, 65..70] then Result := XDec[ord(X)] else Result := Z; end; function HashCrypt(const Hash: String; Key: Integer): String; Var I, J: Integer; S: ShortString; P: Integer; begin { Cryptage avec une clef alphanumérique - comme le cryptage de César ! } Result := ''; if not IsHash(Hash) then Exit; Result := Uppercase(Hash); S := IntToStr(Key); P := 0; for I := 1 to Length(Hash) do begin Inc(P); if P = Length(S) + 1 then P := 1; for J := 1 to StrToInt(S[P]) do Result[I] := hxinc(Result[I]); end; end; function HashUncrypt(const Hash: String; Key: Integer): String; Var I, J: Integer; S: ShortString; P: Integer; begin { Décryptage ... } Result := ''; if not IsHash(Hash) then Exit; Result := Uppercase(Hash); S := IntToStr(Key); P := 0; for I := 1 to Length(Hash) do begin Inc(P); if P = Length(S) + 1 then P := 1; for J := 1 to StrToInt(S[P]) do Result[I] := hxdec(Result[I]); end; end; function IsHash(const Hash: String): Boolean; Var I: Integer; begin { Vérification de la validité de la chaîne comme hash. } Result := False; if Length(Hash) <> 32 then Exit; { Si la taille est différente de 32, c'est déjà mort ... } { Si l'on rencontre un seul caractère qui ne soit pas dans les règles, on s'en va ... } for I := 1 to 32 do if not (Hash[I] in ['0'..'9', 'A'..'F', 'a'..'f']) then Exit; { Si la chaine a passé tous les tests, c'est bon ! } Result := True; end; end.
{$S-,R-,V-,I-,B-,F+,A-} unit ANSiDrv; interface uses opcrt,dos; type ClearScreenProc = procedure; SoundBellProc = procedure; const {Prevent remote from changing our video mode} InhibitModeChange : Boolean = False; UseVT100Mode : Boolean = False; {!!.02} MaskBlinkOnInverse : Boolean = True; {!!.02} procedure WriteCharAnsi(C : Char); {-Writes C (and handles ANSI escape sequences)} procedure WriteStringAnsi(S : String); {-Writes S (and handles ANSI escape sequences)} procedure SetClearScreenProc(CSP : ClearScreenProc); {-Sets a ClearScreen procedure to be called on FormFeed characters} procedure SetSoundBellProc(SBP : SoundBellProc); {-Sets a SoundBell procedure to be called on Bell characters} implementation type {Token types} ParserType = (GotNone, GotEscape, GotBracket, GotSemiColon, GotParm, GotCommand); const {Special parser characters} CR = #13; Escape = #27; LeftBracket = #91; Semicolon = #59; FormFeed = #12; BellChar = #07; EqualSign = #61; QuestionMark = #63; {!!.02} {For sizing parser} MaxQueueChars = 10; MaxParms = 5; {For sizing the screen} AnsiWidth : Word = 80; AnsiHeight : Word = 24; {For saving TextAttr states} Inverse : Boolean = False; Intense : Boolean = False; {For saving and restoring the cursor state} SaveX : Byte = 1; SaveY : Byte = 1; var {For saving invalid escape sequences} SaveCharQueue : array[1..MaxQueueChars] of Char; QTail : Byte; {For collecting and converting parameters} Parms : array[1..MaxParms] of String[5]; ParmInt : array[1..MaxParms] of Integer; ParmDefault : array[1..MaxParms] of Boolean; ParmIndex : Byte; {Current token} ParserState : ParserType; {User hooks} ClearScreen : ClearScreenProc; SoundBell : SoundBellProc; procedure WriteStringAnsi(S : String); var I : Byte; begin for I := 1 to Length(S) do WriteCharAnsi(S[I]); end; procedure InitParser; {-Initialize parser for next ansi sequence} var I : Byte; begin QTail := 0; ParmIndex := 1; for I := 1 to MaxParms do begin Parms[I] := ''; ParmDefault[I] := False; end; ParserState := GotNone; end; procedure PushChar(C : Char); {-Push C into the saved char queue} begin if QTail < MaxQueueChars then begin Inc(QTail); SaveCharQueue[QTail] := C; end; end; function HeadChar(var C : Char) : Boolean; {-Returns the first character on the saved stack and moves the rest down} begin if QTail > 0 then begin C := SaveCharQueue[1]; HeadChar := True; Dec(QTail); Move(SaveCharQueue[2], SaveCharQueue[1], QTail); end else HeadChar := False; end; procedure BuildParm(C : Char); {-Gets the next character of the current parameter} begin Parms[ParmIndex] := Parms[ParmIndex] + C; end; procedure ConvertParms(C : Char); {!!.02} {-Convert the parms into integers} var I, Code : Integer; begin for I := 1 to MaxParms do begin Val(Parms[I], ParmInt[I], Code); if Code <> 0 then begin ParmInt[I] := 1; ParmDefault[I] := True; end; end; if ParmDefault[1] and (C in ['J', 'K']) then {!!.02} if UseVT100Mode then {!!.02} ParmInt[1] := 0 {!!.02} else {!!.02} ParmInt[1] := 2; {!!.02} if (ParmInt[1] = 0) and (C in ['A','B','C','D']) then {!!.03} ParmInt[1] := 1; {!!.03} end; procedure ClearPart(X1, Y1, X2, Y2 : Integer); {-Clear from X1, Y1 to X2, Y2} var Row, Col : Integer; SaveX, SaveY : Word; procedure ClearRow(X1, X2 : Integer); var I : Integer; begin GotoXY(X1, WhereY); if X2 = AnsiWidth then ClrEol else for I := X1 to X2 do Write(' '); end; begin {Save cursor position} SaveX := WhereX; SaveY := WhereY; GotoXY(X1, Y1); if Y1 = Y2 then ClearRow(X1, X2) else begin ClearRow(X1, AnsiWidth); if Y1+1 <= Y2-1 then for Row := Y1+1 to Y2-1 do begin GotoXY(1, Row); ClearRow(1, AnsiWidth); end; GotoXY(1, Y2); ClearRow(1, X2); end; GotoXY(SaveX, SaveY); end; procedure GotoXYCheck(X, Y : Integer); {-GotoXY that checks against negative numbers} begin if X < 1 then X := 1; if Y < 1 then Y := 1; GotoXY(X, Y); end; procedure ReportCursorPosition; {!!.02} {-Output CPR sequence with cursor position (no error checking)} const AnsiStart = #27'['; var S1, S2 : String[8]; I : Byte; begin {Make an output string like so: <esc>[<wherex>;<wherey>R} Str(WhereX, S1); Str(WhereY, S2); S1 := AnsiStart + S1 + ';' + S2 + 'R'; end; procedure ProcessCommand(C : Char); {-Process the current command} var x,I, TextFg, TextBk : Byte; begin {Convert parameter strings to integers (and assign defaults)} ConvertParms(C); {Act on the accumulated parameters} case C of 'f' : Begin gotoxyCheck(parmint[2], parmint[1]); {HVP - horizontal and vertical position} End; 'H' : {CUP - cursor position} begin GotoXYcheck(ParmInt[2], ParmInt[1]); end; 'A' : {CUU - cursor up} GotoXYCheck(WhereX, WhereY - ParmInt[1]); 'B' : {CUD - cursor down} GotoXYCheck(WhereX, WhereY + ParmInt[1]); 'C' : {CUF - cursor forward} GotoXYCheck(WhereX + ParmInt[1], WhereY); 'D' : {CUB - cursor back} GotoXYCheck(WhereX - ParmInt[1], WhereY); 'J' : {ED - erase display} case ParmInt[1] of 0 : ClearPart(WhereX, WhereY, AnsiWidth, AnsiHeight); 1 : ClearPart(1, 1, WhereX, WhereY); 2 : For X:=1 to 25 do Begin GotoXy(1,X); ClrEol; GotoXy(1,1) End; end; 'K' : {EL - erase in line} begin if ParmDefault[1] then ParmInt[1] := 0; case ParmInt[1] of 0 : ClrEol; 1 : ClearPart(1, WhereY, WhereX, WhereY); 2 : ClearPart(1, WhereY, AnsiWidth, WhereY); end; end; 'l', 'h' : {SM - set mode (supports text modes only)} if not InhibitModeChange then begin case ParmInt[1] of 0 : TextMode(BW40); 1 : TextMode(CO40); 2 : TextMode(BW80); 3 : TextMode(CO80); 4 : TextMode(c80+font8x8); end; case ParmInt[1] of 0,1 : AnsiWidth := 40; 2,3 : AnsiWidth := 80; end; end; 'm' : {SGR - set graphics rendition (set background color)} begin for I := 1 to ParmIndex do begin if Inverse then {Restore inverted TextAttr before continuing} TextAttr := (TextAttr shl 4) or (TextAttr shr 4); {Separate out the forground and background bits} TextFg := TextAttr and $0F; TextBk := TextAttr and $F0; {Process the color command} case ParmInt[I] of 0 : begin TextAttr := $07; {White on black} Inverse := False; Intense := False; end; 1 : Intense := True; {Set intense bit later} 4 : Intense := True; {Subst intense for underline} 5 : TextAttr := TextAttr or $80; {Set blinking on} 7 : Inverse := True; {Invert TextAttr later} 8 : TextAttr := $00; {Invisible} 27 : Inverse := False; {Stop inverting TextAttr} 30 : TextAttr := TextBk or $00; {Black foreground} 31 : TextAttr := TextBk or $04; {Red foreground} 32 : TextAttr := TextBk or $02; {Green foreground} 33 : TextAttr := TextBk or $06; {Yellow forground} 34 : TextAttr := TextBk or $01; {Blue foreground} 35 : TextAttr := TextBk or $05; {Magenta foreground} 36 : TextAttr := TextBk or $03; {Cyan foreground} 37 : TextAttr := TextBk or $07; {White foreground} 40 : TextAttr := TextFg; {Black background} 41 : TextAttr := TextFg or $40; {Red background} 42 : TextAttr := TextFg or $20; {Green background} 43 : TextAttr := TextFg or $60; {Yellow background} 44 : TextAttr := TextFg or $10; {Blue background} 45 : TextAttr := TextFg or $50; {Magenta background} 46 : TextAttr := TextFg or $30; {Cyan background} 47 : TextAttr := TextFg or $70; {White background} end; {Fix up TextAttr for inverse and intense} if Inverse then begin {!!.02} TextAttr := (TextAttr shl 4) or (TextAttr shr 4); if MaskBlinkOnInverse then {!!.02} TextAttr := TextAttr and $7F; {!!.02} end; {!!.02} if Intense then TextAttr := TextAttr or $08; end; end; 'n' : {DSR - device status report} {!!.02} if ParmInt[1] = 6 then {!!.02} ReportCursorPosition; {!!.02} 's' : {SCP - save cursor position} begin SaveX := WhereX; SaveY := WhereY; end; 'u' : {RCP - restore cursor position} GotoXY(SaveX, SaveY); else {Invalid esc sequence - display all the characters accumulated so far} While HeadChar(C) do Case C of FormFeed : ClearScreen; BellChar : SoundBell; Else Write(C); End; end; end; procedure WriteCharAnsi(C : Char); label ErrorExit; begin PushChar(C); case ParserState of GotNone : {Not in an ANSI sequence} Begin if C = Escape then ParserState := GotEscape else Case C of FormFeed : ClearScreen; BellChar : SoundBell; Else Write(C); End; QTail := 0; End; GotEscape : {Last character was escape -- need [} if C = LeftBracket then ParserState := GotBracket else goto ErrorExit; GotParm, GotBracket, GotSemicolon : {Need parameter char, semicolon, equalsign or command} if (C >= #48) and (C <= #57) then begin {It's a number, go add it to the current parameter} BuildParm(C); ParserState := GotParm; end else if (C = EqualSign) or (C = QuestionMark) then {!!.02} {just ignore it} else if C = Semicolon then {It's a semicolon, prepare for next parameter} if ParserState = GotSemicolon then goto ErrorExit else begin ParserState := GotSemicolon; Inc(ParmIndex); if ParmIndex > MaxParms then goto ErrorExit; end else begin {Must be a command, go process it} ProcessCommand(C); InitParser; end; end; Exit; ErrorExit: {Invalid escape sequence -- display all the characters accumulated so far} while HeadChar(C) do Write(C); InitParser; end; procedure DefClearScreen; begin window(1,1,80,24); { Depends on Stats Bar type } ClrScr; end; procedure DefSoundBell; begin Sound(220); Delay(200); NoSound; end; procedure SetClearScreenProc(CSP : ClearScreenProc); {-Sets a ClearScreen procedure to be called on FormFeed characters} begin ClearScreen := CSP; end; procedure SetSoundBellProc(SBP : SoundBellProc); {-Sets a SoundBell procedure to be called on Bell characters} begin SoundBell := SBP; end; begin InitParser; SoundBell := DefSoundBell; ClearScreen := DefClearScreen; end.
unit uMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Buttons, BZLogger; type { TMainForm } TMainForm = class(TForm) btnLog : TButton; btnLogNotice : TButton; btnLogStatus : TButton; btnLogWarn : TButton; btnLogError : TButton; btnLogException : TButton; btnViewLog : TButton; btnLogHint : TButton; btnHalt : TButton; btnShowLogView : TButton; btnHideLogView : TButton; procedure btnLogClick(Sender : TObject); procedure btnLogNoticeClick(Sender : TObject); procedure btnLogStatusClick(Sender : TObject); procedure btnLogWarnClick(Sender : TObject); procedure btnLogErrorClick(Sender : TObject); procedure tnLogHint(Sender : TObject); procedure btnLogHintClick(Sender : TObject); procedure btnViewLogClick(Sender : TObject); procedure FormShow(Sender : TObject); procedure FormCloseQuery(Sender : TObject; var CanClose : boolean); procedure btnHaltClick(Sender : TObject); procedure btnShowLogViewClick(Sender : TObject); procedure btnHideLogViewClick(Sender : TObject); private procedure GetLog( aLevel: TBZLogLevel; aTimeStamp : TDateTime; const aMessage, ParseMsg : String); protected FLogStr : String; FConsoleLoggerWriter : TBZConsoleLoggerWriter; procedure LogToMemo; public end; var MainForm : TMainForm; implementation {$R *.lfm} //uses // uViewLoggerMainForm; { TMainForm } procedure TMainForm.btnLogClick(Sender : TObject); begin GlobalLogger.Log('Texte de log simple'); end; procedure TMainForm.btnLogNoticeClick(Sender : TObject); begin GlobalLogger.LogNotice('Texte de log de type Notification'); end; procedure TMainForm.btnLogStatusClick(Sender : TObject); begin GlobalLogger.LogStatus('Texte de log de type Status'); end; procedure TMainForm.btnLogWarnClick(Sender : TObject); begin GlobalLogger.LogWarning('Texte de log de type Warning'); end; procedure TMainForm.btnLogErrorClick(Sender : TObject); begin GlobalLogger.LogError('Texte de log de type Error'); end; procedure TMainForm.tnLogHint(Sender : TObject); begin GlobalLogger.LogException('Texte de log de type Exception'); end; procedure TMainForm.btnLogHintClick(Sender : TObject); begin GlobalLogger.LogHint('Texte de log de type Conseil'); end; procedure TMainForm.btnViewLogClick(Sender : TObject); begin //ViewLoggerMainForm.Show; end; procedure TMainForm.FormShow(Sender : TObject); begin FConsoleLoggerWriter := TBZConsoleLoggerWriter.Create(GlobalLogger); FConsoleLoggerWriter.Enabled := True; GlobalLogger.LogWriters.AddWriter(FConsoleLoggerWriter); GlobalLogger.LogWriters.Items[1].Enabled := true; GlobalLogger.HandleApplicationException := True; //GlobalLogger.OnCallBack := @GetLog; //ViewLoggerMainForm.Top := Self.Top; //ViewLoggerMainForm.Left := Self.Left + Self.Width + 4; //ViewLoggerMainForm.Show; end; procedure TMainForm.FormCloseQuery(Sender : TObject; var CanClose : boolean); begin GlobalLogger.OnCallBack := nil; end; procedure TMainForm.btnHaltClick(Sender : TObject); begin raise Exception.Create('Une Exception à été levée - Fin de l''application'); end; procedure TMainForm.btnShowLogViewClick(Sender : TObject); begin GlobalLogger.LogViewEnabled:= True; GlobalLogger.ShowLogView; end; procedure TMainForm.btnHideLogViewClick(Sender : TObject); begin GlobalLogger.HideLogView; //GlobalLogger.LogViewEnabled:= False; end; procedure TMainForm.GetLog(aLevel : TBZLogLevel; aTimeStamp : TDateTime; const aMessage, ParseMsg : String); begin FLogStr := ParseMsg; //TThread.Synchronize(GlobalLogger, @LogToMemo); // La synchronisation n'est pas indispensable ici LogToMemo; end; procedure TMainForm.LogToMemo; begin //Close; //ViewLoggerMainForm.MemoLog.Append(FLogStr); end; end.
unit RT_Database; interface uses Classes, SysUtils, Contnrs; type TTaxiList = class; TStreet = class; IObserver = interface ['{7A891E6A-BB65-483F-9272-35BFEE32F578}'] procedure Notify(Sender: TObject; Subject: TObject; Params: array of const); end; IDisableable = interface ['{A525D5D2-E07C-4A93-B9DD-25F15CB8D0E7}'] function GetIsEnabled: Boolean; procedure Enable; procedure Disable; property IsEnabled: Boolean read GetIsEnabled; end; TObserverList = class (TInterfaceList) private function GetItem(Index: Integer): IObserver; public procedure Register(Observer: IObserver); procedure Unregister(Observer: IObserver); procedure Notify(Sender: TObject; Subject: TObject; Params: array of const); property Items[Index: Integer]: IObserver read GetItem; default; end; TTaxiStop = class (TObject) private FObservers: TObserverList; FId: Integer; FName: String; FTaxis: TTaxiList; procedure SetName(Value: String); public constructor Create; destructor Destroy; override; property Id: Integer read FId write FId; property Name: String read FName write SetName; property Taxis: TTaxiList read FTaxis write FTaxis; property Observers: TObserverList read FObservers; end; TTaxiStopList = class (TObjectList) private FObservers: TObserverList; FStreet: TStreet; function GetItem(Index: Integer): TTaxiStop; function GetById(Id: Integer): TTaxiStop; function GetByName(Name: String): TTaxiStop; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create(AOwnsObjects: Boolean); destructor Destroy; override; property Street: TStreet read FStreet write FStreet; property Items[Index: Integer]: TTaxiStop read GetItem; default; property ById[Id: Integer]: TTaxiStop read GetById; property ByName[Name: String]: TTaxiStop read GetByName; property Observers: TObserverList read FObservers; end; TStreet = class (TObject) private FObservers: TObserverList; FId: Integer; FName: String; FStart: String; FStop: String; FTaxiStops: TTaxiStopList; procedure SetName(Value: String); procedure SetStart(Value: String); procedure SetStop(Value: String); public constructor Create; destructor Destroy; override; property Id: Integer read FId write FId; property Name: String read FName write SetName; property Start: String read FStart write SetStart; property Stop: String read FStop write SetStop; property TaxiStops: TTaxiStopList read FTaxiStops; property Observers: TObserverList read FObservers; end; TStreetList = class (TObjectList) private FObservers: TObserverList; function GetItem(Index: Integer): TStreet; function GetById(Id: Integer): TStreet; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create(AOwnsObjects: Boolean); destructor Destroy; override; property Items[Index: Integer]: TStreet read GetItem; default; property ById[Id: Integer]: TStreet read GetById; property Observers: TObserverList read FObservers; end; TTaxi = class (TObject) private FObservers: TObserverList; FId: Integer; FName: String; FNumber: String; FCallSign: String; procedure SetName(Value: String); procedure SetNumber(Value: String); procedure SetCallSign(Value: String); public constructor Create; destructor Destroy; override; property Id: Integer read FId write FId; property Name: String read FName write SetName; property Number: String read FNumber write SetNumber; property CallSign: String read FCallSign write SetCallSign; property Observers: TObserverList read FObservers; end; TTaxiList = class (TObjectList) private FObservers: TObserverList; FTaxiStop: TTaxiStop; function GetItem(Index: Integer): TTaxi; function GetByCallSign(CallSign: String): TTaxi; function GetById(Id: Integer): TTaxi; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create(AOwnsObjects: Boolean); destructor Destroy; override; property TaxiStop: TTaxiStop read FTaxiStop write FTaxiStop; property Items[Index: Integer]: TTaxi read GetItem; default; property ByCallSign[CallSign: String]: TTaxi read GetByCallSign; property ById[Id: Integer]: TTaxi read GetById; property Observers: TObserverList read FObservers; end; TFare = class (TObject) private FObservers: TObserverList; FId: Integer; FStreet: String; FStreetId: Integer; FAddress1: String; FAddress2: String; FTaxiId: Integer; FReceived: TDateTime; FDispatched: TDateTime; FDelay: TDateTime; FDelayed: Boolean; FInformation: Boolean; FSent: Boolean; procedure SetStreet(Value: String); procedure SetStreetId(Value: Integer); procedure SetAddress1(Value: String); procedure SetAddress2(Value: String); procedure SetTaxiId(Value: Integer); procedure SetReceived(Value: TDateTime); procedure SetDispatched(Value: TDateTime); procedure SetDelay(Value: TDateTime); procedure SetDelayed(Value: Boolean); procedure SetInformation(Value: Boolean); procedure SetSent(Value: Boolean); public constructor Create; destructor Destroy; override; property Id: Integer read FId write FId; property Street: String read FStreet write SetStreet; property StreetId: Integer read FStreetId write SetStreetId; property Address1: String read FAddress1 write SetAddress1; property Address2: String read FAddress2 write SetAddress2; property TaxiId: Integer read FTaxiId write SetTaxiId; property Received: TDateTime read FReceived write SetReceived; property Dispatched: TDateTime read FDispatched write SetDispatched; property Delay: TDateTime read FDelay write SetDelay; property Delayed: Boolean read FDelayed write SetDelayed; property Information: Boolean read FInformation write SetInformation; property Sent: Boolean read FSent write SetSent; property Observers: TObserverList read FObservers; end; TFareList = class (TObjectList) private FObservers: TObserverList; function GetItem(Index: Integer): TFare; function GetById(Id: Integer): TFare; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create(AOwnsObjects: Boolean); destructor Destroy; override; property Items[Index: Integer]: TFare read GetItem; default; property ById[Id: Integer]: TFare read GetById; property Observers: TObserverList read FObservers; end; TClient = class (TObject) private FObservers: TObserverList; FId: Integer; FName: String; FStreet: String; FAddress1: String; FAddress2: String; FTelephone: String; procedure SetId(Value: Integer); procedure SetName(Value: String); procedure SetStreet(Value: String); procedure SetAddress1(Value: String); procedure SetAddress2(Value: String); procedure SetTelephone(Value: String); public constructor Create; destructor Destroy; override; property Id: Integer read FId write SetId; property Name: String read FName write SetName; property Street: String read FStreet write SetStreet; property Address1: String read FAddress1 write SetAddress1; property Address2: String read FAddress2 write SetAddress2; property Telephone: String read FTelephone write SetTelephone; property Observers: TObserverList read FObservers; end; TClientList = class (TObjectList) private FObservers: TObserverList; function GetItem(Index: Integer): TClient; function GetById(Id: Integer): TClient; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create(AOwnsObjects: Boolean); destructor Destroy; override; property Items[Index: Integer]: TClient read GetItem; default; property ById[Id: Integer]: TClient read GetById; property Observers: TObserverList read FObservers; end; TDatabase = class (TObject) private FStreets: TStreetList; FTaxiStops: TTaxiStopList; FTaxis: TTaxiList; FFares: TFareList; FClients: TClientList; class procedure Initialize; class procedure Shutdown; public class function Instance: TDatabase; constructor Create; destructor Destroy; override; property Streets: TStreetList read FStreets; property TaxiStops: TTaxiStopList read FTaxiStops; property Taxis: TTaxiList read FTaxis; property Fares: TFareList read FFares; property Clients: TClientList read FClients; end; implementation { TObserverList } { Private declarations } function TObserverList.GetItem(Index: Integer): IObserver; begin Result := Get(Index) as IObserver; end; { Public declarations } procedure TObserverList.Register(Observer: IObserver); begin Assert(IndexOf(Observer) = -1, 'Error: this observer has already been registered'); Add(Observer); end; procedure TObserverList.Unregister(Observer: IObserver); begin Assert(IndexOf(Observer) <> -1, 'Error: this observer has not been registered'); Remove(Observer); end; procedure TObserverList.Notify(Sender: TObject; Subject: TObject; Params: array of const); var I: Integer; PerformNotification: Boolean; begin for I := 0 to Count - 1 do if Assigned(Items[I]) then begin if Supports(Items[I], IDisableable) then PerformNotification := (Items[I] as IDisableable).IsEnabled else PerformNotification := True; if PerformNotification then Items[I].Notify(Sender, Subject, Params); end; end; { TTaxiStop } { Private declarations } procedure TTaxiStop.SetName(Value: String); begin if Value <> FName then begin FName := Value; Observers.Notify(Self, Self, ['Name', Name]); end; end; { Public declarations } constructor TTaxiStop.Create; begin inherited Create; FObservers := TObserverList.Create; FTaxis := TTaxiList.Create(False); Taxis.TaxiStop := Self; end; destructor TTaxiStop.Destroy; begin Observers.Clear; FreeAndNil(FTaxis); FreeAndNil(FObservers); inherited Destroy; end; { TTaxiStopList } { Private declarations } function TTaxiStopList.GetItem(Index: Integer): TTaxiStop; begin Result := TObject(Get(Index)) as TTaxiStop; end; function TTaxiStopList.GetById(Id: Integer): TTaxiStop; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Id = Items[I].Id then begin Result := Items[I]; Break; end; end; function TTaxiStopList.GetByName(Name: String): TTaxiStop; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if AnsiSameText(Name, Items[I].Name) then begin Result := Items[I]; Break; end; end; { Protected declarations } procedure TTaxiStopList.Notify(Ptr: Pointer; Action: TListNotification); begin Observers.Notify(Self, Ptr, [Integer(Action)]); inherited Notify(Ptr, Action); end; { Public declarations } constructor TTaxiStopList.Create(AOwnsObjects: Boolean); begin inherited Create(AOwnsObjects); FObservers := TObserverList.Create; end; destructor TTaxiStopList.Destroy; begin Observers.Clear; Clear; FreeAndNil(FObservers); inherited Destroy; end; { TStreet } { Private declarations } procedure TStreet.SetName(Value: String); begin if FName <> Value then begin FName := Value; Observers.Notify(Self, Self, ['Name', Name]); end; end; procedure TStreet.SetStart(Value: String); begin if FStart <> Value then begin FStart := Value; Observers.Notify(Self, Self, ['Start', Start]); end; end; procedure TStreet.SetStop(Value: String); begin if FStop <> Value then begin FStop := Value; Observers.Notify(Self, Self, ['Stop', Stop]); end; end; { Public declarations } constructor TStreet.Create; begin inherited Create; FTaxiStops := TTaxiStopList.Create(False); TaxiStops.Street := Self; FObservers := TObserverList.Create; end; destructor TStreet.Destroy; begin FreeAndNil(FTaxiStops); FreeAndNil(FObservers); inherited Destroy; end; { TStreetList } { Private declarations } function TStreetList.GetItem(Index: Integer): TStreet; begin Result := TObject(Get(Index)) as TStreet; end; function TStreetList.GetById(Id: Integer): TStreet; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Items[I].Id = Id then begin Result := Items[I]; Break; end; end; { Protected declarations } procedure TStreetList.Notify(Ptr: Pointer; Action: TListNotification); begin Observers.Notify(Self, Ptr, [Integer(Action)]); inherited Notify(Ptr, Action); end; { Public declarations } constructor TStreetList.Create(AOwnsObjects: Boolean); begin inherited Create(AOwnsObjects); FObservers := TObserverList.Create; end; destructor TStreetList.Destroy; begin Observers.Clear; Clear; FreeAndNil(FObservers); inherited Destroy; end; { TTaxi } { Private declarations } procedure TTaxi.SetName(Value: String); begin if FName <> Value then begin FName := Value; Observers.Notify(Self, Self, ['Name', Name]); end; end; procedure TTaxi.SetNumber(Value: String); begin if FNumber <> Value then begin FNumber := Value; Observers.Notify(Self, Self, ['Number', Number]); end; end; procedure TTaxi.SetCallSign(Value: String); begin if FCallSign <> Value then begin FCallSign := Value; Observers.Notify(Self, Self, ['CallSign', CallSign]); end; end; { Public declarations } constructor TTaxi.Create; begin inherited Create; FObservers := TObserverList.Create; end; destructor TTaxi.Destroy; begin FreeAndNil(FObservers); inherited Destroy; end; { TTaxiList } { Private declarations } function TTaxiList.GetItem(Index: Integer): TTaxi; begin Result := TObject(Get(Index)) as TTaxi; end; function TTaxiList.GetByCallSign(CallSign: String): TTaxi; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Items[I].CallSign = CallSign then begin Result := Items[I]; Break; end; end; function TTaxiList.GetById(Id: Integer): TTaxi; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Items[I].Id = Id then begin Result := Items[I]; Break; end; end; { Protected declarations } procedure TTaxiList.Notify(Ptr: Pointer; Action: TListNotification); begin Observers.Notify(Self, Ptr, [Integer(Action)]); inherited Notify(Ptr, Action); end; { Public declarations } constructor TTaxiList.Create(AOwnsObjects: Boolean); begin inherited Create(AOwnsObjects); FObservers := TObserverList.Create; end; destructor TTaxiList.Destroy; begin Observers.Clear; Clear; FreeAndNil(FObservers); inherited Destroy; end; { TFare } { Private declarations } procedure TFare.SetStreet(Value: String); begin if FStreet <> Value then begin FStreet := Value; Observers.Notify(Self, Self, ['Street', Street]); end; end; procedure TFare.SetStreetId(Value: Integer); begin if FStreetId <> Value then begin FStreetId := Value; Observers.Notify(Self, Self, ['StreetId', StreetId]); end; end; procedure TFare.SetAddress1(Value: String); begin if FAddress1 <> Value then begin FAddress1 := Value; Observers.Notify(Self, Self, ['Address1', Address1]); end; end; procedure TFare.SetAddress2(Value: String); begin if FAddress2 <> Value then begin FAddress2 := Value; Observers.Notify(Self, Self, ['Address2', Address2]); end; end; procedure TFare.SetTaxiId(Value: Integer); begin if FTaxiId <> Value then begin FTaxiId := Value; Observers.Notify(Self, Self, ['TaxiId', TaxiId]); end; end; procedure TFare.SetReceived(Value: TDateTime); begin if FReceived <> Value then begin FReceived := Value; Observers.Notify(Self, Self, ['Received', Received]); end; end; procedure TFare.SetDispatched(Value: TDateTime); begin if FDispatched <> Value then begin FDispatched := Value; Observers.Notify(Self, Self, ['Dispatched', Dispatched]); end; end; procedure TFare.SetDelay(Value: TDateTime); begin if FDelay <> Value then begin FDelay := Value; Observers.Notify(Self, Self, ['Delay', Delay]); end; end; procedure TFare.SetDelayed(Value: Boolean); begin if FDelayed <> Value then begin FDelayed := Value; Observers.Notify(Self, Self, ['Delayed', Delayed]); end; end; procedure TFare.SetInformation(Value: Boolean); begin if FInformation <> Value then begin FInformation := Value; Observers.Notify(Self, Self, ['Information', Information]); end; end; procedure TFare.SetSent(Value: Boolean); begin if FSent <> Value then begin FSent := Value; Observers.Notify(Self, Self, ['Sent', Sent]); end; end; { Public declarations } constructor TFare.Create; begin inherited Create; FObservers := TObserverList.Create; end; destructor TFare.Destroy; begin FreeAndNil(FObservers); inherited Destroy; end; { TFareList } { Private declarations } function TFareList.GetItem(Index: Integer): TFare; begin Result := TObject(Get(Index)) as TFare; end; function TFareList.GetById(Id: Integer): TFare; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Items[I].Id = Id then begin Result := Items[I]; Break; end; end; { Protected declarations } procedure TFareList.Notify(Ptr: Pointer; Action: TListNotification); begin Observers.Notify(Self, Ptr, [Integer(Action)]); inherited Notify(Ptr, Action); end; { Public declarations } constructor TFareList.Create(AOwnsObjects: Boolean); begin inherited Create(AOwnsObjects); FObservers := TObserverList.Create; end; destructor TFareList.Destroy; begin Observers.Clear; Clear; FreeAndNil(FObservers); inherited Destroy; end; { TClient } { Private declarations } procedure TClient.SetId(Value: Integer); begin if Value <> FId then begin FId := Value; Observers.Notify(Self, Self, ['Id', Id]); end; end; procedure TClient.SetName(Value: String); begin if Value <> FName then begin FName := Value; Observers.Notify(Self, Self, ['Name', Name]); end; end; procedure TClient.SetStreet(Value: String); begin if Value <> FStreet then begin FStreet := Value; Observers.Notify(Self, Self, ['Street', Street]); end; end; procedure TClient.SetAddress1(Value: String); begin if Value <> FAddress1 then begin FAddress1 := Value; Observers.Notify(Self, Self, ['Address1', Address1]); end; end; procedure TClient.SetAddress2(Value: String); begin if Value <> FAddress2 then begin FAddress2 := Value; Observers.Notify(Self, Self, ['Address2', Address2]); end; end; procedure TClient.SetTelephone(Value: String); begin if Value <> FTelephone then begin FTelephone := Value; Observers.Notify(Self, Self, ['Telephone', Telephone]); end; end; { Public declarations } constructor TClient.Create; begin inherited Create; FObservers := TObserverList.Create; end; destructor TClient.Destroy; begin FreeAndNil(FObservers); inherited Destroy; end; { TClientList } { Private declarations } function TClientList.GetItem(Index: Integer): TClient; begin Result := TObject(Get(Index)) as TClient; end; function TClientList.GetById(Id: Integer): TClient; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Items[I].Id = Id then begin Result := Items[I]; Break; end; end; { Protected declarations } procedure TClientList.Notify(Ptr: Pointer; Action: TListNotification); begin Observers.Notify(Self, Ptr, [Integer(Action)]); inherited Notify(Ptr, Action); end; { Public declarations } constructor TClientList.Create(AOwnsObjects: Boolean); begin inherited Create(AOwnsObjects); FObservers := TObserverList.Create; end; destructor TClientList.Destroy; begin Observers.Clear; Clear; FreeAndNil(FObservers); inherited Destroy; end; { TDatabase } var _Instance: TDatabase = nil; { Private declarations } class procedure TDatabase.Initialize; begin _Instance := TDatabase.Create; end; class procedure TDatabase.Shutdown; begin FreeAndNil(_Instance); end; { Public declarations } class function TDatabase.Instance: TDatabase; begin Result := _Instance; end; constructor TDatabase.Create; begin inherited Create; FStreets := TStreetList.Create(True); FTaxiStops := TTaxiStopList.Create(True); FTaxis := TTaxiList.Create(True); FFares := TFareList.Create(True); FClients := TClientList.Create(True); end; destructor TDatabase.Destroy; begin FreeAndNil(FClients); FreeAndNil(FFares); FreeAndNil(FTaxis); FreeAndNil(FTaxiStops); FreeAndNil(FStreets); inherited Destroy; end; initialization TDatabase.Initialize; finalization TDatabase.Shutdown; end.
unit matmatrices; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, operadores; type TMatriz1 = class public matrizA:matriz; matrizB:matriz; matrizC:cadena; valor:real; function CMtr(x,y:Integer): matriz; procedure MostrarMatriz(M: matriz;x,y:Integer); function Suma(A,B : matriz; m,n:Integer):cadena; function Resta(A,B: matriz; m,n:Integer) : cadena; function Multiplicacion(A,B:Matriz;m,n,c,d:Integer): cadena; function Division(A,B:Matriz;m,n,c,d:Integer): cadena; function Invierte(Dim: Integer;Sist,Inv:matriz) : cadena; procedure MetodoGauss(); function Potencia(A,B:Matriz;m,n,e:Integer): cadena; function MulEsc(A:matriz;esc:real;m,n:Integer): cadena; function Transpuesta(var A: matriz;m,n:Integer): cadena; function Traza(A: matriz;n,m:Integer): real; function Determinante(A:matriz;filas:Integer):real; function Execute(opcion:string;m:Integer;n:Integer;c,d:Integer;var Text:string;var Rows:Integer;var Cols:Integer;variable:real):cadena; function Invierte2(Dim: Integer;Sist,Inv:matriz) : matriz; function Multiplicacion2(A,B:Matriz;m,n,c,d:Integer): matriz; constructor create(); overload; destructor Destroy(); private end; operator *(a,b:matriz):matriz; operator +(a,b:matriz):matriz; operator -(a,b:matriz):matriz; operator /(a,b:matriz):matriz; implementation constructor TMatriz1.create(); begin end; destructor TMatriz1.Destroy(); begin end; function TMatriz1.Execute(opcion:string;m :Integer;n:Integer;c,d:Integer;var Text:string;var Rows:Integer;var Cols:Integer;variable:real):cadena; var R:cadena; val:string; valI:Integer; begin opcion:=LowerCase(opcion); Text:=''; val:=''; valI:=0; case opcion of 'sumar': begin if((m=c) and (n=d)) then begin Rows:=m;Cols:=d;Execute:=Suma(matrizA,matrizB,m,n); end else begin Rows:=0;Cols:=0;Text:='No se puede sumar las dimenciones son diferentes !';Execute:=R; end; end; 'restar': begin if((m=c) and (n=d)) then begin Rows:=m;Cols:=d;Execute:=Resta(matrizA,MatrizB,m,n); end else begin Rows:=0;Cols:=0;Text:='No de puede restar las dimenciones son diferentes !';Execute:=R; end; end; 'multiplicar': begin if(n=c) then begin Rows:=m;Cols:=d; Execute:=Multiplicacion(matrizA,matrizB,m,n,c,d);end else begin Rows:=0;Cols:=0;Text:='No se puede multiplicar, dimenciones no validas !';Execute:=R; end; end; 'dividir':begin if((n=c) and (d=c)) then begin Rows:=m;Cols:=d; Execute:=Division(matrizA,matrizB,m,n,c,d); end else begin Rows:=0;Cols:=0;Text:='No se pudo dividir, dimenciones no validad !'; Execute:=R;end; end; 'power':begin if(m=n) then begin val:=FloatToStr(variable); valI:=StrToInt(val); ShowMessage(IntToStr(valI)); if(valI=-2) then begin Rows:=m;Cols:=n;Execute:=Invierte(m,matrizA,matrizB); end else begin Rows:=m;Cols:=n;Execute:=Potencia(matrizA,matrizB,m,n,valI);end; end else begin Rows:=0;Cols:=0;Text:='Expreción no valida !';Execute:=R;end; end; 'transpuesta':begin if(m=n) then begin Rows:=m;Cols:=n;Execute:=Transpuesta(matrizA,m,n); end else begin Rows:=0;Cols:=0;Text:='No se pudo transponer, la matriz no es cuadrada !'; Execute:=R;end; end; 'inversa':begin if(m=n) then begin Rows:=m;Cols:=n;Execute:=Invierte(m,matrizA,matrizB); end else begin Rows:=0;Cols:=0;Text:='No se pudo invertir, la matriz no es cuadrada !'; Execute:=R;end; end; 'mulesc':begin Execute:=MulEsc(matrizA,variable+1,m,n); Rows:=m;Cols:=n; end; 'traza':begin if(m=n) then begin Rows:=0;Cols:=0;Text:= FloatToStr(Traza(matrizA,n,m));Execute:=R; end else begin Rows:=0;Cols:=0;Text:='La matriz no es cuadrada !'; Execute:=R;end; end; 'determinante':begin if(m=n) then begin Rows:=0;Cols:=0;Text:= FloatToStr(Determinante(matrizA,m));Execute:=R; end else begin Rows:=0;Cols:=0;Text:='La matriz no es cuadrada !'; Execute:=R;end; end; else begin Execute:=matrizC;end; end; end; procedure TMatriz1.MostrarMatriz(M:matriz;x,y:Integer); var i: Integer; j: Integer; begin for i:= 0 to x-1 do begin for j := 0 to y-1 do begin write(FloatToStr(M[i,j])+' '); end; writeLn(); end; end; function TMatriz1.CMtr(x,y:Integer): matriz; var i: Integer; j: Integer; mdata : real; M: matriz; begin for i:= 0 to x-1 do begin for j:=0 to y-1 do begin write('Ingrese los datos '); read(mdata); M[i,j] := mdata; end; end; Result := M; end; function TMatriz1.Suma(A,B : matriz; m,n:Integer):cadena; var i : Integer; j : Integer; C : cadena; begin for i:=0 to m-1 do begin for j:=0 to n-1 do begin C[i,j] := FloatToStr(A[i,j]+B[i,j]); end; end; Result := C; end; function TMatriz1.Resta(A,B: matriz; m,n:Integer) : cadena; var i : Integer; j : Integer; C : cadena; begin for i:=0 to m-1 do begin for j:=0 to n-1 do begin C[i,j] := FloatToStr(A[i,j]-B[i,j]); end; end; Result := C; end; function TMatriz1.Multiplicacion(A,B:Matriz;m,n,c,d:Integer): cadena; var i : Integer; j : Integer; k : Integer; CC : cadena; begin for i:=0 to m-1 do begin for j:=0 to c-1 do begin CC[i,j] :=FloatToStr(0); for k:=0 to n-1 do begin CC[i,j] := FloatToStr(StrToFloat(CC[i,j])+(A[i,k]*B[k,j])); end; end; end; Result := CC; end; function TMatriz1.Multiplicacion2(A,B:Matriz;m,n,c,d:Integer): matriz; var i : Integer; j : Integer; k : Integer; CC : matriz; begin for i:=0 to m-1 do begin for j:=0 to c-1 do begin CC[i,j] :=(0); for k:=0 to n-1 do begin CC[i,j] :=((CC[i,j])+(A[i,k]*B[k,j])); end; end; end; Result := CC; end; function TMatriz1.Potencia(A,B:Matriz;m,n,e:Integer): cadena; var i,j:Integer; CC:matriz; C:cadena; begin CC:=A; for i:=0 to e-1 do begin CC:=Multiplicacion2(A,CC,m,n,m,n); end; for i:=0 to m-1 do begin for j:=0 to n-1 do begin C[i,j]:=FloatToStr(CC[i,j]); end; end; Result:=C; end; function TMatriz1.MulEsc(A:matriz;esc:real;m,n:Integer): cadena; var i : Integer; j : Integer; C : cadena; begin for i:=0 to m-1 do begin for j:=0 to n-1 do begin C[i,j] := FloatToStr(A[i,j]*esc); end; end; Result := C; end; function TMatriz1.Transpuesta(var A: matriz;m,n:Integer): cadena; var i : Integer; j : Integer; i1 : Integer; j1 : Integer; C : cadena; begin j1 := 0; for i:=0 to m-1 do begin i1 := 0; for j:=0 to n-1 do begin C[j1,i1] := FloatToStr(A[j,i]); i1 := i1 + 1; end; j1 := j1+1; end; Result := C; end; function TMatriz1.Traza(A: matriz;n,m:Integer): real; var i : Integer; C : real; begin C := 0; for i:=0 to m-1 do begin C:=A[i,i]+C; end; Traza := C; end; function TMatriz1.Determinante(A:matriz;filas:Integer):real; var i : Integer; j : Integer; n : Integer; det : real; B : matriz; begin if filas = 2 then det := A[0,0] * A[1,1] - A[0,1]*A[1,0] else begin det := 0; for n:= 0 to filas-1 do begin for i:=1 to filas-1 do begin for j := 0 to n-1 do B[i-1,j] := A[i,j]; for j:=n+1 to filas-1 do B[i-1,j-1] := A[i,j]; end; if(n+2) mod 2 = 0 then i:= 1 else i := -1; det := det + i*A[0,n]*Determinante(B,filas-1); end; end; Result := det; end; procedure TMatriz1.MetodoGauss(); var M : matriz; aux : real; i,j,k,n : Integer; begin writeLn(' <<<Metodo de Gauss>>> '); write(' Matriz cuadrada de orden N= '); read(n); writeLn(' Digite los elementos de la matriz en la posicion '); for i := 1 to n do begin for j := 1 to n do begin write(' M=['+IntToStr(i)+','+IntToStr(j)+']= '); read(M[i,j]); end; write(' Termino idependiente de X'+IntToStr(i)+' '); read(M[i,n+1]); end; for i := 1 to n do begin if(M[i,i] <> 0) then begin aux := 1/M[i,i]; for j := 1 to n+1 do begin M[i,j] := aux*M[i,j]; end; for j := 1 to n do begin if (j <> i) then begin aux := -M[j,i]; for k := 1 to n+1 do begin M[j,k] := M[j,k] + aux*M[i,k]; end; end; end; end; end; writeLn(); writeLn('La matriz identidad es'); writeLn(); for i := 1 to n do begin for j := 1 to n do begin write(FloatToStr(M[i,j])+' '); end; writeLn(); end; writeLn('El valor de las incognitas es : '); for i := 1 to n do begin writeLn('\X'+IntToStr(i)+' = '+ FloatToStr(M[i,n+1])+LineEnding); end; read(); end; function TMatriz1.Invierte(Dim: Integer;Sist,Inv:matriz) : cadena; var NoCero,Col,C1,C2,A,i,j : Integer; Pivote,V1,V2 : real; R:cadena; begin if ( Determinante(Sist,Dim) <> 0) then begin for C1 := 0 to Dim-1 do for C2 := 0 to Dim-1 do begin if (C1 = C2) then begin Inv[C1,C2] := 1; end else Inv[C1,C2] := 0; end; for Col :=0 to Dim-1 do begin NoCero :=0; A := Col; while (NoCero = 0) do begin if ((Sist[A,Col]>0.0000001) or ((Sist[A,Col]<-0.0000001))) then begin NoCero := 1; end else A := A+1; end; Pivote := Sist[A,Col]; for C1 := 0 to Dim-1 do begin V1 := Sist[A,C1]; Sist[A,C1] := Sist[Col,C1]; Sist[Col,C1] := V1/Pivote; V2 := Inv[A,C1]; Inv[A,C1] := Inv[Col,C1]; Inv[Col,C1] := V2/Pivote; end; for C2 := Col+1 to Dim-1 do begin V1 := Sist[C2,Col]; for C1 := 0 to Dim-1 do begin Sist[C2,C1] := Sist[C2,C1] - V1*Sist[Col,C1]; Inv[C2,C1] := Inv[C2,C1]-V1*Inv[Col,C1]; end; end; end; for Col := Dim-1 downto 0 do for C1 := (Col-1) downto 0 do begin V1 := Sist[C1,Col]; for C2 := 0 to Dim-1 do begin Sist[C1,C2] := Sist[C1,C2] - V1*Sist[Col,C2]; Inv[C1,C2] := Inv[C1,C2] - V1*Inv[Col,C2]; end; end; for i:=0 to Dim-1 do for j:=0 to Dim-1 do begin R[i,j]:=FloatToStr(Inv[i,j]); end; Result := R; end else begin ShowMessage('La Determinante es 0 , no tiene Inversa !!!'); Result := R; exit(); end; end; function TMatriz1.Invierte2(Dim: Integer;Sist,Inv:matriz) : matriz; var NoCero,Col,C1,C2,A,i,j : Integer; Pivote,V1,V2 : real; R:cadena; begin if ( Determinante(Sist,Dim) <> 0) then begin for C1 := 0 to Dim-1 do for C2 := 0 to Dim-1 do begin if (C1 = C2) then begin Inv[C1,C2] := 1; end else Inv[C1,C2] := 0; end; for Col :=0 to Dim-1 do begin NoCero :=0; A := Col; while (NoCero = 0) do begin if ((Sist[A,Col]>0.0000001) or ((Sist[A,Col]<-0.0000001))) then begin NoCero := 1; end else A := A+1; end; Pivote := Sist[A,Col]; for C1 := 0 to Dim-1 do begin V1 := Sist[A,C1]; Sist[A,C1] := Sist[Col,C1]; Sist[Col,C1] := V1/Pivote; V2 := Inv[A,C1]; Inv[A,C1] := Inv[Col,C1]; Inv[Col,C1] := V2/Pivote; end; for C2 := Col+1 to Dim-1 do begin V1 := Sist[C2,Col]; for C1 := 0 to Dim-1 do begin Sist[C2,C1] := Sist[C2,C1] - V1*Sist[Col,C1]; Inv[C2,C1] := Inv[C2,C1]-V1*Inv[Col,C1]; end; end; end; for Col := Dim-1 downto 0 do for C1 := (Col-1) downto 0 do begin V1 := Sist[C1,Col]; for C2 := 0 to Dim-1 do begin Sist[C1,C2] := Sist[C1,C2] - V1*Sist[Col,C2]; Inv[C1,C2] := Inv[C1,C2] - V1*Inv[Col,C2]; end; end; Result := Inv; end else begin ShowMessage('La Determinante es 0 , no tiene Inversa !!!'); Result := Sist; exit(); end; end; function TMatriz1.Division(A,B:Matriz;m,n,c,d:Integer): cadena; var res : cadena; Inv:matriz; begin if(Determinante(B,c) <> 0 ) then begin Inv := Invierte2(c,B,Inv); res := Multiplicacion(A,Inv,m,n,c,d); result := res; end else ShowMessage('La Determinante es 0 , no se puede dividir!!!'); end; operator *(a,b:matriz):matriz; begin end; operator +(a,b:matriz):matriz; begin end; operator -(a,b:matriz):matriz; begin end; operator /(a,b:matriz):matriz; begin end; end.
program SmokeDetector; {$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif} {$ifdef FPC}{$mode OBJFPC}{$H+}{$endif} uses SysUtils, IPConnection, Device, BrickletIndustrialDigitalIn4; const HOST = 'localhost'; PORT = 4223; type TSmokeDetector = class private ipcon: TIPConnection; brickletIndustrialDigitalIn4: TBrickletIndustrialDigitalIn4; public constructor Create; destructor Destroy; override; procedure ConnectedCB(sender: TIPConnection; const connectedReason: byte); procedure EnumerateCB(sender: TIPConnection; const uid: string; const connectedUid: string; const position: char; const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber; const deviceIdentifier: word; const enumerationType: byte); procedure InterruptCB(sender: TBrickletIndustrialDigitalIn4; const interruptMask: word; const valueMask: word); procedure Execute; end; var sd: TSmokeDetector; constructor TSmokeDetector.Create; begin ipcon := nil; brickletIndustrialDigitalIn4 := nil; end; destructor TSmokeDetector.Destroy; begin if (brickletIndustrialDigitalIn4 <> nil) then brickletIndustrialDigitalIn4.Destroy; if (ipcon <> nil) then ipcon.Destroy; inherited Destroy; end; procedure TSmokeDetector.ConnectedCB(sender: TIPConnection; const connectedReason: byte); begin if (connectedReason = IPCON_CONNECT_REASON_AUTO_RECONNECT) then begin WriteLn('Auto Reconnect'); while (true) do begin try ipcon.Enumerate; break; except on e: Exception do begin WriteLn('Enumeration Error: ' + e.Message); Sleep(1000); end; end; end; end; end; procedure TSmokeDetector.EnumerateCB(sender: TIPConnection; const uid: string; const connectedUid: string; const position: char; const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber; const deviceIdentifier: word; const enumerationType: byte); begin if ((enumerationType = IPCON_ENUMERATION_TYPE_CONNECTED) or (enumerationType = IPCON_ENUMERATION_TYPE_AVAILABLE)) then begin if (deviceIdentifier = BRICKLET_INDUSTRIAL_DIGITAL_IN_4_DEVICE_IDENTIFIER) then begin try brickletIndustrialDigitalIn4 := TBrickletIndustrialDigitalIn4.Create(uid, ipcon); brickletIndustrialDigitalIn4.SetDebouncePeriod(10000); brickletIndustrialDigitalIn4.SetInterrupt(15); brickletIndustrialDigitalIn4.OnInterrupt := {$ifdef FPC}@{$endif}InterruptCB; WriteLn('Industrial Digital In 4 initialized'); except on e: Exception do begin WriteLn('Industrial Digital In 4 init failed: ' + e.Message); brickletIndustrialDigitalIn4 := nil; end; end; end; end; end; procedure TSmokeDetector.InterruptCB(sender: TBrickletIndustrialDigitalIn4; const interruptMask: word; const valueMask: word); begin if (valueMask > 0) then begin WriteLn('Fire! Fire!'); end; end; procedure TSmokeDetector.Execute; begin ipcon := TIPConnection.Create; while (true) do begin try ipcon.Connect(HOST, PORT); break; except on e: Exception do begin WriteLn('Connection Error: ' + e.Message); Sleep(1000); end; end; end; ipcon.OnEnumerate := {$ifdef FPC}@{$endif}EnumerateCB; ipcon.OnConnected := {$ifdef FPC}@{$endif}ConnectedCB; while (true) do begin try ipcon.Enumerate; break; except on e: Exception do begin WriteLn('Enumeration Error: ' + e.Message); Sleep(1000); end; end; end; WriteLn('Press key to exit'); ReadLn; end; begin sd := TSmokeDetector.Create; sd.Execute; sd.Destroy; end.
unit uMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus, StdCtrls, BZImageViewer, BZColors, BZGraphic, BZBitmap, {%H-}BZBitmapIO; Const cLargeurImageCarteMax = 110; cHauteurImageCarteMax = 160; // Decalage en pixel des cartes pour l'affichage de toutes les cartes d'une CardList cDecalageCarte = 40; type // Couleur d'une carte TCardColor =(ccHeart, ccDiamond, ccSpade, ccClub); // Valeur d'une carte TCardValue = (cvAce, cvTwo, vcThree, cvFour, cvFive, cvSix, cvSeven, cvEight, cvNine, cvTen, cvJack, cvQueen, cvKing); const // CardList des noms de fichier des cartes cCardFileNames : array[TCardColor] of array[TCardValue] of string = ( ('ace_of_hearts' , '2_of_hearts' , '3_of_hearts', '4_of_hearts', '5_of_hearts', '6_of_hearts' , '7_of_hearts', '8_of_hearts', '9_of_hearts', '10_of_hearts', 'jack_of_hearts2', 'queen_of_hearts2', 'king_of_hearts2'), ('ace_of_diamonds' , '2_of_diamonds' , '3_of_diamonds', '4_of_diamonds', '5_of_diamonds', '6_of_diamonds' , '7_of_diamonds', '8_of_diamonds', '9_of_diamonds', '10_of_diamonds', 'jack_of_diamonds2', 'queen_of_diamonds2', 'king_of_diamonds2'), ('ace_of_spades' , '2_of_spades' , '3_of_spades', '4_of_spades', '5_of_spades', '6_of_spades' , '7_of_spades', '8_of_spades', '9_of_spades', '10_of_spades', 'jack_of_spades2', 'queen_of_spades2', 'king_of_spades2'), ('ace_of_clubs' , '2_of_clubs' , '3_of_clubs', '4_of_clubs', '5_of_clubs', '6_of_clubs' , '7_of_clubs', '8_of_clubs', '9_of_clubs', '10_of_clubs', 'jack_of_clubs2', 'queen_of_clubs2', 'king_of_clubs2')); Type // Description d'une carte TCard = packed record Color : TCardColor; // Couleur de la carte Value : TCardValue; // Valeur de la carte Image : TBZBitmap; // Image de la carte à afficher end; PCard = ^TCard; //Pointeur sur une carte TCardPointers = Array[1..52] of PCard; type TMainForm = class(TForm) image1 : TBZImageViewer; image10 : TBZImageViewer; image11 : TBZImageViewer; image12 : TBZImageViewer; image13 : TBZImageViewer; image14 : TBZImageViewer; image15 : TBZImageViewer; image16 : TBZImageViewer; image2 : TBZImageViewer; image3 : TBZImageViewer; image4 : TBZImageViewer; image5 : TBZImageViewer; image6 : TBZImageViewer; image7 : TBZImageViewer; image8 : TBZImageViewer; image9 : TBZImageViewer; MainMenu : TMainMenu; MenuItem1 : TMenuItem; mnuAbout : TMenuItem; mnuExitApp : TMenuItem; mnuNewGame : TMenuItem; procedure FormClose(Sender : TObject; var CloseAction : TCloseAction); procedure FormCreate(Sender : TObject); procedure FormShow(Sender : TObject); procedure imageMouseDown(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer); procedure mnuExitAppClick(Sender : TObject); procedure mnuNewGameClick(Sender : TObject); procedure ImageClick(Sender : TObject); private // Sera utile pour le tirage aléatoire des cartes FCardDistibution : Array[1..52] of Boolean; // Les quatre images en haut à gauche FDeckTemps : Array[1..4] of TList; // Les quatre images en haut à droite FDeckFinals : Array[1..4] of TList; // Les huit images en bas FDecks : array[1..8] of TList; // Liste pour stocker les cartes sélectionnées si il y en plus de une FSelectionList : TList; // Jeu de carte complets, CardList de tous les pointeurs de cartes dans un tableau FCards : TCardPointers; FSelection : Boolean; // Drapeau lorsqu'une ou plusieurs cartes sont sélectionnées FSelectionCount : Integer; // Nombre de carte sélectionnées FMousePoint : TPoint; // Position de la souris dans les TImages FSelectionListIndex : Integer; // Numero de la Liste de carte ou on fait la selection FSelectionCard : PCard; // Carte sélectionnée utilisée pour les tests de vérifications // Tableau de référence des TImage de notre application // Va permettre de simplifier les interactions FImageRef : Array[1..16] of TBZImageViewer; // Tableau pour stocker nos 4 images de fond pour les tas finaux FCardBackgrounds : Array[1..4] of TBZBitmap; protected { Initalise la CardList de tirage des cartes leur valeur est mise à FAUX (False) car aucune carte n'a été tirée } procedure InitCardsDistribution; { Distribution des cartes aléatoirement dans les huit CardLists "FTasDeCartes" } procedure DistributeCards; { Creation d'une nouvelle carte et retourne celle-ci Note : L'image de la carte sera automatique chargé en fonction de sa couleur et valeur } function CreateCard(CardColor : TCardColor; CardValue : TCardValue) : PCard; { Creation de toutes les cartes du jeux dans le tableau de pointeurs "FCartes } procedure CreateGameCards; { Creation des CardLists de cartes du jeux et chargements des images } procedure CreateCardLists; { Détruit toutes les CardLists de carte du jeux } procedure DestroyAllCardLists; { Vides toutes les CardLists de carte du jeux, sans libérer les pointeurs des cartes } procedure ClearCardLists; { Ajoute un pointeur carte dans une CardList } procedure AddCardInList(CardList : TList; Card : PCard); { Pioche la dernière carte d'une CardList et efface celle-ci de la CardList } function GetLastCardInList(CardList : TList) : PCard; { Efface la derniere carte d'une CardList } procedure DeleteLastCardInList(CardList : TList); { Detruit toutes les cartes d'une CardList et la CardList elle même } procedure DestroyCardList(CardList : TList); { Retourne CardList Suivant Index, basé sur les numero de Tag des TImage } function GetCardList(Index : Integer) : TList; { Creation de la liste de sélection, utilisé si plusieurs cartes sont sélectionnées } procedure CreateSelectionList(aList : TList; StartSelectionIndex : Integer); { Affiche tous les "Bitmap" (image) des cartes d'une CardList, dans un control visuel "TImage', en les décalant. Si le paramètre "Selection" est à VRAI (True) alors la dernière carte sera affichée en couleur inverse} procedure DisplayCardList(CardList : TList; img : TBZImageViewer; Selection : Boolean); { Retourne VRAI (true) si on peux déposer la carte sur un tas final } function CanMoveOnFinalDeck(IndexList : Integer; aCard : PCard) : Boolean; { Retourne VRAI (true) si on peux déposer la carte sur un tas de carte temporaire } function CanMoveOnTempDeck(IndexList : Integer) : Boolean; { Retourne VRAI (true) si on peux déposer la carte sur un tas de carte principal } function CanMoveOnDeck(IndexList : Integer; aCard : PCard) : Boolean; { Retourne VRAI (True) si on a déposé toutes les cartes sur les tas finaux } function CheckIfWin : Boolean; public procedure NewGame; end; var MainForm : TMainForm; implementation {$R *.lfm} { TMainForm } procedure TMainForm.FormCreate(Sender : TObject); Var Img : TBZImageViewer; i, cnt : Integer; TmpBmp : TBZBitmap; begin CreateGameCards; CreateCardLists; DistributeCards; FSelectionList := TList.Create; // On doit initialiser les bitmaps des TImage car ceux-ci sont vide //Image9.Picture.Bitmap := TBitmap.Create; //Image9.Picture.Bitmap.SetSize(cLargeurImageCarteMax, Image9.Height); // Plutot que d'ajouter les 8 TImage correspondant aux tas de cartes // on va parcourir la liste des controle présent sur notre form cnt := 1; for i := 0 to Self.ControlCount - 1 do begin if Self.Controls[i] is TBZImageViewer then begin Img := TBZImageViewer(Self.Controls[i]); FImageRef[cnt] := Img; // On sauvegarde la réference // On créé les Bitmap et on remplis avec une couleur de fond if (Img.Tag < 5) then begin TmpBmp := TBZBitmap.Create; TmpBmp.SetSize(cLargeurImageCarteMax, cHauteurImageCarteMax); TmpBmp.Canvas.Pen.Style := ssClear; TmpBmp.Canvas.Brush.Style := bsSolid; TmpBmp.Canvas.Brush.Color := clrDarkGreen; TmpBmp.Canvas.Rectangle(0,0,cLargeurImageCarteMax, cHauteurImageCarteMax); Img.Picture.Bitmap.Assign(TmpBmp); FreeAndNil(TmpBmp); end else if (img.Tag >= 5) and (img.Tag <= 8) then begin FCardBackgrounds[Img.tag - 4] := TBZBitmap.Create; FCardBackgrounds[Img.tag - 4].SetSize(cLargeurImageCarteMax, cHauteurImageCarteMax); // on a déja préchargé les bitmaps dans nos TImage // On fais juste une copie FCardBackgrounds[Img.tag - 4].Assign(Img.Picture.Bitmap); end else if (Img.Tag > 8) then begin TmpBmp := TBZBitmap.Create; TmpBmp.SetSize(cLargeurImageCarteMax, Img.Height); TmpBmp.Canvas.Pen.Style := ssClear; TmpBmp.Canvas.Brush.Style := bsSolid; TmpBmp.Canvas.Brush.Color := clrDarkGreen; TmpBmp.Canvas.Rectangle(0,0,cLargeurImageCarteMax, Img.Height); Img.Picture.Bitmap.Assign(TmpBmp); FreeAndNil(TmpBmp); end; inc(cnt); end; end; FSelection := False; end; procedure TMainForm.FormShow(Sender : TObject); begin DisplayCardList(FDecks[1], Image9, false); DisplayCardList(FDecks[2], Image10, false); DisplayCardList(FDecks[3], Image11, false); DisplayCardList(FDecks[4], Image12, false); DisplayCardList(FDecks[5], Image13, false); DisplayCardList(FDecks[6], Image14, false); DisplayCardList(FDecks[7], Image15, false); DisplayCardList(FDecks[8], Image16, false); end; procedure TMainForm.imageMouseDown(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer); begin FMousePoint.Create(x,y); end; procedure TMainForm.mnuExitAppClick(Sender : TObject); begin Close; end; procedure TMainForm.mnuNewGameClick(Sender : TObject); begin NewGame; end; procedure TMainForm.ImageClick(Sender : TObject); Var Img : TBZImageViewer; ListeA, ListeB : TList; Ok : Boolean; R : TRect; idx, y1, y2, i : Integer; begin Ok := False; Img := TBZImageViewer(Sender); if FSelection then begin ListeA := GetCardList(FSelectionListIndex); ListeB := GetCardList(img.Tag); Case Img.Tag of 1, 2, 3, 4 : Ok := CanMoveOnTempDeck(img.tag); 5, 6, 7, 8 : Ok := CanMoveOnFinalDeck(img.Tag, FSelectionCard); else Ok := CanMoveOnDeck(Img.Tag, FSelectionCard); end; if Ok then // La carte sélectionnée peut-être déplacée begin // On Ajoute la ou les cartes selectionnées dans la nouvelle liste if FSelectionCount > 1 then begin for i := 0 to (FSelectionList.Count - 1) do begin AddCardInList(ListeB, PCard(FSelectionList.Items[i])); end; end else AddCardInList(ListeB, FSelectionCard); end else begin // Non, alors on remet les cartes dans la liste d'origine if FSelectionCount > 1 then begin for i := 0 to (FSelectionList.Count - 1) do begin AddCardInList(ListeA, PCard(FSelectionList.Items[i])); end; end else AddCardInList(ListeA, FSelectionCard); end; DisplayCardList(ListeB, FimageRef[img.Tag], false); DisplayCardList(ListeA, FimageRef[FSelectionListIndex], false); FSelection := False; if CheckIfWin then begin if MessageDlg('Bravo vous avez gagné !'+LineEnding+'Souhaitez vous commencer une nouvelle partie ?', mtConfirmation, [mbYes, mbNo],0) = mrYes then begin NewGame; end; end; end else begin y1 := 0; y2 := cDecalageCarte; FSelectionCount := 0; FSelectionListIndex := Img.Tag; ListeA := GetCardList(FSelectionListIndex); if FSelectionListIndex >=9 then begin if ListeA.Count > 0 then begin R := Rect(0,y1, cLargeurImageCarteMax, y2); for i := 0 to ListeA.Count - 1 do begin if (i < (ListeA.Count - 1)) then R := Rect(0,y1, cLargeurImageCarteMax, y2) else R := Rect(0,y1, cLargeurImageCarteMax, y1 + cHauteurImageCarteMax); if R.Contains(FMousePoint) then begin FSelectionCount := ListeA.Count - i; Break; end; y1 := y1 + cDecalageCarte; y2 := y2 + cDecalageCarte; end; DisplayCardList(ListeA, FimageRef[FSelectionListIndex], True); // On conserve la carte selectionnée dans une variable globale if FSelectionCount > 1 then begin Idx := (ListeA.Count - 1) - (FSelectionCount - 1); FSelectionCard := PCard(ListeA.Items[Idx]); CreateSelectionList(ListeA, Idx); end else FSelectionCard := GetLastCardInList(ListeA); end; end else begin if ListeA.Count > 0 then begin FSelectionCount := 1; DisplayCardList(ListeA, FimageRef[FSelectionListIndex], True); FSelectionCard := GetLastCardInList(ListeA); end; end; FSelection := True; end; end; procedure TMainForm.FormClose(Sender : TObject; var CloseAction : TCloseAction); Var i : Integer; begin // On libere nos listes et tous les pointeurs des cartes DestroyAllCardLists; FreeAndNil(FSelectionList); // On libère nos images de fond for i := 4 downto 1 do FreeAndNil(FCardBackgrounds[i]); end; procedure TMainForm.InitCardsDistribution; Var i : Byte; begin for i := 1 to 52 do begin FCardDistibution[i] := False; end; end; procedure TMainForm.DistributeCards; Var i, j, n : Byte; nbCards : Byte; // Nombre de carte à tirer par liste begin InitCardsDistribution; // Remize à zero de la liste pour l'aide au tirage Randomize; // Initialisation de la génération de nombre aléatoire // Tirage des sept premiers tas de carte for i := 1 to 7 do begin if i > 4 then nbCards := 6 else nbCards := 7; j := 1; While (j <= nbCards) do begin n := (Random(104) div 2) + 1; // Tirage d'une nombre entre 1 et 52 if not(FCardDistibution[n]) then // Si la carte n'a pas encore été tirée begin AddCardInList(FDecks[i], FCards[n]); FCardDistibution[n] := True; inc(j); end; end; end; // On ajoute les cartes restantes dans le dernier tas de carte For i := 1 to 52 do begin if not(FCardDistibution[i]) then begin AddCardInList(FDecks[8], FCards[i]); end; end; end; function TMainForm.CreateCard(CardColor : TCardColor; CardValue : TCardValue) : PCard; Var NewCard : PCard; begin New(NewCard); //Allocation du pointeur de la nouvelle carte en mémoire // On définie les propriétés. On utilise ^ car c'est un pointeur NewCard^.Color := CardColor; NewCard^.Value := CardValue; NewCard^.Image := TBZBitmap.Create; // Creation du Bitmap NewCard^.Image.LoadFromFile('../../../images/' + cCardFileNames[CardColor][CardValue] + '.png'); Result := NewCard; end; procedure TMainForm.CreateGameCards; Var i : TCardColor; j : TCardValue; cnt : Byte; begin cnt := 1; for i := ccHeart to ccClub do begin for j:= cvAce to cvKing do begin FCards[cnt] := CreateCard(i,j); inc(cnt) end; end; end; procedure TMainForm.CreateCardLists; Var i : Byte; begin for i := 1 to 8 do begin if i < 5 then begin FDeckTemps[i] := TList.Create; FDeckFinals[i] := TList.Create; end; FDecks[i] := TList.Create; end; end; procedure TMainForm.DestroyAllCardLists; Var i : Byte; begin for i := 8 downto 1 do begin if i < 5 then begin DestroyCardList(FDeckTemps[i]); DestroyCardList(FDeckFinals[i]); end; DestroyCardList(FDecks[i]); end; end; procedure TMainForm.ClearCardLists; Var i : Byte; j : Integer; begin for i := 8 downto 1 do begin if i < 5 then begin if FDeckTemps[i].Count > 0 then for j := (FDeckTemps[i].Count - 1) downto 0 do FDeckTemps[i].Delete(j); if FDeckFinals[i].Count > 0 then for j := (FDeckFinals[i].Count - 1) downto 0 do FDeckFinals[i].Delete(j); end; if FDecks[i].Count > 0 then for j := (FDecks[i].Count - 1) downto 0 do FDecks[i].Delete(j); end; end; procedure TMainForm.AddCardInList(CardList : TList; Card : PCard); begin CardList.Add(Card); end; function TMainForm.GetLastCardInList(CardList : TList) : PCard; begin Result := CardList.Items[(CardList.Count - 1)]; DeleteLastCardInList(CardList); end; procedure TMainForm.DeleteLastCardInList(CardList : TList); begin CardList.Delete((CardList.Count - 1)); end; procedure TMainForm.DestroyCardList(CardList : TList); Var p : PCard; i : integer; begin if CardList.Count > 0 then begin for i := (CardList.Count - 1) downto 0 do begin p := CardList.Items[i]; CardList.Delete(i); FreeAndNil(P^.Image); // NE PAS OUBLIER DE LIBERER LES BITMAPS Dispose(p); end; end; FreeAndNil(CardList); end; function TMainForm.GetCardList(Index : Integer) : TList; begin Case Index of 1, 2, 3, 4 : begin Result := FDeckTemps[Index]; end; 5,6,7,8 : begin Result := FDeckFinals[Index - 4] end; else begin Result := FDecks[Index - 8]; end; end; end; procedure TMainForm.CreateSelectionList(aList : TList; StartSelectionIndex : Integer); var i, cnt : integer; begin // On vide la liste de slection cnt := FSelectionList.Count; if (cnt > 0) then begin for i := (cnt-1) downto 0 do // IMPORTANT ! Attention d'effacer les éléments en partant du dernier begin FSelectionList.Delete(i); end; end; // On remplis la liste de selection avec les cartes sélectionnées cnt := aList.Count; for i := StartSelectionIndex to (cnt - 1) do begin FSelectionList.Add(PCard(aList.Items[i])); end; // On efface les cartes sélectionnées de la liste d'origine for i := (cnt - 1) downto StartSelectionIndex do aList.Delete(i); end; procedure TMainForm.DisplayCardList(CardList : TList; img : TBZImageViewer; Selection : Boolean); Var i, cnt : Integer; Decalage : Integer; Card : PCard; TmpBmp : TBZBitmap; begin Decalage := 0; cnt := (CardList.Count - 1); if ((Img.Tag >= 5) and (Img.Tag <= 8)) then // S'agit-il des tas finaux begin // Oui on copie l' image de fond Img.Picture.Bitmap.PutImage(FCardBackgrounds[Img.tag - 4],0,0,255,dmSet,amAlpha); //Img.Picture.Bitmap.Clear(clrYellow); end else begin // On efface avec la couleur du fond Img.Picture.Bitmap.Canvas.Pen.Style := ssClear; Img.Picture.Bitmap.Canvas.Brush.Style := bsSolid; Img.Picture.Bitmap.Canvas.Brush.Color := clrDarkGreen; Img.Picture.Bitmap.Canvas.Rectangle(0,0,Img.Width, Img.Height); end; if cnt < 0 then begin img.Invalidate; exit; // Rien à dessiner on sort end; if (Img.Tag >= 9) then // On affiche nos tas de cartes begin for i := 0 to cnt do begin Card := CardList.Items[i]; if Selection then begin //if FSelectionCount > 1 then //begin if (i >= (cnt - (FSelectionCount-1))) then begin TmpBmp := Card^.Image.CreateClone; TmpBmp.ColorFilter.Negate(); Img.Picture.Bitmap.PutImage(TmpBmp,0,Decalage,255,dmSet,amAlpha); FreeAndNil(TmpBmp); end else begin Img.Picture.Bitmap.PutImage(Card^.Image,0,Decalage,255,dmSet,amAlpha); end; //end //else //if i = cnt then //begin // TmpBmp := Card^.Image.CreateClone; // TmpBmp.ColorFilter.Negate(); // Img.Picture.Bitmap.PutImage(TmpBmp,0,Decalage,255,dmSet,amAlpha); // FreeAndNil(TmpBmp); //end //else //begin // Img.Picture.Bitmap.PutImage(Card^.Image,0,Decalage,255,dmSet,amAlpha); // Transfert de l'image de la carte dans le TImage //end; end else begin Img.Picture.Bitmap.PutImage(Card^.Image,0,Decalage,255,dmSet,amAlpha); // Transfert de l'image de la carte dans le TImage end; Decalage := Decalage + cDecalageCarte; end; end else begin // Pour les autres on n'affiche que la dernière Card := CardList.Items[cnt]; if Selection then // Transfert de l'image slectionner en couleur inverse de la carte dans le TImage begin TmpBmp := Card^.Image.CreateClone; TmpBmp.ColorFilter.Negate(); Img.Picture.Bitmap.PutImage(TmpBmp,0,0,255,dmSet,amAlpha); FreeAndNil(TmpBmp); end else begin //Card^.Image.ColorFilter.SwapChannel(scmRedBlue); Img.Picture.Bitmap.PutImage(Card^.Image ,0,0,255,dmSet,amAlpha); // Transfert de l'image de la carte dans le TImage end; end; Img.Invalidate; // Pour rafraichir le TImage end; function TMainForm.CanMoveOnFinalDeck(IndexList : Integer; aCard : PCard) : Boolean; Var aList : TList; Idx : Integer; begin Result := False; if FSelectionCount > 1 then exit; // On ne peux pas placer plus d'une carte aList := GetCardList(IndexList); if aList.Count = 13 then Exit; // La liste est pleine on sort Idx := IndexList - 4; Case idx of 1 : Result := (aCard^.Color = ccHeart); 2 : Result := (aCard^.Color = ccDiamond); 3 : Result := (aCard^.Color = ccSpade); 4 : Result := (aCard^.Color = ccClub); end; if aList.Count < 1 then begin Result := Result and (aCard^.Value = cvAce); end else begin Result := Result and (aCard^.Value = TCardValue(aList.Count)); end; end; function TMainForm.CanMoveOnTempDeck(IndexList : Integer) : Boolean; Var aList : TList; begin Result := False; if FSelectionCount > 1 then exit; // On ne peux pas placer plus d'une carte aList := GetCardList(IndexList); Result := aList.Count < 1; end; function TMainForm.CanMoveOnDeck(IndexList : Integer; aCard : PCard) : Boolean; Var Card : PCard; aList : TList; begin Result := False; aList := GetCardList(IndexList); if aList.Count < 1 then Exit(true); Card := aList.Items[(aList.Count - 1)]; // On recupere la derniere carte de la liste ou on veux déposer la carte Case Card^.Color of ccHeart, ccDiamond : Result := (aCard^.Color = ccSpade) or (aCard^.Color = ccClub); ccSpade, ccClub : Result := (aCard^.Color = ccHeart) or (aCard^.Color = ccDiamond); end; if Result then begin Result := Result and (Card^.Value = TCardValue((ord(aCard^.Value) + 1))); //(Card^Value + 1) end; end; function TMainForm.CheckIfWin : Boolean; begin // On fait simplement la somme de tous les tas Result := (FDeckFinals[1].Count + FDeckFinals[2].Count + FDeckFinals[3].Count + FDeckFinals[4].Count) = 52; end; procedure TMainForm.NewGame; begin Screen.Cursor := crHourGlass; ClearCardLists; DistributeCards; FSelectionCount := 0; FSelectionCard := nil; FSelection := False; // On affiche nos tas de cartes DisplayCardList(FDecks[1], Image9, false); DisplayCardList(FDecks[2], Image10, false); DisplayCardList(FDecks[3], Image11, false); DisplayCardList(FDecks[4], Image12, false); DisplayCardList(FDecks[5], Image13, false); DisplayCardList(FDecks[6], Image14, false); DisplayCardList(FDecks[7], Image15, false); DisplayCardList(FDecks[8], Image16, false); DisplayCardList(FDeckTemps[1], Image1, False); DisplayCardList(FDeckTemps[2], Image2, False); DisplayCardList(FDeckTemps[3], Image3, False); DisplayCardList(FDeckTemps[4], Image4, False); DisplayCardList(FDeckFinals[1], Image5, False); DisplayCardList(FDeckFinals[2], Image6, False); DisplayCardList(FDeckFinals[3], Image7, False); DisplayCardList(FDeckFinals[4], Image8, False); Screen.Cursor := crDefault; end; end.
unit uPessoa; interface type TPessoa = class private FNome: String; FCpf: String; FIdade: Integer; procedure setNome(Value: String); procedure setCpf(Value: String); procedure setIdade(Value: Integer); function getNome: String; function getCpf: String; function getIdade: Integer; public Property Nome: String read getNome write setNome; Property Cpf: String read getCpf write setCpf; Property Idade: Integer read getIdade write setIdade; end; implementation { TPessoa } function TPessoa.getCpf: String; begin Result := FCpf; end; function TPessoa.getIdade: Integer; begin Result := FIdade; end; function TPessoa.getNome: String; begin Result := FNome; end; procedure TPessoa.setCpf(Value: String); begin FCpf := Value; end; procedure TPessoa.setIdade(Value: Integer); begin FIdade := Value; end; procedure TPessoa.setNome(Value: String); begin FNome := Value; end; end.
unit Unit1; {definicje procedur i funkcji} interface const n = 9; type Tab10 = Array[0..n] of Integer; {pierwsza procka zewnetrzna} procedure Hello(); {przekazywanie do procedury zmiennej: - bez znacznika przekazywana jset kopia - VAR - przekazuje oryginalne dane - CONST - przekazuje oryginal ale nie pozwala na jego modyfikowac daje nam to oszczednosc czasu i pamieci} procedure Kwadrat ( var liczba:Integer ); {dwie procedury do inicjalizowania tablicy zdefiniowanej w typach oraz druga wyswietlajaca tablice tego samego typu} procedure Generuj ( var tab:Tab10 ); procedure Wyswietl( const tab:Tab10 ); procedure MedianaW ( const tab:Tab10 ); {deklarcacje procedur i funkcji } implementation /////////////////////////////////////////////////////////////////////////////// procedure Hello(); begin writeln('Hello'); end; /////////////////////////////////////////////////////////////////////////////// procedure Kwadrat ( var liczba:Integer ); begin liczba := liczba * liczba; end; /////////////////////////////////////////////////////////////////////////////// procedure Generuj ( var tab:Tab10 ); var rec_a:Integer; begin for rec_a:=low(tab) to high(tab) do tab[rec_a] := random(100); end; /////////////////////////////////////////////////////////////////////////////// procedure Wyswietl( const tab:Tab10 ); var rec_a : integer; begin for rec_a:=low(tab) to high(tab) do write(tab[rec_a]:3); writeln(); end; procedure MedianaW ( const tab:Tab10 ); var rec_a:Integer; suma:Integer; begin suma:=0; for rec_a := low(tab) to high(tab) do inc(suma, tab[rec_a]); writeln(suma); end; end.
(* @file UDisplayConstants.pas * @author Willi Schinmeyer * @date 2011-10-27 * * UDisplayConstants Unit * * Contains constants e.g. regarding screen size, Tetromino display etc. *) unit UDisplayConstants; interface uses crt; const (* Window size in characters *) SCREEN_WIDTH : integer = 80; SCREEN_HEIGHT : integer = 50; //char representating a Tetromino part CELL_OCCUPIED_CHAR : char = '#'; //the empty char must not be anything else than space because //otherwise I'd have to set the color, which I don't. CELL_EMPTY_CHAR : char = ' '; implementation begin end.
unit uDM; interface uses SysUtils, Classes, Controls, DB, DBClient, MConnect, SConnect, DBIntf, InvokeServerIntf, SvcInfoIntf; type Tdm = class(TDataModule, IDBConnection, IDBAccess, IInvokeServer, ISvcInfoEx) Conn: TSocketConnection; private function CheckConnct: Boolean; protected {IDBConnection} function GetConnected: Boolean; procedure SetConnected(const Value: Boolean); property Connected: Boolean read GetConnected write SetConnected; procedure ConnConfig; function GetDBConnection: TObject; {IDBAccess} procedure BeginTrans; procedure CommitTrans; procedure RollbackTrans; procedure QuerySQL(Cds: TClientDataSet; const SQLStr: String); procedure ExecuteSQL(const SQLStr: String); procedure ApplyUpdate(const TableName: String; Cds: TClientDataSet); {IInvokeServer} function AppServer: Variant; {ISvcInfoEx} procedure GetSvcInfo(Intf: ISvcInfoGetter); public { Public declarations } end; var dm: Tdm; implementation uses SysSvc, _sys, RegIntf, DialogIntf, uConfig; {$R *.dfm} const Key_DBConn = 'SYSTEM\DBCONNECTION'; Key_IPAddr = 'IPADDR'; Key_Port = 'PORT'; { Tdm } procedure Tdm.ApplyUpdate(const TableName: String; Cds: TClientDataSet); var r: Shortint; begin CheckConnct; if Cds.State in [dsEdit, dsInsert] then cds.Post; if Cds.ChangeCount = 0 then exit; r := self.Conn.AppServer.ApplyUpdate(TableName, Cds.Delta); if r = 1 then Cds.MergeChangeLog else (SysService as IDialog).ShowError('提交数据出错!'); end; procedure Tdm.BeginTrans; begin //方法未实现... end; procedure Tdm.CommitTrans; begin //方法未实现... end; procedure Tdm.RollbackTrans; begin //方法未实现... end; procedure Tdm.ExecuteSQL(const SQLStr: String); begin CheckConnct; self.Conn.AppServer.ExecSQL(SQLStr); end; function Tdm.GetConnected: Boolean; begin Result := self.Conn.Connected; end; function Tdm.GetDBConnection: TObject; begin Result := self.Conn; end; procedure Tdm.QuerySQL(Cds: TClientDataSet; const SQLStr: String); begin CheckConnct; Cds.Data := self.Conn.AppServer.QryData(SQLStr); end; procedure Tdm.ConnConfig; var Reg: IRegistry; IpAddr: Widestring; Port: Integer; begin Reg := SysService as IRegistry; if Reg.OpenKey(Key_DBConn, True) then begin frmConfig := TfrmConfig.Create(nil); try Reg.ReadString(Key_IPAddr, IPAddr); Reg.ReadInteger(Key_Port, Port); frmConfig.edt_IPAddr.Text := IPAddr; frmConfig.edt_Port.Text := Inttostr(Port); if frmConfig.ShowModal = mrOK then begin IpAddr := frmConfig.edt_IPAddr.Text; Port := StrToIntDef(frmConfig.edt_Port.Text, 211); Reg.WriteString(Key_IPAddr, IpAddr); Reg.WriteInteger(Key_Port, Port); Reg.SaveData; self.Conn.Connected := False; self.Conn.Host := IpAddr; self.Conn.Port := Port; self.Conn.Connected := True; end; finally frmConfig.Free; end; end; end; procedure Tdm.SetConnected(const Value: Boolean); begin self.Conn.Connected := Value; end; function Tdm.CheckConnct: Boolean; var Reg: IRegistry; IpAddr: Widestring; Port: Integer; begin Result := True; if self.Conn.Connected then exit; try Reg := SysService as IRegistry; if Reg.OpenKey(Key_DBConn, True) then begin Reg.ReadString(Key_IPAddr, IPAddr); Reg.ReadInteger(Key_Port, Port); self.Conn.Address := IpAddr; self.Conn.Port := Port; self.Conn.Connected := True; Result := True; end; except on E: Exception do (SysService as IDialog).ShowError(E); end; end; function Tdm.AppServer: Variant; begin Result := self.Conn.AppServer; end; procedure Tdm.GetSvcInfo(Intf: ISvcInfoGetter); var SvcInfoRec: TSvcInfoRec; begin SvcInfoRec.ModuleName := ExtractFileName(SysUtils.GetModuleName(HInstance)); SvcInfoRec.GUID := GUIDToString(IDBConnection); SvcInfoRec.Title := 'Midas连接接口(IDBConnection)'; SvcInfoRec.Version := '20100609.001'; SvcInfoRec.Comments := '用于连接Midas中间层服务器'; Intf.SvcInfo(SvcInfoRec); SvcInfoRec.GUID := GUIDToString(IDBAccess); SvcInfoRec.Title := 'Midas数据库访问接口(IDBAccess)'; SvcInfoRec.Version := '20100609.001'; SvcInfoRec.Comments := '用于操作数据库'; Intf.SvcInfo(SvcInfoRec); SvcInfoRec.GUID := GUIDToString(IInvokeServer); SvcInfoRec.Title := 'Midas远程方法调用接口(IInvokeServer)'; SvcInfoRec.Version := '20100609.001'; SvcInfoRec.Comments := '用于远程方法调用'; Intf.SvcInfo(SvcInfoRec); end; end.
unit Mailboxes; interface type HCkTask = Pointer; HCkMailboxes = Pointer; HCkString = Pointer; function CkMailboxes_Create: HCkMailboxes; stdcall; procedure CkMailboxes_Dispose(handle: HCkMailboxes); stdcall; function CkMailboxes_getCount(objHandle: HCkMailboxes): Integer; stdcall; function CkMailboxes_getLastMethodSuccess(objHandle: HCkMailboxes): wordbool; stdcall; procedure CkMailboxes_putLastMethodSuccess(objHandle: HCkMailboxes; newPropVal: wordbool); stdcall; function CkMailboxes_GetFlags(objHandle: HCkMailboxes; index: Integer; outStr: HCkString): wordbool; stdcall; function CkMailboxes__getFlags(objHandle: HCkMailboxes; index: Integer): PWideChar; stdcall; function CkMailboxes_GetMailboxIndex(objHandle: HCkMailboxes; mbxName: PWideChar): Integer; stdcall; function CkMailboxes_GetName(objHandle: HCkMailboxes; index: Integer; outStr: HCkString): wordbool; stdcall; function CkMailboxes__getName(objHandle: HCkMailboxes; index: Integer): PWideChar; stdcall; function CkMailboxes_GetNthFlag(objHandle: HCkMailboxes; index: Integer; flagIndex: Integer; outStr: HCkString): wordbool; stdcall; function CkMailboxes__getNthFlag(objHandle: HCkMailboxes; index: Integer; flagIndex: Integer): PWideChar; stdcall; function CkMailboxes_GetNumFlags(objHandle: HCkMailboxes; index: Integer): Integer; stdcall; function CkMailboxes_HasFlag(objHandle: HCkMailboxes; index: Integer; flagName: PWideChar): wordbool; stdcall; function CkMailboxes_HasInferiors(objHandle: HCkMailboxes; index: Integer): wordbool; stdcall; function CkMailboxes_IsMarked(objHandle: HCkMailboxes; index: Integer): wordbool; stdcall; function CkMailboxes_IsSelectable(objHandle: HCkMailboxes; index: Integer): wordbool; stdcall; function CkMailboxes_LoadTaskResult(objHandle: HCkMailboxes; task: HCkTask): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkMailboxes_Create; external DLLName; procedure CkMailboxes_Dispose; external DLLName; function CkMailboxes_getCount; external DLLName; function CkMailboxes_getLastMethodSuccess; external DLLName; procedure CkMailboxes_putLastMethodSuccess; external DLLName; function CkMailboxes_GetFlags; external DLLName; function CkMailboxes__getFlags; external DLLName; function CkMailboxes_GetMailboxIndex; external DLLName; function CkMailboxes_GetName; external DLLName; function CkMailboxes__getName; external DLLName; function CkMailboxes_GetNthFlag; external DLLName; function CkMailboxes__getNthFlag; external DLLName; function CkMailboxes_GetNumFlags; external DLLName; function CkMailboxes_HasFlag; external DLLName; function CkMailboxes_HasInferiors; external DLLName; function CkMailboxes_IsMarked; external DLLName; function CkMailboxes_IsSelectable; external DLLName; function CkMailboxes_LoadTaskResult; external DLLName; end.
unit common; {$DEFINE ERR_RICHDLG} interface uses eval,windows,dialogs,sysutils; function loadErrInfo(name:string):string; function ShowScrErrDlg(line:integer;msg,scrfile,source:pchar;scrcount,flag:integer):integer; function ShowEpErrorDlg(epstr:pchar;epstrCount:integer;errpos:integer;errmsg:pchar):integer; procedure ShowMessage(Msg:string); procedure InitErrDialogs; implementation uses DLG_SCR_ERROR,ep_errdlg; procedure ShowMessage(Msg:string); begin //dialogs.ShowMessage(Msg); MessageBox(0,Pchar(msg),'EPEval',MB_OK); end; function loadErrInfo(name:string):string; begin result:=ep_errdlg.loadErrInfo(name) end; function ShowScrErrDlg(line:integer;msg,scrfile,source:pchar;scrcount,flag:integer):integer; const sMsg='Source:"%s" '+#13#10+'Line: %d'+#13#10+'%s '; var str:string; begin {$IFDEF ERR_RICHDLG} result:=DLG_SCR_ERROR.ShowScrErrDlg(line,msg,scrfile,source,scrcount,flag); {$ELSE} if (flag=1) then str:='Parsing Error' else str:='Evaluation Error'; MessageBox(0,pchar(format(sMsg,[scrfile,line,msg])),pchar(str),MB_OK+MB_ICONERROR); {$ENDIF} end; function ShowEpErrorDlg(epstr:pchar;epstrCount:integer;errpos:integer;errmsg:pchar):integer; const sMsg='Error:"%s"'+#13#10+#13#10+'%s'; sTitle='Erreur d''Úvalutation Ó la colonne %d '; begin {$IFDEF ERR_RICHDLG} result:=ep_errdlg.ShowEpErrorDlg(epstr,epstrCount,errpos,Errmsg) ; {$ELSE} MessageBox(0,pchar(format(sMsg,[string(errmsg),string(epstr)])),pchar(format(sTitle,[errpos])),MB_OK+MB_ICONERROR); {$ENDIF} end; procedure InitErrDialogs; begin ErrForm:=TErrForm.create(nil); E_form:=TE_form.create(nil); end; procedure FreeErrDialogs; begin FreeAndNil(ErrForm); FreeAndNil(E_Form); end; initialization {initialise les boites de dialogs} initErrDialogs; finalization freeErrDialogs; end.
unit u_frmentrega; {$mode objfpc}{$H+} interface uses Classes, SysUtils, db, Forms, Controls, Graphics, Dialogs, StdCtrls, DBCtrls, Buttons, Grids, ButtonPanel, LCLType, ZDataset, m_conn; type { TFrmEntrega } TFrmEntrega = class(TForm) BtnAgregar: TBitBtn; BtnDel: TBitBtn; Bp: TButtonPanel; DSEmpleado: TDataSource; DSConsu: TDataSource; CbEmpleado: TDBLookupComboBox; CbConsumible: TDBLookupComboBox; ILimgs: TImageList; TxtEntregar: TEdit; GroupBox1: TGroupBox; GroupBox2: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; TxtExistencia: TLabel; SGMateriales: TStringGrid; ZQ: TZQuery; procedure BtnAgregarClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure CbConsumibleChange(Sender: TObject); procedure CbConsumibleSelect(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure OKButtonClick(Sender: TObject); procedure TxtEntregarEditingDone(Sender: TObject); private Cerrar: Boolean; existencia: integer; public end; var FrmEntrega: TFrmEntrega; implementation {$R *.lfm} { TFrmEntrega } procedure TFrmEntrega.CbConsumibleSelect(Sender: TObject); begin // Obtener la existencia ZQ.Close; ZQ.SQL.Text:='select counts from inventory_stock where inventory_consumable_id = :inv'; ZQ.Params.ParamByName('inv').AsInteger:=CbConsumible.KeyValue; ZQ.Open; existencia:=ZQ.FieldByName('counts').AsInteger; TxtExistencia.Caption:='Existencia: ' + IntToStr(existencia); end; procedure TFrmEntrega.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin Cerrar:=True; end; procedure TFrmEntrega.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin CanClose:=Cerrar; end; procedure TFrmEntrega.OKButtonClick(Sender: TObject); var id_del, i: integer; begin dmconn.Conn.StartTransaction; try ZQ.Close; // Guardar relacion de entrega con el empleado ZQ.SQL.Text:='insert into inventory_deliveries(date_delivery, user_users_id)'+ ' values(:fecha, :user)'; ZQ.Params.ParamByName('fecha').AsDate:=Now; ZQ.Params.ParamByName('user').AsInteger:=CbEmpleado.KeyValue; ZQ.ExecSQL; // Obtener el id de la tabla insertada ZQ.Close; ZQ.SQL.Text:='SELECT last_insert_id() AS id'; ZQ.Open; id_del:=ZQ.FieldByName('id').AsInteger; ZQ.Close; // Crear relación de la entrega y los bienes for i:=1 to SGMateriales.RowCount - 1 do begin ZQ.SQL.Text:='insert into inventory_consumable_has_inventory_deliveries'+ '(inventory_consumable_id, inventory_deliveries_id, total_delivery) '+ 'values(:con_id, :del_id, :total)'; ZQ.Params.ParamByName('con_id').AsInteger:=StrToInt(SGMateriales.Cells[0,i]); ZQ.Params.ParamByName('del_id').AsInteger:=id_del; ZQ.Params.ParamByName('total').AsInteger:=StrToInt(SGMateriales.Cells[2,i]); ZQ.ExecSQL; // Descontar del inventario end; dmconn.Conn.Commit; Cerrar:=True; except dmconn.Conn.Rollback; end; end; procedure TFrmEntrega.TxtEntregarEditingDone(Sender: TObject); begin end; procedure TFrmEntrega.CbConsumibleChange(Sender: TObject); begin //ShowMessage(CbConsumible.DataSource.DataSet.FieldValues['id']); //TxtExistencia.Caption:='Existencia: ' + DSConsu.DataSet.Fields[2].AsString; end; procedure TFrmEntrega.BtnAgregarClick(Sender: TObject); var i: integer; id: string; begin // Verificar si ya se encuentra el consumible en la lista for i := 0 to (SGMateriales.RowCount - 1) do begin id := CbConsumible.KeyValue; if SGMateriales.Cells[0, i] = id then begin Application.MessageBox('El material a agregar ya se encuetra en el listado', 'Dato existente', MB_ICONEXCLAMATION); Exit; end; end; SGMateriales.RowCount:=SGMateriales.RowCount + 1; SGMateriales.Row:=SGMateriales.RowCount - 1; with SGMateriales do begin Cells[0, SGMateriales.Row]:=CbConsumible.KeyValue; Cells[1, SGMateriales.Row]:=CbConsumible.Text; Cells[2, SGMateriales.Row]:=TxtEntregar.Text; end; end; procedure TFrmEntrega.CancelButtonClick(Sender: TObject); begin Cerrar:=True; end; end.
unit UClassView; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,StdCtrls; type THaveNewDataEvent = procedure (sender:TObject;str:string) of object; TBeforeAddToMemoEvent = procedure (Sender: TObject) of object; TView = class(TObject) private fCount: LongInt; fFileName: string; fForm: TForm; fMemo: TMemo; fOnBeforeAddToMemo: TBeforeAddToMemoEvent; fOnNewData: THaveNewDataEvent; fPosition: LongInt; fPreloadCount: Integer; fSize: LongInt; function ExTrim(str: string): string; protected stream: TStream; procedure addToMemo(s:string); procedure createStream; procedure freeStream; function GetSize: LongInt; public constructor Create; destructor Destroy; override; function ChangeType: Integer; function GetCountStrings: LongInt; procedure LoadFile(const aFileName: string); function Read(aFromRow: Integer = -1): string; procedure Update; property FileName: string read fFileName; property Form: TForm read fForm write fForm; property Memo: TMemo read fMemo write fMemo; property PreloadCount: Integer read fPreloadCount write fPreloadCount; published property OnBeforeAddToMemo: TBeforeAddToMemoEvent read fOnBeforeAddToMemo write fOnBeforeAddToMemo; property OnNewData: THaveNewDataEvent read fOnNewData write fOnNewData; end; implementation { ************************************ TView ************************************* } constructor TView.Create; begin inherited Create; fFileName:=''; stream:=nil; fPreloadCount:=0; end; destructor TView.Destroy; begin freeStream(); inherited Destroy; end; procedure TView.addToMemo(s:string); begin if (Assigned(fOnBeforeAddToMemo)) then fOnBeforeAddToMemo(self); memo.Lines.Add(Utf8ToAnsi(s)); end; function TView.ChangeType: Integer; begin end; procedure TView.createStream; begin stream:=TFileStream.Create(FileName,fmOpenRead); //TFileStream(stream).LoadFromFile(FileName,fmOpenRead); end; function TView.ExTrim(str: string): string; var space: string; begin space:='[<'+IntToStr(random(1000))+'space'+IntToStr(random(1000))+'>]'; result:=StringReplace(str,' ',space,[rfReplaceAll, rfIgnoreCase]); result:=StringReplace(Trim(result),space,' ',[rfReplaceAll, rfIgnoreCase]); end; procedure TView.freeStream; begin if (stream<>nil) then stream.free; stream:=nil; end; function TView.GetCountStrings: LongInt; var s: AnsiChar; cSize: LongInt; begin createStream(); result:=0; try cSize:=stream.Read(s,sizeof(s)); if (cSize>0) then begin result:=1; while (cSize>0) do begin cSize:=stream.Read(s,sizeof(s)); if (Ord(s)=10) then result:=result+1; end; end; except end; freeStream(); //------------------------------- end; function TView.GetSize: LongInt; begin try createStream(); result := stream.Size; freeStream(); except result := -1; end; end; procedure TView.LoadFile(const aFileName: string); begin fFileName:=aFileName; fMemo.Clear; fSize :=GetSize(); if (fPreloadCount>0) then begin fCount:=GetCountStrings(); if (fCount>fPreloadCount) then Read(fCount-fPreloadCount-1) else Read(fCount); fPosition:=fSize; end else begin fPosition:=fSize; Read(); end; end; function TView.Read(aFromRow: Integer = -1): string; const cMaxCount = 5; // максимальное кол-во строк отображаемое а хинте var cCount: Integer; s: AnsiChar; cSize: LongInt; cCursor: Integer; outString: string; cResult:TStringList; /// список строк для отображения в хинте i:integer; begin createStream(); cResult:=TStringList.Create; try cCursor:=0; outString:=''; if (aFromRow = -1) then stream.Position:=fPosition; cSize:=stream.Read(s,sizeof(s)); while ( cSize>0 ) do begin if (Ord(s) = 10) then begin cCursor:=cCursor+1; if (aFromRow = -1) or (cCursor > aFromRow) then begin if (outString<>'') then begin self.addToMemo(outString); //result:=outString; if (Trim(outString)<>'') then begin cResult.Add(ExTrim(outString)); if cResult.Count>cMaxCount then cResult.Delete(0); end; end; outString:=''; end; end else begin if (aFromRow = -1) or (cCursor > aFromRow) then outString:=outString + s; end; cSize:=stream.Read(s,sizeof(s)); end; if (outString<>'') then begin self.addToMemo(outString); //result:=outString; if (Trim(outString)<>'') then begin cResult.Add(ExTrim(outString)); if cResult.Count>cMaxCount then cResult.Delete(0); end; end; // формируем спиоск строк к отображению в хинте cCount:=cMaxCount; if (cResult.Count<cCount) then cCount:=cResult.Count; for i := 0 to cCount-1 do begin if (i>0) then result:=result+#13#10; result:=result+cResult.Strings[i]; end; // ---------------------------------------- except end; cResult.Free; freeStream(); end; procedure TView.Update; var cCurrentSize: LongInt; cLast: string; begin cCurrentSize:=GetSize(); if (cCurrentSize < fSize ) then begin memo.Clear; fSize := cCurrentSize; fPosition:=fSize; end else if (cCurrentSize > fSize ) then begin fSize := cCurrentSize; cLast :=Read(); if (Assigned(fOnNewData)) then fOnNewData(self,cLast); SendMessage(memo.Handle, EM_LINESCROLL, 0,memo.Lines.Count); fPosition:=fSize; end; end; end.
// Debugger interface // Works close together with Breakpoints.pas, LWPEdit.pas and Backtrace.pas. // Breakpoints keeps a list of breakpoints for each window. // LWPEdit shows breakpoints and current position. // Backtrace deals with the parsing of input for variable display. // This unit communicates with GDB, handles the display in the Lightbugs window, and extracts information from its responses (although this resonsability is mostly left to Backtrace.pas). // One more kind to catch: //ParseReplyLLDB parses "test(11280,0xa04d31a8) malloc: *** error for object 0x1b9b000: pointer being freed was not allocated" //ParseReplyLLDB parses "*** set a breakpoint in malloc_error_break to debug" {$mode macpas} unit Lightbugs; interface uses strutils, MacOSAll, ProcessUtils, LWPGlobals, TransDisplay, FileUtils, // SkelView, Console, TransSkel4, Settings, cprocintf, UtilsTypes, Splitter, Scroller, QDCG, Backtrace, SetVariableDialog, SimpleParser, sysutils; procedure DoDebugMenu (item: integer); {Menu handler} procedure BugsRun; function BugsRunning: Boolean; procedure BugsRunWithDebug(theSpec: FSSpecString); procedure BugsChangedBreakpoints(theWind: WindowPtr; line: Longint; add: Boolean); procedure BugsRunTo(theWind: WindowPtr; line: Longint); // Set temporary breakpoint and run procedure BugsInit; procedure BugsShowWindow; procedure BugsShowObserveWindow; procedure BugsShowGDBWindow; //procedure BugsGDB; const kBugsStepOver = 0; kBugsStepIn = 1; kBugsStepOut = 2; procedure BugsDoStep(cmd: Longint); procedure BugsStop; var OKtoSetBreaks : boolean = true; // Access local variables function BugsGetPrompt: AnsiString; function BugsDebuggerIsGDB: Boolean; implementation uses Breakpoints, LWPEdit, AlertsUtils, AboutWindowUnit, DirectGDB; var // bugsWind: WindowPtr; bugs1Wind: WindowPtr; observeWind: WindowPtr; // directgdbWind: WindowPtr; gBugsRunning: Boolean; canNotContinue: Boolean; // NEW THINGS for switching between GDB and LLDB // These are set by BugsRunWithDebug var lengthDBName: Longint = 3; // 3, 4 debugName: AnsiString = 'gdb'; gDebuggerPrompt: AnsiString = '(gdb) '; debugPath: AnsiString; gDebuggerIsGDB: Boolean = true; gPascalMode: Boolean = false; // Access local variables function BugsGetPrompt: AnsiString; begin BugsGetPrompt := gDebuggerPrompt; end; function BugsDebuggerIsGDB: Boolean; begin BugsDebuggerIsGDB := gDebuggerIsGDB; end; procedure ResizeVariables; forward; // In some cases it is sufficient to build a list of simplistic tokens // using a few delimiter characters // Variant of SplitStringToList with other set. // Make a common one with the list as parameter? Yes! function ParseToWords(s1: AnsiString): StringArr; var i: Longint; theStrings: StringArr; s, returnedLine: AnsiString; begin SetLength(theStrings, 0); s := s1; i := 1; while i < Length(s) do begin if s[i] in [#10, #13, ' '] then begin // CRLF first on line, ignored if i = 1 then begin Delete(s, 1, 1); i := 1; end else // Not first in line, save line begin returnedLine := Copy(s, 1, i-1); Delete(s, 1, i); // WriteLn('TR€FF i ', i, ':"', returnedLine, '"'); SetLength(theStrings, Length(theStrings)+1); theStrings[Length(theStrings)-1] := returnedLine; i := 1; end end else i := i + 1; end; // No more CRLF, save the rest if not empty if s <> '' then begin SetLength(theStrings, Length(theStrings)+1); theStrings[Length(theStrings)-1] := s; end; return theStrings; end; procedure UpdateExpressions; forward; type FileNameRec = record name: AnsiString; fileName: AnsiString; value: AnsiString; varType: AnsiString; // type? typeId: Longint; // array/pekare/record borde noteras // last known value? end; var globalVariables: array of VarInfoRec; // FileNameRec; localVariables: array of VarInfoRec; // FileNameRec; // Type numbers - moved to Backtrace (*const kScalarOrUnknown = 0; kArray = 1; kPointer = 2; kRecord = 3; kObject = 4; kStringPointer = 5;*) // Obsolete procedure ParseType(ptypeReply: AnsiString; var typeNumber: Longint); // Skall till fŠltet ??? // ptypeReply Šr utan inledande och avslutande skrot // Identify what type it is: scalar, array, pointer, record var i: Longint; words: StringArr; begin WriteLn(ptypeReply, ' should be parsed. --------------'); if Copy(ptypeReply, 1, 5) = '^Char' then begin WriteLn(ptypeReply, ' It is a string pointer! --------------'); typeNumber := kStringPointer; end else if ptypeReply[1] = '^' then begin WriteLn('It is a pointer! --------------'); typeNumber := kPointer; // FŒnga namnet? Men det har vi nog redan? end else if Copy(ptypeReply, 1, 5) = 'array' then begin WriteLn('It is an array! --------------'); i := 8; while ptypeReply[i] in ['0'..'9'] do i+=1; WriteLn('It starts at ', Copy(ptypeReply, 8, i-8), ' --------------'); typeNumber := kArray; // arrayBase := end else begin WriteLn('Trying ParseToWords on ', ptypeReply); words := ParseToWords(ptypeReply); WriteLn('ParseToWords gave ', Length(words), ' words.'); // Kolla att words Šr lŒng nog if High(words) < 4 then begin WriteLn('It is probably a scalar since words is too short --------------'); typeNumber := kScalarOrUnknown; end else if words[4] = 'record' then begin WriteLn(words[2], ' is an record ', ' --------------'); typeNumber := kRecord; end else begin WriteLn('It is probably a scalar since ', words[4], ' was not record --------------'); typeNumber := kScalarOrUnknown; end; end; end; procedure BugsEnable; begin gBugsRunning := true; canNotContinue := false; EnableMenuItem(debugMenu, 4); EnableMenuItem(debugMenu, 5); EnableMenuItem(debugMenu, 6); EnableMenuItem(debugMenu, 7); end; procedure BugsDisable; begin gBugsRunning := false; canNotContinue := false; DisableMenuItem(debugMenu, 4); DisableMenuItem(debugMenu, 5); DisableMenuItem(debugMenu, 6); DisableMenuItem(debugMenu, 7); end; // For the already available globals, get current values procedure UpdateGlobalsValues; var i: Longint; repl: AnsiString; begin for i := 0 to High(globalVariables) do begin repl := ReadToPrompt(gCurrentProcess, 'print ' + globalVariables[i].name, gDebuggerPrompt); repl := Copy(repl, 1, Length(repl) - 4 - lengthDBName); // Remove (gdb) (* for j := 1 to Length(repl) do if repl[j] = '=' then begin repl := Copy(repl, j+2, Length(repl)); break; end;*) globalVariables[i].value := repl; WriteLn('repl = ', repl, ' for ', globalVariables[i].name); globalVariables[i].value := ParseVariable(repl); end; end; // Called (once only) at launch of Pascal program. Globals are found with "info variables" and parsed here. procedure ParseGlobals(s: AnsiString); var l, words: StringArr; currentFile: AnsiString; i, k: Longint; begin currentFile := 'None'; // Delete everything after "Non-debugging" k := pos('Non-debugging', s); // stuff after this is junk for us if k > 0 then delete(s, k, length(s) - k); l := SplitStringToList(s); // WriteLn('List length = ', Length(l)); for i := Low(l) to High(l) do begin (* if l[i] = 'Non-debugging symbols:' then begin WriteLn('Non-debugging symbols found at ', i); Exit(ParseGlobals); end;*) words := ParseToWords(l[i]); if Length(words) >= 2 then if words[0] = 'File' then begin currentFile := words[1]; WriteLn('Current file: ', currentFile); end; if Length(words) >= 3 then begin if words[0] = 'static' then // How about non-static variables? begin SetLength(globalVariables, Length(globalVariables)+1); globalVariables[High(globalVariables)].name := words[1]; // globalVariables[High(globalVariables)].fileName := currentFile; // WriteLn('Found global variable: ', words[1], ' in ', currentFile); WriteLn('type: ', words[3]); // Borde ta resten av raden // Get type globalVariables[High(globalVariables)].varType := Copy(l[i], Length(words[0]) + Length(words[1]) + Length(words[2]) + 3, Length(l[i])); end; end; end; end; var gParseScopeNeeded: Boolean; // Do we need to run UpdateState? gParseScopeTimer: EventLoopTimerRef; // Shall return file name, and NOT read the file. procedure ParseReplyBAD(s: AnsiString; var filename: AnsiString; var linenumber: Longint; var linenumberstring: AnsiString); var l: StringArr; path, rownumber, charnumber: AnsiString; i, p, oldp, rowNum, err: Longint; //fileSpec: FSSpecString; pos, tokenStart, tokenEnd, tokenType, editIndex: Longint; tokenValue: AnsiString; begin filename := ''; linenumber := 0; linenumberstring := ''; // Parse s! // Likely contents: // SOMETIMES Breakpoint 2, ZAP (I=1) at forever.pas:10 // SOMETIMES ZAP (I=0) at forever.pas:9 // ALWAYS /Users/ingemar/Lightweight IDE/The Bug/forever.pas:10:110:beg:0x189a // SOMETIMES Program exited normally. Done! // Sometimes (step): // 10 data := 'Hej hopp 123 -456 3.4 fil.namn'; (Only line number useful!) // 1) Starts with space? Then it is an info-row. No, SUB SUB! // - Path up to ":" // - Row number // - Some other numberr??? // - Some more than I don't understand yet. // 2) Starts with Breakpoint? // - Breakpoint number, comma. // - File name, position // 3) Starts with something else! // - Function name // - Argument in parentheses, should be saved, show // - File name, row number // LLDB: * thread #1: tid = 0x5c41a, 0x00010f67 SimpleParserTest`PASCALMAIN + 23 at SimpleParserTest.pas:10, queue = 'com.apple.main-thread', stop reason = one-shot breakpoint 1 // GDB: Temporary breakpoint 1, PASCALMAIN () at SimpleParserTest.pas:10 // But for LLDB... // Typical lines: // At breakpoint: //Process 3571 stopped //* thread #1: tid = 0x42e42, 0x00011031 SimpleParserTest`PASCALMAIN + 225 at SimpleParserTest.pas:15, queue = 'com.apple.main-thread', stop reason = step over // frame #0: 0x00011031 SimpleParserTest`PASCALMAIN + 225 at SimpleParserTest.pas:15 // 12 repeat // 13 SimpleParserGetToken(data, pos, tokenStart, tokenEnd, tokenType, tokenValue); // 14 WriteLn('"', tokenValue, '", ', tokenType); //-> 15 until pos >= Length(data); // 16 // 17 WriteLn('GDB style'); // 18 data := 'Breakpoint 3 at 0x1164d: file test.pas, line 11.'; // 1) Starts with *: Search for "at", then get file name and line number! // What more? // -> shows line number only... Not so interesting. // At step: Same! :) // Lacks detection of end of program! // Program end in GDB: // Program exited? (Important! Old GDB vs new!) // Program end in LLDB: // Process 7858 exited with status = 0 (0x00000000) // Should also detect crashes! // Don't quit the debugger until something else happens, like a compilation. "run" or "continue" as far as possible. l := SplitStringToList(s); for i := 0 to High(l) do if Length(l[i]) > 0 then begin HelpAppendLn('ParseReply parses "'+l[i]+'"'); pos := 1; SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); if tokenValue = #26 then begin // Old parser - parses "standard info line" of GDB p := 3; while p < Length(l[i]) do // Search to ':' begin p := p + 1; if l[i][p] = ':' then Leave; end; // WriteLn('Found : at ', p); path := Copy(l[i], 3, p-3); WriteLn('Found path = ', path); oldp := p; while p < Length(l[i]) do // Search to ':' begin p := p + 1; if l[i][p] = ':' then Leave; end; rownumber := Copy(l[i], oldp+1, p-oldp-1); WriteLn('Found row number = ', rownumber); Val(rownumber, rowNum, err); if err <> 0 then begin StringToNum(rowNumber, rowNum); // Always works (but may generate strange values) WriteLn('GARBAGE WARNING: ', rowNumber); end; oldp := p; while p < Length(l[i]) do // Search to ':' begin p := p + 1; if l[i][p] = ':' then Leave; end; charnumber := Copy(l[i], oldp+1, p-oldp-1); WriteLn('Found char number = ', charnumber); // Return result! filename := path; linenumber := rowNum; linenumberstring := rowNumber; end; if (tokenValue = '*') or (tokenValue = 'Breakpoint') or (tokenValue = 'Temporary') then // * for LLDB, "Breakpoint" for GDB. Then this works for both? begin // Search for "at" repeat SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); until (pos >= Length(l[i])) or (tokenValue = 'at'); if pos < Length(s) then begin // Now get: // Filename (may include "-" etc!) SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, filename); // Set gPascalMode depending on current file type! gPascalMode := GetExtensionType(filename) = kExtTypePascal; // Colon SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); // Row number SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, linenumberstring); Val(linenumberstring, linenumber); HelpAppendLn('Found '+filename+' at '+linenumberstring); if Length(filename) > 0 then if linenumber > 0 then begin editIndex := FindOrOpen(fileName, debugPath); if editIndex > 0 then begin fileName := GetPathFromIndex(editIndex); // UpdateFinger(fileName, linenumber); // gParseScopeNeeded := true; end; end; end; // Exit(ParseReply); end; // else // HelpAppendLn('Found nothing'); end; end; // OLD parser, works for GDB procedure ParseReply(s: AnsiString; var filename: AnsiString; var linenumber: Longint; var linenumberstring: AnsiString); var l: StringArr; path, rownumber, charnumber: AnsiString; i, p, oldp, rowNum, err: Longint; //fileSpec: FSSpecString; pos, tokenStart, tokenEnd, tokenType, editIndex: Longint; tokenValue: AnsiString; begin filename := ''; linenumber := 0; linenumberstring := ''; // Parse s! // Likely contents: // SOMETIMES Breakpoint 2, ZAP (I=1) at forever.pas:10 // SOMETIMES ZAP (I=0) at forever.pas:9 // ALWAYS /Users/ingemar/Lightweight IDE/The Bug/forever.pas:10:110:beg:0x189a // SOMETIMES Program exited normally. Done! // Sometimes (step): // 10 data := 'Hej hopp 123 -456 3.4 fil.namn'; (Only line number useful!) // 1) Starts with space? Then it is an info-row. No, SUB SUB! // - Path up to ":" // - Row number // - Some other numberr??? // - Some more than I don't understand yet. // 2) Starts with Breakpoint? // - Breakpoint number, comma. // - File name, position // 3) Starts with something else! // - Function name // - Argument in parentheses, should be saved, show // - File name, row number // GDB: Temporary breakpoint 1, PASCALMAIN () at SimpleParserTest.pas:10 // Program end in GDB: // Program exited? (Important! Old GDB vs new!) l := SplitStringToList(s); // WriteLn('List length = ', Length(l)); for i := Low(l) to High(l) do begin WriteLn('Parsing reply "', l[i], '"'); if Ord(l[i][1]) = 26 then // Double SUB = standard info line begin p := 3; while p < Length(l[i]) do // Search to ':' begin p := p + 1; if l[i][p] = ':' then Leave; end; // WriteLn('Found : at ', p); path := Copy(l[i], 3, p-3); WriteLn('Found path = ', path); oldp := p; while p < Length(l[i]) do // Search to ':' begin p := p + 1; if l[i][p] = ':' then Leave; end; rownumber := Copy(l[i], oldp+1, p-oldp-1); WriteLn('Found row number = ', rownumber); Val(rownumber, rowNum, err); if err <> 0 then begin StringToNum(rowNumber, rowNum); // Always works (but may generate strange values) WriteLn('GARBAGE WARNING: ', rowNumber); end; oldp := p; while p < Length(l[i]) do // Search to ':' begin p := p + 1; if l[i][p] = ':' then Leave; end; charnumber := Copy(l[i], oldp+1, p-oldp-1); WriteLn('Found char number = ', charnumber); // Return result! filename := path; linenumber := rowNum; linenumberstring := rowNumber; end else if Length(l[i]) >= 14 then begin // if l[i] = 'Program exited normally.' then // 'Program exited normally.' if Copy(l[i], 1, 14) = 'Program exited' then // 'Program exited normally.' begin canNotContinue := true; // Indicated "run" instead of "continue" //haltedButCanBeRestared := true; // WHat should I call this? // BugsDisable; // ProcessTerminate(gCurrentProcess); end; if l[i][1] = '[' then // Bracket indicates possible "exited normally" in official GDB begin if Copy(l[i], Length(l[i]) - 15, 15) = 'exited normally' then begin canNotContinue := true; // Indicated "run" instead of "continue" // haltedButCanBeRestared := true; // WHat should I call this? end; end; if Copy(l[i], 1, 23) = 'Program received signal' then // TEST FOR CRASH HERE begin canNotContinue := true; // Indicated "run" instead of "continue" // programCrashed := true; end; end else begin // WriteLn('Not interesting'); // Borde funktion och argument fŒngas upp? end; end; end; // Parses data coming from LLDB at any time. Especially stop at breakpoints. // Shall return file name, and NOT read the file. procedure ParseReplyLLDB(s: AnsiString; var filename: AnsiString; var linenumber: Longint; var linenumberstring: AnsiString); var l: StringArr; path, rownumber, charnumber: AnsiString; i, p, oldp, rowNum, err: Longint; //fileSpec: FSSpecString; pos, tokenStart, tokenEnd, tokenType, editIndex: Longint; tokenValue: AnsiString; begin filename := ''; linenumber := 0; linenumberstring := ''; (* START: Process 45344 launched: '/Users/ingemar/test' (i386) STOPP VID BRYTPUNKT: Process 45344 stopped * thread #1: tid = 0x5c288c, 0x00010fa8 test`PASCALMAIN + 24 at test.pas:32, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 frame #0: 0x00010fa8 test`PASCALMAIN + 24 at test.pas:32 STOPP VID TEMPOR€R BRYTPUNKT (tbreak): Process 45381 stopped * thread #1: tid = 0x5c5fce, 0x00010f98 test`PASCALMAIN + 24 at test.pas:32, queue = 'com.apple.main-thread', stop reason = one-shot breakpoint 1 frame #0: 0x00010f98 test`PASCALMAIN + 24 at test.pas:32 STOPP VID CTRL-C Process 45352 stopped * thread #1: tid = 0x5c2be8, 0x9040cf7a libsystem_kernel.dylib`mach_msg_trap + 10, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP frame #0: 0x9040cf7a libsystem_kernel.dylib`mach_msg_trap + 10 STOPP VID BAD ACCESS Process 45371 stopped * thread #1: tid = 0x5c41a4, 0x0001110b test`PASCALMAIN + 395 at test.pas:44, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=2, address=0x0) frame #0: 0x0001110b test`PASCALMAIN + 395 at test.pas:44 STOPP F…R ATT "RUN" KR€VER BEKR€FTELSE There is a running process, kill it and restart?: [Y/n] *) // LLDB: * thread #1: tid = 0x5c41a, 0x00010f67 SimpleParserTest`PASCALMAIN + 23 at SimpleParserTest.pas:10, queue = 'com.apple.main-thread', stop reason = one-shot breakpoint 1 // Typical lines: // At breakpoint: //Process 3571 stopped //* thread #1: tid = 0x42e42, 0x00011031 SimpleParserTest`PASCALMAIN + 225 at SimpleParserTest.pas:15, queue = 'com.apple.main-thread', stop reason = step over // frame #0: 0x00011031 SimpleParserTest`PASCALMAIN + 225 at SimpleParserTest.pas:15 // 12 repeat // 13 SimpleParserGetToken(data, pos, tokenStart, tokenEnd, tokenType, tokenValue); // 14 WriteLn('"', tokenValue, '", ', tokenType); //-> 15 until pos >= Length(data); // 16 // 17 WriteLn('GDB style'); // 18 data := 'Breakpoint 3 at 0x1164d: file test.pas, line 11.'; // 1) Starts with *: Search for "at", then get file name and line number! // What more? // -> shows line number only... Not so interesting. // At step: Same! :) // Lacks detection of end of program! // Program end in LLDB: // Process 7858 exited with status = 0 (0x00000000) // Should also detect crashes! // Don't quit the debugger until something else happens, like a compilation. "run" or "continue" as far as possible. l := SplitStringToList(s); for i := 0 to High(l) do if Length(l[i]) > 0 then begin HelpAppendLn('ParseReplyLLDB parses "'+l[i]+'"'); pos := 1; SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); if (tokenValue = '*') then // * for LLDB, "Breakpoint" for GDB. Then this works for both? begin // Search for "at" repeat SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); until (pos >= Length(l[i])) or (tokenValue = 'at'); if pos < Length(s) then begin // Now get: // Filename (may include "-" etc!) SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, filename); // Set gPascalMode depending on current file type! gPascalMode := GetExtensionType(filename) = kExtTypePascal; // Colon SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); // Row number SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, linenumberstring); Val(linenumberstring, linenumber); HelpAppendLn('Found '+filename+' at '+linenumberstring); WriteLn('Found '+filename+' at '+linenumberstring); if Length(filename) > 0 then if linenumber > 0 then begin editIndex := FindOrOpen(fileName, debugPath); if editIndex > 0 then begin fileName := GetPathFromIndex(editIndex); // UpdateFinger(fileName, linenumber); // gParseScopeNeeded := true; end; end; // Sšk till "stop", fšr att sška efter "stop reason". repeat SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); until (pos >= Length(l[i])) or (tokenValue = 'stop'); if pos < Length(l[i]) then // was "s" begin SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); // reason SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); // = // Resten Šr "stop reason" tokenValue := Copy(l[i], pos, Length(l[i])); WriteLn('FOUND stop reason: ', tokenValue); HelpAppendLn('FOUND stop reason: ' + tokenValue); WriteLn('FOUND stop reason: ', l[i]); HelpAppendLn('FOUND stop reason: ' + l[i]); // At this point we can report the stop reason as needed! // Mark the program as stopped? Mark as continuable or re-runnable? //FOUND stop reason: one-shot breakpoint 1 //FOUND stop reason: EXC_BAD_ACCESS (code=2, address=0x0) // First word of stop reason SimpleParserGetToken(l[i], pos, tokenStart, tokenEnd, tokenType, tokenValue); // = if tokenValue = 'EXC_BAD_ACCESS' then begin canNotContinue := true; MessageAlert('Bad access exception', 'You can run to start over or cmd-. to halt.'); end; // Detect SIGSTOP! // Where do I catch "one-shot breakpoint 1"? end; end; end else // Some messages to detect: // "run" med kšrande program: // There is a running process, kill it and restart?: [Y/n] // "quit" med kšrande program: // Quitting LLDB will kill one or more processes. Do you really want to proceed: [Y/n] // "continue" nŠr programmet inte kšrs -> run // error: Process must be launched. // Process exited: // Process 45548 exited with status = 0 (0x00000000) if tokenValue = 'Process' then begin // WriteLn('PROCESS: ', l[i]); // HelpAppendLn('PROCESS: ' + l[i]); SimpleParserGetToken(l[i], pos, tokenType, tokenValue); // process number SimpleParserGetToken(l[i], pos, tokenType, tokenValue); // exited if tokenValue = 'exited' then begin // Save status! canNotContinue := true; end; // Process number // exited // with // status // = // error number // ( // error number in hex // ) // If "exited", save status // Others? end else if tokenValue = 'There' then begin // WriteLn('THERE: ', l[i]); // HelpAppendLn('THERE: ' + l[i]); if Copy(l[i], 1, 55) = 'There is a running process, kill it and restart?: [Y/n]' then begin ProcessWrite(gCurrentProcess, 'Y' + Char(10)); // Send "Y"! end; end else if tokenValue = 'error' then begin // WriteLn('ERROR: ', l[i]); // HelpAppendLn('ERROR: ' + l[i]); if l[i] = 'error: Process must be launched.' then begin ProcessWrite(gCurrentProcess, 'run' + Char(10)); // Send "run"! end; end; end; end; procedure UpdateVariablesWindow; var control: ControlRef; begin // I really just need to inval the variables view // GetWindowPortBounds(bugsWind, bounds); // InvalWindowRect(bugsWind, bounds); // Update data for variables field 2 (zoom in) and 3 (memory) ResizeVariables; // Calls UpdateVariables2Data, UpdateVariables3Data VMGetControl( bugs1Wind, 'Vari', 0, control); HIViewSetNeedsDisplay(control, true); VMGetControl( bugs1Wind, 'Vari', 1, control); HIViewSetNeedsDisplay(control, true); VMGetControl( bugs1Wind, 'Vari', 2, control); HIViewSetNeedsDisplay(control, true); VMGetControl( bugs1Wind, 'Vari', 3, control); HIViewSetNeedsDisplay(control, true); end; var backTraceVars: OutArrType; backTraceStack: StringArr; (* // Anropas av BugsData, typiskt nŠr en ny plats i filen uppnŒs. // NŒgot av en central punkt fšr datasamling, men skumt namn fšr detta. procedure ParseReplyScopeStatus(msg: AnsiString); var s, rownumberstring, filename: AnsiString; rownumber: Longint; begin ParseReply(msg, filename, rownumber, rownumberstring); // WriteLn('Parsed reply and got "', filename, '", (', rownumberstring, ')', rownumber); if filename = '' then Exit(ParseReplyScopeStatus); if rownumber <= 0 then Exit(ParseReplyScopeStatus); // WriteLn('Parsed reply OK, get backtrace and analyze'); // Set a flag that we want "info scope" and "backtrace full" within a certain time! // And do it ONLY if nothing else happened! // info scope - kan bli inaktuell av backtrace all s := ReadToPrompt(gCurrentProcess, 'info scope ' + rownumberstring, gDebuggerPrompt); ParseScope(s); // NYTT: backtrace all s := ReadToPrompt(gCurrentProcess, 'backtrace full', gDebuggerPrompt); // WriteLn(s); ParseBacktrace(s, backTraceVars, backTraceStack); // WriteLn('Backtrace returned ', Length(backTraceVars), ' variables and ', Length(backTraceStack), ' stack levels.'); GetStatus; // For additions above UpdateExpressions; UpdateGlobalsValues; UpdateVariablesWindow; // Finally, tell the editor. filename + rownumberstring // WriteLn('Please update finger to ', fileName); UpdateFinger(fileName, rownumber); end; *) // Sreehari's LLDB functions // rewritten by Ingemar to use the SimpleParser, then unified to a single function since the format is the same for both cases. //Example: //Global variables for /Users/ingemar/test.pas in /Users/ingemar/test: //(ANSISTRING) S = 0x00000000 //(SMALLINT) X = 0 //(SMALLINT) Y = 0 //(SMALLINT) Z = 0 // (<anonymous struct>) R = (A = 0, B = 0, C = 0) // (RECTYPE) RR = (D = 0, E = 0, F = 0) // (SMALLINT [3]) ARR = ([0] = 0, [1] = 0, [2] = 0) // Make the value look nicer procedure BeautifyValue(var value: AnsiString); begin if gPascalMode then begin if value = '0x00000000' then value := 'nil'; if Copy(value, 1, 2) = '0x' then value := '$' + Copy(value, 3, Length(value)); end; end; procedure ParseVariablesLLDB(s:AnsiString; var variableList: OutArrType);//; fileName: AnsiString); var i:LongInt; position, tokenStart, tokenEnd, tokenType : LongInt; tokenValue, typeName, variableName, variableValue, stringValue: AnsiString; l: StringArr; procedure StoreVariable(typeId: Longint; value, name: AnsiString); var typeIds: AnsiString; begin SetLength(variableList, Length(variableList)+1); BeautifyValue(value); variableList[High(variableList)].name := name; // Probably upper case for FPC code if gPascalMode then MatchCase(name); // Will this know which file to search? variableList[High(variableList)].displayname := name; // Corrected to match the code variableList[High(variableList)].typeId := typeId; variableList[High(variableList)].value := value; // variableList[High(variableList)].fileName := fileName; Str(typeId, typeIds); // HelpAppendLn('ParseVariablesLLDB found: ' + name + ' with value ' + value + ' and type ' + typeIds); end; begin HelpAppendLn('ParseVariablesLLDB parses: '#13'-----------------'#13 + s + #13'-----------------'); SetLength(variableList, 0); l := SplitStringToList(s); for i := 0 to High(l) do begin position := 1; SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, tokenValue); if tokenValue = '(' then begin typeName := ''; // This assumed (SMALLINT) etc - but it might be more than one identifier! (E.g. *) while (position < Length(l[i])) and (tokenValue <> ')') and (tokenValue <> '[') do begin SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, tokenValue); typeName := typeName + tokenValue; end; // SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, typeName); // SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, tokenValue); if tokenValue = ')' then begin SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, variableName); SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, tokenValue); // = if tokenValue = '=' then begin SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, variableValue); // If the value is hex, then a string might follow! if tokenType = kNumericToken then // Scalar number! begin // Store! StoreVariable(kScalarOrUnknown, variableValue, variableName); end; if tokenType = kHexToken then begin SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, stringValue); // Store! if tokenType = kStringToken then StoreVariable(kStringPointer, stringValue, variableName) else StoreVariable(kScalarOrUnknown, variableValue, variableName); end; // But how about records?! (RECTYPE) RR = (D = 0, E = 0, F = 0) // Can this be an object? if variableValue = '(' then begin // Store! StoreVariable(kRecord, '(record)', variableName); end; // { may be a complex struct. if variableValue = '{' then begin // Store! StoreVariable(kRecord, '(record)', variableName); end; end; end else if tokenValue = '[' then // array! begin // And arrays! (SMALLINT [3]) ARR = ([0] = 0, [1] = 0, [2] = 0) // Parse until we find the name! repeat SimpleParserGetToken(l[i], position, tokenStart, tokenEnd, tokenType, variableName); until (position >= Length(l[i])) or (tokenType = kAlphaNumericToken); // Store! StoreVariable(kArray, '(array)', variableName); end; end; end; end; // End of Sreehari's LLDB functions // Replaces ParseReplyScopeStatus // To be called some time after BugsData! procedure UpdateState(theTimer: EventLoopTimerRef; userData: Pointer); MWPascal; var s{, rownumberstring, filename}: AnsiString; // rownumber: Longint; begin RemoveEventLoopTimer(gParseScopeTimer); gParseScopeTimer := nil; if not gParseScopeNeeded then Exit(UpdateState); if not ProcessRunning(gCurrentProcess) then Exit(UpdateState); // info scope - replaced by backtrace full // s := ReadToPrompt(gCurrentProcess, 'info scope ' + rownumberstring, gDebuggerPrompt); // ParseScope(s); // if debugName = 'gdb' then if gDebuggerIsGDB then begin // backtrace full for locals s := ReadToPrompt(gCurrentProcess, 'backtrace full', gDebuggerPrompt); ParseBacktrace(s, backTraceVars, backTraceStack); end else begin // ta v for globals // fr v for locals s := ReadToPrompt(gCurrentProcess, 'ta v', gDebuggerPrompt); ParseVariablesLLDB(s, globalVariables); //(lldb) ta v //Global variables for /Users/ingemar/SimpleParserTest.pas in /Users/ingemar/SimpleParserTest: //(ANSISTRING) DATA = 0x000303fc "Hej hopp 123 -456 3.4 fil.namn" //(LONGINT) POS = 0 //(LONGINT) TOKENSTART = 0 //(LONGINT) TOKENEND = 0 //(LONGINT) TOKENTYPE = 0 //(ANSISTRING) TOKENVALUE = 0x00000000 s := ReadToPrompt(gCurrentProcess, 'fr v', gDebuggerPrompt); ParseVariablesLLDB(s, backTraceVars); // backTraceVars, backTraceStack); // Varfšr inte globalVariables/localVariables VarInfoRec? // Varfšr OutArrType + StringArr? // Jo, OutArrType = array av VarInfoRec! //(lldb) fr v //(ANSISTRING) DATA = 0x000303fc "Hej hopp 123 -456 3.4 fil.namn" //(LONGINT) POS = 1 //(LONGINT) TOKENSTART = 0 //(LONGINT) TOKENEND = 0 //(LONGINT) TOKENTYPE = 0 //(ANSISTRING) TOKENVALUE = 0x00000000 //(ANSISTRING) S = 0x00000000 //(LONGINT) BUFFERLENGTH = 2 //(BOOLEAN) HEXFLAG = false //(CHAR) CR = <empty constant data> //(CHAR) LF = <empty constant data> //(CHAR) TAB = <empty constant data> // Can we also get the stack for LLDB? To put in the backTraceStack? end; DirectGDBGetStatus; // For DirectGDB UpdateExpressions; if gDebuggerIsGDB then // if debugName = 'gdb' then UpdateGlobalsValues; // For LLDB, globals are updated above by "ta v" UpdateVariablesWindow; gParseScopeNeeded := false; end; procedure QueueUpdateState; begin if gParseScopeTimer <> nil then RemoveEventLoopTimer(gParseScopeTimer); InstallEventLoopTimer (GetMainEventLoop(), kEventDurationSecond, 0, UpdateState, nil, gParseScopeTimer); end; procedure BugsStop; var pid: Longint; begin // Sending a plain ctrl-C does not help. // if gBugsRunning then // ProcessWrite(gCurrentProcess, #3); // This is supposed to be a ctrl-C but doesn't work either. // (but it works in 10.7!) if gBugsRunning then if gCurrentProcess <> nil then begin WriteLn('*** BugsStop! BugsStop! Waiting at the BugsStop!'); pid := kill(gCurrentProcess^.pid, SIGINT); // pid := kill(gCurrentProcess^.pid, SIGTRAP); // Terminates // pid := kill(gCurrentProcess^.pid, SIGABRT); // Terminates end; end; procedure BugsDoStep(cmd: Longint); var //s: AnsiString; cmdStr: AnsiString; begin case cmd of kBugsStepOver: cmdStr := 'next'; kBugsStepIn: cmdStr := 'step'; kBugsStepOut: cmdStr := 'finish'; end; // WriteLn(cmdStr); if gBugsRunning then if cmdStr <> '' then if gCurrentProcess <> nil then ProcessWrite(gCurrentProcess, cmdStr + Char(10)); // DUGER INTE! Ta svaret med vanlig kšrning? // s := ReadToPrompt(gCurrentProcess, cmdStr, gDebuggerPrompt); // SetDView(bugsWind, 'Stat', 0); // DisplayString(s); // ParseReplyScopeStatus(s); end; // Run data callback // This procedure collects data when running modelessly // Echoes to the message window. // Every line is fed to ParseReplyScopeStatus for analysis, // and then ParseReplyScopeStatus may issue more commands for // inspecting variables etc. // NO - we call ParseReply for imminent data, then queue a call to PasceScope! procedure BugsData(oneLineOfData: AnsiString; privateData: Pointer); var // {i,} limit: Longint; {s,} rownumberstring, filename: AnsiString; rownumber: Longint; const FF = Char(12); // Form feed = ASCII(12). BEL = Char(7); // Bell begin WriteLn('BugsData "', oneLineOfData, '"'); //HelpAppendLn('BugsData "' + oneLineOfData + '"'); // Not line by line! // Search for FF character! // But why here, why not in Console? Moved there 160402. (* limit := 1; for i := 1 to Length(oneLineOfData) do begin if oneLineOfData[i] = FF then begin HelpClear; limit := i+1; // Send from here end; if oneLineOfData[i] = BEL then SysBeep(1); end;*) // if limit = 1 then HelpAppend(oneLineOfData); // if no FF // else // HelpAppend(Copy(oneLineOfData, limit, Length(oneLineOfData))); HelpForceUpdate; // ParseReplyScopeStatus(oneLineOfData); // NEW: ParseReply, then queue a request to "info scope" and "backtrace full" if gDebuggerIsGDB then ParseReply(oneLineOfData, filename, rownumber, rownumberstring) else ParseReplyLLDB(oneLineOfData, filename, rownumber, rownumberstring); if filename = '' then Exit(BugsData); if rownumber <= 0 then Exit(BugsData); // Finally, tell the editor. filename + rownumberstring UpdateFinger(fileName, rownumber); gParseScopeNeeded := true; // Set a flag that we want "info scope" and "backtrace full" within a certain time! // And do it ONLY if nothing else happened! QueueUpdateState; (* // info scope - kan bli inaktuell av backtrace full s := ReadToPrompt(gCurrentProcess, 'info scope ' + rownumberstring, gDebuggerPrompt); ParseScope(s); s := ReadToPrompt(gCurrentProcess, 'backtrace full', gDebuggerPrompt); ParseBacktrace(s, backTraceVars, backTraceStack); GetStatus; // For additions above UpdateExpressions; UpdateGlobalsValues; UpdateVariablesWindow; *) // Finally, tell the editor. filename + rownumberstring // UpdateFinger(fileName, rownumber); end; // Run finished callback procedure BugsDone(aborted: Boolean; result: Integer; privateData: Pointer); var cleanNamePtr: StringPtr; begin writeln('**bugs done **'); cleanNamePtr := StringPtr(privateData); if aborted then HelpAppendLn('--- ' + debugName + ' ' + cleanNamePtr^ + ' stopped ---') else if result = 0 then HelpAppendLn('--- ' + debugName + ' ' + cleanNamePtr^ + ' finished ---') else HelpAppendLn('--- ' + debugName + ' ' + cleanNamePtr^ + ' finished with error ---'); HelpMainMessage(''); // Reset // ST€NG AV DEBUGGER H€R! BugsDisable; UpdateFinger(' ', -1); // No file should have the finger end; procedure BugsShowWindow; begin ShowWindow(bugs1Wind); SelectWindow(bugs1Wind); end; procedure BugsShowObserveWindow; begin ShowWindow(observeWind); SelectWindow(observeWind); end; procedure BugsShowGDBWindow; begin ShowWindow(directgdbWind); SelectWindow(directgdbWind); end; // Is this used at all? procedure DoDebugMenu (item: integer); {Menu handler} begin case item of 1: begin ShowWindow(bugs1Wind); SelectWindow(bugs1Wind); end; 3: // Step over begin BugsDoStep(kBugsStepOver); OKtoSetBreaks := false; UpdateFinger(' ', -1); // No file should have the finger while running end; 4: // Step into begin BugsDoStep(kBugsStepIn); OKtoSetBreaks := false; UpdateFinger(' ', -1); // No file should have the finger while running end; 5: // Step out begin BugsDoStep(kBugsStepOut); OKtoSetBreaks := false; UpdateFinger(' ', -1); // No file should have the finger while running end; end; end; // "run" command procedure BugsRun; //var // s: AnsiString; begin if canNotContinue then ProcessWrite(gCurrentProcess, 'run' + Char(10)) else ProcessWrite(gCurrentProcess, 'continue' + Char(10)); canNotContinue := false; // s := ReadToPrompt(gCurrentProcess, 'run', gDebuggerPrompt); // Gšr nŒgot fšr att veta att det rullar? SŒ man mŒste fŒnga upp prompt pŒ annat stŠlle? UpdateFinger(' ', -1); // No file should have the finger while running OKtoSetBreaks := false; end; function BugsRunning: Boolean; begin // True om debuggern Šr igŒng! return gBugsRunning; end; (* // User set or reset breakpoint procedure BugsChangedBreakpoints(theWind: WindowPtr; line: Longint; add: Boolean); var theSpec: FSSpecString; str: Str255; err: OSErr; s: AnsiString; actualLine: Longint; brNumber: Longint; begin if not BugsRunning then Exit(BugsChangedBreakpoints); // Filename or full path? err := GetEditFSSpec(theWind, theSpec); if err <> noErr then Exit(BugsChangedBreakpoints); NumToString(line, str); // WriteLn('BugsChangedBreakpoints ', line, GetLastToken(theSpec)); // PROBLEM: Hangs if breakpoint set when running // Check if running? // (Fixed with timeout?) if gCurrentProcess <> nil then if add then begin if gDebuggerIsGDB then // if debugName = 'gdb' then s := ReadToPrompt(gCurrentProcess, 'break ' + GetLastToken(theSpec) + ':' + str, gDebuggerPrompt) else // lldb s := ReadToPrompt(gCurrentProcess, 'b ' + GetLastToken(theSpec) + ':' + str, gDebuggerPrompt); WriteLn('Breakpoint reply: '+ s); HelpAppendLn('Breakpoint reply: '+ s); // LLDB reply: // Breakpoint 2: where = test`PASCALMAIN + 119 at test.pas:38, address = 0x00011007 // Parse s to check where it REALLY ended up! // Two rows in reply, number is last in first and first in last (!) actualLine := GetBreakpointLineFromReply(s, brNumber); // if line <> actualLine then - anropa ALLTID fšr att spara brNumber! MoveBreakpoint(line, actualLine, theWind, brNumber); br^.brNumber := brNumber; end else if gDebuggerIsGDB then begin s := ReadToPrompt(gCurrentProcess, 'clear ' + GetLastToken(theSpec) + ':' + str, gDebuggerPrompt); end else begin // LLDB delete breakpoint! // br del NR // So what is the number? // Either save at other time, or br l and parse! end; end; *) procedure BugsRunTo(theWind: WindowPtr; line: Longint); // Set temporary breakpoint and run var theSpec: FSSpecString; str: Str255; err: OSErr; s: AnsiString; begin if not BugsRunning then Exit(BugsRunTo); err := GetEditFSSpec(theWind, theSpec); if err <> noErr then Exit(BugsRunTo); NumToString(line, str); if gCurrentProcess <> nil then begin s := ReadToPrompt(gCurrentProcess, 'tbreak ' + GetLastToken(theSpec) + ':' + str, gDebuggerPrompt); BugsRun; end; end; // Check if a breakpoint was successfully set function CheckTBreak(s: AnsiString): Boolean; var strArr: StringArr; i: Longint; begin (* Example run debugging GPC program: (gdb) tbreak main Breakpoint 1 at 0x2bf4: file <implicit code>, line 308. (gdb) tbreak PASCALMAIN Function "PASCALMAIN" not defined. Make breakpoint pending on future shared library load? (y or [n]) *) strArr := ParseToWords(s); for i := Low(strArr) to High(strArr) do WriteLn('TBREAK LIST ', i:1, ':', strArr[i]); if Length(strArr) > 0 then begin if strArr[0] = 'Breakpoint' then return true; if strArr[0] = 'Function' then begin // ProcessWrite(gCurrentProcess, Char(10)); // Skip question (see above) return false; end; end; return true; end; procedure BugsRunWithDebug(theSpec: FSSpecString); var cleanName: AnsiString; path, commandLine, pathOnly: AnsiString; cleanNamePtr: StringPtr; extType: Integer; i: Longint; bp: BreakpointPtr; lineStr, s: AnsiString; actualLine: Longint; // Used when correcting breakpoint positions brNumber: Longint; begin // Clear some old debugging data SetLength(globalVariables, 0); SetLength(localVariables, 0); // SetLength(variablePosToIndex, 0); // UngefŠr som Run, men genom gdb, och kopplas till Lightbugs // Visa debuggerfšnster, antar jag. // SŠtt brytpunkter! // SŠtt variabler som anvŠnds fšr att vŠxla mellan GDB och LLDB debugName := GetLastToken(gSettings.gdb); gDebuggerIsGDB := debugName = 'gdb'; gDebuggerPrompt := '(' + debugName + ') '; // Works for both GDB and LLDB lengthDBName := Length(debugName); debugPath := theSpec; // Check if "which" can find the compiler if it is missing! // Only checks FPS PPC and 386, not iOS if gVersionGDB = kProcessUtilsFailedString then begin CheckCompilersExists; // Get fresh data. if gVersionGDB = kProcessUtilsFailedString then begin s := ProcessToString('which ' + debugName); if Length(s) > 1 then begin while s[Length(s)] in [#10, #13] do s := Copy(s, 1, Length(s)-1); if QuestionAlert(debugName + ' seems to be located at '+s, 'Correct settings?') then begin // Skall in i dialogen OCH variabeln Šndras! gSettings.gdb := s; // Should trigger save settings! SetSettingsDialogItemString('GDBp', 0, s); CheckFPCVersion; // MessageAlert('GDB now at "'+gSettings.gdb+'"', gVersionGDB); end; end; end; end; if gVersionGDB = kProcessUtilsFailedString then begin if not QuestionAlert(debugName + ' does not seem to be installed', 'Try anyway?') then begin Exit(BugsRunWithDebug); end else begin end; end; // Make sure that no other process is already running if gCurrentProcess <> nil then begin if ProcessRunning(gCurrentProcess) then begin DebugStr('Another process is already running'); Exit(BugsRunWithDebug); end else begin // Old process terminated but not disposed. This is normal! ProcessDispose(gCurrentProcess); end; end; path := theSpec; // We need the path without filename. pathOnly := TrimLastToken(path); WriteLn('Try chdir to: "', pathOnly, '"'); //HelpAppendLn('Try chdir to: "'+ pathOnly+ '"'); chdir({MacRomanToUTF8}(pathOnly)); // Set that as current dir // Bugg? €r inte sškvŠgen redan UTF8? €ndrat 130729 WriteLn('chdir OK'); cleanName := TrimExtension(GetLastToken(theSpec)); // ConvertPathToCommandLineFormat(cleanName); // Allow spaces in name path := TrimExtension(path); // CHECK IF BINARY EXISTS! What is the easiest and safest way? // // Command-line arguments (0.8.2) // if gSettingsTargetArgs <> '' then // tcmd := ' ' + gSettingsTargetArgs // else // tcmd := ''; // DOES NOT WORK. How do you end command-line args to debugging? (Answer: set args) WriteLn('TRIVIAL CHECKING'); // Bad feedback of stdio. Should work line by line - and be threaded properly. if IsCommandLineToolMode(theSpec) then // if gFlags^^.commandLineToolMode then begin // commandLine := '/usr/bin/gdb "' + path + {tcmd +} '"'; // INTE cleanName commandLine := gSettings.gdb + ' "' + cleanName + {tcmd +} '"'; // INTE cleanName -- why not? // commandLine := gSettings.gdb + ' "' + path + {tcmd +} '"'; // INTE cleanName -- why not? HelpAppendLn('COMMAND LINE TOOL MODE ACTIVE'); end else // commandLine := gSettings.gdb + ' "' + path+'.app/Contents/MacOS/'+cleanName + {tcmd +} '"'; // Use " instead of shell-style \ - WORKS! commandLine := gSettings.gdb + ' "' + cleanName+'.app/Contents/MacOS/'+cleanName + {tcmd +} '"'; // Use " instead of shell-style \ - WORKS! // commandLine := '/usr/bin/gdb "' + path+'.app/Contents/MacOS/'+cleanName + {tcmd +} '"'; // Use " instead of shell-style \ - WORKS! if gDebuggerIsGDB then // if debugName = 'gdb' then commandLine := commandLine + ' -f -q -d "' + pathOnly + '"' else commandLine := commandLine + {' -f -q -d "' +} pathOnly + '"'; // L€GG TILL ALLA PATHS I SETTINGS! // Java and makefile are not supported extType := GetExtensionType(theSpec); if extType in [kExtTypeJava, kExtTypeMakefile] then begin HelpAppendLn('Debugging not supported for target'); Exit(BugsRunWithDebug); end; HelpMainMessage('Running/debugging ' + cleanName); // Show status HelpAppendLn('Command: '+commandLine); HelpAppendLn('--- ' + debugName + ' ' + cleanName + ' starts ---'); // now Run! cleanNamePtr := StringPtr(NewPtr(Length(cleanName) + 1)); cleanNamePtr^:= cleanName; if gCurrentProcess <> nil then HelpAppendLn('SERIOUS PROCESS MANAGEMENT ERROR'); WriteLn('LAUNCHING'); gCurrentProcess := ProcessLaunch({MacRomanToUTF8}(commandLine), true); // Bugfix 130729 if gCurrentProcess <> nil then begin ProcessSetCallbacks(gCurrentProcess, @BugsData, @BugsDone, Pointer(cleanNamePtr)); if gCurrentProcess^.doneCallback = nil then HelpAppendLn('NO DONE CALLBACK!'); ProcessSetLineBuffering(gCurrentProcess, false); // SelectWindow(theErrorMsgWind); SelectWindow(helpWind); // New feature 080504: bring launched app to front // Not included here - we rather want the source in front. Copy to "run" command in debugger? end else begin HelpAppendLn('Launch failed - fork failed'); HelpMainMessage(''); // Show status Exit(BugsRunWithDebug); end; BugsEnable; // Read startup messages // This should not be needed - but it is! // Insufficient readout of old data in ReadToPrompt? s := ReadToPrompt(gCurrentProcess, '', gDebuggerPrompt); if gDebuggerIsGDB then // if debugName = 'gdb' then begin s := ReadToPrompt(gCurrentProcess, 'set confirm off', gDebuggerPrompt); s := ReadToPrompt(gCurrentProcess, 'set pagination off', gDebuggerPrompt); end; // Language is usually automatic, but we must always use Pascal style, since that's what we parse! // Especially, we issue commands with Pascal syntax! if gDebuggerIsGDB then // if debugName = 'gdb' then s := ReadToPrompt(gCurrentProcess, 'set language pascal', gDebuggerPrompt); // s := ReadToPrompt(gCurrentProcess, 'handle SIGINT stop', gDebuggerPrompt); did not help if extType = kExtTypePascal then begin // NEW // Only for Pascal? No, always? // THIS CRASHES GDB DUE TO A BUG!!! For large programs! // s := ReadToPrompt(gCurrentProcess, 'info variables', gDebuggerPrompt); // ParseGlobals(s); end; // Set breakpoints! // Go though all open windows and set any breakpoints! for i := 1 to kMaxEditWindows do begin if editWind[i] <> nil then begin bp := GetWindowBreakpoints(editWind[i]); // Getthe first in the list while bp <> nil do begin Str(bp^.line, lineStr); if bp^.enabled then begin if gDebuggerIsGDB then s := ReadToPrompt(gCurrentProcess, 'break "' + {MacRomanToUTF8}(bp^.filename) + '":' + lineStr, gDebuggerPrompt) else s := ReadToPrompt(gCurrentProcess, 'b"' + {MacRomanToUTF8}(bp^.filename) + '":' + lineStr, gDebuggerPrompt); // Check if breakpoint is in the right place actualLine := GetBreakpointLineFromReply(s, brNumber); // Also returns breakpoint number - do we need that? if bp^.line <> actualLine then MoveBreakpoint(bp^.line, actualLine, editWind[i], brNumber); end; // UTF here8?! Not tested!!! // WriteLn('break ' + bp^.filename + ':' + lineStr); bp := bp^.next; end; end; end; // Pascal and C starts differently! // start/run to main WriteLn('start/run to main'); //if not AtLeastOneBreakPoint then begin if extType = kExtTypePascal then begin s := ReadToPrompt(gCurrentProcess, 'tbreak PASCALMAIN', gDebuggerPrompt); // Temporary breakpoint at Pascal main so we can run past init code. if not CheckTBreak(s) then begin // If it failed, it might be GPC code! Start as C. s := ReadToPrompt(gCurrentProcess, 'tbreak main', gDebuggerPrompt); // Temporary breakpoint at Pascal main so we can run past init code. // CheckTBreak(s); end end else if extType = kExtTypeC then begin s := ReadToPrompt(gCurrentProcess, 'tbreak main', gDebuggerPrompt); // Temporary breakpoint at Pascal main so we can run past init code. // CheckTBreak(s); end; end; WriteLn('tbreak: ', s); // s := ReadToPrompt(gCurrentProcess, 'run ', gDebuggerPrompt); // Run to start of main ProcessWriteLn(gCurrentProcess, 'run'); OKtoSetBreaks := false; // if AtLeastOneBreakPoint then // it's ok and probably desired to go run up to the first breakpoint, otherwise not // s := ReadToPrompt(gCurrentProcess, 'continue ', gDebuggerPrompt); // continue to first breakpoint WriteLn('run: ', s); // It works WITHOUT this parsing - why? // ParseReplyScopeStatus(s); // Borde parsa svaret och visa! // s := ReadToPrompt(gCurrentProcess, 'start ', gDebuggerPrompt); // Run to start of main // WriteLn(s); end; // These should not be here but they should be somewhere. Maybe in View Manager. function CGRectToRect(cgr: CGRect): Rect; var r: Rect; begin r.left := Trunc(cgr.origin.x); r.top := Trunc(cgr.origin.y); r.right := Trunc(r.left + cgr.size.width); r.bottom := Trunc(r.top + cgr.size.height); return r; end; function RectToCGRect(r: Rect): CGRect; var cgr: CGRect; begin cgr.origin.x := r.left; cgr.origin.y := r.top; cgr.size.width := r.right - r.left; cgr.size.height := r.bottom - r.top; return cgr; end; //type // FileNameRec = record // name: AnsiString; // fileName: AnsiString; // value: AnsiString; // varType: AnsiString; // // type? // // last known value? // end; //var // globalVariables: array of FileNameRec; // localVariables: array of FileNameRec; // "print" pŒ alla globaler // …vriga skrivs med vŠrdet de fŒtt tidigare // Klickbara - skicka klickad till annan vy // Hur gšr man detta i flera nivŒer? // Klick pŒ innehŒll, minns vŠgen dit och gŒ in? var gSelectedFrame: Longint; // Stack view //procedure VariablesDraw(theView: HIViewRef; viewRect: Rect; userData: Pointer); procedure VariablesDraw(theView: HIViewRef; cgContext: CGContextRef; cgviewRect: CGRect; userData: Pointer); var i: Longint; // s: String; viewRect, r: Rect; begin viewRect := CGRectToRect(cgviewRect); // UseViewContext(cgContext, cgviewRect.size.height); CreatePort(cgContext, cgviewRect.size.height); BackColor(whiteColor); EraseRect(viewRect); QDCG.TextSize(12); // Boxes for stack frames to click in to select frame. for i := 0 to High(backTraceStack)+2 do begin SetRect(r, viewRect.left, 20*i, viewRect.right, 20*(i+1)); if i = gSelectedFrame then // Mark selected (faked) begin ForeColor(lighterBlueColor); PaintRect(r); end; ForeColor(lighterGrayColor); FrameRect(r); ForeColor(blackColor); MoveTo(10, (i+1)*20-2); if i = 0 then DrawString('All') else if i = 1 then DrawString('Globals') else DrawString(backTraceStack[i-2]); end; ForeColor(blackColor); FinishPort; end; procedure VariablesMouse(theView: HIViewRef; cgwhere: CGPoint; mods, button: Longint; userData: Pointer); var control: HIViewRef; begin gSelectedFrame := Trunc(cgwhere.y / 20); WriteLn('VariablesMouse'); // VMGetControl( bugsWind, 'Vari', 0, control); HIViewSetNeedsDisplay(theView, true); // Uppdatera Šven Vari 1 = variable view ResizeVariables; // Can be optimized to just #1 VMGetControl( bugs1Wind, 'Vari', 0, control); // Samma som ovan? HIViewSetNeedsDisplay(control, true); VMGetControl( bugs1Wind, 'Vari', 1, control); // Nonexistent?! Or added in code? HIViewSetNeedsDisplay(control, true); end; procedure VariablesKey(theView: HIViewRef; key: Char; mods: Longint; userData: Pointer); begin WriteLn('VariablesKey'); end; var variablePosToIndex: array of Integer; // For knowing what we click! procedure VariablesDraw1(theView: HIViewRef; cgContext: CGContextRef; cgviewRect: CGRect; userData: Pointer); var i, j: Longint; // s: String; viewRect: Rect; begin viewRect := CGRectToRect(cgviewRect); // UseViewContext(cgContext, cgviewRect.size.height); CreatePort(cgContext, cgviewRect.size.height); QDCG.BackColor(whiteColor); QDCG.EraseRect(viewRect); QDCG.TextSize(12); if gSelectedFrame = 0 then // All begin SetLength(variablePosToIndex, Length(backTraceVars) + Length(globalVariables)); for i := 0 to High(globalVariables) do begin MoveTo(10, (i+1)*20); // DrawString(globalVariables[i].name + ' = ' + globalVariables[i].value+ ':'+ globalVariables[i].varType); DrawString(globalVariables[i].displayname + ' = ' + globalVariables[i].value); variablePosToIndex[i] := -i-1; // Negativt index = globals end; // Important: The frameNumber is not yet supported by LLDB code! for i := 0 to High(backTraceVars) do begin MoveTo(10, (i+1 + Length(globalVariables))*20); if High(backTraceStack) >= backTraceVars[i].frameNumber then DrawString(backTraceVars[i].displayname + ' = ' + backTraceVars[i].value + ' (' + backTraceStack[backTraceVars[i].frameNumber] + ')') else DrawString(backTraceVars[i].displayname + ' = ' + backTraceVars[i].value); variablePosToIndex[i+Length(globalVariables)] := i; end; end else if gSelectedFrame = 1 then // Globals begin SetLength(variablePosToIndex, Length(globalVariables)); for i := 0 to High(globalVariables) do begin MoveTo(10, (i+1)*20); // DrawString(globalVariables[i].name + ' = ' + globalVariables[i].value+ ':'+ globalVariables[i].varType); DrawString(globalVariables[i].displayname + ' = ' + globalVariables[i].value); // value sŠtts inte variablePosToIndex[i] := -i-1; // Negativt index = globals end; end else // Frame # if gSelectedFrame - 2 begin SetLength(variablePosToIndex, Length(backTraceVars)); // Temporary j := 0; for i := 0 to High(backTraceVars) do if backTraceVars[i].frameNumber = gSelectedFrame - 2 then begin MoveTo(10, (j+1)*20); // DrawString(globalVariables[i].name + ' = ' + globalVariables[i].value+ ':'+ globalVariables[i].varType); DrawString(backTraceVars[i].displayname + ' = ' + backTraceVars[i].value); variablePosToIndex[j] := i; j += 1; end; SetLength(variablePosToIndex, j); end; (* MoveTo(10, 3*20); LineTo(200, 3*20); for i := 0 to High(localVariables) do begin MoveTo(10, i*20 + 3*20); DrawString(localVariables[i].name + ' = ' + localVariables[i].value+ ':'+ localVariables[i].varType); // value sŠtts till name? end; *) FinishPort; end; var // var2DisplayData: AnsiString; var2DisplayVariable: VarInfoRec; var2History: array of VarInfoRec; // History of previous variables in var2 procedure VariablesMouse1(theView: HIViewRef; where: CGPoint; mods, button: Longint; userData: Pointer); var i: Longint; // repl: AnsiString; control: ControlRef; var2Edit: VarInfoRec; begin WriteLn(button, ',', mods); if (button <> 1) or (mods <> 0) then // Anything but a straight click begin i := Trunc(where.y / 20); if i <= High(variablePosToIndex) then if variablePosToIndex[i] < 0 then begin var2Edit := globalVariables[-variablePosToIndex[i]-1]; // Open variable editor! ShowSetVariableDialog(var2Edit); end else begin var2Edit := backTraceVars[variablePosToIndex[i]]; // Open variable editor! ShowSetVariableDialog(var2Edit); end; end; // Open question: Should var2History be emptied when clicking here? // WriteLn('VariablesMouse1'); // Vilken variabel Šr klickad pŒ? i := Trunc(where.y / 20); if i <= High(variablePosToIndex) then if variablePosToIndex[i] < 0 then begin // ATT FIXA: Peka in i pekare! (Funkar!) WriteLn('Global #', -variablePosToIndex[i]-1, '=', globalVariables[-variablePosToIndex[i]-1].name); var2DisplayVariable := globalVariables[-variablePosToIndex[i]-1]; // repl := ReadToPrompt(gCurrentProcess, 'print ' + var2DisplayVariable.name, gDebuggerPrompt); // var2DisplayData := ParseExpandVariable(repl); end else begin WriteLn('Local #', variablePosToIndex[i], '=', backTraceVars[variablePosToIndex[i]].name); var2DisplayVariable := backTraceVars[variablePosToIndex[i]]; // repl := ReadToPrompt(gCurrentProcess, 'print ' + var2DisplayVariable.name, gDebuggerPrompt); // var2DisplayData := ParseExpandVariable(repl); end else WriteLn('Hit no variable'); // Click means show expanded view in Vari 2 // Show memory in Vari 3? // print? // Pekare gšr print med pek. (Dock ej strŠng.) ResizeVariables; VMGetControl( bugs1Wind, 'Vari', 2, control); HIViewSetNeedsDisplay(control, true); VMGetControl( bugs1Wind, 'Vari', 3, control); HIViewSetNeedsDisplay(control, true); end; procedure VariablesKey1(theView: HIViewRef; key: Char; mods: Longint; userData: Pointer); begin WriteLn('VariablesKey1'); end; var // NEW: var2printArr: OutArrType; var2printScalar: AnsiString; var2EmergencyArr: StringArr; // For debugging of missing ParsePrint data! procedure UpdateVariables2Data; var repl: AnsiString; fr: String; begin if var2DisplayVariable.name <> '' then begin Str(var2DisplayVariable.frameNumber, fr); repl := ReadToPrompt(gCurrentProcess, 'frame ' + fr, gDebuggerPrompt); if var2DisplayVariable.typeId = kPointer then begin // Note!!! ^ is wrong for C code! Must use *! if gDebuggerIsGDB and gPascalMode then repl := ReadToPrompt(gCurrentProcess, 'print ' + var2DisplayVariable.name + '^', gDebuggerPrompt) else repl := ReadToPrompt(gCurrentProcess, 'print (*' + var2DisplayVariable.name + ')', gDebuggerPrompt) end else repl := ReadToPrompt(gCurrentProcess, 'print ' + var2DisplayVariable.name, gDebuggerPrompt); //WriteLn('**************UpdateVariables2Data before cleaning: "', repl, '"'); if gDebuggerIsGDB then begin repl := Copy(repl, 1, Length(repl) - 7); // Tag bort (gdb) --- I wonder, is it really a "gdb" we want to remove?! ParsePrint(repl, var2printArr, var2printScalar); end else ParsePrintLLDB(repl, var2printArr, var2printScalar); // CleanLLDBPrint(repl); // Remove (TYPE) och $NR (insignificant command number) The type may be saved and corrected. //WriteLn('**************UpdateVariables2Data: "', repl, '"'); // var2DisplayData := ParseExpandVariable(repl); // var2DisplayDataList := SplitStringToList(var2DisplayData); Obsolete? if Length(var2printArr) = 0 then begin // SetLength(var2printArr, 1); var2EmergencyArr := SplitStringToList(repl); end; end; end; var gVariables3Data: StringArr; // AnsiString; // Make the Variables3 memory dump more readable procedure CleanMemoryDump(var repl: AnsiString); var i, j: Longint; prev: Char; begin j := 1; prev := '-'; for i := 1 to Length(repl) do begin repl[j] := repl[i]; if repl[i] = #9 then repl[j] := ' '; if repl[i] = 'x' then if prev = '0' then begin repl[j-1] := '$'; j -= 1; end; j += 1; prev := repl[i]; end; SetLength(repl, j); end; procedure UpdateVariables3Data; var repl, addr: AnsiString; begin if BugsRunning then if var2DisplayVariable.name <> '' then begin // WriteLn('Getting address for Vari 3'); if var2DisplayVariable.typeId = kPointer then repl := ReadToPrompt(gCurrentProcess, 'print ' + var2DisplayVariable.name, gDebuggerPrompt) else repl := ReadToPrompt(gCurrentProcess, 'print ' + '@' + var2DisplayVariable.name, gDebuggerPrompt); // WriteLn('reply = ', repl); addr := GetAHexValue(repl); // Kan fŒ "address requested for identifier "var" which is in register" // WriteLn('addr = ', addr); if addr <> '' then begin repl := ReadToPrompt(gCurrentProcess, 'x/100bx ' + addr, gDebuggerPrompt); // DrawString(repl); CleanMemoryDump(repl); gVariables3Data := SplitStringToList(repl); end; end; end; procedure VariablesDraw2(theView: HIViewRef; cgContext: CGContextRef; cgviewRect: CGRect; userData: Pointer); var i: Longint; s: String; viewRect: Rect; // repl: AnsiString; // list: StringArr; // Old raw output pol: PolyHandle; begin viewRect := CGRectToRect(cgviewRect); // UseViewContext(cgContext, cgviewRect.size.height); CreatePort(cgContext, cgviewRect.size.height); QDCG.BackColor(whiteColor); QDCG.EraseRect(viewRect); QDCG.TextSize(12); if BugsRunning then if var2DisplayVariable.name <> '' then begin ForeColor(blackColor); if Length(var2History) > 0 then begin pol := OpenPoly; MoveTo(5, 13); LineTo(15, 6); LineTo(15, 20); ClosePoly; PaintPoly(pol); KillPoly(pol); end; MoveTo(20, 20); // Room for button DrawString(var2DisplayVariable.name + ':'); if var2printScalar <> '' then begin MoveTo(10, 0*20 + 2*20); // DrawString('(scalar) "' + var2printScalar + '"'); DrawString(var2printScalar); end else if Length(var2printArr) = 0 then begin MoveTo(10, 2*20); // Rad 2 // DrawString('Got NOTHING from ParsePrint of "' + var2DisplayVariable.name + '"'); // Emergency output (e.g. Cannot access memory at address...): for i := 0 to High(var2EmergencyArr) do begin MoveTo(10, i*20 + 2*20); DrawString(var2EmergencyArr[i]); end; // WriteLn('PROBLEM:'); // WriteLn(repl); end else for i := 0 to High(var2printArr) do begin MoveTo(10, i*20 + 2*20); if var2printArr[i].name = '' then begin Str(i, s); DrawString('['+ s+ '] '); end else DrawString(var2printArr[i].name + ': '); DrawString(var2printArr[i].value); // Debug: // Str(var2printArr[i].typeId, s); // DrawString(' Type: ' + s); end; end; FinishPort; end; procedure VariablesMouse2(theView: HIViewRef; where: CGPoint; mods, button: Longint; userData: Pointer); var i: Longint; s: String; control: ControlRef; tmpName, tmpDisplayName: AnsiString; // localvar2DisplayVariable: VarInfoRec; procedure MoveToNewVariable(name, displayname, value: AnsiString; typeId: Longint); begin SetLength(var2History, Length(var2History)+1); var2History[High(var2History)] := var2DisplayVariable; var2DisplayVariable.name := name; var2DisplayVariable.displayname := displayname; var2DisplayVariable.value := value; var2DisplayVariable.typeId := typeId; end; begin i := Trunc(where.y / 20) - 1; WriteLn('VariablesMouse2 at index ', i); // Modify var2DisplayVariable! // How depends on type. if i < 0 then // Back in history! begin if Length(var2History) > 0 then begin var2DisplayVariable := var2History[High(var2History)]; SetLength(var2History, Length(var2History)-1); // Redisplay view 2 (self) and 3 ResizeVariables; VMGetControl( bugs1Wind, 'Vari', 2, control); HIViewSetNeedsDisplay(control, true); VMGetControl( bugs1Wind, 'Vari', 3, control); HIViewSetNeedsDisplay(control, true); Exit(VariablesMouse2); end; Exit(VariablesMouse2); // Negative index never OK end; if Length(var2printArr) = 0 then begin // if scalar is a pointer // HŠnder bara vid pekare till pekare? if (Copy(var2DisplayVariable.value, 1, 2) = '0x') or (var2DisplayVariable.value = '(pointer)') then begin MoveToNewVariable('(*'+var2DisplayVariable.name + ')', var2DisplayVariable.displayname + '^', '', kScalarOrUnknown); WriteLn('Click on pointer ' + var2DisplayVariable.name + ' = ' + var2DisplayVariable.value); end else WriteLn('Click on scalar ' + var2DisplayVariable.value); // Ingen aning om typen den pekar pŒ... end else begin if i > High(var2printArr) then Exit(VariablesMouse2); // Save to history SetLength(var2History, Length(var2History)+1); var2History[High(var2History)] := var2DisplayVariable; // if var2DisplayVariable.typeId = kPointer then // repl := ReadToPrompt(gCurrentProcess, 'print ' + var2DisplayVariable.name + '^', gDebuggerPrompt) tmpName := var2DisplayVariable.name; tmpDisplayName := var2DisplayVariable.displayname; if var2DisplayVariable.typeId = kPointer then begin tmpDisplayName := tmpDisplayName + '^'; // tmpName := tmpName + '^'; if GDB and FPC! tmpName := '(*' + tmpName + ')'; WriteLn('Click on pointer, got ', tmpName, ' (click on ', var2printArr[i].typeId, ')'); end; // Hur vet jag vad pekaren pekade pŒ??? // €r det inte pekare lŠngre efter ParseExpandVariable? // print ra[2].d[3]^ funkar if var2printArr[i].name <> '' then // Name exists = record begin WriteLn('Record hit at ', i, '(', var2printArr[i].name, ')'); tmpDisplayName := tmpDisplayName + '.' + var2printArr[i].displayname; // NOT ALWAYS RIGHT - Fails at array of record! ] at end means array. Right? Or [ at start? // if var2printArr[i].name[Length(var2printArr[i].name)] = ']' then if var2printArr[i].name[1] = '[' then tmpName := tmpName + var2printArr[i].name else tmpName := tmpName + '.' + var2printArr[i].name; end else begin WriteLn('Array hit at ', i); Str(i, s); tmpName := tmpName + '[' + s + ']'; tmpDisplayName := tmpDisplayName + '[' + s + ']'; end; if var2printArr[i].typeId = kPointer then // Was the clicked field a pointer? begin WriteLn('Clicked field ', i, ' is a pointer'); // var2DisplayVariable.name := var2DisplayVariable.name + '^'; end; // var2DisplayVariable.name := tmpName; // var2DisplayVariable.typeId := var2printArr[i].typeId; // var2DisplayVariable.value := var2printArr[i].value; MoveToNewVariable(tmpName, tmpDisplayName, var2printArr[i].value, var2printArr[i].typeId); // FIXA DISPLAYNAME! end; // var2DisplayVariable := localvar2DisplayVariable; // Redisplay view 2 (self) and 3 ResizeVariables; VMGetControl( bugs1Wind, 'Vari', 2, control); HIViewSetNeedsDisplay(control, true); VMGetControl( bugs1Wind, 'Vari', 3, control); HIViewSetNeedsDisplay(control, true); end; procedure VariablesKey2(theView: HIViewRef; key: Char; mods: Longint; userData: Pointer); begin WriteLn('VariablesKey'); end; procedure VariablesDraw3(theView: HIViewRef; cgContext: CGContextRef; cgviewRect: CGRect; userData: Pointer); var viewRect: Rect; i: Longint; begin viewRect := CGRectToRect(cgviewRect); // UseViewContext(cgContext, cgviewRect.size.height); CreatePort(cgContext, cgviewRect.size.height); QDCG.TextSize(12); // ForeColor(lighterYellowColor); ForeColor(whiteColor); PaintRect(viewRect); // EraseRect(viewRect); // ForeColor(darkMagentaColor); ForeColor(blackColor); MoveTo(10, 30); if BugsRunning then if var2DisplayVariable.name <> '' then begin // UpdateVariables3Data; // Move to data in for i := 0 to High(gVariables3Data) do begin MoveTo(10, 30 + i * 20); DrawString(gVariables3Data[i]); end; end; FinishPort; end; procedure VariablesMouse3(theView: HIViewRef; where: CGPoint; mods, button: Longint; userData: Pointer); begin WriteLn('VariablesMouse3'); end; procedure VariablesKey3(theView: HIViewRef; key: Char; mods: Longint; userData: Pointer); begin WriteLn('VariablesKey3'); end; (* Status view is removed! procedure StatusDraw(theView: HIViewRef; viewRect: MacOSAll.Rect; userData: Pointer); begin WriteLn('StatusDraw'); MacOSAll.EraseRect(viewRect); MacOSAll.EraseRect(viewRect); MacOSAll.MoveTo(100, 100); MacOSAll.DrawString('Status'); end; procedure StatusMouse(theView: HIViewRef; where: MacOSAll.Point; mods: Longint; userData: Pointer); begin WriteLn('StatusMouse'); end; procedure StatusKey(theView: HIViewRef; key: Char; mods: Longint; userData: Pointer); begin WriteLn('StatusKey'); end; *) //const // kNumExpressions = 30; var expressionString: array of AnsiString; expressionResults: array of AnsiString; expressionBox: array of ControlRef; expressionResultBox: array of ControlRef; procedure UpdateExpression(i: Integer); var j, c: Longint; s: AnsiString; begin if i > 0 then if i <= High(expressionResultBox) then if Length(expressionString[i]) > 0 then begin // If FPC, upper case on all expressions! if gPascalMode then s := ReadToPrompt(gCurrentProcess, 'print '+UpperCase(expressionString[i]), gDebuggerPrompt) else s := ReadToPrompt(gCurrentProcess, 'print '+expressionString[i], gDebuggerPrompt); if Length(s) > 0 then if s[1] = '$' then begin c := 1; repeat c += 1 until (s[c] = '=') or (c > Length(s)); s := Copy(s, c+2, Length(s)-c); end; // Tag bort (gdb) pŒ slutet s := Copy(s, 1, Length(s)-6); // Tag bort alla vagnreturer // Mšjlig felkŠllla? Nja, knappast. s := DelChars(s, #13); s := DelChars(s, #10); // for c := Length(s) downto 1 do // begin // if s[c] in [#10, #13] then // s := Copy(s, 1, c-1) + Copy(s, c+1, Length(s)-c); // end; VMSetStringValue(expressionResultBox[i], s); end; end; procedure UpdateExpressions; var i: Longint; begin for i := 0 to High(expressionBox) do UpdateExpression(i); end; // Problem: It seems impossible to know which text box that was changed. Why do I get // another view reference than the one I put in? Answer: Old text boxes seem to be the problem. // With the newer ones, it worked. function ExpressionChanged(theView: HIViewRef; myPtr: Pointer): Boolean; var i: Integer; type AnsiStringPtr = ^AnsiString; //var // theString: AnsiString; // theCFStr: CFStringRef; begin for i := 0 to High(expressionBox) do if theView = expressionBox[i] then if BugsRunning then UpdateExpression(i); end; const kExpressionBoxHeight = 20; var splitData, upperSplitData, lowerSplitData: SplitDataPtr; uplowScrollData, lowupScrollData, lowlowScrollData: ScrollDataPtr; var gLastTotalLengthVariables1, gLastTotalLengthVariables2: Longint; // Fungerar dŒligt! // Skalar inte om nŠr jag vill. procedure ResizeVariables; // Resize or data change var // fr, pfr: HIRect; // root, parent: HIViewRef; r, pr: MacOSAll.Rect; totalLengthVariables1, totalLengthVariables2: Longint; // var0, var1, var2, var3: ControlRef; begin WriteLn('*** Anropar UpdateVariables2Data frŒn ResizeVariables (rŠtt plats):'); UpdateVariables2Data; UpdateVariables3Data; // Inval properly? NOT enough! // HIViewSetNeedsDisplay(uplowScrollData^.contentView, true); // HIViewSetNeedsDisplay(lowupScrollData^.contentView, true); // HIViewSetNeedsDisplay(lowlowScrollData^.contentView, true); // VMGetControl( bugsWind, 'Vari', 0, var0); // VMGetControl( bugsWind, 'Vari', 1, var1); // VMGetControl( bugsWind, 'Vari', 2, var2); // VMGetControl( bugsWind, 'Vari', 3, var3); // VMGetControlId(upperSplitData^.upper, 'Vari', 0); // InstallSkelViewHandler(bugsWind, upperSplitData^.upper, VariablesDraw, VariablesMouse, VariablesKey, nil); // VMSetControlId(uplowScrollData^.contentView, 'Vari', 1); // InstallSkelViewHandler(bugsWind, uplowScrollData^.contentView, VariablesDraw1, VariablesMouse1, VariablesKey1, nil); // VMSetControlId(lowupScrollData^.contentView, 'Vari', 2); // InstallSkelViewHandler(bugsWind, lowupScrollData^.contentView, VariablesDraw2, VariablesMouse2, VariablesKey2, nil); // VMSetControlId(lowlowScrollData^.contentView, 'Vari', 3); // Jobbar frŒn variablerna totalLengthVariables1, totalLengthVariables2 // MŒste matcha vad som ritas i VariablesDraw1, VariablesDraw2 // variables 2: variable zoom view (lowUp) totalLengthVariables2 := 0; if var2printScalar <> '' then totalLengthVariables2 := 2 else if Length(var2printArr) = 0 then totalLengthVariables2 := 2 else totalLengthVariables2 := Length(var2printArr); GetControlBounds(lowUpScrollData^.contentView, r); GetControlBounds(lowUpScrollData^.peepHoleView, pr); if (totalLengthVariables2 <> gLastTotalLengthVariables2) or (pr.right - pr.left <> r.right - r.left) then begin // Variabelzoom, vŠl? (Variables2) Korrekt bredd, fel hšjd. r.bottom := r.top + totalLengthVariables2 * 20 + 2*20; r.right := r.left + (pr.right - pr.left); // Bredd skall anpassas efter innehŒllet! SetControlBounds(lowUpScrollData^.contentView, r); gLastTotalLengthVariables2 := totalLengthVariables2; HIViewSetNeedsDisplay(lowUpScrollData^.peepHoleView, true); end; // variables 1: variables list (upLow) totalLengthVariables1 := 0; if gSelectedFrame = 0 then // All totalLengthVariables1 := Length(globalVariables) + Length(backTraceVars) else if gSelectedFrame = 1 then // Globals totalLengthVariables1 := Length(globalVariables) else // Frame # if gSelectedFrame - 2 totalLengthVariables1 := Length(backTraceVars); WriteLn('totalLengthVariables1 = ', totalLengthVariables1); GetControlBounds(upLowScrollData^.contentView, r); GetControlBounds(upLowScrollData^.peepHoleView, pr); if (totalLengthVariables1 <> gLastTotalLengthVariables1) or (pr.right - pr.left <> r.right - r.left) then begin // Variables1, variabellistan r.bottom := r.top + totalLengthVariables1 * 20 + 1*20; r.right := r.left + (pr.right - pr.left); // Bredd skall anpassas efter innehŒllet! SetControlBounds(upLowScrollData^.contentView, r); gLastTotalLengthVariables1 := totalLengthVariables1; HIViewSetNeedsDisplay(upLowScrollData^.peepHoleView, true); end; // uplowScrollData^.contentView = variables1? // lowlowScrollData^.contentView = variables3=memory? end; // For Observe! //procedure BugsResize(resized: Boolean); procedure ObserveResize(theWind: WindowRef); var i, oldCount, newCount: Longint; fr, wfr: HIRect; root, parent: HIViewRef; r: Rect; cr: CGRect; begin if theWind <> observeWind then WriteLn('This should absolutely never happen!!?'); // if resized then begin // Get size of window GetRootControl (observeWind, root); HIViewGetFrame (root, wfr); // Get parent of boxes //VMGetControl(observeWind, 'Expr', 0, parent); parent := SkelGetContentView(observeWind); HIViewGetFrame (parent, wfr); // WriteLn(Length(expressionBox)); // WriteLn(wfr.size.height / kExpressionBoxHeight); // TEST: Kill old views! // Workaround for a bug that caused crashes after resize. Seems to work - but why? // NO - does not help! // for i := 0 to High(expressionBox) do // begin // DisposeControl(expressionBox[i]); // DisposeControl(expressionResultBox[i]); // end; // SetLength(expressionBox, 0); // SetLength(expressionResultBox, 0); // SetLength(expressionString, 0); // SetLength(expressionResults, 0); // Create subviews if needed if wfr.size.height / kExpressionBoxHeight > Length(expressionBox) then begin oldCount := Length(expressionBox); newCount := Trunc(wfr.size.height / kExpressionBoxHeight); i := High(expressionBox) +1; SetLength(expressionBox, newCount); SetLength(expressionResultBox, newCount); SetLength(expressionString, newCount); SetLength(expressionResults, newCount); for i := i to newCount-1 do begin expressionBox[i]:=nil; SetRect(r, 0,i*kExpressionBoxHeight, 300, (i+1)*kExpressionBoxHeight-1); cr := RectToCGRect(r); HITextViewCreate(HIRectPtr(@cr), 0, 0, expressionBox[i]); HIViewSetVisible(expressionBox[i], true); SetRect(r, 302,i*kExpressionBoxHeight, 600, (i+1)*kExpressionBoxHeight-1); cr := RectToCGRect(r); HITextViewCreate (HIRectPtr(@cr), 0, 0, expressionResultBox[i]); HIViewSetVisible(expressionResultBox[i], true); InstallViewHandlerByRef(observeWind, expressionBox[i], kViewDataString, @expressionString[i], ExpressionChanged, nil); VMSetStringValue(expressionBox[i], ''); HIViewAddSubview (parent, expressionBox[i]); HIViewAddSubview (parent, expressionResultBox[i]); end; end; // Resizing of subviews for i := 0 to High(expressionBox) do begin // OSStatus HIViewGetFrame (HIViewRef inView, HIRect *outRect); // OSStatus HIViewSetFrame (HIViewRef inView, const HIRect *inRect); HIViewGetFrame (expressionBox[i], fr); // Modify fr.size.width := wfr.size.width / 2-1; HIViewSetFrame (expressionBox[i], fr); HIViewGetFrame (expressionResultBox[i], fr); // Modify fr.size.width := wfr.size.width / 2; fr.origin.x := wfr.size.width / 2+1; HIViewSetFrame (expressionResultBox[i], fr); end; // VMGetControl( bugsWind, 'Expr', 0, control); // Get the size // Get all // Resize variable views here? ResizeVariables; end; end; procedure ObserveUpdate(theView: HIViewRef; viewRect: QDCG.Rect; userData: Pointer); begin ForeColor(lightGreyColor); PaintRect(viewRect); end; procedure BugsInit; var control: HIViewRef; r: MacOSAll.Rect; rr: Rect; begin // CreateWindowFromNib(SkelGetMainNib, CFSTR('Observe'), observeWind); // dummy := SkelWindow(observeWind, nil{@Mouse}, nil{@HelpKey}, BugsResize{@Update}, nil{@Activate}, nil{@DoClose}, nil{@Halt}, nil, true); SetRect(rr, 372, 65, 700, 250); observeWind := SkelNewWindow(rr, 'Observe', ObserveUpdate{theDrawProc: VMQDCGDrawProcPtr}, nil {theMouseProc: VMQDCGMouseProcPtr}, nil{theKeyProc: TSKeyProcPtr}, nil {userData: Pointer}, nil {pActivate: TSBooleanProcPtr}, nil{pClose}, nil{pClobber}, nil {pIdle: TSNoArgProcPtr;}, true, 0, nil, nil, 0, ObserveResize{resizeProc: TSResizeProcPtr}); // observeWind := SkelNewWindow(rr, 'Observe'); // dummy := SkelWindow(observeWind, nil{@Mouse}, nil{@HelpKey}, nil{@Update}, nil{@Activate}, nil{@DoClose}, nil{@Halt}, nil, true); // CreateWindowFromNib(SkelGetMainNib, CFSTR('LightBugs'), bugsWind); SetRect(rr, 272, 65, 900, 700); bugs1Wind := SkelNewWindow(rr, 'Light Bugs', nil{theDrawProc: VMQDCGDrawProcPtr}, nil {theMouseProc: VMQDCGMouseProcPtr}, nil{theKeyProc: TSKeyProcPtr}, nil {userData: Pointer}, nil {pActivate: TSBooleanProcPtr}, nil{pClose}, nil{pClobber}, nil {pIdle: TSNoArgProcPtr;}, true, 0, nil, nil, 0, nil{resizeProc: TSResizeProcPtr}); // bugs1Wind := SkelNewWindow(rr, 'Light Bugs'); // dummy := SkelWindow(bugs1Wind, nil{@Mouse}, nil{@HelpKey}, nil{@Update}, nil{@Activate}, nil{@DoClose}, nil{@Halt}, nil, true); // InstallAllTabs(bugsWind); // NewDView(bugsWind, 'Stac', 0); // Install HIView to be used as displayview // NewDView(bugsWind, 'Vari', 0); // Install HIView to be used as displayview // NewDView(bugsWind, 'Stat', 0); // Install HIView to be used as displayview // VMGetControl( bugs1Wind, 'Vari', 0, control); control := SkelGetContentView(bugs1Wind); VMSetControlId(control, '----', 100); // or dispose? splitData := EmbedInSplitter(nil, control, false, 0.4); // Split main Variables view upperSplitData := EmbedInSplitter(nil, splitData^.upper, true, 0.3); // Split upper sideways lowerSplitData := EmbedInSplitter(nil, splitData^.lower, false, 0.5); // Split main Variables view MacOSAll.SetRect(r, 0,0,600,800); uplowScrollData := EmbedInScroller(nil, upperSplitData^.lower, true, true, true, r); lowupScrollData := EmbedInScroller(nil, lowerSplitData^.upper, true, true, true, r); lowlowScrollData := EmbedInScroller(nil, lowerSplitData^.lower, true, true, true, r); VMSetControlId(upperSplitData^.upper, 'Vari', 0); // InstallQDSkelViewHandler(bugsWind, upperSplitData^.upper, VariablesDraw, VariablesMouse, VariablesKey, nil); InstallSkelViewHandler(bugs1Wind, upperSplitData^.upper, VariablesDraw, VariablesMouse, VariablesKey, nil); VMSetControlId(uplowScrollData^.contentView, 'Vari', 1); // InstallQDSkelViewHandler(bugsWind, uplowScrollData^.contentView, VariablesDraw1, VariablesMouse1, VariablesKey1, nil); InstallSkelViewHandler(bugs1Wind, uplowScrollData^.contentView, VariablesDraw1, VariablesMouse1, VariablesKey1, nil); VMSetControlId(lowupScrollData^.contentView, 'Vari', 2); // InstallQDSkelViewHandler(bugsWind, lowupScrollData^.contentView, VariablesDraw2, VariablesMouse2, VariablesKey2, nil); InstallSkelViewHandler(bugs1Wind, lowupScrollData^.contentView, VariablesDraw2, VariablesMouse2, VariablesKey2, nil); VMSetControlId(lowlowScrollData^.contentView, 'Vari', 3); // InstallQDSkelViewHandler(bugsWind, lowlowScrollData^.contentView, VariablesDraw3, VariablesMouse3, VariablesKey3, nil); InstallSkelViewHandler(bugs1Wind, lowlowScrollData^.contentView, VariablesDraw3, VariablesMouse3, VariablesKey3, nil); gLastTotalLengthVariables1 := 1; gLastTotalLengthVariables2 := -1; // BakŒtknapp i var2 // lowupScrollData^.contentView // Nej, det Šr lŠttare att bara rita den! // SŒ hŠr: // Stšrre vyer skall ligga i Scrollers // Ytan delas flera gŒnger av Splitters // gŠrna lite i stil med Lightsbug // Status view is removed // VMGetControl( bugsWind, 'Stat', 0, control); // InstallQDSkelViewHandler(bugsWind, control, StatusDraw, StatusMouse, StatusKey, nil); // VMGetControl( bugsWind, 'Expr', 0, control); // BugsResize(true); // CreateExpressionControls(control); ObserveResize(observeWind); // Init subunits DirectGDBInit; // Init DirectGDB - now in its own window InitSetVariableDialog; // Skapa fšnstret? Dolt? BugsDisable; end; // NŒn pollning mŒste in. Vem gšr den? Huvudprogrammets bakgrundsprocess? // RunDone och RunData som i huvudprogrammet. // RunData Šr viktigast! Tar emot data, parsar, lŠgger ut data i debugfšnster, // visar positionen (via anrop till LWPEdit), och gšr fler anrop vid behov. // RunDone bara stŠnger av debuggerinterfacet, inaktiverar allting. // OBS att build+RunWithDebug mŒste kunna gšras. end.
unit POSPrinter; { This is basically a nice wrapper for the ESC/POS protocol. } { For more information you can check: } { Specification Document: http://content.epson.de/fileadmin/content/files/RSD/downloads/escpos.pdf } { Programming Guide: http://download.delfi.com/SupportDL/Epson/Manuals/TM-T88IV/Programming%20manual%20APG_1005_receipt.pdf } interface const { Characters used by the ESC/POS protocol. } ESC = #27; GS = #29; LF = #10; NUL = #00; { Barcode types. } BARCODE_UPCA = #00; BARCODE_UPCE = #01; BARCODE_JAN13 = #02; BARCODE_JAN8 = #03; BARCODE_CODE39 = #04; BARCODE_ITF = #05; BARCODE_CODABAR = #06; { Justification types. } JUSTIFY_LEFT = #00; JUSTIFY_CENTER = #01; JUSTIFY_RIGHT = #02; { Cut types. } CUT_PARTIAL = #66; CUT_FULL = #65; CUT_PREPARE = #00; { Underline types. } UNDERLINE_NOTHING = #00; UNDERLINE_LIGHT = #01; UNDERLINE_HEAVY = #02; type TPOSPrinter = record Name: String; Width: Integer; MaxCharLine: Integer; end; var POS: TPOSPrinter; procedure SetupPrinter(name: String; width: Integer; max_char: Integer); procedure BeginPrint(title: String); procedure EndPrint; procedure PrinterFeed(num: Integer); procedure PrinterCut(ctype: Char); procedure PrinterJustify(jtype: Char); procedure PrinterUnderline(utype: Char); procedure PrinterBold(enable: Boolean); procedure PrintLine(line: String); procedure PrintLine(left: String; right: String); procedure PrintBarcode(number: String; btype: Char; print_num: Boolean); procedure PrintTestPage(printcs: Boolean); implementation uses Printers, SysUtils; { Sets the printer stuff. } procedure SetupPrinter(name: String; width: Integer; max_char: Integer); begin POS.Name := name; POS.Width := width; POS.MaxCharLine := max_char; Printer.SetPrinter(name); Printer.RawMode := true; end; { Begins the printing process. } procedure BeginPrint(title: String); begin Printer.Title := title; Printer.BeginDoc; Printer.Write(ESC + '@'); { Resets the printer formatting. } end; { Ends the printing process. } procedure EndPrint; begin Printer.EndDoc; end; { Line feeds. } procedure PrinterFeed(num: Integer); begin if num > 0 then Printer.Write(ESC + 'd' + chr(num)) else if num < 0 then Printer.Write(ESC + 'v' + chr(num + (num * 2))); end; { Cuts the paper. } procedure PrinterCut(ctype: Char); begin if ctype = CUT_PREPARE then PrinterFeed(3) else Printer.Write(ESC + 'V' + ctype); end; { Change the print justification. } procedure PrinterJustify(jtype: Char); begin Printer.Write(ESC + 'a' + jtype); end; { Sets the underline style font. } procedure PrinterUnderline(utype: Char); begin Printer.Write(ESC + '-' + utype); end; procedure PrinterBold(enable: Boolean); begin if enable then Printer.Write(ESC + 'E' + #01) else Printer.Write(ESC + 'E' + #00); end; { Prints a standard text line. } procedure PrintLine(line: String); begin Printer.Write(line + LF); end; { Prints a line with two strings spaced in the middle. } procedure PrintLine(left: String; right: String); var space: Integer; str: String; i: Integer; begin space := POS.MaxCharLine - (Length(left) + Length(right)); str := left; if space > 0 then begin for i := 1 to space do begin str := str + ' '; end; end; str := str + right; PrintLine(str); end; { Prints a barcode. } procedure PrintBarcode(number: String; btype: Char; print_num: Boolean); begin Printer.Write(GS + 'k' + btype + number + NUL); { Print the number below the barcode. } if print_num then begin PrintLine(number); end; end; procedure PrintTestPage(printcs: Boolean); var idx: Integer; begin PrinterJustify(JUSTIFY_CENTER); PrintLine('ESC/POS Printer Test Page'); PrinterFeed(1); PrintLine('Printer Data'); PrinterJustify(JUSTIFY_LEFT); PrintLine('Name: ' + POS.Name); PrintLine('Paper Width: ' + IntToStr(POS.Width)); PrintLine('Max Char. per Line: ' + IntToStr(POS.MaxCharLine)); PrinterFeed(1); PrintLine('Hello world!'); PrintLine('Forward feed 3'); PrinterFeed(3); PrintLine('Reverse feed 3'); PrinterFeed(-3); PrintLine('No Underline'); PrinterUnderline(UNDERLINE_LIGHT); PrintLine('Light Underline'); PrinterUnderline(UNDERLINE_HEAVY); PrintLine('Heavy Underline'); PrinterUnderline(UNDERLINE_NOTHING); PrintLine('No emphasis'); PrinterBold(true); PrintLine('With emphasis'); PrinterBold(false); { TODO: Fonts here. } PrinterFeed(1); PrinterJustify(JUSTIFY_LEFT); PrintLine('Left'); PrinterJustify(JUSTIFY_CENTER); PrintLine('Center'); PrinterJustify(JUSTIFY_RIGHT); PrintLine('Right'); PrinterJustify(JUSTIFY_CENTER); { Barcodes } for idx := 0 to 6 do begin PrintLine('Barcode ' + IntToStr(idx)); PrintBarcode('987612', chr(idx), true); end; if printcs then begin PrinterFeed(2); PrintLine('Character Set'); PrinterJustify(JUSTIFY_LEFT); for idx := 33 to 255 do begin PrintLine(IntToStr(idx) + ' ' + chr(idx)); end; end; end; end.
unit uSmartPhoneAssemblyPlant; interface uses uSmartPhone , uSmartPhoneFactory ; type TSmartPhoneAssemblyPlant = class public procedure AssemblePhone(const aSmartPhoneFactory: TBaseSmartPhoneFactory); end; implementation uses System.SysUtils ; { TSmartPhoneStore } procedure TSmartPhoneAssemblyPlant.AssemblePhone(const aSmartPhoneFactory: TBaseSmartPhoneFactory); var LSmartPhone: TBaseSmartPhone; begin LSmartPhone := aSmartPhoneFactory.GetSmartPhone; try WriteLn(Format('About to build a %s smartphone.', [LSmartPhone.Name])); LSmartPhone.GatherParts; LSmartPhone.Assemble; finally LSmartPhone.Free; end; end; end.
unit CatHTTP; { Catarinka - HTTP and HTML related functions Copyright (c) 2003-2017 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details ColorToHTMLColor function by Ralf Mimoun } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.Classes, System.SysUtils, Vcl.Graphics, CatStringLoop; {$ELSE} Classes, SysUtils, Graphics, CatStringLoop; {$ENDIF} type TURLParts = record Filename: string; Fileext: string; Host: string; Path: string; Port: integer; Protocol: string; end; type THTTPRequestParts = record Method: string; Path: string; Data: string; // POST data end; type THTTPHostParts = record Name: string; Port: integer; end; { THTTPHeaderLoop - Loops through a list of HTTP headers Expects a list like HTTP/1.1 200 OK Date: Sun, 09 Jul 2017 16:35:05 GMT Server: Apache (...) } type THTTPHeaderLoop = class(TStringLoop) private fFieldName:string; fFieldNameLower:string; fFieldValue:string; public constructor Create; function Found: boolean; procedure LoadFromResponse(const sl: tstrings); overload; procedure LoadFromResponse(const s:string); overload; property FieldName:string read fFieldName; property FieldNameLower:string read fFieldNameLower; property FieldValue:string read fFieldValue; end; { TURLParamsLoop - Loops through URL params Expects a URL to be loaded with LoadFromURL() Example: obj.LoadFromURL('http://somehost/index.php?url=1&id=2'); } type TURLParamsLoop = class(TStringLoop) private fParamName:string; fParamNameLower:string; fParamValue:string; public function Found: boolean; procedure LoadFromURL(const aURL:string); property ParamName:string read fParamName; property ParamNameLower:string read fParamNameLower; property ParamValue:string read fParamValue; end; // HTML functions function BoolToDisplayState(const b: boolean): string; function ColorToHTMLColor(const Color: TColor): string; function DequoteHTMLAttribValue(const s: string): string; function HtmlColorToColor(const Color: string): TColor; function HtmlEntityDecode(const s: string): string; function HtmlEscape(const s: string): string; function HtmlUnescape(const s: string): string; function StripHTML(const s: string): string; function StripPHPCode(const s: string): string; // HTTP functions function CrackHTTPHost(const Host: string): THTTPHostParts; function CrackHTTPRequest(const r: string): THTTPRequestParts; function ExtractHTTPRequestPath(const r: string): string; function ExtractHTTPRequestPostData(const r: string): string; function ExtractHTTPResponseHeader(const r: string): string; function ExtractHTTPResponseStatusCode(const r: string): integer; function GetField(const Field, ReqStr: string): string; function PostDataToJSON(const s: string): string; function RemoveHeaderFromResponse(const r: string): string; // URL functions function CrackURL(const url: string): TURLParts; function ChangeURLPath(const url, newpath: string): string; function ExtractUrlFileExt(const url: string): string; function ExtractUrlFileName(const url: string): string; function ExtractUrlHost(const url: string): string; function ExtractUrlPath(const url: string; const includeparams: boolean = true): string; function ExtractUrlPort(const url: string): integer; function FileUrlToFilename(const url: string): string; function GenerateURL(const Host: string; const Port: integer): string; function URLDecode(const s: string): string; function URLEncode(const s: string; plus: boolean = false; const preserve: TSysCharSet = ['0' .. '9', 'A' .. 'Z', 'a' .. 'z', ' ']): string; function URLEncode_U(const s: string; plus: boolean = false; const preserve: TSysCharSet = ['0' .. '9', 'A' .. 'Z', 'a' .. 'z', ' ']): string; function URLEncodeFull(const s: string): string; function URLPathTitleCase(const s: string): string; implementation uses CatStrings, CatJSON; function BoolToDisplayState(const b: boolean): string; begin if b then result := 'block' else result := 'none'; end; // By Ralf Mimoun function ColorToHTMLColor(const Color: TColor): string; var cl: LongInt; begin cl := ColorToRGB(Color); result := format('#%6.6x', [((cl and $FF0000) shr 16) + ((cl and $00FF00)) + ((cl and $0000FF) shl 16)]); end; function ChangeURLPath(const url, newpath: string): string; var oldpath, reppath: string; begin oldpath := '/' + ExtractUrlPath(url); reppath := newpath; result := replacestr(url + ' ', oldpath + ' ', reppath); end; // Expects Host[:Port] and will return its parts // Example usage: // CrackHost('127.0.0.1').port returns 80 // CrackHost('127.0.0.1:8080').port returns 8080 // CrackHost('[2001:4860:0:2001::68]:8080').port returns 8080 function CrackHTTPHost(const Host: string): THTTPHostParts; var url: string; begin url := 'http://' + Host + '/'; result.Name := ExtractUrlHost(url); result.Port := ExtractUrlPort(url); end; function CrackHTTPRequest(const r: string): THTTPRequestParts; begin result.Method := before(r, ' '); result.Path := ExtractHTTPRequestPath(r); result.Data := ExtractHTTPRequestPostData(r); end; function CrackURL(const url: string): TURLParts; begin result.Fileext := ExtractUrlFileExt(url); result.Filename := ExtractUrlFileName(url); result.Host := ExtractUrlHost(url); result.Path := ExtractUrlPath(url); result.Port := ExtractUrlPort(url); result.Protocol := before(url, ':'); end; // A special dequote for HTML attribute values // "value" -> value, 'value' -> value function DequoteHTMLAttribValue(const s: string): string; const cQuotes = ['"', '''']; var i: integer; last: char; firstisquote: boolean; begin result := s; i := length(s); if i = 0 then Exit; last := LastChar(s); firstisquote := CharInSet(s[1], cQuotes); if (firstisquote = true) and (s[1] = last) then begin Delete(result, 1, 1); SetLength(result, length(result) - 1); end else if (firstisquote = false) and (ContainsAnyOfChars(s, cQuotes) = true) then begin // uncommon, but handling something like: value" target="new" if pos(' ', s) <> 0 then result := before(s, ' '); end; end; function PostDataToJSON(const s: string): string; var d: TCatJSON; slp: TStringLoop; n, v: string; begin d := TCatJSON.Create; slp := TStringLoop.Create; slp.LoadFromString(replacestr(s, '&', crlf)); while slp.Found do begin n := before(slp.current, '='); v := after(slp.current, '='); v := URLDecode(v); if isValidJSONName(n) then d[n] := v; end; slp.free; result := d.Text; d.free; end; function ExtractHTTPResponseStatusCode(const r: string): integer; var rlines: tstringlist; st: string; begin result := -1; rlines := tstringlist.Create; rlines.Text := r; if rlines.count <> 0 then begin st := after(rlines[0], ' '); // this is the status code st := before(st, ' '); if isinteger(st) then // confirm before returning result := StrToInt(st); end; rlines.free; end; function RemoveHeaderFromResponse(const r: string): string; var i: integer; start: boolean; begin result := emptystr; start := false; for i := 1 to length(r) do begin if start = false then begin if (r[i] = #10) and (r[i - 1] = #13) and (r[i - 2] = #10) and (r[i - 3] = #13) then start := true; end else result := result + r[i]; end; end; function ExtractHTTPResponseHeader(const r: string): string; var i: integer; collected: boolean; begin result := emptystr; collected := false; for i := 1 to length(r) do begin if collected = false then if (r[i] = #10) and (r[i - 1] = #13) and (r[i - 2] = #10) and (r[i - 3] = #13) then break else result := result + r[i]; end; end; function FileUrlToFilename(const url: string): string; var f: string; begin f := url; f := after(f, 'file://'); f := replacestr(f, '/', '\\'); result := f; end; // Generates an URL from a hostname function GenerateURL(const Host: string; const Port: integer): string; var proto, sport: string; begin if Port = 443 then proto := 'https://' else proto := 'http://'; if (Port <> 80) and (Port <> 443) then sport := ':' + inttostr(Port); result := proto + Host + sport; end; function StripHTML(const s: string): string; var i: integer; strip: boolean; begin result := emptystr; strip := false; for i := 1 to length(s) do begin if s[i] = '<' then strip := true; if strip then begin if s[i] = '>' then begin strip := false; Continue; end; end else result := result + s[i]; end; end; function StripPHPCode(const s: string): string; var i: integer; strip: boolean; begin result := emptystr; strip := false; for i := 1 to length(s) do begin if (s[i] = '<') and (s[i + 1] = '?') then strip := true; if strip then begin if (s[i] = '>') and (s[i - 1] = '?') then begin strip := false; Continue; end; end else result := result + s[i]; end; end; function HtmlEscape(const s: string): string; begin result := replacestr(s, '&', '&amp;'); result := replacestr(result, '<', '&lt;'); result := replacestr(result, '>', '&gt;'); result := replacestr(result, '"', '&quot;'); result := replacestr(result, '''', '&#x27;'); end; function HtmlUnescape(const s: string): string; begin result := replacestr(s, '&amp;', '&'); result := replacestr(result, '&lt;', '<'); result := replacestr(result, '&gt;', '>'); result := replacestr(result, '&quot;', '"'); result := replacestr(result, '&#x27;', ''''); end; // Returns the value of field from a request/response header function GetField(const Field, ReqStr: string): string; var slp: TStringLoop; afield: string; begin result := emptystr; afield := lowercase(Field); if pos(afield, lowercase(ReqStr)) = 0 then Exit; // not found slp := TStringLoop.Create; slp.LoadFromString(ReqStr); while slp.Found do begin if beginswith(trim(slp.CurrentLower), afield + ':') then begin // found result := trim(after(slp.current, ':')); slp.Stop; end; end; slp.free; end; function HtmlColorToColor(const Color: string): TColor; var cl: string; begin cl := Color; Delete(cl, 1, 1); result := StrToIntDef('$' + Copy(cl, 5, 2) + Copy(cl, 3, 2) + Copy(cl, 1, 2), $00FFFFFF); end; function ExtractUrlFileName(const url: string): string; var i: integer; begin result := url; if pos('?', result) <> 0 then result := before(result, '?'); i := LastDelimiter('/', result); result := Copy(result, i + 1, length(result) - (i)); end; function ExtractUrlFileExt(const url: string): string; begin result := ExtractUrlFileName(url); if pos('?', result) <> 0 then result := before(result, '?'); result := extractfileext(result); end; function ExtractUrlHost(const url: string): string; begin result := after(url, '://'); result := before(result, '/'); if beginswith(result, '[') then begin // ipv6 format result := after(result, '['); result := before(result, ']'); result := '[' + result + ']'; end else begin // ipv4 format if pos(':', result) <> 0 then result := before(result, ':'); end; end; function ExtractUrlPort(const url: string): integer; var temp: string; begin result := 80; // default if beginswith(lowercase(url), 'https://') then result := 443; temp := after(url, '://'); temp := before(temp, '/'); if pos(':', temp) <> 0 then begin // port provided via format [proto]://[host]:[port]/ if beginswith(temp, '[') then // ipv6 format temp := after(temp, ']:') else // ipv4 format temp := after(temp, ':'); if isinteger(temp) then result := StrToInt(temp); end; end; function ExtractUrlPath(const url: string; const includeparams: boolean = true): string; begin result := after(url, '://'); result := after(result, '/'); if includeparams = false then begin if pos('?', result) <> 0 then result := before(result, '?'); end; end; function ExtractHTTPRequestPostData(const r: string): string; var slp: TStringLoop; foundempty, postbegin: boolean; postdata: string; begin postdata := emptystr; foundempty := false; postbegin := false; slp := TStringLoop.Create; slp.LoadFromString(r); while slp.Found do begin if foundempty then begin if trim(slp.current) <> emptystr then postbegin := true; end; if postbegin then begin if postdata = emptystr then postdata := slp.current else postdata := postdata + crlf + slp.current; end; if trim(slp.current) = emptystr then foundempty := true; end; result := postdata; slp.free; end; function HtmlEntityDecode(const s: string): string; begin result := replacestr(s, '&lt;', '<'); result := replacestr(result, '&gt;', '>'); result := replacestr(result, '&quot;', '"'); result := replacestr(result, '&amp;', '&'); end; function ExtractHTTPRequestPath(const r: string): string; var sl: tstringlist; begin result := '/'; sl := tstringlist.Create; sl.Text := r; if sl.count <> 0 then begin result := after(sl[0], ' '); // path, after HTTP method result := before(result, ' '); // before HTTP version end; sl.free; end; function URLDecode(const s: string): string; var i: integer; begin result := emptystr; if length(s) = 0 then result := emptystr else begin i := 1; while i <= length(s) do begin if s[i] = '%' then begin result := result + Chr(HexToInt(s[i + 1] + s[i + 2])); Inc(i, 2); end else if s[i] = '+' then result := result + ' ' else result := result + s[i]; Inc(i); end; end; end; function URLEncode(const s: string; plus: boolean = false; const preserve: TSysCharSet = ['0' .. '9', 'A' .. 'Z', 'a' .. 'z', ' ']): string; var i: integer; sp: string; begin if length(s) = 0 then result := emptystr else begin if plus then sp := '+' else sp := '%20'; for i := 1 to length(s) do begin if not(CharInSet(s[i], preserve)) then result := result + '%' + IntToHex(ord(s[i]), 2) else if (s[i] = ' ') then result := result + sp else result := result + s[i]; end; end; end; function URLEncode_U(const s: string; plus: boolean = false; const preserve: TSysCharSet = ['0' .. '9', 'A' .. 'Z', 'a' .. 'z', ' ']): string; var i: integer; sp: string; begin if length(s) = 0 then result := emptystr else begin if plus then sp := '+' else sp := '%u0020'; for i := 1 to length(s) do begin if not(CharInSet(s[i], preserve)) then result := result + '%u' + IntToHex(Integer(s[i]), 4) else if (s[i] = ' ') then result := result + sp else result := result + s[i]; end; end; end; function URLEncodeFull(const s: string): string; begin result := URLEncode(s, false, []); end; // TitleCase function adapted to work with URL paths function URLPathTitleCase(const s: string): string; var i: integer; begin result := s; for i := 1 to length(result) - 1 do if CharInSet(result[i], (['~', '/'] - ['.', '-', 'A' .. 'Z', 'a' .. 'z'])) then if CharInSet(result[i + 1], ['a' .. 'z']) then result[i + 1] := char(ord(result[i + 1]) and not $20); end; {------------------------------------------------------------------------------} constructor THTTPHeaderLoop.Create; begin inherited Create(nil); end; procedure THTTPHeaderLoop.LoadFromResponse(const s:string); var sl:tstringlist; begin sl := TStringList.Create; sl.Text := s; Load(sl); sl.Free; end; procedure THTTPHeaderLoop.LoadFromResponse(const sl: tstrings); var bs:string; begin // Deletes the first line if it is not a field // Handles a line like: HTTP/1.1 200 OK, GET / HTTP/1.1, etc if sl.Count<>0 then begin if pos(' ',sl[0])<> 0 then begin bs := before(sl[0],' '); if endswith(bs,':') = false then sl.Delete(0); end; end; // If there is an empty line, delete it and what comes after it if pos(crlf+crlf, sl.text) <> 0 then sl.text := before(sl.Text,crlf+crlf); inherited Load(sl); end; function THTTPHeaderLoop.Found: boolean; const cSep = ':'; begin result := inherited found; fFieldName:=emptystr; fFieldValue:=emptystr; fFieldNameLower:=emptystr; if pos(cSep,Current) <> 0 then begin fFieldName:=trim(before(current,cSep)); fFieldValue:=trim(after(current,cSep)); fFieldNameLower:=lowercase(FieldName); end; end; {------------------------------------------------------------------------------} procedure TURLParamsLoop.LoadFromURL(const aURL:string); var params,url:string; begin url := trim(aURL); url := replacestr(url, ' ','%20'); params := emptystr; if occurs('?', url) <> 0 then begin params := gettoken(url, '?', 2); params := replacestr(params,'&',crlf); end; fList.CommaText := params; Reset; end; function TURLParamsLoop.Found: boolean; const cSep = '='; begin result := inherited found; fParamName:=emptystr; fParamValue:=emptystr; fParamNameLower:=emptystr; if pos(cSep,Current) <> 0 then begin fParamName:=trim(before(current,cSep)); fParamValue:=trim(after(current,cSep)); fParamNameLower:=lowercase(fParamName); end; end; end. // ------------------------------------------------------------------------// end.
unit PessoaTelefoneDTO; interface uses Atributos, SynCommons, mORMot; type TPessoa_Telefone = class(TSQLRecord) private FID_PESSOA: TID; FTIPO: Integer; FNUMERO: RawUTF8; FOBSERVACAO: RawUTF8; //Usado no lado cliente para controlar quais registros serão persistidos FPersiste: String; public [TColumn('PERSISTE', 'Persiste', 60, [], True)] property Persiste: String read FPersiste write FPersiste; published [TColumn('ID_PESSOA', 'Id Pessoa', 80, [], False)] property Id_Pessoa: TID read FID_PESSOA write FID_PESSOA; [TColumn('TIPO', 'Tipo', 80, [ldGrid, ldLookup, ldCombobox], False)] property Tipo: Integer read FTIPO write FTIPO; [TColumn('NUMERO', 'Numero', 112, [ldGrid, ldLookup, ldCombobox], False)] property Numero: RawUTF8 read FNUMERO write FNUMERO; [TColumn('OBSERVACAO', 'Observacao', 500, [ldGrid, ldLookup, ldCombobox], False)] property Observacao: RawUTF8 read FOBSERVACAO write FOBSERVACAO; end; implementation end.
{********************************** File Header ******************************** File Name : Videocap.pas Author : gcasais Date Created: 21/01/2004 Language : ES-AR Description : Objetos, Wrappers y métodos para VFW *******************************************************************************} unit Videocap; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls,stdctrls, ExtCtrls, vfw, MMSystem, SyncObjs, JPEG; type // Audio TChannel = (Stereo, Mono); TFrequency = (f8000Hz, f11025Hz, f22050Hz, f44100Hz); TResolution = (r8Bit, r16Bit); type TCapStatusProc = TNotifyEvent; TCapStatusCallback = procedure (Sender:TObject; nID:integer; status:string) of object; TVideoStream = procedure (sender:TObject; lpVhdr:PVIDEOHDR) of object; TAudioStream = procedure (sender:TObject; lpWHdr:PWAVEHDR) of object; TError = procedure (sender:TObject; nID:integer; errorstr:string) of object; TOnNewPreviewFrameMemoryNotifyEvent = procedure (Sender: TObject; MemoryForFrame: TMemoryStream) of object; TOnNewPreviewFrameImageNotifyEvent = procedure (Sender: TObject; ImageForFrame: TImage) of object; // Excepciones type ENoDriverException = class(Exception); type ENoCapWindowException = class(Exception); type ENotConnectException = class(Exception); type ENoOverlayException = class(Exception); type EFalseFormat = class(Exception); type ENotOpen = class(Exception); type EBufferFileError = class(Exception); type TAudioFormat = class (TPersistent) private FChannels :TChannel; FFrequency:TFrequency; FRes :TResolution; private procedure SetAudio(Handle:Thandle); public constructor Create; published property Channels: TChannel read FChannels write Fchannels default Mono; property Frequency: TFrequency read FFrequency write fFrequency default f8000Hz; property Resolution : TResolution read FRes write FRes default r8Bit; end; type TVideoCap = class(TCustomControl) private FOnNewPreviewFrameMemory: TOnNewPreviewFrameMemoryNotifyEvent; FOnNewPreviewFrameImage: TOnNewPreviewFrameImageNotifyEvent; FAutoSelectYUY2: Boolean; FJPEGSectionTypeList: array of UInt8; FMemorForPreview: TMemoryStream; FImgForPreview: TImage; FControlForPreview: TCustomControl; fCenter: Boolean; fdriverIndex : Integer; fVideoDriverName : String; fhCapWnd : THandle; fpDrivercaps : PCapDriverCaps; fpDriverStatus : pCapStatus; fscale : Boolean; fprop : Boolean; fpreviewrate : Word; fmicrosecpframe : Cardinal; fCapVideoFileName : String; fTempFileName : String; fTempFileSize : Word; fCapSingleImageFileName : String; fcapAudio : Boolean; fcapTimeLimit : Word; fIndexSize : Cardinal; fcapToFile : Boolean; FAudioFormat : TAudioFormat; fCapStatusprocedure : TCapStatusProc; fcapStatusCallBack : TCapStatusCallback; fcapVideoStream : TVideoStream; fcapAudioStream : TAudiostream; fcapFrameCallback : TVideoStream; fcapError : TError; procedure Setsize(var msg:TMessage); message WM_SIZE; function GetDriverCaps: Boolean; procedure DeleteDriverProps; procedure CreateTmpFile (drvopn: Boolean); function GetDriverStatus (callback:boolean): Boolean; procedure SetDriverOpen (value: Boolean) ; function GetDriverOpen : Boolean; function GetPreview: Boolean; function GetOverlay: Boolean; procedure SizeCap; procedure Setprop (value: Boolean); procedure SetCenter(Value: Boolean); procedure SetAutoSelectYUY2(Value: Boolean); procedure SetMicroSecPerFrame(value: Cardinal); procedure setFrameRate (value: Word); function GetFrameRate: Word; procedure SetDriverIndex(value:integer); function CreateCapWindow:boolean; procedure DestroyCapwindow; function GetCapWidth:word; function GetCapHeight:word; function GetHasDlgVFormat : Boolean; function GetHasDlgVDisplay : Boolean; function GetHasDlgVSource : Boolean; function GetHasVideoOverlay: Boolean; procedure Setoverlay(value:boolean); procedure SetPreview(value:boolean); procedure SetScale(value:Boolean); procedure SetpreviewRate(value:word); function GetCapInProgress:boolean; procedure SetIndexSize(value:cardinal); function GetBitMapInfoNP:TBITMAPINFO; function GetBitmapHeader:TBitmapInfoHeader; procedure SetBitmapHeader(Header:TBitmapInfoHeader); procedure SetBufferFileSize(value:word); // CallBacks de captura procedure SetStatCallBack(value:TCapStatusCallback); procedure SetCapVideoStream(value:TVideoStream); procedure SetCapAudioStream(value:TAudioStream); procedure SetCapFrameCallback(value:TVideoStream); procedure SetCapError(value:TError); procedure CreateImgForPreview; procedure DestroyImgForPreview; function IsImgForPreviewMode: Boolean; {$IFDEF UNICODE} procedure SavePreviewToMemory; {$ELSE} procedure SavePreviewToMemory(IsBitmap: Boolean); {$ENDIF} procedure MoveCapOut; procedure SetInternalControlBounds; function IsInternalControl(AChild: TControl): Boolean; function CaptureFrameForPreview(lpVhdr: PVIDEOHDR): LRESULT; protected procedure SetParent(AParent: TWinControl); override; function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override; procedure Loaded; override; procedure AdjustSize; override; function GetControlExtents: TRect; override; public procedure SetBounds(ALeft: Integer; ATop: Integer; AWidth: Integer; AHeight: Integer); override; procedure SetDriverName(value:String); constructor Create(AOwner: TComponent); override; destructor destroy; override; property HasDlgFormat:Boolean read GetHasDlgVFormat; property HasDlgDisplay:Boolean read GetHasDlgVDisplay; property HasDlgSource:Boolean read GetHasDlgVSource; property HasVideoOverlay:boolean read GetHasVideoOverlay; property CapWidth: word read GetCapWidth; property CapHeight: word read GetCapHeight; property CapInProgess: boolean read getCapinProgress; property BitMapInfo:TBitmapinfo read GetBitmapInfoNP; // Header Bitmapinfo function DlgVFormat:Boolean; function DlgVDisplay:boolean; function DlgVSource:boolean; function DlgVCompression:Boolean; function GrabFrame:boolean; function GrabFrameNoStop:boolean; function SaveAsDIB:Boolean; function SaveToClipboard:Boolean; function StartCapture:Boolean; function StopCapture:Boolean; function GetBitmapInfo(var p:Pointer):integer; procedure SetBitmapInfo(p:Pointer;size:integer); property BitMapInfoHeader:TBitmapInfoHeader read GetBitmapHeader write SetBitmapHeader; function SaveCap:boolean; function CapSingleFramesOpen:boolean; function CapSingleFramesClose:boolean; function CapSingleFrame:boolean; function IsBitmapHeaderSupport(Header:TBitmapInfoHeader): Boolean; procedure TestCurrentFormat; function IsCurrentFormatNotSupport: Boolean; function CurrentIsBitmapFormat: Boolean; function IsNeedFixData: Boolean; function IsNotifyDataEvent: Boolean; function TrySelectYUY2: Boolean; published property OnNewPreviewFrameMemory: TOnNewPreviewFrameMemoryNotifyEvent read FOnNewPreviewFrameMemory write FOnNewPreviewFrameMemory; property OnNewPreviewFrameImage: TOnNewPreviewFrameImageNotifyEvent read FOnNewPreviewFrameImage write FOnNewPreviewFrameImage; property AutoSize; property align; property color default clBlack; property visible; property DriverOpen: boolean read getDriveropen write setDriverOpen; property DriverIndex:integer read fdriverindex write SetDriverIndex; property DriverName: string read fVideoDriverName write SetDrivername; property VideoOverlay:boolean read GetOverlay write SetOverlay; property VideoPreview:boolean read GetPreview write SetPreview; property PreviewScaleToWindow:boolean read fscale write Setscale; property PreviewScaleProportional:boolean read fprop write Setprop; property PreviewfCenterToWindows: Boolean read fCenter write SetCenter; Property AutoSelectYUY2: Boolean read FAutoSelectYUY2 write SetAutoSelectYUY2; property PreviewRate:word read fpreviewrate write SetpreviewRate; property MicroSecPerFrame:cardinal read fmicrosecpframe write SetMicroSecPerFrame; property FrameRate:word read getFramerate write setFrameRate; Property CapAudio:Boolean read fcapAudio write fcapAudio; property VideoFileName:string read fCapVideoFileName write fCapVideoFileName; property SingleImageFile:string read FCapSingleImageFileName write FCapSingleImageFileName; property CapTimeLimit:word read fCapTimeLimit write fCapTimeLimit; property CapIndexSize:cardinal read findexSize write setIndexSize; property CapToFile:boolean read fcaptoFile write fcapToFile; property CapAudioFormat:TAudioformat read FAudioformat write FAudioFormat; property BufferFileSize:word read ftempfilesize write SetBufferFileSize; property OnStatus:TCapStatusProc read fCapStatusprocedure write FCapStatusProcedure; property OnStatusCallback:TCapStatusCallback read fcapStatuscallback write SetStatCallback; property OnVideoStream:TVideoStream read fcapVideoStream write SetCapVideoStream; property OnFrameCallback:TVideoStream read FcapFramecallback write SetCapFrameCallback; property OnAudioStream:TAudioStream read fcapAudioStream write SetCapAudioStream; property OnError:TError read fcapError write SetCapError; property OnMouseMove; property OnMouseUp; property OnMouseDown; property OnClick; Property OnDblClick; end; const Jpeg_default_dht: array[0..419] of Byte = ( $ff,$c4, //* DHT (Define Huffman Table) identifier */ $01,$a2, //* section size: $01a2, from this two bytes to the end, inclusive */ $00, //* DC Luminance */ $00,$01,$05,$01,$01,$01,$01,$01,$01,$00,$00,$00,$00,$00,$00,$00, //* BITS */ $00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b, //* HUFFVALS */ $10, //* AC Luminance */ $00,$02,$01,$03,$03,$02,$04,$03,$05,$05,$04,$04,$00,$00,$01,$7d, //* BITS */ $01,$02,$03,$00,$04,$11,$05,$12,$21,$31,$41,$06,$13,$51,$61,$07, //* HUFFVALS */ $22,$71,$14,$32,$81,$91,$a1,$08,$23,$42,$b1,$c1,$15,$52,$d1,$f0, $24,$33,$62,$72,$82,$09,$0a,$16,$17,$18,$19,$1a,$25,$26,$27,$28, $29,$2a,$34,$35,$36,$37,$38,$39,$3a,$43,$44,$45,$46,$47,$48,$49, $4a,$53,$54,$55,$56,$57,$58,$59,$5a,$63,$64,$65,$66,$67,$68,$69, $6a,$73,$74,$75,$76,$77,$78,$79,$7a,$83,$84,$85,$86,$87,$88,$89, $8a,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$a2,$a3,$a4,$a5,$a6,$a7, $a8,$a9,$aa,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$c2,$c3,$c4,$c5, $c6,$c7,$c8,$c9,$ca,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$e1,$e2, $e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8, $f9,$fa, $01, //* DC Chrominance */ $00,$03,$01,$01,$01,$01,$01,$01,$01,$01,$01,$00,$00,$00,$00,$00, //* BITS */ $00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b, //* HUFFVALS */ $11, //* AC Chrominance */ $00,$02,$01,$02,$04,$04,$03,$04,$07,$05,$04,$04,$00,$01,$02,$77, //* BITS */ $00,$01,$02,$03,$11,$04,$05,$21,$31,$06,$12,$41,$51,$07,$61,$71, //* HUFFVALS */ $13,$22,$32,$81,$08,$14,$42,$91,$a1,$b1,$c1,$09,$23,$33,$52,$f0, $15,$62,$72,$d1,$0a,$16,$24,$34,$e1,$25,$f1,$17,$18,$19,$1a,$26, $27,$28,$29,$2a,$35,$36,$37,$38,$39,$3a,$43,$44,$45,$46,$47,$48, $49,$4a,$53,$54,$55,$56,$57,$58,$59,$5a,$63,$64,$65,$66,$67,$68, $69,$6a,$73,$74,$75,$76,$77,$78,$79,$7a,$82,$83,$84,$85,$86,$87, $88,$89,$8a,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$a2,$a3,$a4,$a5, $a6,$a7,$a8,$a9,$aa,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$c2,$c3, $c4,$c5,$c6,$c7,$c8,$c9,$ca,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da, $e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$f2,$f3,$f4,$f5,$f6,$f7,$f8, $f9,$fa); const Jpeg_default_sio: array[0..1] of Byte = ($FF, $D8); const Jpeg_default_app0: array[0..17] of Byte = ( $FF, $E0, $00, $10, $4A, $46, $49, $46, $00, $01, $01, $01, $00, $60, $00, $60, $00, $00); function GetDriverList: TStringList; procedure FrameToBitmap(Bitmap:TBitmap;FrameBuffer:pointer; BitmapInfo:TBitmapInfo); procedure BitmapToFrame(Bitmap:TBitmap; FrameBuffer:pointer; BitmapInfo:TBitmapInfo); function GetVideoCapDeviceNameByDriverIndex(const DriverIndex: Cardinal; DisplayMode: Boolean = False): string; function GetBitmapInfoHeader(Compression: DWORD; Width, Height: Longint; BitCount: Word): TBitmapInfoHeader; implementation uses Registry, Clipbrd, Math; function GetDeviceDisplayName(FullName: string): string; var I: Integer; begin Result := FullName; with TStringList.Create do try {$IFDEF UNICODE} Text := StringReplace(FullName, ';', LineBreak, [rfReplaceAll]); {$ELSE} Text := StringReplace(FullName, ';', sLineBreak, [rfReplaceAll]); {$ENDIF} for I := Count - 1 downto 0 do begin if Trim(Strings[I]) <> '' then begin Result := Strings[I]; break; end; end; finally Free; end; end; resourcestring msvideoRegKey = {HKEY_LOCAL_MACHINE\}'SYSTEM\CurrentControlSet\Control\MediaResources\msvideo'; GenericImageText = 'Generic Image Capture'; DevicePath_Text = 'DevicePath'; DeviceDesc_Text = 'DeviceDesc'; Description_Text = 'Description'; EnumKey = 'SYSTEM\CurrentControlSet\Enum'; function GetVideoCapDeviceNameByDriverIndex(const DriverIndex: Cardinal; DisplayMode: Boolean = False): string; var TempDeviceKey, TempDriverName: string; AReg: TRegistry; I: Integer; name: array[0..128] of char; ver : array[0..128] of char; AKeys: TStrings; isFound: Boolean; begin Result := GenericImageText; if capGetDriverDescription(DriverIndex,name,128,ver,128) then begin Result := StrPas(name); TempDriverName := Result; end else begin exit; end; AReg := TRegistry.Create; AKeys := TStringList.Create; try AReg.RootKey := HKEY_LOCAL_MACHINE; if AReg.OpenKeyReadOnly(msvideoRegKey) then begin AKeys.Clear; AReg.GetKeyNames(AKeys); AReg.CloseKey; isFound := False; for i := 0 to AKeys.Count -1 do begin if AReg.OpenKeyReadOnly(msvideoRegKey + '\' + AKeys.Strings[i]) then begin if AReg.ValueExists(DevicePath_Text) and AReg.ValueExists(Description_Text) then begin if AReg.ReadString(Description_Text) = TempDriverName then begin TempDeviceKey := AReg.ReadString(DevicePath_Text); TempDeviceKey := StringReplace(TempDeviceKey,'\\?',EnumKey,[rfIgnoreCase]); TempDeviceKey := StringReplace(TempDeviceKey,'#','\',[rfIgnoreCase,rfReplaceAll]); TempDeviceKey := StringReplace(TempDeviceKey,'\global','',[rfIgnoreCase,rfReplaceAll]); AReg.CloseKey; While not AReg.KeyExists(TempDeviceKey) do begin TempDeviceKey := ExtractFileDir(TempDeviceKey); if Trim(TempDeviceKey) = '' then begin break; end; end; if Trim(TempDeviceKey) <> '' then begin if AReg.OpenKeyReadOnly(TempDeviceKey) then begin if AReg.ValueExists(DeviceDesc_Text) then begin Result := AReg.ReadString(DeviceDesc_Text); isFound := True; end; AReg.CloseKey; end; end; end; end; AReg.CloseKey; end; if isFound then begin break; end; end; AReg.CloseKey; end; if isFound and DisplayMode then begin Result := GetDeviceDisplayName(Result); end; finally if Assigned(AReg) then begin FreeAndNil(AReg); end; if Assigned(AKeys) then begin FreeAndNil(AKeys); end; end; end; function GetBitmapInfoHeader(Compression: DWORD; Width, Height: Longint; BitCount: Word): TBitmapInfoHeader; var ByteCount: Integer; begin FillMemory(@Result, Sizeof(Result), 0); Result.biSize := 40; Result.biWidth := Width; Result.biHeight := Height; Result.biPlanes := 1; Result.biBitCount := BitCount; Result.biCompression := Compression; ByteCount := Result.biBitCount div 8; if Result.biBitCount mod 8 <> 0 then inc(ByteCount); Result.biSizeImage := Result.biWidth * Result.biHeight * ByteCount; end; function GetMJPGBitmapInfoHeader(Width, Height: Longint): TBitmapInfoHeader; begin Result := GetBitmapInfoHeader(BI_MJPG, Width, Height, 24); end; function GetYUY2BitmapInfoHeader(Width, Height: Longint): TBitmapInfoHeader; begin Result := GetBitmapInfoHeader(BI_YUY2, Width, Height, 16); end; function GetYUYVBitmapInfoHeader(Width, Height: Longint): TBitmapInfoHeader; begin Result := GetBitmapInfoHeader(BI_YUYV, Width, Height, 16); end; function GetRGB24BitmapInfoHeader(Width, Height: Longint): TBitmapInfoHeader; begin Result := GetBitmapInfoHeader(BI_RGB, Width, Height, 24); end; function GetRGB32BitmapInfoHeader(Width, Height: Longint): TBitmapInfoHeader; begin Result := GetBitmapInfoHeader(BI_RGB32, Width, Height, 32); end; function GetARGB32BitmapInfoHeader(Width, Height: Longint): TBitmapInfoHeader; begin Result := GetBitmapInfoHeader(BI_RGB32, Width, Height, 32); end; function GetRGBBitmapInfoHeader(Width, Height: Longint): TBitmapInfoHeader; begin Result := GetBitmapInfoHeader(BI_RGB, Width, Height, 32); end; function StatusCallbackProc(hWnd : HWND; nID : Integer; lpsz : Pchar): LRESULT; stdcall; var Control:TVideoCap; begin Control:=TVideoCap(capGetUserData(hwnd)); if assigned(control) then begin if assigned(control.fcapStatusCallBack) then control.fcapStatusCallBack(control,nId,strPas(lpsz)); end; Result:= 1; end; // Callback para video stream function VideoStreamCallbackProc(hWnd:Hwnd; lpVHdr:PVIDEOHDR):LRESULT; stdcall; var Control:TVideoCap; begin Control:= TVideoCap(capGetUserData(hwnd)); if Assigned(control) then begin if Assigned(control.fcapVideoStream ) then begin control.fcapVideoStream(control,lpvHdr); Result := 1; end; if Control.VideoPreview then begin Result := Control.CaptureFrameForPreview(lpVhdr); end; end; end; function FindJPEGSectionType(TypeList: array of UInt8; AType: UInt8): Boolean; var I: Integer; begin Result := False; for I := Low(TypeList) to High(TypeList) do begin if TypeList[I] = AType then begin Result := True; break; end; end; end; function FrameCallbackProc(hwnd:Hwnd; lpvhdr:PVideoHdr):LRESULT;stdcall; var Control:TVideoCap; begin Control:= TVideoCap(capGetUserData(hwnd)); if Assigned(Control) then begin if Assigned(Control.fcapFrameCallback ) then begin Control.fcapFrameCallback(control,lpvHdr); Result := 1; end; Result := Control.CaptureFrameForPreview(lpVhdr); end; end; function AudioStreamCallbackProc(hwnd:HWND;lpWHdr:PWaveHdr):LRESULT; stdcall; var Control: TVideoCap; begin Control:= TVideoCap(capGetUserData(hwnd)); if assigned(control) then if assigned(control.fcapAudioStream) then begin Control.fcapAudioStream(control,lpwhdr); end; Result:= 1; end; function ErrorCallbackProc(hwnd:HWND;nId:integer;lzError:Pchar):LRESULT;stdcall; var Control:TVideoCap; begin Control:= TVideoCap(capGetUserData(hwnd)); if assigned(control) then if assigned(control.fcaperror) then begin control.fcapError(control,nId,StrPas(lzError)); end; result:= 1; end; function WCapproc(hw:HWND;messa:UINT; w:wParam; l:lParam):LRESULT;stdcall; var oldwndProc:TFNWndProc; parentWnd:HWND; begin oldwndproc:=TFNWndProc(GetWindowLong(hw,GWL_USERDATA)); case Messa of WM_MOUSEMOVE, WM_LBUTTONDBLCLK, WM_LBUTTONDOWN,WM_RBUTTONDOWN,WM_MBUTTONDOWN , WM_LBUTTONUP,WM_RBUTTONUP,WM_MBUTTONUP: begin ParentWnd:=HWND(GetWindowLong(hw,GWL_HWNDPARENT)); sendMessage(ParentWnd,messa,w,l); result := integer(true); end else result:= callWindowProc(oldwndproc,hw,messa,w,l); end; end; constructor TVideoCap.Create(aowner:TComponent); begin inherited create(aowner); ControlStyle := ControlStyle - [csAcceptsControls] - [csDoubleClicks]; height := 240; width := 320; Color := clBlack; fVideoDriverName := ''; fdriverindex := -1 ; fhCapWnd := 0; fCapVideoFileName := 'Video.avi'; fCapSingleImageFileName := 'Capture.bmp'; fscale := false; fprop := false; fpreviewrate := 15; fmicrosecpframe := 66667; fpDrivercaps := nil; fpDriverStatus := nil; fcapToFile := true; findexSize := 0; ftempFileSize := 0; fCapStatusprocedure := nil; fcapStatusCallBack := nil; fcapVideoStream := nil; fcapAudioStream := nil; FAudioformat:= TAudioFormat.Create; fCenter := False; FAutoSelectYUY2 := True; FImgForPreview := nil; FMemorForPreview := TMemoryStream.Create; SetLength(FJPEGSectionTypeList, 0); FControlForPreview := nil; DestroyImgForPreview; end; Destructor TVideoCap.destroy; Begin DestroyCapWindow; deleteDriverProps; fAudioformat.free; SetLength(FJPEGSectionTypeList, 0); FreeAndNil(FMemorForPreview); FreeAndNil(FImgForPreview); FreeAndNil(FControlForPreview); inherited destroy; end; function TVideoCap.CurrentIsBitmapFormat: Boolean; var Bh: TBitmapInfoHeader; begin Result := False; if not DriverOpen then exit; Bh := BitMapInfoHeader; Result := (Bh.biCompression = BI_RGB) or (Bh.biCompression = BI_RGB1) or (Bh.biCompression = BI_RGB4) or (Bh.biCompression = BI_RGB8) or (Bh.biCompression = BI_RGB565) or (Bh.biCompression = BI_RGB555) or (Bh.biCompression = BI_RGB24) or (Bh.biCompression = BI_ARGB32) or (Bh.biCompression = BI_RGB32); end; function TVideoCap.IsNotifyDataEvent: Boolean; begin Result := False; if not Result then begin Result := Assigned(OnNewPreviewFrameImage); end; if not Result then begin Result := Assigned(OnNewPreviewFrameMemory); end; end; function TVideoCap.IsNeedFixData: Boolean; var Bh: TBitmapInfoHeader; begin Result := False; if not DriverOpen then exit; Bh := BitMapInfoHeader; // if (Bh.biCompression = BI_YUY2) or // (Bh.biCompression = BI_RGB24) or // (Bh.biCompression = BI_RGB32) or // (Bh.biCompression = BI_RGB) or // (Bh.biCompression = BI_YUYV) then // begin // end // else // begin // // end; Result := Bh.biCompression = BI_MJPG; // or more. end; procedure TVideoCap.MoveCapOut; begin MoveWindow(fhcapWnd, ClientRect.Left + 1 - Capwidth, ClientRect.Top + 1 - capheight, Capwidth, capheight, True); capPreviewScale(fhCapWnd, False); end; procedure TVideoCap.SetParent(AParent: TWinControl); begin inherited SetParent(AParent); if AParent <> nil then begin if FImgForPreview <> nil then FImgForPreview.Parent := Self; if FControlForPreview <> nil then FControlForPreview.Parent := Self; end else begin if FImgForPreview <> nil then FImgForPreview.Parent := nil; if FControlForPreview <> nil then FControlForPreview.Parent := nil; end; end; function TVideoCap.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; begin Result := inherited CanAutoSize(NewWidth, NewHeight); if Result then begin NewWidth := CapWidth; if NewWidth = 0 then NewWidth := 160; NewHeight := CapHeight; if NewHeight = 0 then NewHeight := 120; end; end; procedure TVideoCap.Loaded; begin inherited; AdjustSize; end; procedure TVideoCap.AdjustSize; begin inherited; SetInternalControlBounds; end; procedure TVideoCap.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited SetBounds(ALeft, ATop, AWidth, AHeight); SetInternalControlBounds; end; function TVideoCap.IsInternalControl(AChild: TControl): Boolean; begin Result := False; if AChild = nil then exit; if (Parent <> nil) and (AChild.Parent <> Self) then exit; Result := True; if AChild = FImgForPreview then exit; if AChild = FControlForPreview then exit; if AChild = self then exit; Result := False; end; function TVideoCap.GetControlExtents: TRect; var I: Integer; begin Result := Rect(MaxInt, MaxInt, 0, 0); for I := 0 to ControlCount - 1 do begin if IsInternalControl(Controls[I]) then Continue; with Controls[I] do if Visible or (csDesigning in ComponentState) and not (csNoDesignVisible in ControlStyle) then begin if Left < Result.Left then Result.Left := Left; if Top < Result.Top then Result.Top := Top; if Left + Width > Result.Right then Result.Right := Left + Width; if Top + Height > Result.Bottom then Result.Bottom := Top + Height; end; end; end; procedure TVideoCap.SetInternalControlBounds; begin if Parent = nil then exit; if IsImgForPreviewMode then begin FImgForPreview.AutoSize := False; FImgForPreview.Parent := Self; FImgForPreview.BoundsRect := ClientRect; FImgForPreview.Align := alClient; FControlForPreview.Align := alNone; //Must Show. FControlForPreview.SetBounds(ClientRect.Left, ClientRect.Top, 10, 10); SetWindowPos(FControlForPreview.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE); MoveCapOut; end else begin if (FControlForPreview = nil) then begin DestroyImgForPreview; end; FControlForPreview.Parent := Self; FControlForPreview.BoundsRect := ClientRect; SetWindowPos(FControlForPreview.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE); FControlForPreview.Align := alClient; SizeCap; end; end; function TVideoCap.CaptureFrameForPreview(lpVhdr: PVIDEOHDR): LRESULT; var S: UInt16; C, I: Integer; T: UInt8; bmpInfo: TBitmapInfo; Bmpfilehd: BITMAPFILEHEADER; BeginIndex: Integer; EndIndex: Integer; // IsCloseData: Boolean; begin Result := 0; // IsCloseData := True; if (lpvhdr <> nil) and (lpvhdr.dwBytesUsed <> 0) and (IsNeedFixData or IsNotifyDataEvent) then begin // FillMemory(@bihIn, Sizeof(BITMAPINFOHEADER), 0); // FillMemory(@bihOut, Sizeof(BITMAPINFOHEADER), 0); // bihIn := bmpInfo.bmiHeader; // bihIn.biWidth := 0; // bihIn.biHeight := 0; // bihIn.biSizeImage := 0; // bihOut.biPlanes := 1; // bihOut.biSize := SizeOf(BITMAPINFOHEADER); // bihOut.biWidth := bihIn.biWidth; // bihOut.biHeight := bihIn.biHeight; // bihOut.biPlanes := 1; // bihOut.biCompression := BI_RGB24; // bihOut.biBitCount := 24; // bihOut.biSizeImage := bihIn.biSizeImage; // aHIC := ICLocate(ICTYPE_VIDEO, 0, Addr(bihIn), Addr(bihOut), ICMODE_DECOMPRESS); // if (aHIC <> 0) then // try // if (ICDecompressBegin(aHIC, Addr(bihIn), Addr(bihOut)) = ICERR_OK) then // begin // try // Buf := GetMemory(bmpInfo.bmiHeader.biSizeImage); // try // if (ICDecompress(aHIC, 0, Addr(bihIn), lpVhdr.lpData, Addr(bihOut), Buf) = ICERR_OK) then // begin // bmpInfo.bmiHeader := bihOut; // GetWindowRect(Capture.Handle, WndRect); // pDC := GetDC(Capture.Handle); // MemDC := CreateCompatibleDC(pDC); // bmp := CreateCompatibleBitmap(MemDC, bmpInfo.bmiHeader.biWidth, bmpInfo.bmiHeader.biHeight); // pOldBmp := HGDIOBJ(Addr(bmp)); // pOldBmp := SelectObject(MemDC, pOldBmp); // SetDIBitsToDevice(MemDC, 0, 0, bmpInfo.bmiHeader.biWidth, bmpInfo.bmiHeader.biHeight, 0, 0, 0, // bmpInfo.bmiHeader.biHeight, Buf, &bmpInfo, DIB_RGB_COLORS); // BitBlt(pDC, 0, 0, WndRect.Width, WndRect.Height, &MemDC, 0, 0, SRCCOPY); // end; // finally // FreeMemory(Buf); // end; // finally // ICDecompressEnd(aHIC); // end; // end; // finally // ICClose(aHIC); // end;; // fccType := ICTYPE_VIDEO; // I := 0; // While ICInfo(fccType, I, Addr(AICINFO)) do // begin // Inc(I); // aHIC := ICOpen(AICINFO.fccType, AICINFO.fccHandler, ICMODE_QUERY); // if (aHIC <> 0) then // try // ICGetInfo(aHIC, Addr(AICINFO), SizeOf(TICINFO)); // ShowMessage(AICINFO.szDescription); // finally // ICClose(aHIC); // end; // end; bmpInfo := BitMapInfo; if bmpInfo.bmiHeader.biCompression = BI_MJPG then begin SetLength(FJPEGSectionTypeList, 0); I := 2; C := 0; while (I < lpvhdr.dwBytesUsed) do begin while (I < lpvhdr.dwBytesUsed) do begin if lpvhdr.lpData[I] = $FF then begin Inc(I); break; end; Inc(I); end; Inc(C); Inc(I); WordRec(S).Hi := lpvhdr.lpData[I]; Inc(I); WordRec(S).Lo := lpvhdr.lpData[I]; Inc(I, S - 1); end; SetLength(FJPEGSectionTypeList, C); I := 2; C := 0; while (I < lpvhdr.dwBytesUsed) do begin while (I < lpvhdr.dwBytesUsed) do begin if lpvhdr.lpData[I] = $FF then begin Inc(I); break; end; Inc(I); end; T := lpvhdr.lpData[I]; FJPEGSectionTypeList[C] := T; Inc(C); Inc(I); WordRec(S).Hi := lpvhdr.lpData[I]; Inc(I); WordRec(S).Lo := lpvhdr.lpData[I]; Inc(I, S - 1); end; BeginIndex := 0; EndIndex := lpVhdr.dwBytesUsed - 2; //https://blog.csdn.net/yangysng07/article/details/9025443 for I := 0 to lpVhdr.dwBytesUsed div 2 - 1 do begin //找到 DQT; if (lpVhdr.lpData[I * 2] = $FF) and (lpVhdr.lpData[I * 2 + 1] = $DB) then begin BeginIndex := I * 2; break; end; end; EndIndex := BeginIndex; for I := lpVhdr.dwBytesUsed - 2 downto 0 do begin if (lpVhdr.lpData[I] = $FF) and (lpVhdr.lpData[I + 1] = $D9) then begin EndIndex := I; break; end; end; if (EndIndex <> BeginIndex) or (EndIndex - BeginIndex + 2 <> 0) then begin // if (lpVhdr.dwFlags = 0) or // (lpVhdr.dwFlags and VHDR_PREPARED = VHDR_PREPARED) then if True then begin FMemorForPreview.Position := 0; //写入 JPEG_SIO FMemorForPreview.Write(Jpeg_default_sio[0], Length(Jpeg_default_sio)); if not FindJPEGSectionType(FJPEGSectionTypeList, $D8) then begin //写入 JPEG_APP0 FMemorForPreview.Write(Jpeg_default_app0[0], Length(Jpeg_default_app0)); end; if not FindJPEGSectionType(FJPEGSectionTypeList, $C4) then begin //写入 JPEG_DHT FMemorForPreview.Write(Jpeg_default_dht[0], Length(Jpeg_default_dht)); end; FMemorForPreview.Write(lpVhdr.lpData[BeginIndex], EndIndex - BeginIndex + 2); end else begin FMemorForPreview.Write(lpVhdr.lpData[0], lpVhdr.dwBytesUsed); end; FMemorForPreview.Size := FMemorForPreview.Position; {$IFDEF UNICODE} SavePreviewToMemory; {$ELSE} SavePreviewToMemory(False); {$ENDIF} end; end else if CurrentIsBitmapFormat and IsNotifyDataEvent then begin Bmpfilehd.bfType := $DBFF; Bmpfilehd.bfSize := lpVhdr.dwBytesUsed + SizeOf(Bmpfilehd) + SizeOf(bmpInfo.bmiHeader); Bmpfilehd.bfReserved1 := 0; Bmpfilehd.bfReserved2 := 0; Bmpfilehd.bfOffBits := SizeOf(Bmpfilehd) + SizeOf(bmpInfo.bmiHeader); FMemorForPreview.Position := 0; FMemorForPreview.Write(Bmpfilehd, SizeOf(Bmpfilehd)); FMemorForPreview.Write(bmpInfo.bmiHeader, SizeOf(bmpInfo.bmiHeader)); FMemorForPreview.Write(lpVhdr.lpData[0], lpVhdr.dwBytesUsed); FMemorForPreview.Size := FMemorForPreview.Position; {$IFDEF UNICODE} SavePreviewToMemory; {$ELSE} SavePreviewToMemory(True); {$ENDIF} end else begin DestroyImgForPreview; end; Result := 1; end else begin DestroyImgForPreview; end; end; {$IFDEF UNICODE} procedure TVideoCap.SavePreviewToMemory; {$ELSE} procedure TVideoCap.SavePreviewToMemory(IsBitmap: Boolean); {$ENDIF} var JpegImg: TJPEGImage; begin {$IFDEF DEBUG} // FMemorForPreview.Position := 0; // FMemorForPreview.SaveToFile('c:\a.jpg'); {$ENDIF} CreateImgForPreview; FMemorForPreview.Position := 0; if Assigned(OnNewPreviewFrameMemory) then begin OnNewPreviewFrameMemory(Self, FMemorForPreview); FMemorForPreview.Position := 0; end; FImgForPreview.AutoSize := True; FImgForPreview.Center := False; FImgForPreview.Stretch := False; FImgForPreview.Proportional := True; try {$IFDEF UNICODE} FImgForPreview.Picture.LoadFromStream(FMemorForPreview); {$ELSE} if IsBitmap then begin FImgForPreview.Picture.Bitmap.LoadFromStream(FMemorForPreview); end else begin JpegImg := TJPEGImage.Create; try FMemorForPreview.Position := 0; JpegImg.LoadFromStream(FMemorForPreview); FImgForPreview.Picture.Assign(JpegImg); finally FreeAndNil(JpegImg); end; end; {$ENDIF} except //发生错误停止。 capPreview(fhCapWnd, False); Raise; end; FImgForPreview.AutoSize := False; FImgForPreview.Proportional := fprop; FImgForPreview.Stretch := fscale; FImgForPreview.Center := fCenter; if Assigned(OnNewPreviewFrameImage) then begin OnNewPreviewFrameImage(Self, FImgForPreview); end; end; procedure TVideoCap.CreateImgForPreview; begin if (not (csDestroying in ComponentState)) then begin if (FImgForPreview = nil) then begin FImgForPreview := TImage.Create(Self); FImgForPreview.ControlStyle := FImgForPreview.ControlStyle + [csNoDesignVisible]; if Parent <> nil then begin FImgForPreview.Parent := Self; end; FImgForPreview.Name := 'PreviewImage'; { do not localize } FImgForPreview.SetSubComponent(True); SetInternalControlBounds; DoubleBuffered := True; end; FImgForPreview.Center := fCenter; FImgForPreview.Proportional := fprop; FImgForPreview.Stretch := fscale; end; end; procedure TVideoCap.DestroyImgForPreview; begin if (not (csDestroying in ComponentState)) then begin if (FControlForPreview = nil) then begin FControlForPreview := TCustomControl.Create(Self); FControlForPreview.ControlStyle := FControlForPreview.ControlStyle + [csNoDesignVisible]; if Parent <> nil then begin FControlForPreview.Parent := Self; end; FControlForPreview.Name := 'Preview'; { do not localize } FControlForPreview.SetSubComponent(True); SetInternalControlBounds; end; if FImgForPreview <> nil then begin FControlForPreview.BringToFront; FreeAndNil(FImgForPreview); end; end; end; function TVideoCap.IsImgForPreviewMode: Boolean; begin Result := (FImgForPreview <> nil); end; procedure TVideoCap.SetSize(var msg:TMessage); begin if (fhCapWnd <> 0) and (Fscale or fCenter) then begin if msg.msg = WM_SIZE then SizeCap; end; end; procedure TVideoCap.SizeCap; var h, w: integer; f,cf:single; begin if IsImgForPreviewMode then exit; if not fscale then begin h := CapHeight; w := CapWidth; end else begin if fprop then begin f:= Width/height; cf:= CapWidth/CapHeight; if f > cf then begin h:= height; w:= round(h*cf); end else begin w:= width; h:= round(w*1/cf); end end else begin h:= height; w:= Width; end; end; if fCenter then begin MoveWindow(fhcapWnd, (ClientWidth - w) div 2, (ClientHeight - h) div 2, w, h, True); end else begin MoveWindow(fhcapWnd,0, 0 , w, h, True); end; end; procedure TVideoCap.DeleteDriverProps; begin if assigned(fpDrivercaps) then begin Dispose(fpDrivercaps); fpDriverCaps:= nil; end; if assigned(fpDriverStatus) then begin dispose(fpDriverStatus); fpDriverStatus:= nil; end; end; procedure TVideoCap.CreateTmpFile(drvOpn:boolean); var s,f: Array [0..MAX_PATH] of char; size :Word; ok :Boolean; e :Exception; begin if (ftempFileName ='') and (ftempFileSize = 0) then exit; if drvOpn then Size := ftempFileSize else size:=0; if fTempFileName = '' then begin GetTempPath(sizeof(s),@s); GetTempFileName(s,'cap',0,f); ftempfilename := f; end; if size <> 0 then begin capFileSetCaptureFile(fhCapWnd,strpCopy(f,ftempfilename)); ok:=capFileAlloc(fhcapWnd, 1024 * 1024 * ftempFileSize); if not ok then begin e:= EBufferFileError.Create('Unable to create Temporary File'); if not (csDesigning in ComponentState) then begin raise e; end; end; end else begin capFileSetCaptureFile(fhCapWnd,strpCopy(f, fCapVideoFileName)); DeleteFile(fTempfileName); fTempFileName:= ''; end; end; procedure TVideoCap.SetBufferFileSize(Value:word); begin if value = fTempFilesize then exit; ftempFileSize:=value; if DriverOpen Then CreateTmpFile(true); end; function TVideoCap.GetDriverCaps:boolean; var savestat : integer; begin result:= false; if assigned(fpDrivercaps) then begin result:= true; exit; end; if fdriverIndex = -1 then exit; savestat := fhCapwnd; if fhCapWnd = 0 then CreateCapWindow; if fhCapWnd = 0 then exit; new(fpDrivercaps); if capDriverGetCaps(fhCapWnd, fpDriverCaps, sizeof(TCapDriverCaps)) then begin result:= true; if savestat = 0 then destroyCapWindow; exit; end; Dispose(fpDriverCaps); fpDriverCaps := nil; if savestat = 0 then destroyCapWindow; end; function TVideoCap.GetBitMapInfoNp:TBitmapinfo; var e:Exception; begin if DriverOpen then begin capGetVideoFormat(fhcapWnd, @result,sizeof(TBitmapInfo)); exit; end ; FillChar(result, sizeof(TBitmapInfo),0); e:= ENotOpen.Create('The driver is closed'); if not (csDesigning in ComponentState) then begin raise e; end; end; function TVideoCap.GetBitMapInfo(var p:Pointer):integer; var size:integer; e:Exception; begin p:=nil; if driverOpen then begin //Size:= capGetVideoFormat(fhcapWnd,p,0); size := capGetVideoFormatSize(fhcapWnd); GetMem(p,size); capGetVideoFormat(fhcapwnd,p,size); result:=size; exit; end; e:= ENotOpen.Create('The driver is closed'); if not (csDesigning in ComponentState) then begin raise e; end; end; function TVideoCap.IsBitmapHeaderSupport(Header:TBitmapInfoHeader): Boolean; var size:integer; p:Pointer; e:Exception; begin Result := False; if driverOpen then begin Size:= capGetVideoFormatSize(fhcapWnd); GetMem(p,size); try capGetVideoFormat(fhcapwnd,p,size); PBitmapInfo(P).bmiHeader := Header; Result:=capSetVideoFormat(fhcapWnd,p,size); finally FreeMem(p); end; Exit; end; e:= ENotOpen.Create('The driver is closed'); if not (csDesigning in ComponentState) then begin raise e; end; end; procedure TVideoCap.SetBitmapInfo(p:Pointer;size:integer); var e: Exception; supported: Boolean; begin if driverOpen then begin supported:=capSetVideoFormat(fhcapWnd,p,size); if not supported then begin e:=EFalseFormat.Create('Format not supported' ); if not (csDesigning in ComponentState) then begin raise e; end; end; Exit; end; e:= ENotOpen.Create('The driver is closed'); if not (csDesigning in ComponentState) then begin raise e; end; end; function TVideoCap.GetBitMapHeader:TBitmapinfoHeader; var e:Exception; begin if DriverOpen then begin capGetVideoFormat(fhcapWnd, @result,sizeof(TBitmapInfoHeader)); exit; end; FillChar(result,sizeof(TBitmapInfoHeader),0); e:= ENotOpen.Create('The driver is closed'); if not (csDesigning in ComponentState) then begin raise e; end; end; procedure TVideoCap.SetBitMapHeader(header:TBitmapInfoHeader); var e: Exception; begin if driveropen then begin if not capSetVideoFormat(fhcapWnd,@header,sizeof(TBitmapInfoHeader)) then begin e:= EFalseFormat.Create('Format not supported'); if not (csDesigning in ComponentState) then begin raise e; end; end; exit; end else begin e:= ENotOpen.Create('The driver is closed'); if not (csDesigning in ComponentState) then begin raise e; end; end; end; function TVideoCap.getDriverStatus(callback:boolean):boolean; begin result := false; if assigned(fCapStatusProcedure)and callback then fcapStatusprocedure (Self); if fhCapWnd <> 0 then begin if not assigned(fpDriverstatus) then new(fpDriverStatus); if capGetStatus(fhCapWnd,fpdriverstatus, sizeof(TCapStatus)) then begin result:= true; end; end; end; procedure TVideoCap.SetDrivername(value:string); var i:integer; name:array[0..80] of char; ver :array[0..80] of char; begin if fVideoDrivername = value then exit; for i:= 0 to 9 do if capGetDriverDescription( i,name,80,ver,80) then if strpas(name) = value then begin fVideoDriverName := value; Driverindex:= i; exit; end; fVideoDrivername:= ''; DriverIndex:= -1; end; procedure TVideoCap.SetDriverIndex(value:integer); var name:array[0..80] of char; ver :array[0..80] of char; begin if value = fdriverindex then exit; destroyCapWindow; deleteDriverProps; if value > -1 then begin if capGetDriverDescription(value,name,80,ver,80) then fVideoDriverName:= StrPas(name) else value:= -1; end; if value = -1 then fvideoDriverName:= ''; fdriverindex:= value; end; function TVideoCap.CreateCapWindow; var Ex:Exception; savewndproc:NativeInt; IsFrameCallbacked: Boolean; IsVideoStreamCallbacked: Boolean; begin if fhCapWnd <> 0 then begin result:= true; exit; end; if fdriverIndex = -1 then begin Ex := ENoDriverException.Create('There is no driver selected'); GetDriverStatus(true); if not (csDesigning in ComponentState) then begin raise Ex; end; exit; end; fhCapWnd := capCreateCaptureWindow( PChar(Name), WS_CHILD or WS_VISIBLE , 0, 0, Width, FControlForPreview.Height, Handle, 5001); if fhCapWnd =0 then begin Ex:= ENoCapWindowException.Create('Cannot create the Capture window'); GetDriverStatus(true); if not (csDesigning in ComponentState) then begin raise Ex; end; exit; end; capSetUserData(fhCapwnd,integer(self)); savewndproc:=SetWindowLong(fhcapWnd,GWL_WNDPROC,integer(@WCapProc)); SetWindowLong(fhcapWnd,GWL_USERDATA,savewndProc); if assigned(fcapStatusCallBack ) then capSetCallbackOnStatus(fhcapWnd , @StatusCallbackProc); IsFrameCallbacked := True; if assigned(fcapFrameCallback) then begin capSetCallbackOnFrame(fhcapWnd, @FrameCallbackProc); IsFrameCallbacked := True; end; if assigned(fcapError) then capSetCallbackOnError(fhcapWnd, @ErrorCallBackProc); if assigned(fcapVideoStream) then begin capSetCallbackOnVideoStream(fhcapwnd, @VideoStreamCallbackProc); IsVideoStreamCallbacked := True; end; if assigned(fcapAudioStream) then capSetCallbackOnWaveStream(fhcapWnd, @AudioStreamCallbackProc); if not capDriverConnect(fhCapWnd, fdriverIndex) then begin Ex:= ENotConnectException.Create('The driver can not connect with the Capture window'); Destroycapwindow; GetDriverStatus(true); if not (csDesigning in ComponentState) then begin raise Ex; end; exit; end; if (not IsFrameCallbacked) or (IsNeedFixData or IsNotifyDataEvent) then begin capSetCallbackOnVideoStream(fhcapwnd, @VideoStreamCallbackProc); IsFrameCallbacked := True; end; if not IsVideoStreamCallbacked or (IsNeedFixData or IsNotifyDataEvent) then begin capSetCallbackOnFrame(fhcapWnd, @FrameCallbackProc); IsVideoStreamCallbacked := True; end; CreateTmpFile(True); capPreviewScale(fhCapWnd, fscale); capPreviewRate(fhCapWnd, round( 1000/fpreviewrate)); // Bh := BitMapInfoHeader; // if (Bh.biCompression = BI_YUY2) or // (Bh.biCompression = BI_RGB24) or // (Bh.biCompression = BI_RGB32) or // (Bh.biCompression = BI_RGB) or // (Bh.biCompression = BI_YUYV) then // begin // end // else // begin // Bh := GetYUY2BitmapInfoHeader(Bh.biWidth, Bh.biHeight); // if IsBitmapHeaderSupport(Bh) then // BitMapInfoHeader := Bh; // Bh := GetYUYVBitmapInfoHeader(Bh.biWidth, Bh.biHeight); // if IsBitmapHeaderSupport(Bh) then // BitMapInfoHeader := Bh; // Bh := GetYUY2BitmapInfoHeader(Bh.biWidth, Bh.biHeight); // if IsBitmapHeaderSupport(Bh) then // BitMapInfoHeader := Bh; // Bh := GetRGB24BitmapInfoHeader(Bh.biWidth, Bh.biHeight); // if IsBitmapHeaderSupport(Bh) then // BitMapInfoHeader := Bh; // Bh := GetRGBBitmapInfoHeader(Bh.biWidth, Bh.biHeight); // if IsBitmapHeaderSupport(Bh) then // BitMapInfoHeader := Bh; // Bh := GetRGB32BitmapInfoHeader(Bh.biWidth, Bh.biHeight); // if IsBitmapHeaderSupport(Bh) then // BitMapInfoHeader := Bh; // Bh := BitMapInfoHeader; // if Bh.biCompression = BI_MJPG then // begin // //目前不支持。 // end; // end; GetDriverStatus(true); Sizecap; result:= true; end; procedure TVideoCap.SetStatCallBack(value:TCapStatusCallback); begin fcapStatusCallBack := value; if DriverOpen then if assigned(fcapStatusCallBack) then capSetCallbackOnStatus(fhcapWnd , @StatusCallbackProc) else capSetCallbackOnStatus(fhcapWnd ,nil); end; procedure TVideoCap.SetCapVideoStream(value:TVideoStream); begin fcapVideoStream:= value; if DriverOpen then if assigned(fcapVideoStream) then capSetCallbackOnVideoStream(fhcapwnd, @VideoStreamCallbackProc) else capSetCallbackOnVideoStream(fhcapwnd, nil); end; procedure TVideoCap.SetCapFrameCallback(value:TVideoStream); begin fcapframeCallback:= value; if DriverOpen then if assigned(fcapFrameCallback) then capSetCallbackOnFrame(fhcapwnd, @FrameCallBackProc) else capSetCallbackOnFrame(fhcapwnd, nil); end; procedure TVideoCap.SetCapAudioStream(value:TAudioStream); begin fcapAudioStream:= value; if DriverOpen then if assigned(fcapAudioStream) then capSetCallbackOnWaveStream(fhcapWnd, @AudioStreamCallbackProc) else capSetCallbackOnWaveStream(fhcapWnd,nil); end; procedure TVideoCap.SetCapError(value:TError); begin fcapError:= value; if DriverOpen then if assigned(fcapError) then capSetCallbackOnError(fhcapWnd, @ErrorCallbackProc) else capSetCallbackOnError(fhcapWnd,nil); end; procedure TVideoCap.DestroyCapWindow; begin if fhCapWnd = 0 then exit; CreateTmpFile(False); CapDriverDisconnect(fhCapWnd); SetWindowLong(fhcapWnd,GWL_WNDPROC,GetWindowLong(fhcapwnd,GWL_USERDATA)); DestroyWindow( fhCapWnd ) ; DestroyImgForPreview; fhCapWnd := 0; end; function TVideoCap.GetHasVideoOverlay:Boolean; begin if getDriverCaps then Result := fpDriverCaps^.fHasOverlay else result:= false; end; function TVideoCap.GetHasDlgVFormat:Boolean; begin if getDriverCaps then Result := fpDriverCaps^.fHasDlgVideoFormat else result:= false; end; function TVideoCap.GetHasDlgVDisplay : Boolean; begin if getDriverCaps then Result := fpDriverCaps^.fHasDlgVideoDisplay else result:= false; end; function TVideoCap.GetHasDlgVSource : Boolean; begin if getDriverCaps then Result := fpDriverCaps^.fHasDlgVideoSource else result:= false; end; function TVideoCap.DlgVFormat:boolean; var savestat : integer; begin result:= false; if fdriverIndex = -1 then exit; savestat := fhCapwnd; if fhCapWnd = 0 then if not CreateCapWindow then exit; result :=capDlgVideoFormat(fhCapWnd); if result then GetDriverStatus(true); if savestat = 0 then destroyCapWindow; if result then begin Sizecap; Repaint; end; end; function TVideoCap.DlgVDisplay:boolean; var savestat : integer; begin result:= false; if fdriverIndex = -1 then exit; savestat := fhCapwnd; if fhCapWnd = 0 then if not CreateCapWindow then exit; result:=capDlgVideoDisplay(fhCapWnd) ; if result then GetDriverStatus(true); if savestat = 0 then destroyCapWindow; if result then begin SizeCap; Repaint; end; end; function TVideoCap.DlgVSource:boolean; var savestat : integer; begin result:= false; if fdriverIndex = -1 then exit; savestat := fhCapwnd; if fhCapWnd = 0 then if not createCapWindow then exit; result:= capDlgVideoSource(fhCapWnd); if result then GetDriverStatus(true); if savestat = 0 then destroyCapWindow; if result then begin SizeCap; Repaint; end; end; function TVideoCap.DlgVCompression; var savestat : integer; begin result:= false; if fdriverIndex = -1 then exit; savestat := fhCapwnd; if fhCapWnd = 0 then if not createCapWindow then exit; result:=capDlgVideoCompression(fhCapWnd); if savestat = 0 then destroyCapWindow; end; function TVideoCap.GrabFrame:boolean; begin result:= false; if not DriverOpen then exit; Result:= capGrabFrame(fhcapwnd); if result then GetDriverStatus(true); end; function TVideoCap.GrabFrameNoStop:boolean; begin result:= false; if not DriverOpen then exit; Result:= capGrabFrameNoStop(fhcapwnd); if result then GetDriverStatus(true); end; function TVideoCap.SaveAsDIB:Boolean; var s:array[0..MAX_PATH] of char; begin result:= false; if not DriverOpen then exit; if IsImgForPreviewMode then begin FImgForPreview.Picture.SaveToFile(fCapSingleImageFileName); exit; end; result := capFileSaveDIB(fhcapwnd,strpCopy(s,fCapSingleImageFileName)); end; function TVideoCap.SaveToClipboard:boolean; begin result:= false; if not Driveropen then exit; if IsImgForPreviewMode then begin Clipboard.Assign(FImgForPreview.Picture); exit; end; result:= capeditCopy(fhcapwnd); end; procedure TVideoCap.Setoverlay(value:boolean); var ex:Exception; begin if value = GetOverlay then exit; if gethasVideoOverlay = false then begin Ex:= ENoOverlayException.Create('The driver does not support Overlay'); if not (csDesigning in ComponentState) then begin raise Ex; end; exit; end; if value = true then begin if fhcapWnd = 0 then CreateCapWindow; GrabFrame; end; capOverlay(fhCapWnd,value); GetDriverStatus(true); invalidate; end; function TVideoCap.GetOverlay:boolean; begin if fhcapWnd = 0 then result := false else Result:= fpDriverStatus^.fOverlayWindow; end; function TVideoCap.IsCurrentFormatNotSupport: Boolean; begin Result := False; exit; if not DriverOpen then exit; Result := BitMapInfoHeader.biCompression = BI_MJPG; end; procedure TVideoCap.TestCurrentFormat; var Ex: Exception; begin if not DriverOpen then exit; if IsCurrentFormatNotSupport then begin Ex:= EFalseFormat.Create('Current format not supported'); if not (csDesigning in ComponentState) then begin raise Ex; end; exit; end; end; procedure TVideoCap.SetPreview(value:boolean); begin if value = GetPreview then exit; if value = true then if fhcapWnd = 0 then CreateCapWindow; TestCurrentFormat; TrySelectYUY2; capPreview(fhCapWnd,value); GetDriverStatus(true); invalidate; end; function TVideoCap.GetPreview:boolean; begin if fhcapWnd = 0 then result := false else Result:= fpDriverStatus^.fLiveWindow; end; procedure TVideoCap.SetPreviewRate(value:word); begin if value = fpreviewrate then exit; if value < 1 then value := 1; if value > 30 then value := 30; fpreviewrate:= value; if DriverOpen then capPreviewRate(fhCapWnd, round( 1000/fpreviewrate)); end; procedure TVideoCap.SetMicroSecPerFrame(value:cardinal); begin if value = fmicrosecpframe then exit; if value < 33333 then value := 33333; fmicrosecpframe := value; end; procedure TVideoCap.setFrameRate(value:word); begin if value <> 0 then fmicrosecpframe:= round(1.0/value*1000000.0); end; function TVideoCap.GetFrameRate:word; begin if fmicrosecpFrame > 0 then result:= round(1./ fmicrosecpframe * 1000000.0) else result:= 0; end; function TVideoCap.StartCapture; var CapParms:TCAPTUREPARMS; name:array[0..MAX_PATH] of char; begin result := false; if not DriverOpen then exit; capCaptureGetSetup(fhCapWnd, @CapParms, sizeof(TCAPTUREPARMS)); if ftempfilename='' then capFileSetCaptureFile(fhCapWnd,strpCopy(name, fCapVideoFileName)); CapParms.dwRequestMicroSecPerFrame := fmicrosecpframe; CapParms.fLimitEnabled := BOOL(FCapTimeLimit); CapParms.wTimeLimit := fCapTimeLimit; CapParms.fCaptureAudio := fCapAudio; CapParms.fMCIControl := FALSE; CapParms.fYield := TRUE; CapParms.vKeyAbort := VK_ESCAPE; CapParms.fAbortLeftMouse := FALSE; CapParms.fAbortRightMouse := FALSE; if CapParms.fLimitEnabled then begin CapParms.dwIndexSize:= frameRate*FCapTimeLimit; if fCapAudio then CapParms.dwIndexSize := CapParms.dwIndexSize + 5*FCapTimeLimit; end else begin if CapParms.dwIndexSize = 0 then CapParms.DwIndexSize := 100000 else CapParms.dwIndexSize := findexSize; end; if CapParms.dwIndexSize < 1800 then CapParms.dwIndexSize:= 1800; if CapParms.dwIndexSize > 324000 then CapParms.dwIndexSize:= 324000; capCaptureSetSetup(fhCapWnd, @CapParms, sizeof(TCAPTUREPARMS)); if fCapAudio then FAudioformat.SetAudio(fhcapWnd); if CapToFile then result:= capCaptureSequence(fhCapWnd) else result := capCaptureSequenceNoFile(fhCapWnd); GetDriverStatus(true); end; function TVideoCap.StopCapture; begin result:=false; if not DriverOpen then exit; result:=CapCaptureStop(fhcapwnd); GetDriverStatus(true); end; function TVideoCap.SaveCap:Boolean; var name:array[0..MAX_PATH] of char; begin result := capFileSaveAs(fhcapwnd,strPCopy(name,fCapVideoFileName)); end; procedure TVideoCap.SetIndexSize(value:cardinal); begin if value = 0 then begin findexSize:= 0; exit; end; if value < 1800 then value := 1800; if value > 324000 then value := 324000; findexsize:= value; end; function TVideoCap.GetCapInProgress:boolean; begin result:= false; if not DriverOpen then exit; GetDriverStatus(false); result:= fpDriverStatus^.fCapturingNow ; end; procedure TVideoCap.SetScale(value:boolean); begin if value = fscale then exit; fscale:= value; if DriverOpen then begin if IsImgForPreviewMode then begin FImgForPreview.Stretch := fscale; end else begin capPreviewScale(fhCapWnd, fscale); SizeCap; Repaint; end; end; end; procedure TVideoCap.Setprop(value:Boolean); begin if value = fprop then exit; fprop:=value; if DriverOpen then if IsImgForPreviewMode then begin FImgForPreview.Proportional := fprop; end else begin Sizecap; Repaint; end; end; procedure TVideoCap.SetCenter(Value: Boolean); begin if fCenter = Value then exit; fCenter := Value; if DriverOpen then if IsImgForPreviewMode then begin FImgForPreview.Center := fCenter; end else begin Sizecap; Repaint; end; end; function TVideoCap.TrySelectYUY2: Boolean; var Bh: TBitmapInfoHeader; begin Result := False; if not DriverOpen then exit; if FAutoSelectYUY2 and IsNeedFixData then begin Bh := BitMapInfoHeader; Bh := GetYUY2BitmapInfoHeader(Bh.biWidth, Bh.biHeight); Result := IsBitmapHeaderSupport(Bh); if Result then begin BitMapInfoHeader := Bh; end; end; end; procedure TVideoCap.SetAutoSelectYUY2(Value: Boolean); begin if FAutoSelectYUY2 = Value then exit; FAutoSelectYUY2 := Value; if not DriverOpen then exit; TrySelectYUY2; end; function TVideoCap.GetCapWidth; begin if assigned(fpDriverStatus) then result:= fpDriverStatus^.uiImageWidth else Result:= 0; end; function TVideoCap.GetCapHeight; begin if assigned(fpDriverStatus) then result:= fpDriverStatus^.uiImageHeight else Result:= 0; end; procedure TVideoCap.SetDriverOpen(value:boolean); begin if value = GetDriverOpen then exit; if value = false then DestroyCapWindow; if value = true then CreateCapWindow; end; function TVideoCap.GetDriverOpen:boolean; begin result := fhcapWnd <> 0; end; function TVideoCap.CapSingleFramesOpen:boolean; var name :array [0..MAX_PATH] of char; CapParms:TCAPTUREPARMS; begin result := false; if not DriverOpen then exit; capCaptureGetSetup(fhCapWnd, @CapParms, sizeof(TCAPTUREPARMS)); if ftempfilename='' then capFileSetCaptureFile(fhCapWnd,strpCopy(name, fCapVideoFileName)); CapParms.dwRequestMicroSecPerFrame := fmicrosecpframe; CapParms.fLimitEnabled := BOOL(0); CapParms.fCaptureAudio := false; CapParms.fMCIControl := FALSE; CapParms.fYield := TRUE; CapParms.vKeyAbort := VK_ESCAPE; CapParms.dwIndexSize := findexSize; if CapParms.dwIndexSize < 1800 then CapParms.dwIndexSize:= 1800; if CapParms.dwIndexSize > 324000 then CapParms.dwIndexSize:= 324000; capCaptureSetSetup(fhCapWnd, @CapParms, sizeof(TCAPTUREPARMS)); result:= capCaptureSingleFrameOpen(fhcapWnd); end; function TVideoCap.CapSingleFramesClose:boolean; var E:Exception; begin if not driverOpen then begin e:= ENotOpen.Create('The driver is not Active'); if not (csDesigning in ComponentState) then begin raise e; end; exit; end; result:= CapCaptureSingleFrameClose(fhcapWnd); end; function TVideoCap.CapSingleFrame:boolean; var E:Exception; begin Result := False; if not driverOpen then begin e:= ENotOpen.Create('The driver is not Active'); if not (csDesigning in ComponentState) then begin raise e; end; exit; end; result:= CapCaptureSingleFrame(fhcapWnd); end; constructor TAudioFormat.create; begin inherited create; FChannels:=Mono; FFrequency:=f8000Hz; Fres:=r8Bit; end; procedure TAudioFormat.SetAudio(handle:Thandle); Var WAVEFORMATEX:TWAVEFORMATEX; begin if handle= 0 then exit; capGetAudioFormat(handle,@WAVEFORMATEX, SizeOf(TWAVEFORMATEX)); case FFrequency of f8000hz :WAVEFORMATEX.nSamplesPerSec:=8000; f11025Hz:WAVEFORMATEX.nSamplesPerSec:=11025; f22050Hz:WAVEFORMATEX.nSamplesPerSec:=22050; f44100Hz:WAVEFORMATEX.nSamplesPerSec:=44100; end; WAVEFORMATEX.nAvgBytesPerSec:= WAVEFORMATEX.nSamplesPerSec; if FChannels=Mono then WAVEFORMATEX.nChannels:=1 else WAVEFORMATEX.nChannels:=2; if FRes=r8Bit then WAVEFORMATEX.wBitsPerSample:=8 else WAVEFORMATEX.wBitsPerSample:=16; capSetAudioFormat(handle,@WAVEFORMATEX, SizeOf(TWAVEFORMATEX)); end; function GetDriverList:TStringList; var i: integer; Name: array[0..80] of char; Ver : array[0..80] of char; begin result:= TStringList.Create; result.Capacity:= 10; result.Sorted:= false; for i:= 0 to 9 do begin if capGetDriverDescription(i, Name, Length(Name), Ver, Length(Ver)) then begin Result.Add(StrPas(name) + ' ' + StrPas(Ver)); end else begin Exit; end; end; end; procedure FrameToBitmap(Bitmap: TBitmap; FrameBuffer: Pointer; BitmapInfo:TBitmapInfo); var hdd:Thandle; begin with Bitmap do begin Width:= BitmapInfo.bmiHeader.biWidth; Height:=Bitmapinfo.bmiHeader.biHeight; hdd:= DrawDibOpen; DrawDibDraw(hdd,canvas.handle,0,0,BitmapInfo.BmiHeader.biwidth,BitmapInfo.bmiheader.biheight,@BitmapInfo.bmiHeader, frameBuffer,0,0,bitmapInfo.bmiHeader.biWidth,bitmapInfo.bmiHeader.biheight,0); DrawDibClose(hdd); end; end; procedure BitmapToFrame(Bitmap:TBitmap; FrameBuffer:pointer; BitmapInfo:TBitmapInfo); var ex:Exception; begin if bitmapInfo.bmiHeader.BiCompression <> bi_RGB then begin ex:= EFalseFormat.Create('The DIB format is not supported'); raise ex; end; with Bitmap do GetDiBits(canvas.handle,handle,0,BitmapInfo.bmiHeader.biheight,FrameBuffer,BitmapInfo,DIB_RGB_COLORS); end; end.
unit UStackList4; interface type { As TStackList1, but add inlining } TStackList4<T: record; TSize: record> = record private type P = ^T; private FData: TSize; FCapacity: Integer; FCount: Integer; function GetItem(const AIndex: Integer): T; inline; public procedure Initialize; procedure Add(const AItem: T); inline; property Count: Integer read FCount; property Items[const AIndex: Integer]: T read GetItem; default; end; implementation uses System.Classes, System.SysUtils; { TStackList4<T, TSize> } procedure TStackList4<T, TSize>.Add(const AItem: T); var Target: P; begin if (FCount >= FCapacity) then raise EInvalidOperation.Create('List is full'); Target := @FData; Inc(Target, FCount); Target^ := AItem; Inc(FCount); end; function TStackList4<T, TSize>.GetItem(const AIndex: Integer): T; var Item: P; begin if (AIndex < 0) or (AIndex >= FCount) then raise EArgumentOutOfRangeException.Create('List index out of range'); Item := @FData; Inc(Item, AIndex); Result := Item^; end; procedure TStackList4<T, TSize>.Initialize; begin if IsManagedType(T) or IsManagedType(TSize) then raise EInvalidOperation.Create('A stack based collection cannot contain managed types'); FCapacity := SizeOf(FData) div SizeOf(T); FCount := 0; end; end.
unit smuRelatorio; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, smuBasico, 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, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uQuery, Datasnap.DBClient, uClientDataSet, uUtils, uSQLGenerator, uTypes, System.DateUtils; type TsmRelatorio = class(TsmBasico) qSaldo_Rubrica: TRFQuery; qSaldo_RubricaID_RUBRICA: TIntegerField; qSaldo_RubricaID_PROJETO: TIntegerField; qSaldo_RubricaNOME_PROJETO: TStringField; qSaldo_RubricaNOME_RUBRICA: TStringField; qSaldo_Semente_Muda: TRFQuery; qSaldo_Semente_MudaNOME: TStringField; qSaldo_Semente_MudaNOME_CIENTIFICO: TStringField; qSaldo_Semente_MudaFAMILIA_BOTANICA: TStringField; qSaldo_Semente_MudaQTDE_SEMENTE_ESTOQUE: TBCDField; qTaxas_Especie: TRFQuery; qTaxas_EspecieID: TIntegerField; qTaxas_EspecieNOME: TStringField; qTaxas_EspecieNOME_CIENTIFICO: TStringField; qTaxas_EspecieFAMILIA_BOTANICA: TStringField; qTaxas_EspecieTEMPO_GERMINACAO: TIntegerField; qTaxas_EspecieTEMPO_DESENVOLVIMENTO: TIntegerField; qTaxas_EspecieTAXA_CLASSIFICACAO: TBCDField; qTaxas_EspecieTAXA_GERMINACAO: TBCDField; qSaldo_Semente_MudaQTDE_MUDA_PRONTA: TIntegerField; qSaldo_Semente_MudaQTDE_MUDA_DESENVOLVIMENTO: TIntegerField; qTaxas_EspecieQTDE_SEMENTE_ESTOQUE: TBCDField; qTaxas_EspecieQTDE_MUDA_DESENVOLVIMENTO: TIntegerField; qTaxas_EspecieQTDE_MUDA_PRONTA: TIntegerField; qTaxas_EspecieQTDE_SEMENTE_KILO: TIntegerField; qPatrimonio: TRFQuery; qPatrimonioIDENTIFICACAO: TStringField; qPatrimonioNOME_ITEM: TStringField; qPatrimonioDATA_AQUISICAO: TSQLTimeStampField; qPatrimonioVALOR_INICIAL: TBCDField; qPatrimonioLOCALIZACAO: TStringField; qPatrimonioSTATUS: TSmallintField; qPatrimonioCALC_VALOR_ATUAL: TBCDField; qPatrimonioTAXA_DEPRECIACAO_ANUAL: TIntegerField; qPatrimonioID_ITEM_PATRIMONIO: TIntegerField; qGasto_Area_Atuacao: TRFQuery; qGasto_Area_AtuacaoID_AREA_ATUACAO_ORIGEM: TIntegerField; qGasto_Area_AtuacaoAREA_ATUACAO: TStringField; qGasto_Area_AtuacaoGASTO: TFMTBCDField; qGasto_Area_AtuacaoPROJETO: TStringField; qTransferencia_Financeira: TRFQuery; qTransferencia_FinanceiraID: TIntegerField; qTransferencia_FinanceiraID_PESSOA: TIntegerField; qTransferencia_FinanceiraID_FUNDO_ORIGEM: TIntegerField; qTransferencia_FinanceiraFUNDO_ORIGEM: TStringField; qTransferencia_FinanceiraID_FUNDO_DESTINO: TIntegerField; qTransferencia_FinanceiraFUNDO_DESTINO: TStringField; qTransferencia_FinanceiraID_PROJETO_RUBRICA_ORIGEM: TIntegerField; qTransferencia_FinanceiraPROJETO_ORIGEM: TStringField; qTransferencia_FinanceiraRUBRICA_ORIGEM: TStringField; qTransferencia_FinanceiraID_PROJETO_RUBRICA_DESTINO: TIntegerField; qTransferencia_FinanceiraPROJETO_DESTINO: TStringField; qTransferencia_FinanceiraRUBRICA_DESTINO: TStringField; qTransferencia_FinanceiraVALOR: TBCDField; qTransferencia_FinanceiraDATA: TSQLTimeStampField; qTransferencia_FinanceiraTIPO: TSmallintField; qTransferencia_FinanceiraORIGEM: TStringField; qTransferencia_FinanceiraDESTINO: TStringField; qTransferencia_FinanceiraRESPONSAVEL: TStringField; qGasto_Fornecedor: TRFQuery; qGasto_FornecedorVALOR_PAGO: TBCDField; qGasto_FornecedorID_FORNECEDOR: TIntegerField; qGasto_FornecedorNOME_FANTASIA: TStringField; qGasto_FornecedorRAZAO_SOCIAL: TStringField; qGasto_FornecedorCPF_CNPJ: TStringField; qGasto_FornecedorVALOR_TOTAL: TBCDField; qGasto_FornecedorDATA_PAGAMENTO: TDateField; qGasto_Atividade: TRFQuery; qGasto_AtividadeID: TIntegerField; qGasto_AtividadeNOME: TStringField; qGasto_AtividadeID_SOLICITANTE: TIntegerField; qGasto_AtividadeID_RESPONSAVEL: TIntegerField; qGasto_AtividadeSOLICITANTE: TStringField; qGasto_AtividadeRESPONSAVEL: TStringField; qGasto_AtividadeSTATUS: TSmallintField; qGasto_AtividadeDATA_INICIAL: TSQLTimeStampField; qGasto_AtividadeDATA_FINAL: TSQLTimeStampField; qGasto_AtividadeDESCRICAO: TStringField; qGasto_AtividadeVALOR: TBCDField; qGasto_AtividadeVALOR_PAGO: TFMTBCDField; qMatriz_Produtiva: TRFQuery; qMatriz_ProdutivaID_ESPECIE: TIntegerField; qMatriz_ProdutivaESPECIE: TStringField; qMatriz_ProdutivaID_MATRIZ: TIntegerField; qMatriz_ProdutivaMATRIZ: TStringField; qMatriz_ProdutivaTAXA: TBCDField; qGasto_Plano_Contas: TRFQuery; qLote_Muda_Comprado: TRFQuery; qLote_Muda_CompradoID: TIntegerField; qLote_Muda_CompradoNOME: TStringField; qLote_Muda_CompradoID_ESPECIE: TIntegerField; qLote_Muda_CompradoESPECIE: TStringField; qLote_Muda_CompradoID_FORNECEDOR: TIntegerField; qLote_Muda_CompradoFORNECEDOR: TStringField; qLote_Muda_CompradoVALOR_UNITARIO: TBCDField; qLote_Muda_CompradoVALOR: TBCDField; qLote_Semente_Comprado: TRFQuery; qLote_Semente_CompradoID: TIntegerField; qLote_Semente_CompradoNOME: TStringField; qLote_Semente_CompradoID_ESPECIE: TIntegerField; qLote_Semente_CompradoESPECIE: TStringField; qLote_Semente_CompradoID_FORNECEDOR: TIntegerField; qLote_Semente_CompradoFORNECEDOR: TStringField; qLote_Semente_CompradoVALOR_UNITARIO: TBCDField; qLote_Semente_CompradoVALOR: TBCDField; qGasto_Plano_Contas_Detalhado: TRFQuery; qGasto_Plano_Contas_DetalhadoID: TIntegerField; qGasto_Plano_Contas_DetalhadoNOME: TStringField; qGasto_Plano_Contas_DetalhadoID_PROJETO: TIntegerField; qGasto_Plano_Contas_DetalhadoPROJETO: TStringField; qGasto_Plano_Contas_DetalhadoID_FUNDO: TIntegerField; qGasto_Plano_Contas_DetalhadoNOME_FUNDO: TStringField; qGasto_Plano_Contas_DetalhadoID_RUBRICA: TIntegerField; qGasto_Plano_Contas_DetalhadoRUBRICA: TStringField; qGasto_Plano_Contas_DetalhadoDESCRICAO: TStringField; qGasto_Plano_Contas_DetalhadoVALOR_TOTAL: TBCDField; qGasto_Plano_Contas_DetalhadoVALOR_PAGO: TBCDField; qLote_Semente_Vendido: TRFQuery; qLote_Muda_Vendido: TRFQuery; qLote_Muda_VendidoID: TIntegerField; qLote_Muda_VendidoNOME: TStringField; qLote_Muda_VendidoID_ESPECIE: TIntegerField; qLote_Muda_VendidoESPECIE: TStringField; qLote_Muda_VendidoID_CLIENTE: TIntegerField; qLote_Muda_VendidoQTDE: TBCDField; qLote_Muda_VendidoVALOR_UNITARIO: TBCDField; qLote_Muda_VendidoVALOR: TBCDField; qLote_Semente_VendidoID: TIntegerField; qLote_Semente_VendidoNOME: TStringField; qLote_Semente_VendidoID_ESPECIE: TIntegerField; qLote_Semente_VendidoESPECIE: TStringField; qLote_Semente_VendidoID_CLIENTE: TIntegerField; qLote_Semente_VendidoQTDE: TBCDField; qLote_Semente_VendidoVALOR_UNITARIO: TBCDField; qLote_Semente_VendidoVALOR: TBCDField; qLote_Muda_CompradoQTDE: TBCDField; qLote_Semente_CompradoQTDE: TBCDField; qLote_Muda_VendidoCLIENTE: TStringField; qLote_Semente_VendidoCLIENTE: TStringField; qView_Movimentacao_Financeira: TRFQuery; qView_Movimentacao_FinanceiraID_MOVIMENTACAO: TIntegerField; qView_Movimentacao_FinanceiraID_ORGANIZACAO: TIntegerField; qView_Movimentacao_FinanceiraNOME_ORGANIZACAO: TStringField; qView_Movimentacao_FinanceiraID_ORIGEM_RECURSO: TIntegerField; qView_Movimentacao_FinanceiraID_UNICO_ORIGEM_RECURSO: TStringField; qView_Movimentacao_FinanceiraORIGEM_RECURSO: TStringField; qView_Movimentacao_FinanceiraTIPO: TIntegerField; qView_Movimentacao_FinanceiraDESCRICAO_TIPO: TStringField; qView_Movimentacao_FinanceiraDESCRICAO_MOVIMENTACAO: TStringField; qView_Movimentacao_FinanceiraDATA: TDateField; qView_Movimentacao_FinanceiraDATA_PAGAMENTO_RECEBIMENTO: TDateField; qView_Movimentacao_FinanceiraFORMA_PAGAMENTO_RECEBIMENTO: TIntegerField; qView_Movimentacao_FinanceiraVALOR_TOTAL: TBCDField; qView_Movimentacao_FinanceiraVALOR_TOTAL_PAGO_RECEBIDO: TBCDField; qView_Movimentacao_FinanceiraCALC_VALOR_RESTANTE: TBCDField; qView_Movimentacao_FinanceiraCALC_SALDO: TBCDField; qSaldo: TRFQuery; qSaldoID_ORGANIZACAO: TIntegerField; qSaldoNOME_ORGANIZACAO: TStringField; qSaldoID_ORIGEM_RECURSO: TIntegerField; qSaldoID_UNICO_ORIGEM_RECURSO: TStringField; qSaldoORIGEM_RECURSO: TStringField; qSaldoSALDO: TBCDField; qSaldoTIPO_ORIGEM: TIntegerField; qView_Movimentacao_FinanceiraCALC_DESCRICAO_FORMA_PGTO: TStringField; qTubete_Semeado: TRFQuery; qTubete_SemeadoQTDE_TUBETE: TLargeintField; qTubete_SemeadoID_ESPECIE: TIntegerField; qTubete_SemeadoNOME: TStringField; qTubete_SemeadoNOME_CIENTIFICO: TStringField; qConta_Pagar: TRFQuery; qConta_PagarID: TIntegerField; qConta_PagarID_VINCULO: TIntegerField; qConta_PagarRAZAO_SOCIAL: TStringField; qConta_PagarCPF_CNPJ: TStringField; qConta_PagarNUMERO_DOCUMENTO: TStringField; qConta_PagarDATA_PAGAMENTO: TDateField; qConta_PagarVALOR: TBCDField; qConta_PagarVALOR_PAGO: TBCDField; qSaldo_Semente_MudaID_FAMILIA_BOTANICA: TIntegerField; qSaldo_Semente_MudaID: TIntegerField; qSaldo_Semente_MudaQTDE_FAMILIA: TIntegerField; qSaldo_RubricaORCAMENTO: TBCDField; qSaldo_RubricaGASTO: TBCDField; qSaldo_RubricaGASTO_TRANSFERENCIA: TBCDField; qSaldo_RubricaRECEBIDO_TRANSFERENCIA: TBCDField; qSaldo_RubricaAPROVISIONADO: TBCDField; qLote_Muda_VendidoCALC_MES: TStringField; qLote_Muda_CompradoCALC_MES: TStringField; qLote_Semente_CompradoCALC_MES: TStringField; qLote_Semente_VendidoCALC_MES: TStringField; qLote_Muda_VendidoDATA: TSQLTimeStampField; qLote_Semente_VendidoDATA: TSQLTimeStampField; qLote_Muda_CompradoDATA: TSQLTimeStampField; qLote_Semente_CompradoDATA: TSQLTimeStampField; qSaldo_RubricaRECEBIDO: TBCDField; qSaldo_RubricaSALDO_REAL: TBCDField; procedure qPatrimonioCalcFields(DataSet: TDataSet); procedure qView_Movimentacao_FinanceiraCalcFields(DataSet: TDataSet); procedure qLote_Muda_VendidoCalcFields(DataSet: TDataSet); private { Private declarations } protected function fprMontarWhere(ipTabela, ipWhere: string; ipParam: TParam): string; override; end; var smRelatorio: TsmRelatorio; implementation uses dmuPrincipal; {$R *.dfm} function TsmRelatorio.fprMontarWhere(ipTabela, ipWhere: string; ipParam: TParam): string; var vaValor, vaOperador: string; vaArray: TArray<integer>; begin Result := inherited; TUtils.ppuExtrairValorOperadorParametro(ipParam.Text, vaValor, vaOperador, TParametros.coDelimitador); if (ipTabela = 'PATRIMONIO') then begin if ipParam.Name = TParametros.coStatus then Result := TSQLGenerator.fpuFilterInteger(Result, ipTabela, 'STATUS', vaValor.ToInteger, vaOperador); end else if (ipTabela = 'TRANSFERENCIA_FINANCEIRA') then begin if ipParam.Name = TParametros.coData then Result := TSQLGenerator.fpuFilterData(Result, ipTabela, 'DATA', TUtils.fpuExtrairData(vaValor, 0), TUtils.fpuExtrairData(vaValor, 1), vaOperador) else if ipParam.Name = TParametros.coTipo then Result := TSQLGenerator.fpuFilterInteger(Result, ipTabela, 'TIPO', vaValor.ToInteger, vaOperador) else if ipParam.Name = TParametros.coPessoa then Result := TSQLGenerator.fpuFilterInteger(Result, ipTabela, 'ID_PESSOA', vaValor.ToInteger, vaOperador) end else if (ipTabela = 'GASTO_FORNECEDOR') then begin if ipParam.Name = TParametros.coData then Result := TSQLGenerator.fpuFilterDataSemHora(Result, 'CONTA_PAGAR_PARCELA', 'DATA_PAGAMENTO', TUtils.fpuExtrairData(vaValor, 0), TUtils.fpuExtrairData(vaValor, 1), vaOperador) else if ipParam.Name = TParametros.coFornecedor then Result := TSQLGenerator.fpuFilterInteger(Result, 'CONTA_PAGAR', 'ID_FORNECEDOR', vaValor.ToInteger, vaOperador); end else if (ipTabela = 'GASTO_ATIVIDADE') then begin if ipParam.Name = TParametros.coProjeto then Result := TSQLGenerator.fpuFilterInteger(Result, 'ATIVIDADE', 'ID_PROJETO', vaValor.ToInteger, vaOperador) else if ipParam.Name = TParametros.coAtividade then Result := TSQLGenerator.fpuFilterInteger(Result, 'ATIVIDADE', 'ID', vaValor.ToInteger, vaOperador) end else if (ipTabela = 'MATRIZ_PRODUTIVA') then begin if ipParam.Name = TParametros.coEspecie then Result := TSQLGenerator.fpuFilterInteger(Result, 'LOTE_SEMENTE', 'ID_ESPECIE', vaValor.ToInteger, vaOperador) else if ipParam.Name = TParametros.coData then Result := TSQLGenerator.fpuFilterData(Result, 'LOG', 'DATA_HORA', TUtils.fpuExtrairData(vaValor, 0), TUtils.fpuExtrairData(vaValor, 1), vaOperador) end else if (ipTabela = 'GASTO_PLANO_CONTAS') or (ipTabela = 'GASTO_PLANO_CONTAS_DETALHADO') then begin if ipParam.Name = TParametros.coProjeto then begin if vaValor.ToInteger = -1 then Result := Result + ' (Projeto.id is null) ' + vaOperador else if vaValor.ToInteger = 0 then Result := Result + ' (Projeto.id is not null)' + vaOperador else Result := TSQLGenerator.fpuFilterInteger(Result, 'PROJETO', 'ID', vaValor.ToInteger, vaOperador) end else if ipParam.Name = TParametros.coFundo then begin if vaValor.ToInteger = -1 then Result := Result + ' (Fundo.id is null) ' + vaOperador else if vaValor.ToInteger = 0 then Result := Result + ' (Fundo.id is not null)' + vaOperador else Result := TSQLGenerator.fpuFilterInteger(Result, 'FUNDO', 'ID', vaValor.ToInteger, vaOperador) end else if ipParam.Name = TParametros.coPlanoConta then Result := TSQLGenerator.fpuFilterInteger(Result, 'PLANO_CONTAS', 'ID', vaValor.ToInteger, vaOperador); end else if (ipTabela = 'LOTE_SEMENTE_COMPRADO') or (ipTabela = 'LOTE_MUDA_COMPRADO') then begin if ipParam.Name = TParametros.coData then Result := TSQLGenerator.fpuFilterData(Result, 'COMPRA', 'DATA', TUtils.fpuExtrairData(vaValor, 0), TUtils.fpuExtrairData(vaValor, 1), vaOperador) else if ipParam.Name = TParametros.coEspecie then Result := TSQLGenerator.fpuFilterInteger(Result, 'ESPECIE', 'ID', vaValor.ToInteger, vaOperador); end else if (ipTabela = 'LOTE_SEMENTE_VENDIDO') or (ipTabela = 'LOTE_MUDA_VENDIDO') then begin if ipParam.Name = TParametros.coData then Result := TSQLGenerator.fpuFilterData(Result, 'VENDA', 'DATA', TUtils.fpuExtrairData(vaValor, 0), TUtils.fpuExtrairData(vaValor, 1), vaOperador) else if ipParam.Name = TParametros.coEspecie then Result := TSQLGenerator.fpuFilterInteger(Result, 'ESPECIE', 'ID', vaValor.ToInteger, vaOperador); end else if (ipTabela = 'SALDO') or (ipTabela = 'VIEW_MOVIMENTACAO_FINANCEIRA') then begin if ipParam.Name = TParametros.coData then Result := TSQLGenerator.fpuFilterDataSemHora(Result, 'VIEW_MOVIMENTACAO_FINANCEIRA', 'DATA', TUtils.fpuExtrairData(vaValor, 0), TUtils.fpuExtrairData(vaValor, 1), vaOperador) else if ipParam.Name = TParametros.coOrganizacao then Result := TSQLGenerator.fpuFilterInteger(Result, 'VIEW_MOVIMENTACAO_FINANCEIRA', 'ID_ORGANIZACAO', vaValor.ToInteger, vaOperador) else if ipParam.Name = TParametros.coProjeto then begin if vaValor.ToInteger = -1 then // nao quero q sai nenhum projeto Result := '(' + Result + ' (VIEW_MOVIMENTACAO_FINANCEIRA.TIPO_ORIGEM <> ' + Ord(oriProjeto).ToString + '))' + vaOperador else if vaValor.ToInteger = 0 then // Todos Result := TSQLGenerator.fpuFilterInteger(Result, 'VIEW_MOVIMENTACAO_FINANCEIRA', 'TIPO_ORIGEM', Ord(oriProjeto), vaOperador) else begin Result := '(' + Result + '((VIEW_MOVIMENTACAO_FINANCEIRA.TIPO_ORIGEM = ' + Ord(oriProjeto).ToString + ') AND '; Result := Result + ' (VIEW_MOVIMENTACAO_FINANCEIRA.ID_ORIGEM_RECURSO = ' + vaValor + ')))' + vaOperador; end; end else if ipParam.Name = TParametros.coFundo then begin if vaValor.ToInteger = -1 then // nao quero q sai nenhuma conta no relatorio Result := '(' + Result + ' (VIEW_MOVIMENTACAO_FINANCEIRA.TIPO_ORIGEM <> ' + Ord(oriFundo).ToString + ')) ' + vaOperador else if vaValor.ToInteger = 0 then // Todos Result := TSQLGenerator.fpuFilterInteger(Result, 'VIEW_MOVIMENTACAO_FINANCEIRA', 'TIPO_ORIGEM', Ord(oriFundo), vaOperador) else begin Result := '(' + Result + '((VIEW_MOVIMENTACAO_FINANCEIRA.TIPO_ORIGEM = ' + Ord(oriFundo).ToString + ') AND '; Result := Result + ' (VIEW_MOVIMENTACAO_FINANCEIRA.ID_ORIGEM_RECURSO = ' + vaValor + ')))' + vaOperador; end; end else if ipParam.Name = TParametros.coTipo then begin vaArray := TUtils.fpuConverterStringToArrayInteger(vaValor, TParametros.coDelimitador); Result := TSQLGenerator.fpuFilterInteger(Result, 'VIEW_MOVIMENTACAO_FINANCEIRA', 'TIPO', vaArray, vaOperador) end else if ipParam.Name = TParametros.coAberto then Result := '(' + Result + ' (VIEW_MOVIMENTACAO_FINANCEIRA.VALOR_TOTAL_PAGO_RECEBIDO <> VIEW_MOVIMENTACAO_FINANCEIRA.VALOR_TOTAL))' + vaOperador end else if (ipTabela = 'TUBETE_SEMEADO') then begin if ipParam.Name = TParametros.coEspecie then Result := TSQLGenerator.fpuFilterInteger(Result, 'ESPECIE', 'ID', vaValor.ToInteger, vaOperador); end else if (ipTabela = 'CONTA_PAGAR') then begin if ipParam.Name = TParametros.coData then Result := TSQLGenerator.fpuFilterDataSemHora(Result, 'VIEW_CONTA_PAGAR', 'DATA', TUtils.fpuExtrairData(vaValor, 0), TUtils.fpuExtrairData(vaValor, 1), vaOperador) else if ipParam.Name = TParametros.coProjeto then begin if vaValor.ToInteger = -1 then // nao quero q sai nenhum projeto Result := '(' + Result + ' (VIEW_CONTA_PAGAR.TIPO_ORIGEM <> ' + Ord(oriProjeto).ToString + '))' + vaOperador else if vaValor.ToInteger = 0 then // Todos Result := TSQLGenerator.fpuFilterInteger(Result, 'VIEW_CONTA_PAGAR', 'TIPO_ORIGEM', Ord(oriProjeto), vaOperador) else begin Result := '(' + Result + '((VIEW_CONTA_PAGAR.TIPO_ORIGEM = ' + Ord(oriProjeto).ToString + ') AND '; Result := Result + ' (VIEW_CONTA_PAGAR.ID_ORIGEM_RECURSO = ' + vaValor + ')))' + vaOperador; end; end else if ipParam.Name = TParametros.coFundo then begin if vaValor.ToInteger = -1 then // nao quero q sai nenhuma conta no relatorio Result := '(' + Result + ' (VIEW_CONTA_PAGAR.TIPO_ORIGEM <> ' + Ord(oriFundo).ToString + ')) ' + vaOperador else if vaValor.ToInteger = 0 then // Todos Result := TSQLGenerator.fpuFilterInteger(Result, 'VIEW_CONTA_PAGAR', 'TIPO_ORIGEM', Ord(oriFundo), vaOperador) else begin Result := '(' + Result + '((VIEW_CONTA_PAGAR.TIPO_ORIGEM = ' + Ord(oriFundo).ToString + ') AND '; Result := Result + ' (VIEW_CONTA_PAGAR.ID_ORIGEM_RECURSO = ' + vaValor + ')))' + vaOperador; end; end; end else if (ipTabela = 'SALDO_SEMENTE_MUDA') then begin if ipParam.Name = TParametros.coID_ESPECIE then Result := TSQLGenerator.fpuFilterInteger(Result, 'ESPECIE', 'ID', vaValor.ToInteger, vaOperador) else if ipParam.Name = TParametros.coClassificacao then Result := TSQLGenerator.fpuFilterInteger(Result, 'ESPECIE', 'CLASSIFICACAO', vaValor.ToInteger, vaOperador) else if ipParam.Name = TParametros.coBioma then begin vaArray := TUtils.fpuConverterStringToArrayInteger(vaValor, TParametros.coDelimitador); Result := TSQLGenerator.fpuFilterInteger(Result, 'ESPECIE_BIOMA', 'BIOMA', vaArray, vaOperador) end else if ipParam.Name = TParametros.coCategoria then Result := TSQLGenerator.fpuFilterInteger(Result, 'ESPECIE', 'CATEGORIA_ARMAZENAMENTO', vaValor.ToInteger, vaOperador) else if ipParam.Name = TParametros.coTipo then Result := TSQLGenerator.fpuFilterInteger(Result, 'ESPECIE', 'ID_TIPO_ESPECIE', vaValor.ToInteger, vaOperador) else if ipParam.Name = TParametros.coSaldoPositivo then Result := Result + ' ((Especie.Qtde_Semente_Estoque > 0) OR (Especie.Qtde_Muda_Pronta > 0) OR (Especie.Qtde_Muda_Desenvolvimento > 0)) ' + vaOperador; end end; procedure TsmRelatorio.qLote_Muda_VendidoCalcFields(DataSet: TDataSet); begin inherited; DataSet.FieldByName('CALC_MES').AsString := FormatDateTime('mmmm "de" yyyy',DataSet.FieldByName('DATA').AsDateTime); DataSet.FieldByName('CALC_MES').AsString := Copy(DataSet.FieldByName('CALC_MES').AsString,1,1).ToUpper+ Copy(DataSet.FieldByName('CALC_MES').AsString,2); end; procedure TsmRelatorio.qPatrimonioCalcFields(DataSet: TDataSet); begin inherited; qPatrimonioCALC_VALOR_ATUAL.AsFloat := TUtils.fpuCalcularDepreciacao(qPatrimonioDATA_AQUISICAO.AsDateTime, qPatrimonioVALOR_INICIAL.AsFloat, qPatrimonioTAXA_DEPRECIACAO_ANUAL.AsInteger); end; procedure TsmRelatorio.qView_Movimentacao_FinanceiraCalcFields( DataSet: TDataSet); begin inherited; qView_Movimentacao_FinanceiraCALC_VALOR_RESTANTE.AsFloat := qView_Movimentacao_FinanceiraVALOR_TOTAL.AsFloat - qView_Movimentacao_FinanceiraVALOR_TOTAL_PAGO_RECEBIDO.AsFloat; if qView_Movimentacao_FinanceiraTIPO.AsInteger = Ord(tmReceita) then qView_Movimentacao_FinanceiraCALC_SALDO.AsFloat := qView_Movimentacao_FinanceiraVALOR_TOTAL_PAGO_RECEBIDO.AsFloat else qView_Movimentacao_FinanceiraCALC_SALDO.AsFloat := -qView_Movimentacao_FinanceiraVALOR_TOTAL_PAGO_RECEBIDO.AsFloat; if not qView_Movimentacao_FinanceiraFORMA_PAGAMENTO_RECEBIMENTO.IsNull then qView_Movimentacao_FinanceiraCALC_DESCRICAO_FORMA_PGTO.AsString := FormaPagamennto[TFormaPagamento(qView_Movimentacao_FinanceiraFORMA_PAGAMENTO_RECEBIMENTO.AsInteger)]; end; end.
unit untCalculoImpostoTest; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, System.Classes, System.SysUtils, untCalculoImposto; type // Test methods for class TImpostoA TestTImpostoA = class(TTestCase) strict private FImpostoA: TImpostoA; public procedure SetUp; override; procedure TearDown; override; published procedure TestfcCalcular; end; // Test methods for class TImpostoB TestTImpostoB = class(TTestCase) strict private FImpostoB: TImpostoB; public procedure SetUp; override; procedure TearDown; override; published procedure TestfcCalcular; end; // Test methods for class TImpostoC TestTImpostoC = class(TTestCase) strict private FImpostoC: TImpostoC; public procedure SetUp; override; procedure TearDown; override; published procedure TestfcCalcular; end; implementation procedure TestTImpostoA.SetUp; begin FImpostoA := TImpostoA.Create; FImpostoA.BaseCalculo := 3000; end; procedure TestTImpostoA.TearDown; begin FImpostoA.Free; FImpostoA := nil; end; procedure TestTImpostoA.TestfcCalcular; var ReturnValue: Double; begin ReturnValue := FImpostoA.fcCalcular; // TODO: Validate method results CheckEquals(100, ReturnValue); end; procedure TestTImpostoB.SetUp; begin FImpostoB := TImpostoB.Create; FImpostoB.ImpostoA := TImpostoA.Create; FImpostoB.ImpostoA.BaseCalculo := 3000; end; procedure TestTImpostoB.TearDown; begin FImpostoB.Free; FImpostoB := nil; end; procedure TestTImpostoB.TestfcCalcular; var ReturnValue: Double; begin ReturnValue := FImpostoB.fcCalcular; // TODO: Validate method results CheckEquals(85, ReturnValue); end; procedure TestTImpostoC.SetUp; begin FImpostoC := TImpostoC.Create; FImpostoC.ImpostoB := TImpostoB.Create; FImpostoC.ImpostoB.ImpostoA := TImpostoA.Create; FImpostoC.ImpostoB.ImpostoA.BaseCalculo := 3000; end; procedure TestTImpostoC.TearDown; begin FImpostoC.Free; FImpostoC := nil; end; procedure TestTImpostoC.TestfcCalcular; var ReturnValue: Double; begin ReturnValue := FImpostoC.fcCalcular; // TODO: Validate method results CheckEquals(185, ReturnValue); end; initialization // Register any test cases with the test runner RegisterTest(TestTImpostoA.Suite); RegisterTest(TestTImpostoB.Suite); RegisterTest(TestTImpostoC.Suite); end.
unit Cities; interface const xCities: array[0..4078] of record City: AnsiString; Country: AnsiString; Population: Integer; end = ( (City: 'A Coru'; Country: 'Spain'; Population: 243402), (City: 'Aachen'; Country: 'Germany'; Population: 243825), (City: 'Aalborg'; Country: 'Denmark'; Population: 161161), (City: 'Aba'; Country: 'Nigeria'; Population: 298900), (City: 'Abadan'; Country: 'Iran'; Population: 206073), (City: 'Abaetetuba'; Country: 'Brazil'; Population: 111258), (City: 'Abakan'; Country: 'Russian Federation'; Population: 169200), (City: 'Abbotsford'; Country: 'Canada'; Population: 105403), (City: 'Abeokuta'; Country: 'Nigeria'; Population: 427400), (City: 'Aberdeen'; Country: 'United Kingdom'; Population: 213070), (City: 'Abha'; Country: 'Saudi Arabia'; Population: 112300), (City: 'Abidjan'; Country: 'C魌e d扞voire'; Population: 2500000), (City: 'Abiko'; Country: 'Japan'; Population: 126670), (City: 'Abilene'; Country: 'United States'; Population: 115930), (City: 'Abohar'; Country: 'India'; Population: 107163), (City: 'Abottabad'; Country: 'Pakistan'; Population: 106000), (City: 'Abu Dhabi'; Country: 'United Arab Emirates'; Population: 398695), (City: 'Abuja'; Country: 'Nigeria'; Population: 350100), (City: 'Acapulco de Ju醨ez'; Country: 'Mexico'; Population: 721011), (City: 'Acarigua'; Country: 'Venezuela'; Population: 158954), (City: 'Accra'; Country: 'Ghana'; Population: 1070000), (City: 'Achalpur'; Country: 'India'; Population: 96216), (City: 'Acheng'; Country: 'China'; Population: 197595), (City: 'Acu馻'; Country: 'Mexico'; Population: 110388), (City: 'Ac醡baro'; Country: 'Mexico'; Population: 110487), (City: 'Adamstown'; Country: 'Pitcairn'; Population: 42), (City: 'Adana'; Country: 'Turkey'; Population: 1131198), (City: 'Addis Abeba'; Country: 'Ethiopia'; Population: 2495000), (City: 'Adelaide'; Country: 'Australia'; Population: 978100), (City: 'Aden'; Country: 'Yemen'; Population: 398300), (City: 'Adiyaman'; Country: 'Turkey'; Population: 141529), (City: 'Ado-Ekiti'; Country: 'Nigeria'; Population: 359400), (City: 'Adoni'; Country: 'India'; Population: 136182), (City: 'Afyon'; Country: 'Turkey'; Population: 103984), (City: 'Agadir'; Country: 'Morocco'; Population: 155244), (City: 'Agartala'; Country: 'India'; Population: 157358), (City: 'Aga馻'; Country: 'Guam'; Population: 1139), (City: 'Agege'; Country: 'Nigeria'; Population: 105000), (City: 'Ageo'; Country: 'Japan'; Population: 209442), (City: 'Agra'; Country: 'India'; Population: 891790), (City: 'Aguascalientes'; Country: 'Mexico'; Population: 643360), (City: 'Ahmadnagar'; Country: 'India'; Population: 181339), (City: 'Ahmadpur East'; Country: 'Pakistan'; Population: 96000), (City: 'Ahmedabad'; Country: 'India'; Population: 2876710), (City: 'Ahome'; Country: 'Mexico'; Population: 358663), (City: 'Ahvaz'; Country: 'Iran'; Population: 804980), (City: 'Aix-en-Provence'; Country: 'France'; Population: 134222), (City: 'Aizawl'; Country: 'India'; Population: 155240), (City: 'Aizuwakamatsu'; Country: 'Japan'; Population: 119287), (City: 'Ajman'; Country: 'United Arab Emirates'; Population: 114395), (City: 'Ajmer'; Country: 'India'; Population: 402700), (City: 'Akashi'; Country: 'Japan'; Population: 292253), (City: 'Akishima'; Country: 'Japan'; Population: 106914), (City: 'Akita'; Country: 'Japan'; Population: 314440), (City: 'Akola'; Country: 'India'; Population: 328034), (City: 'Akron'; Country: 'United States'; Population: 217074), (City: 'Aksaray'; Country: 'Turkey'; Population: 102681), (City: 'Akure'; Country: 'Nigeria'; Population: 162300), (City: 'Alagoinhas'; Country: 'Brazil'; Population: 126820), (City: 'Alandur'; Country: 'India'; Population: 125244), (City: 'Alanya'; Country: 'Turkey'; Population: 117300), (City: 'Albacete'; Country: 'Spain'; Population: 147527), (City: 'Albany'; Country: 'United States'; Population: 93994), (City: 'Alberton'; Country: 'South Africa'; Population: 410102), (City: 'Albuquerque'; Country: 'United States'; Population: 448607), (City: 'Alcal?de Henares'; Country: 'Spain'; Population: 164463), (City: 'Alcorc髇'; Country: 'Spain'; Population: 142048), (City: 'Aleppo'; Country: 'Syria'; Population: 1261983), (City: 'Alessandria'; Country: 'Italy'; Population: 90289), (City: 'Alexandria'; Country: 'Egypt'; Population: 3328196), (City: 'Alexandria'; Country: 'United States'; Population: 128283), (City: 'Algeciras'; Country: 'Spain'; Population: 103106), (City: 'Alger'; Country: 'Algeria'; Population: 2168000), (City: 'Alicante [Alacant]'; Country: 'Spain'; Population: 272432), (City: 'Aligarh'; Country: 'India'; Population: 480520), (City: 'Alkmaar'; Country: 'Netherlands'; Population: 92713), (City: 'Allahabad'; Country: 'India'; Population: 792858), (City: 'Allappuzha (Alleppey)'; Country: 'India'; Population: 174666), (City: 'Allende'; Country: 'Mexico'; Population: 134645), (City: 'Allentown'; Country: 'United States'; Population: 106632), (City: 'Almaty'; Country: 'Kazakstan'; Population: 1129400), (City: 'Almere'; Country: 'Netherlands'; Population: 142465), (City: 'Almer韆'; Country: 'Spain'; Population: 169027), (City: 'Almetjevsk'; Country: 'Russian Federation'; Population: 140700), (City: 'Almirante Brown'; Country: 'Argentina'; Population: 538918), (City: 'Almoloya de Ju醨ez'; Country: 'Mexico'; Population: 110550), (City: 'Alofi'; Country: 'Niue'; Population: 682), (City: 'Alor Setar'; Country: 'Malaysia'; Population: 124412), (City: 'Altamira'; Country: 'Mexico'; Population: 127490), (City: 'Alt歟vsk'; Country: 'Ukraine'; Population: 119000), (City: 'Alvorada'; Country: 'Brazil'; Population: 175574), (City: 'Alwar'; Country: 'India'; Population: 205086), (City: 'Amadora'; Country: 'Portugal'; Population: 122106), (City: 'Amagasaki'; Country: 'Japan'; Population: 481434), (City: 'Amarillo'; Country: 'United States'; Population: 173627), (City: 'Ambala'; Country: 'India'; Population: 122596), (City: 'Ambala Sadar'; Country: 'India'; Population: 90712), (City: 'Ambato'; Country: 'Ecuador'; Population: 169612), (City: 'Ambattur'; Country: 'India'; Population: 215424), (City: 'Ambon'; Country: 'Indonesia'; Population: 249312), (City: 'Americana'; Country: 'Brazil'; Population: 177409), (City: 'Amersfoort'; Country: 'Netherlands'; Population: 126270), (City: 'Amiens'; Country: 'France'; Population: 135501), (City: 'Amman'; Country: 'Jordan'; Population: 1000000), (City: 'Amol'; Country: 'Iran'; Population: 159092), (City: 'Amoy [Xiamen]'; Country: 'China'; Population: 627500), (City: 'Amravati'; Country: 'India'; Population: 421576), (City: 'Amritsar'; Country: 'India'; Population: 708835), (City: 'Amroha'; Country: 'India'; Population: 137061), (City: 'Amsterdam'; Country: 'Netherlands'; Population: 731200), (City: 'Anaheim'; Country: 'United States'; Population: 328014), (City: 'Anand'; Country: 'India'; Population: 110266), (City: 'Ananindeua'; Country: 'Brazil'; Population: 400940), (City: 'Anantapur'; Country: 'India'; Population: 174924), (City: 'Anchorage'; Country: 'United States'; Population: 260283), (City: 'Ancona'; Country: 'Italy'; Population: 98329), (City: 'Anda'; Country: 'China'; Population: 136446), (City: 'Andijon'; Country: 'Uzbekistan'; Population: 318600), (City: 'Andimeshk'; Country: 'Iran'; Population: 106923), (City: 'Andong'; Country: 'South Korea'; Population: 188443), (City: 'Andorra la Vella'; Country: 'Andorra'; Population: 21189), (City: 'Andria'; Country: 'Italy'; Population: 94443), (City: 'Angarsk'; Country: 'Russian Federation'; Population: 264700), (City: 'Angeles'; Country: 'Philippines'; Population: 263971), (City: 'Angers'; Country: 'France'; Population: 151279), (City: 'Angra dos Reis'; Country: 'Brazil'; Population: 96864), (City: 'Angren'; Country: 'Uzbekistan'; Population: 128000), (City: 'Anjo'; Country: 'Japan'; Population: 153823), (City: 'Ankang'; Country: 'China'; Population: 142170), (City: 'Ankara'; Country: 'Turkey'; Population: 3038159), (City: 'Ann Arbor'; Country: 'United States'; Population: 114024), (City: 'Annaba'; Country: 'Algeria'; Population: 222518), (City: 'Anqing'; Country: 'China'; Population: 250718), (City: 'Ansan'; Country: 'South Korea'; Population: 510314), (City: 'Anshan'; Country: 'China'; Population: 1200000), (City: 'Anshun'; Country: 'China'; Population: 174142), (City: 'Antalya'; Country: 'Turkey'; Population: 564914), (City: 'Antananarivo'; Country: 'Madagascar'; Population: 675669), (City: 'Antipolo'; Country: 'Philippines'; Population: 470866), (City: 'Antofagasta'; Country: 'Chile'; Population: 251429), (City: 'Antsirab'; Country: 'Madagascar'; Population: 120239), (City: 'Antwerpen'; Country: 'Belgium'; Population: 446525), (City: 'Anyang'; Country: 'China'; Population: 420332), (City: 'Anyang'; Country: 'South Korea'; Population: 591106), (City: 'Anzero-Sudzensk'; Country: 'Russian Federation'; Population: 96100), (City: 'An醦olis'; Country: 'Brazil'; Population: 282197), (City: 'Aomori'; Country: 'Japan'; Population: 295969), (City: 'Aparecida de Goi鈔ia'; Country: 'Brazil'; Population: 324662), (City: 'Apatzing醤'; Country: 'Mexico'; Population: 117849), (City: 'Apeldoorn'; Country: 'Netherlands'; Population: 153491), (City: 'Apia'; Country: 'Samoa'; Population: 35900), (City: 'Apodaca'; Country: 'Mexico'; Population: 282941), (City: 'Apopa'; Country: 'El Salvador'; Population: 88800), (City: 'Apucarana'; Country: 'Brazil'; Population: 105114), (City: 'Aqsu'; Country: 'China'; Population: 164092), (City: 'Aqtau'; Country: 'Kazakstan'; Population: 143400), (City: 'Aqt鯾e'; Country: 'Kazakstan'; Population: 253100), (City: 'Aracaju'; Country: 'Brazil'; Population: 445555), (City: 'Arad'; Country: 'Romania'; Population: 184408), (City: 'Araguari'; Country: 'Brazil'; Population: 98399), (City: 'Aragua韓a'; Country: 'Brazil'; Population: 114948), (City: 'Arak'; Country: 'Iran'; Population: 380755), (City: 'Arapiraca'; Country: 'Brazil'; Population: 178988), (City: 'Araraquara'; Country: 'Brazil'; Population: 174381), (City: 'Araras'; Country: 'Brazil'; Population: 101046), (City: 'Araure'; Country: 'Venezuela'; Population: 94269), (City: 'Arayat'; Country: 'Philippines'; Population: 101792), (City: 'Ara碼r'; Country: 'Saudi Arabia'; Population: 108100), (City: 'Ara鏰tuba'; Country: 'Brazil'; Population: 169303), (City: 'Ardebil'; Country: 'Iran'; Population: 340386), (City: 'Arden-Arcade'; Country: 'United States'; Population: 92040), (City: 'Arecibo'; Country: 'Puerto Rico'; Population: 100131), (City: 'Arequipa'; Country: 'Peru'; Population: 762000), (City: 'Arezzo'; Country: 'Italy'; Population: 91729), (City: 'Argenteuil'; Country: 'France'; Population: 93961), (City: 'Ariana'; Country: 'Tunisia'; Population: 197000), (City: 'Arica'; Country: 'Chile'; Population: 189036), (City: 'Arkangeli'; Country: 'Russian Federation'; Population: 361800), (City: 'Arlington'; Country: 'United States'; Population: 332969), (City: 'Arlington'; Country: 'United States'; Population: 174838), (City: 'Armavir'; Country: 'Russian Federation'; Population: 164900), (City: 'Armenia'; Country: 'Colombia'; Population: 288977), (City: 'Arnhem'; Country: 'Netherlands'; Population: 138020), (City: 'Arrah (Ara)'; Country: 'India'; Population: 157082), (City: 'Arusha'; Country: 'Tanzania'; Population: 102500), (City: 'Arvada'; Country: 'United States'; Population: 102153), (City: 'Arzamas'; Country: 'Russian Federation'; Population: 110700), (City: 'Asahikawa'; Country: 'Japan'; Population: 364813), (City: 'Asaka'; Country: 'Japan'; Population: 114815), (City: 'Asan'; Country: 'South Korea'; Population: 154663), (City: 'Asansol'; Country: 'India'; Population: 262188), (City: 'Ashdod'; Country: 'Israel'; Population: 155800), (City: 'Ashgabat'; Country: 'Turkmenistan'; Population: 540600), (City: 'Ashikaga'; Country: 'Japan'; Population: 165243), (City: 'Ashoknagar-Kalyangarh'; Country: 'India'; Population: 96315), (City: 'Ashqelon'; Country: 'Israel'; Population: 92300), (City: 'Asmara'; Country: 'Eritrea'; Population: 431000), (City: 'Assuan'; Country: 'Egypt'; Population: 219017), (City: 'Astana'; Country: 'Kazakstan'; Population: 311200), (City: 'Astrahan'; Country: 'Russian Federation'; Population: 486100), (City: 'Asunci髇'; Country: 'Paraguay'; Population: 557776), (City: 'Asyut'; Country: 'Egypt'; Population: 343498), (City: 'Athenai'; Country: 'Greece'; Population: 772072), (City: 'Athens-Clarke County'; Country: 'United States'; Population: 101489), (City: 'Atibaia'; Country: 'Brazil'; Population: 100356), (City: 'Atizap醤 de Zaragoza'; Country: 'Mexico'; Population: 467262), (City: 'Atlanta'; Country: 'United States'; Population: 416474), (City: 'Atlixco'; Country: 'Mexico'; Population: 117019), (City: 'Atsugi'; Country: 'Japan'; Population: 212407), (City: 'Atyrau'; Country: 'Kazakstan'; Population: 142500), (City: 'At歩nsk'; Country: 'Russian Federation'; Population: 121600), (City: 'Auckland'; Country: 'New Zealand'; Population: 381800), (City: 'Augsburg'; Country: 'Germany'; Population: 254867), (City: 'Augusta-Richmond County'; Country: 'United States'; Population: 199775), (City: 'Aurora'; Country: 'United States'; Population: 276393), (City: 'Aurora'; Country: 'United States'; Population: 142990), (City: 'Austin'; Country: 'United States'; Population: 656562), (City: 'Avadi'; Country: 'India'; Population: 183215), (City: 'Avarua'; Country: 'Cook Islands'; Population: 11900), (City: 'Avellaneda'; Country: 'Argentina'; Population: 353046), (City: 'Awka'; Country: 'Nigeria'; Population: 111200), (City: 'Ayacucho'; Country: 'Peru'; Population: 118960), (City: 'Aydin'; Country: 'Turkey'; Population: 128651), (City: 'Babol'; Country: 'Iran'; Population: 158346), (City: 'Bacabal'; Country: 'Brazil'; Population: 93121), (City: 'Bacau'; Country: 'Romania'; Population: 209235), (City: 'Bacolod'; Country: 'Philippines'; Population: 429076), (City: 'Bacoor'; Country: 'Philippines'; Population: 305699), (City: 'Badajoz'; Country: 'Spain'; Population: 136613), (City: 'Badalona'; Country: 'Spain'; Population: 209635), (City: 'Bafoussam'; Country: 'Cameroon'; Population: 131000), (City: 'Baghdad'; Country: 'Iraq'; Population: 4336000), (City: 'Bago'; Country: 'Philippines'; Population: 141721), (City: 'Baguio'; Country: 'Philippines'; Population: 252386), (City: 'Bag'; Country: 'Brazil'; Population: 120793), (City: 'Bahawalnagar'; Country: 'Pakistan'; Population: 109600), (City: 'Bahawalpur'; Country: 'Pakistan'; Population: 403408), (City: 'Bahir Dar'; Country: 'Ethiopia'; Population: 96140), (City: 'Bahraich'; Country: 'India'; Population: 135400), (City: 'Bahtim'; Country: 'Egypt'; Population: 275807), (City: 'Bah韆 Blanca'; Country: 'Argentina'; Population: 239810), (City: 'Baia Mare'; Country: 'Romania'; Population: 149665), (City: 'Baicheng'; Country: 'China'; Population: 217987), (City: 'Baidyabati'; Country: 'India'; Population: 90601), (City: 'Bairiki'; Country: 'Kiribati'; Population: 2226), (City: 'Baiyin'; Country: 'China'; Population: 204970), (City: 'Bakersfield'; Country: 'United States'; Population: 247057), (City: 'Baku'; Country: 'Azerbaijan'; Population: 1787800), (City: 'Balakovo'; Country: 'Russian Federation'; Population: 206000), (City: 'Bala歩ha'; Country: 'Russian Federation'; Population: 132900), (City: 'Bala歰v'; Country: 'Russian Federation'; Population: 97100), (City: 'Balikesir'; Country: 'Turkey'; Population: 196382), (City: 'Balikpapan'; Country: 'Indonesia'; Population: 338752), (City: 'Baliuag'; Country: 'Philippines'; Population: 119675), (City: 'Bally'; Country: 'India'; Population: 184474), (City: 'Balti'; Country: 'Moldova'; Population: 153400), (City: 'Baltimore'; Country: 'United States'; Population: 651154), (City: 'Balurghat'; Country: 'India'; Population: 119796), (City: 'Bamako'; Country: 'Mali'; Population: 809552), (City: 'Bamenda'; Country: 'Cameroon'; Population: 138000), (City: 'Banda'; Country: 'India'; Population: 97227), (City: 'Banda Aceh'; Country: 'Indonesia'; Population: 143409), (City: 'Bandar Lampung'; Country: 'Indonesia'; Population: 680332), (City: 'Bandar Seri Begawan'; Country: 'Brunei'; Population: 21484), (City: 'Bandar-e Anzali'; Country: 'Iran'; Population: 98500), (City: 'Bandar-e-Abbas'; Country: 'Iran'; Population: 273578), (City: 'Bandirma'; Country: 'Turkey'; Population: 90200), (City: 'Bandung'; Country: 'Indonesia'; Population: 2429000), (City: 'Bangalore'; Country: 'India'; Population: 2660088), (City: 'Bangkok'; Country: 'Thailand'; Population: 6320174), (City: 'Bangui'; Country: 'Central African Republic'; Population: 524000), (City: 'Banha'; Country: 'Egypt'; Population: 145792), (City: 'Bani Suwayf'; Country: 'Egypt'; Population: 172032), (City: 'Banja Luka'; Country: 'Bosnia and Herzegovina'; Population: 143079), (City: 'Banjarmasin'; Country: 'Indonesia'; Population: 482931), (City: 'Banjul'; Country: 'Gambia'; Population: 42326), (City: 'Bankura'; Country: 'India'; Population: 114876), (City: 'Bansberia'; Country: 'India'; Population: 93447), (City: 'Bantam'; Country: 'Cocos (Keeling) Islands'; Population: 503), (City: 'Banyuwangi'; Country: 'Indonesia'; Population: 89900), (City: 'Baoding'; Country: 'China'; Population: 483155), (City: 'Baoji'; Country: 'China'; Population: 337765), (City: 'Baotou'; Country: 'China'; Population: 980000), (City: 'Baquba'; Country: 'Iraq'; Population: 114516), (City: 'Barahanagar (Baranagar)'; Country: 'India'; Population: 224821), (City: 'Barakaldo'; Country: 'Spain'; Population: 98212), (City: 'Baranovit歩'; Country: 'Belarus'; Population: 167000), (City: 'Barasat'; Country: 'India'; Population: 107365), (City: 'Barbacena'; Country: 'Brazil'; Population: 113079), (City: 'Barcelona'; Country: 'Spain'; Population: 1503451), (City: 'Barcelona'; Country: 'Venezuela'; Population: 322267), (City: 'Barddhaman (Burdwan)'; Country: 'India'; Population: 245079), (City: 'Bareilly'; Country: 'India'; Population: 587211), (City: 'Bari'; Country: 'Italy'; Population: 331848), (City: 'Barinas'; Country: 'Venezuela'; Population: 217831), (City: 'Barisal'; Country: 'Bangladesh'; Population: 170232), (City: 'Barletta'; Country: 'Italy'; Population: 91904), (City: 'Barnaul'; Country: 'Russian Federation'; Population: 580100), (City: 'Barquisimeto'; Country: 'Venezuela'; Population: 877239), (City: 'Barra Mansa'; Country: 'Brazil'; Population: 168953), (City: 'Barra do Pira?'; Country: 'Brazil'; Population: 89388), (City: 'Barrackpur'; Country: 'India'; Population: 133265), (City: 'Barrancabermeja'; Country: 'Colombia'; Population: 178020), (City: 'Barranquilla'; Country: 'Colombia'; Population: 1223260), (City: 'Barreiras'; Country: 'Brazil'; Population: 127801), (City: 'Barretos'; Country: 'Brazil'; Population: 104156), (City: 'Barrie'; Country: 'Canada'; Population: 89269), (City: 'Barueri'; Country: 'Brazil'; Population: 208426), (City: 'Baruta'; Country: 'Venezuela'; Population: 207290), (City: 'Basel'; Country: 'Switzerland'; Population: 166700), (City: 'Basildon'; Country: 'United Kingdom'; Population: 100924), (City: 'Basirhat'; Country: 'India'; Population: 101409), (City: 'Basra'; Country: 'Iraq'; Population: 406296), (City: 'Basse-Terre'; Country: 'Guadeloupe'; Population: 12433), (City: 'Bassein (Pathein)'; Country: 'Myanmar'; Population: 183900), (City: 'Basseterre'; Country: 'Saint Kitts and Nevis'; Population: 11600), (City: 'Bat Yam'; Country: 'Israel'; Population: 137000), (City: 'Bataisk'; Country: 'Russian Federation'; Population: 97300), (City: 'Batam'; Country: 'Indonesia'; Population: 91871), (City: 'Batangas'; Country: 'Philippines'; Population: 247588), (City: 'Batman'; Country: 'Turkey'; Population: 203793), (City: 'Batna'; Country: 'Algeria'; Population: 183377), (City: 'Baton Rouge'; Country: 'United States'; Population: 227818), (City: 'Battambang'; Country: 'Cambodia'; Population: 129800), (City: 'Batumi'; Country: 'Georgia'; Population: 137700), (City: 'Bauru'; Country: 'Brazil'; Population: 313670), (City: 'Bawshar'; Country: 'Oman'; Population: 107500), (City: 'Bayambang'; Country: 'Philippines'; Population: 96609), (City: 'Bayamo'; Country: 'Cuba'; Population: 141000), (City: 'Bayam髇'; Country: 'Puerto Rico'; Population: 224044), (City: 'Bayawan (Tulong)'; Country: 'Philippines'; Population: 101391), (City: 'Baybay'; Country: 'Philippines'; Population: 95630), (City: 'Bayugan'; Country: 'Philippines'; Population: 93623), (City: 'Beau Bassin-Rose Hill'; Country: 'Mauritius'; Population: 100616), (City: 'Beaumont'; Country: 'United States'; Population: 113866), (City: 'Beawar'; Country: 'India'; Population: 105363), (City: 'Beerseba'; Country: 'Israel'; Population: 163700), (City: 'Beihai'; Country: 'China'; Population: 112673), (City: 'Beipiao'; Country: 'China'; Population: 194301), (City: 'Beira'; Country: 'Mozambique'; Population: 397368), (City: 'Beirut'; Country: 'Lebanon'; Population: 1100000), (City: 'Bei碼n'; Country: 'China'; Population: 204899), (City: 'Bekasi'; Country: 'Indonesia'; Population: 644300), (City: 'Belfast'; Country: 'United Kingdom'; Population: 287500), (City: 'Belford Roxo'; Country: 'Brazil'; Population: 425194), (City: 'Belgaum'; Country: 'India'; Population: 326399), (City: 'Belgorod'; Country: 'Russian Federation'; Population: 342000), (City: 'Belize City'; Country: 'Belize'; Population: 55810), (City: 'Bellary'; Country: 'India'; Population: 245391), (City: 'Bellevue'; Country: 'United States'; Population: 109569), (City: 'Bello'; Country: 'Colombia'; Population: 333470), (City: 'Belmopan'; Country: 'Belize'; Population: 7105), (City: 'Belo Horizonte'; Country: 'Brazil'; Population: 2139125), (City: 'Bel閙'; Country: 'Brazil'; Population: 1186926), (City: 'Bender (T頶hina)'; Country: 'Moldova'; Population: 125700), (City: 'Bene Beraq'; Country: 'Israel'; Population: 133900), (City: 'Bengasi'; Country: 'Libyan Arab Jamahiriya'; Population: 804000), (City: 'Bengbu'; Country: 'China'; Population: 449245), (City: 'Bengkulu'; Country: 'Indonesia'; Population: 146439), (City: 'Benguela'; Country: 'Angola'; Population: 128300), (City: 'Beni-Mellal'; Country: 'Morocco'; Population: 140212), (City: 'Benin City'; Country: 'Nigeria'; Population: 229400), (City: 'Benito Ju醨ez'; Country: 'Mexico'; Population: 419276), (City: 'Benoni'; Country: 'South Africa'; Population: 365467), (City: 'Bento Gon鏰lves'; Country: 'Brazil'; Population: 89254), (City: 'Benxi'; Country: 'China'; Population: 770000), (City: 'Beograd'; Country: 'Yugoslavia'; Population: 1204000), (City: 'Beppu'; Country: 'Japan'; Population: 127486), (City: 'Berazategui'; Country: 'Argentina'; Population: 276916), (City: 'Berdjansk'; Country: 'Ukraine'; Population: 130000), (City: 'Berdyt歩v'; Country: 'Ukraine'; Population: 90000), (City: 'Berezniki'; Country: 'Russian Federation'; Population: 181900), (City: 'Bergamo'; Country: 'Italy'; Population: 117837), (City: 'Bergen'; Country: 'Norway'; Population: 230948), (City: 'Bergisch Gladbach'; Country: 'Germany'; Population: 106150), (City: 'Berhampore (Baharampur)'; Country: 'India'; Population: 115144), (City: 'Berkeley'; Country: 'United States'; Population: 102743), (City: 'Berlin'; Country: 'Germany'; Population: 3386667), (City: 'Bern'; Country: 'Switzerland'; Population: 122700), (City: 'Besan鏾n'; Country: 'France'; Population: 117733), (City: 'Betim'; Country: 'Brazil'; Population: 302108), (City: 'Bettiah'; Country: 'India'; Population: 92583), (City: 'Bhagalpur'; Country: 'India'; Population: 253225), (City: 'Bharatpur'; Country: 'India'; Population: 148519), (City: 'Bharuch (Broach)'; Country: 'India'; Population: 133102), (City: 'Bhatinda (Bathinda)'; Country: 'India'; Population: 159042), (City: 'Bhatpara'; Country: 'India'; Population: 304952), (City: 'Bhavnagar'; Country: 'India'; Population: 402338), (City: 'Bhilai'; Country: 'India'; Population: 386159), (City: 'Bhilwara'; Country: 'India'; Population: 183965), (City: 'Bhimavaram'; Country: 'India'; Population: 121314), (City: 'Bhind'; Country: 'India'; Population: 109755), (City: 'Bhir (Bid)'; Country: 'India'; Population: 112434), (City: 'Bhiwandi'; Country: 'India'; Population: 379070), (City: 'Bhiwani'; Country: 'India'; Population: 121629), (City: 'Bhopal'; Country: 'India'; Population: 1062771), (City: 'Bhubaneswar'; Country: 'India'; Population: 411542), (City: 'Bhuj'; Country: 'India'; Population: 102176), (City: 'Bhusawal'; Country: 'India'; Population: 145143), (City: 'Bialystok'; Country: 'Poland'; Population: 283937), (City: 'Bida'; Country: 'Nigeria'; Population: 125500), (City: 'Bidar'; Country: 'India'; Population: 108016), (City: 'Bielefeld'; Country: 'Germany'; Population: 321125), (City: 'Bielsko-Biala'; Country: 'Poland'; Population: 180307), (City: 'Bihar Sharif'; Country: 'India'; Population: 201323), (City: 'Bijapur'; Country: 'India'; Population: 186939), (City: 'Bijsk'; Country: 'Russian Federation'; Population: 225000), (City: 'Bikaner'; Country: 'India'; Population: 416289), (City: 'Bikenibeu'; Country: 'Kiribati'; Population: 5055), (City: 'Bila Tserkva'; Country: 'Ukraine'; Population: 215000), (City: 'Bilaspur'; Country: 'India'; Population: 179833), (City: 'Bilbao'; Country: 'Spain'; Population: 357589), (City: 'Bilbays'; Country: 'Egypt'; Population: 113608), (City: 'Billings'; Country: 'United States'; Population: 92988), (City: 'Binangonan'; Country: 'Philippines'; Population: 187691), (City: 'Binjai'; Country: 'Indonesia'; Population: 127222), (City: 'Binzhou'; Country: 'China'; Population: 133555), (City: 'Biratnagar'; Country: 'Nepal'; Population: 157764), (City: 'Birgunj'; Country: 'Nepal'; Population: 90639), (City: 'Birigui'; Country: 'Brazil'; Population: 94685), (City: 'Birjand'; Country: 'Iran'; Population: 127608), (City: 'Birkenhead'; Country: 'United Kingdom'; Population: 93087), (City: 'Birkirkara'; Country: 'Malta'; Population: 21445), (City: 'Birmingham'; Country: 'United Kingdom'; Population: 1013000), (City: 'Birmingham'; Country: 'United States'; Population: 242820), (City: 'Biserta'; Country: 'Tunisia'; Population: 108900), (City: 'Bishkek'; Country: 'Kyrgyzstan'; Population: 589400), (City: 'Biskra'; Country: 'Algeria'; Population: 128281), (City: 'Bislig'; Country: 'Philippines'; Population: 97860), (City: 'Bismil'; Country: 'Turkey'; Population: 101400), (City: 'Bissau'; Country: 'Guinea-Bissau'; Population: 241000), (City: 'Bi阯 Hoa'; Country: 'Vietnam'; Population: 282095), (City: 'Bi馻n'; Country: 'Philippines'; Population: 201186), (City: 'Blackburn'; Country: 'United Kingdom'; Population: 140000), (City: 'Blackpool'; Country: 'United Kingdom'; Population: 151000), (City: 'Blagove歵歟nsk'; Country: 'Russian Federation'; Population: 222000), (City: 'Blantyre'; Country: 'Malawi'; Population: 478155), (City: 'Blida (el-Boulaida)'; Country: 'Algeria'; Population: 127284), (City: 'Blitar'; Country: 'Indonesia'; Population: 122600), (City: 'Bloemfontein'; Country: 'South Africa'; Population: 334341), (City: 'Blumenau'; Country: 'Brazil'; Population: 244379), (City: 'Boa Vista'; Country: 'Brazil'; Population: 167185), (City: 'Bobo-Dioulasso'; Country: 'Burkina Faso'; Population: 300000), (City: 'Bobruisk'; Country: 'Belarus'; Population: 221000), (City: 'Boca del R韔'; Country: 'Mexico'; Population: 135721), (City: 'Bochum'; Country: 'Germany'; Population: 392830), (City: 'Bogor'; Country: 'Indonesia'; Population: 285114), (City: 'Bogra'; Country: 'Bangladesh'; Population: 120170), (City: 'Boise City'; Country: 'United States'; Population: 185787), (City: 'Bojnurd'; Country: 'Iran'; Population: 134835), (City: 'Bokaro Steel City'; Country: 'India'; Population: 333683), (City: 'Boksburg'; Country: 'South Africa'; Population: 262648), (City: 'Bologna'; Country: 'Italy'; Population: 381161), (City: 'Bolton'; Country: 'United Kingdom'; Population: 139020), (City: 'Bolzano'; Country: 'Italy'; Population: 97232), (City: 'Boma'; Country: 'Congo, The Democratic Republic of the'; Population: 135284), (City: 'Bonn'; Country: 'Germany'; Population: 301048), (City: 'Bordeaux'; Country: 'France'; Population: 215363), (City: 'Borisov'; Country: 'Belarus'; Population: 151000), (City: 'Borujerd'; Country: 'Iran'; Population: 217804), (City: 'Bor錽'; Country: 'Sweden'; Population: 96883), (City: 'Bose'; Country: 'China'; Population: 93009), (City: 'Boston'; Country: 'United States'; Population: 589141), (City: 'Botosani'; Country: 'Romania'; Population: 128730), (City: 'Botshabelo'; Country: 'South Africa'; Population: 177971), (City: 'Bottrop'; Country: 'Germany'; Population: 121097), (City: 'Botucatu'; Country: 'Brazil'; Population: 107663), (City: 'Bouak?'; Country: 'C魌e d扞voire'; Population: 329850), (City: 'Boulder'; Country: 'United States'; Population: 91238), (City: 'Boulogne-Billancourt'; Country: 'France'; Population: 106367), (City: 'Bournemouth'; Country: 'United Kingdom'; Population: 162000), (City: 'Bozhou'; Country: 'China'; Population: 106346), (City: 'Bradford'; Country: 'United Kingdom'; Population: 289376), (City: 'Braga'; Country: 'Portugal'; Population: 90535), (City: 'Bragan鏰 Paulista'; Country: 'Brazil'; Population: 116929), (City: 'Brahmanbaria'; Country: 'Bangladesh'; Population: 109032), (City: 'Brahmapur'; Country: 'India'; Population: 210418), (City: 'Braila'; Country: 'Romania'; Population: 233756), (City: 'Brakpan'; Country: 'South Africa'; Population: 171363), (City: 'Brampton'; Country: 'Canada'; Population: 296711), (City: 'Brasov'; Country: 'Romania'; Population: 314225), (City: 'Bras韑ia'; Country: 'Brazil'; Population: 1969868), (City: 'Bratislava'; Country: 'Slovakia'; Population: 448292), (City: 'Bratsk'; Country: 'Russian Federation'; Population: 277600), (City: 'Braunschweig'; Country: 'Germany'; Population: 246322), (City: 'Brazzaville'; Country: 'Congo'; Population: 950000), (City: 'Breda'; Country: 'Netherlands'; Population: 160398), (City: 'Bremen'; Country: 'Germany'; Population: 540330), (City: 'Bremerhaven'; Country: 'Germany'; Population: 122735), (City: 'Brescia'; Country: 'Italy'; Population: 191317), (City: 'Brest'; Country: 'France'; Population: 149634), (City: 'Brest'; Country: 'Belarus'; Population: 286000), (City: 'Bridgeport'; Country: 'United States'; Population: 139529), (City: 'Bridgetown'; Country: 'Barbados'; Population: 6070), (City: 'Brighton'; Country: 'United Kingdom'; Population: 156124), (City: 'Brindisi'; Country: 'Italy'; Population: 93454), (City: 'Brisbane'; Country: 'Australia'; Population: 1291117), (City: 'Bristol'; Country: 'United Kingdom'; Population: 402000), (City: 'Brjansk'; Country: 'Russian Federation'; Population: 457400), (City: 'Brno'; Country: 'Czech Republic'; Population: 381862), (City: 'Brockton'; Country: 'United States'; Population: 93653), (City: 'Brovary'; Country: 'Ukraine'; Population: 89000), (City: 'Brownsville'; Country: 'United States'; Population: 139722), (City: 'Brugge'; Country: 'Belgium'; Population: 116246), (City: 'Bruxelles [Brussel]'; Country: 'Belgium'; Population: 133859), (City: 'Bucaramanga'; Country: 'Colombia'; Population: 515555), (City: 'Bucuresti'; Country: 'Romania'; Population: 2016131), (City: 'Budapest'; Country: 'Hungary'; Population: 1811552), (City: 'Budaun'; Country: 'India'; Population: 116695), (City: 'Buenaventura'; Country: 'Colombia'; Population: 224336), (City: 'Buenos Aires'; Country: 'Argentina'; Population: 2982146), (City: 'Buffalo'; Country: 'United States'; Population: 292648), (City: 'Buga'; Country: 'Colombia'; Population: 110699), (City: 'Bugulma'; Country: 'Russian Federation'; Population: 94100), (City: 'Buhoro'; Country: 'Uzbekistan'; Population: 237100), (City: 'Bujumbura'; Country: 'Burundi'; Population: 300000), (City: 'Bukan'; Country: 'Iran'; Population: 120020), (City: 'Bukavu'; Country: 'Congo, The Democratic Republic of the'; Population: 201569), (City: 'Bulandshahr'; Country: 'India'; Population: 127201), (City: 'Bulaq al-Dakrur'; Country: 'Egypt'; Population: 148787), (City: 'Bulawayo'; Country: 'Zimbabwe'; Population: 621742), (City: 'Buon Ma Thuot'; Country: 'Vietnam'; Population: 97044), (City: 'Burayda'; Country: 'Saudi Arabia'; Population: 248600), (City: 'Burbank'; Country: 'United States'; Population: 100316), (City: 'Burgas'; Country: 'Bulgaria'; Population: 195255), (City: 'Burgos'; Country: 'Spain'; Population: 162802), (City: 'Burhanpur'; Country: 'India'; Population: 172710), (City: 'Burlington'; Country: 'Canada'; Population: 145150), (City: 'Burnaby'; Country: 'Canada'; Population: 179209), (City: 'Burnpur'; Country: 'India'; Population: 174933), (City: 'Bursa'; Country: 'Turkey'; Population: 1095842), (City: 'Bushehr'; Country: 'Iran'; Population: 143641), (City: 'Butembo'; Country: 'Congo, The Democratic Republic of the'; Population: 109406), (City: 'Butuan'; Country: 'Philippines'; Population: 267279), (City: 'Buzau'; Country: 'Romania'; Population: 148372), (City: 'Bydgoszcz'; Country: 'Poland'; Population: 386855), (City: 'Bytom'; Country: 'Poland'; Population: 205560), (City: 'B鎟um'; Country: 'Norway'; Population: 101340), (City: 'B閏har'; Country: 'Algeria'; Population: 107311), (City: 'B閖a颽'; Country: 'Algeria'; Population: 117162), (City: 'Cabanatuan'; Country: 'Philippines'; Population: 222859), (City: 'Cabimas'; Country: 'Venezuela'; Population: 221329), (City: 'Cabo Frio'; Country: 'Brazil'; Population: 119503), (City: 'Cabo de Santo Agostinho'; Country: 'Brazil'; Population: 149964), (City: 'Cabuyao'; Country: 'Philippines'; Population: 106630), (City: 'Cachoeirinha'; Country: 'Brazil'; Population: 103240), (City: 'Cachoeiro de Itapemirim'; Country: 'Brazil'; Population: 155024), (City: 'Cadiz'; Country: 'Philippines'; Population: 141954), (City: 'Caen'; Country: 'France'; Population: 113987), (City: 'Cagayan de Oro'; Country: 'Philippines'; Population: 461877), (City: 'Cagliari'; Country: 'Italy'; Population: 165926), (City: 'Caguas'; Country: 'Puerto Rico'; Population: 140502), (City: 'Cainta'; Country: 'Philippines'; Population: 242511), (City: 'Cairns'; Country: 'Australia'; Population: 92273), (City: 'Cairo'; Country: 'Egypt'; Population: 6789479), (City: 'Cajamarca'; Country: 'Peru'; Population: 108009), (City: 'Cajeme'; Country: 'Mexico'; Population: 355679), (City: 'Calabar'; Country: 'Nigeria'; Population: 174400), (City: 'Calabozo'; Country: 'Venezuela'; Population: 107146), (City: 'Calama'; Country: 'Chile'; Population: 137265), (City: 'Calamba'; Country: 'Philippines'; Population: 281146), (City: 'Calapan'; Country: 'Philippines'; Population: 105910), (City: 'Calbayog'; Country: 'Philippines'; Population: 147187), (City: 'Calcutta [Kolkata]'; Country: 'India'; Population: 4399819), (City: 'Calgary'; Country: 'Canada'; Population: 768082), (City: 'Cali'; Country: 'Colombia'; Population: 2077386), (City: 'Calicut (Kozhikode)'; Country: 'India'; Population: 419831), (City: 'Callao'; Country: 'Peru'; Population: 424294), (City: 'Cam Pha'; Country: 'Vietnam'; Population: 209086), (City: 'Cam Ranh'; Country: 'Vietnam'; Population: 114041), (City: 'Camag黣y'; Country: 'Cuba'; Population: 298726), (City: 'Camaragibe'; Country: 'Brazil'; Population: 118968), (City: 'Cama鏰ri'; Country: 'Brazil'; Population: 149146), (City: 'Cambridge'; Country: 'United Kingdom'; Population: 121000), (City: 'Cambridge'; Country: 'Canada'; Population: 109186), (City: 'Cambridge'; Country: 'United States'; Population: 101355), (City: 'Camet?'; Country: 'Brazil'; Population: 92779), (City: 'Campeche'; Country: 'Mexico'; Population: 216735), (City: 'Campina Grande'; Country: 'Brazil'; Population: 352497), (City: 'Campinas'; Country: 'Brazil'; Population: 950043), (City: 'Campo Grande'; Country: 'Brazil'; Population: 649593), (City: 'Campo Largo'; Country: 'Brazil'; Population: 91203), (City: 'Campos dos Goytacazes'; Country: 'Brazil'; Population: 398418), (City: 'Can Tho'; Country: 'Vietnam'; Population: 215587), (City: 'Canberra'; Country: 'Australia'; Population: 322723), (City: 'Candelaria'; Country: 'Philippines'; Population: 92429), (City: 'Cangzhou'; Country: 'China'; Population: 242708), (City: 'Canoas'; Country: 'Brazil'; Population: 294125), (City: 'Capas'; Country: 'Philippines'; Population: 95219), (City: 'Cape Breton'; Country: 'Canada'; Population: 114733), (City: 'Cape Coral'; Country: 'United States'; Population: 102286), (City: 'Cape Town'; Country: 'South Africa'; Population: 2352121), (City: 'Caracas'; Country: 'Venezuela'; Population: 1975294), (City: 'Carapicu韇a'; Country: 'Brazil'; Population: 357552), (City: 'Cardiff'; Country: 'United Kingdom'; Population: 321000), (City: 'Cariacica'; Country: 'Brazil'; Population: 319033), (City: 'Carmen'; Country: 'Mexico'; Population: 171367), (City: 'Carolina'; Country: 'Puerto Rico'; Population: 186076), (City: 'Carrefour'; Country: 'Haiti'; Population: 290204), (City: 'Carrollton'; Country: 'United States'; Population: 109576), (City: 'Carson'; Country: 'United States'; Population: 89089), (City: 'Cartagena'; Country: 'Spain'; Population: 177709), (City: 'Cartagena'; Country: 'Colombia'; Population: 805757), (City: 'Cartago'; Country: 'Colombia'; Population: 125884), (City: 'Caruaru'; Country: 'Brazil'; Population: 244247), (City: 'Cary'; Country: 'United States'; Population: 91213), (City: 'Car鷓ano'; Country: 'Venezuela'; Population: 119639), (City: 'Casablanca'; Country: 'Morocco'; Population: 2940623), (City: 'Cascavel'; Country: 'Brazil'; Population: 237510), (City: 'Castanhal'; Country: 'Brazil'; Population: 127634), (City: 'Castell髇 de la Plana [Castell'; Country: 'Spain'; Population: 139712), (City: 'Castilla'; Country: 'Peru'; Population: 90642), (City: 'Castries'; Country: 'Saint Lucia'; Population: 2301), (City: 'Catanduva'; Country: 'Brazil'; Population: 107761), (City: 'Catania'; Country: 'Italy'; Population: 337862), (City: 'Catanzaro'; Country: 'Italy'; Population: 96700), (City: 'Catia La Mar'; Country: 'Venezuela'; Population: 117012), (City: 'Cauayan'; Country: 'Philippines'; Population: 103952), (City: 'Caucaia'; Country: 'Brazil'; Population: 238738), (City: 'Cavite'; Country: 'Philippines'; Population: 99367), (City: 'Caxias'; Country: 'Brazil'; Population: 133980), (City: 'Caxias do Sul'; Country: 'Brazil'; Population: 349581), (City: 'Cayenne'; Country: 'French Guiana'; Population: 50699), (City: 'Cebu'; Country: 'Philippines'; Population: 718821), (City: 'Cedar Rapids'; Country: 'United States'; Population: 120758), (City: 'Celaya'; Country: 'Mexico'; Population: 382140), (City: 'Central Coast'; Country: 'Australia'; Population: 227657), (City: 'Centro (Villahermosa)'; Country: 'Mexico'; Population: 519873), (City: 'Cesena'; Country: 'Italy'; Population: 89852), (City: 'Cesk?Budejovice'; Country: 'Czech Republic'; Population: 98186), (City: 'Ceyhan'; Country: 'Turkey'; Population: 102412), (City: 'Chaguanas'; Country: 'Trinidad and Tobago'; Population: 56601), (City: 'Chalco'; Country: 'Mexico'; Population: 222201), (City: 'Champdani'; Country: 'India'; Population: 98818), (City: 'Chandannagar'; Country: 'India'; Population: 120378), (City: 'Chandigarh'; Country: 'India'; Population: 504094), (City: 'Chandler'; Country: 'United States'; Population: 176581), (City: 'Chandrapur'; Country: 'India'; Population: 226105), (City: 'Chang-won'; Country: 'South Korea'; Population: 481694), (City: 'Changchun'; Country: 'China'; Population: 2812000), (City: 'Changde'; Country: 'China'; Population: 301276), (City: 'Changhwa'; Country: 'Taiwan'; Population: 227715), (City: 'Changji'; Country: 'China'; Population: 132260), (City: 'Changsha'; Country: 'China'; Population: 1809800), (City: 'Changshu'; Country: 'China'; Population: 181805), (City: 'Changzhi'; Country: 'China'; Population: 317144), (City: 'Changzhou'; Country: 'China'; Population: 530000), (City: 'Chaohu'; Country: 'China'; Population: 123676), (City: 'Chaoyang'; Country: 'China'; Population: 222394), (City: 'Chaozhou'; Country: 'China'; Population: 313469), (City: 'Chapec?'; Country: 'Brazil'; Population: 144158), (City: 'Chapra'; Country: 'India'; Population: 136877), (City: 'Charleroi'; Country: 'Belgium'; Population: 200827), (City: 'Charleston'; Country: 'United States'; Population: 89063), (City: 'Charlotte'; Country: 'United States'; Population: 540828), (City: 'Charlotte Amalie'; Country: 'Virgin Islands, U.S.'; Population: 13000), (City: 'Chatsworth'; Country: 'South Africa'; Population: 189885), (City: 'Chattanooga'; Country: 'United States'; Population: 155554), (City: 'Chechon'; Country: 'South Korea'; Population: 137070), (City: 'Cheju'; Country: 'South Korea'; Population: 258511), (City: 'Chelmsford'; Country: 'United Kingdom'; Population: 97451), (City: 'Cheltenham'; Country: 'United Kingdom'; Population: 106000), (City: 'Chemnitz'; Country: 'Germany'; Population: 263222), (City: 'Chengde'; Country: 'China'; Population: 246799), (City: 'Chengdu'; Country: 'China'; Population: 3361500), (City: 'Chennai (Madras)'; Country: 'India'; Population: 3841396), (City: 'Chenzhou'; Country: 'China'; Population: 169400), (City: 'Chesapeake'; Country: 'United States'; Population: 199184), (City: 'Chhindwara'; Country: 'India'; Population: 93731), (City: 'Chiang Mai'; Country: 'Thailand'; Population: 171100), (City: 'Chiayi'; Country: 'Taiwan'; Population: 265109), (City: 'Chiba'; Country: 'Japan'; Population: 863930), (City: 'Chicago'; Country: 'United States'; Population: 2896016), (City: 'Chiclayo'; Country: 'Peru'; Population: 517000), (City: 'Chifeng'; Country: 'China'; Population: 350077), (City: 'Chigasaki'; Country: 'Japan'; Population: 216015), (City: 'Chihuahua'; Country: 'Mexico'; Population: 670208), (City: 'Chilapa de Alvarez'; Country: 'Mexico'; Population: 102716), (City: 'Chill醤'; Country: 'Chile'; Population: 178182), (City: 'Chilpancingo de los Bravo'; Country: 'Mexico'; Population: 192509), (City: 'Chimalhuac醤'; Country: 'Mexico'; Population: 490245), (City: 'Chimbote'; Country: 'Peru'; Population: 336000), (City: 'Chimoio'; Country: 'Mozambique'; Population: 171056), (City: 'Chinandega'; Country: 'Nicaragua'; Population: 97387), (City: 'Chincha Alta'; Country: 'Peru'; Population: 110016), (City: 'Chingola'; Country: 'Zambia'; Population: 142400), (City: 'Chinhae'; Country: 'South Korea'; Population: 125997), (City: 'Chiniot'; Country: 'Pakistan'; Population: 169300), (City: 'Chinju'; Country: 'South Korea'; Population: 329886), (City: 'Chishtian Mandi'; Country: 'Pakistan'; Population: 101700), (City: 'Chisinau'; Country: 'Moldova'; Population: 719900), (City: 'Chittagong'; Country: 'Bangladesh'; Population: 1392860), (City: 'Chittoor'; Country: 'India'; Population: 133462), (City: 'Chitungwiza'; Country: 'Zimbabwe'; Population: 274912), (City: 'Chofu'; Country: 'Japan'; Population: 201585), (City: 'Chonan'; Country: 'South Korea'; Population: 330259), (City: 'Chong-up'; Country: 'South Korea'; Population: 139111), (City: 'Chongjin'; Country: 'North Korea'; Population: 582480), (City: 'Chongju'; Country: 'South Korea'; Population: 531376), (City: 'Chongqing'; Country: 'China'; Population: 6351600), (City: 'Chonju'; Country: 'South Korea'; Population: 563153), (City: 'Chorz體'; Country: 'Poland'; Population: 121708), (City: 'Christchurch'; Country: 'New Zealand'; Population: 324200), (City: 'Chula Vista'; Country: 'United States'; Population: 173556), (City: 'Chunchon'; Country: 'South Korea'; Population: 234528), (City: 'Chungho'; Country: 'Taiwan'; Population: 392176), (City: 'Chungju'; Country: 'South Korea'; Population: 205206), (City: 'Chungli'; Country: 'Taiwan'; Population: 318649), (City: 'Chuzhou'; Country: 'China'; Population: 125341), (City: 'Ch鋜jew'; Country: 'Turkmenistan'; Population: 189200), (City: 'Cianjur'; Country: 'Indonesia'; Population: 114300), (City: 'Cibinong'; Country: 'Indonesia'; Population: 101300), (City: 'Ciego de 羦ila'; Country: 'Cuba'; Population: 98505), (City: 'Cienfuegos'; Country: 'Cuba'; Population: 132770), (City: 'Cilacap'; Country: 'Indonesia'; Population: 206900), (City: 'Cilegon'; Country: 'Indonesia'; Population: 117000), (City: 'Cimahi'; Country: 'Indonesia'; Population: 344600), (City: 'Cimanggis'; Country: 'Indonesia'; Population: 205100), (City: 'Cincinnati'; Country: 'United States'; Population: 331285), (City: 'Ciomas'; Country: 'Indonesia'; Population: 187400), (City: 'Ciparay'; Country: 'Indonesia'; Population: 111500), (City: 'Ciputat'; Country: 'Indonesia'; Population: 270800), (City: 'Circik'; Country: 'Uzbekistan'; Population: 146400), (City: 'Cirebon'; Country: 'Indonesia'; Population: 254406), (City: 'Citeureup'; Country: 'Indonesia'; Population: 105100), (City: 'Citrus Heights'; Country: 'United States'; Population: 103455), (City: 'Citt?del Vaticano'; Country: 'Holy See (Vatican City State)'; Population: 455), (City: 'Ciudad Bol韛ar'; Country: 'Venezuela'; Population: 301107), (City: 'Ciudad Guayana'; Country: 'Venezuela'; Population: 663713), (City: 'Ciudad Losada'; Country: 'Venezuela'; Population: 134501), (City: 'Ciudad Madero'; Country: 'Mexico'; Population: 182012), (City: 'Ciudad Ojeda'; Country: 'Venezuela'; Population: 99354), (City: 'Ciudad Valles'; Country: 'Mexico'; Population: 146411), (City: 'Ciudad de Guatemala'; Country: 'Guatemala'; Population: 823301), (City: 'Ciudad de M閤ico'; Country: 'Mexico'; Population: 8591309), (City: 'Ciudad de Panam'; Country: 'Panama'; Population: 471373), (City: 'Ciudad del Este'; Country: 'Paraguay'; Population: 133881), (City: 'Cixi'; Country: 'China'; Population: 107329), (City: 'Cizah'; Country: 'Uzbekistan'; Population: 124800), (City: 'Clarksville'; Country: 'United States'; Population: 108787), (City: 'Clearwater'; Country: 'United States'; Population: 99936), (City: 'Clermont-Ferrand'; Country: 'France'; Population: 137140), (City: 'Cleveland'; Country: 'United States'; Population: 478403), (City: 'Cluj-Napoca'; Country: 'Romania'; Population: 332498), (City: 'Coacalco de Berrioz醔al'; Country: 'Mexico'; Population: 252270), (City: 'Coatzacoalcos'; Country: 'Mexico'; Population: 267037), (City: 'Cochabamba'; Country: 'Bolivia'; Population: 482800), (City: 'Cochin (Kochi)'; Country: 'India'; Population: 564589), (City: 'Cockburn Town'; Country: 'Turks and Caicos Islands'; Population: 4800), (City: 'Cod?'; Country: 'Brazil'; Population: 103153), (City: 'Coimbatore'; Country: 'India'; Population: 816321), (City: 'Colatina'; Country: 'Brazil'; Population: 107354), (City: 'Colchester'; Country: 'United Kingdom'; Population: 96063), (City: 'Colima'; Country: 'Mexico'; Population: 129454), (City: 'Colombo'; Country: 'Brazil'; Population: 177764), (City: 'Colombo'; Country: 'Sri Lanka'; Population: 645000), (City: 'Colorado Springs'; Country: 'United States'; Population: 360890), (City: 'Columbia'; Country: 'United States'; Population: 116278), (City: 'Columbus'; Country: 'United States'; Population: 711470), (City: 'Columbus'; Country: 'United States'; Population: 186291), (City: 'Comalcalco'; Country: 'Mexico'; Population: 164640), (City: 'Comilla'; Country: 'Bangladesh'; Population: 135313), (City: 'Comit醤 de Dom韓guez'; Country: 'Mexico'; Population: 104986), (City: 'Comodoro Rivadavia'; Country: 'Argentina'; Population: 124104), (City: 'Compton'; Country: 'United States'; Population: 92864), (City: 'Conakry'; Country: 'Guinea'; Population: 1090610), (City: 'Concepcion'; Country: 'Philippines'; Population: 115171), (City: 'Concepci髇'; Country: 'Chile'; Population: 217664), (City: 'Concord'; Country: 'United States'; Population: 121780), (City: 'Concordia'; Country: 'Argentina'; Population: 116485), (City: 'Conselheiro Lafaiete'; Country: 'Brazil'; Population: 97507), (City: 'Constanta'; Country: 'Romania'; Population: 342264), (City: 'Constantine'; Country: 'Algeria'; Population: 443727), (City: 'Contagem'; Country: 'Brazil'; Population: 520801), (City: 'Copiap'; Country: 'Chile'; Population: 120128), (City: 'Coquimbo'; Country: 'Chile'; Population: 143353), (City: 'Coquitlam'; Country: 'Canada'; Population: 101820), (City: 'Coral Springs'; Country: 'United States'; Population: 117549), (City: 'Cork'; Country: 'Ireland'; Population: 127187), (City: 'Corona'; Country: 'United States'; Population: 124966), (City: 'Coronel'; Country: 'Chile'; Population: 93061), (City: 'Coronel Fabriciano'; Country: 'Brazil'; Population: 95933), (City: 'Corpus Christi'; Country: 'United States'; Population: 277454), (City: 'Corrientes'; Country: 'Argentina'; Population: 258103), (City: 'Corumb?'; Country: 'Brazil'; Population: 90111), (City: 'Cosoleacaque'; Country: 'Mexico'; Population: 97199), (City: 'Costa Mesa'; Country: 'United States'; Population: 108724), (City: 'Cotabato'; Country: 'Philippines'; Population: 163849), (City: 'Cotia'; Country: 'Brazil'; Population: 140042), (City: 'Cotonou'; Country: 'Benin'; Population: 536827), (City: 'Cottbus'; Country: 'Germany'; Population: 110894), (City: 'Coventry'; Country: 'United Kingdom'; Population: 304000), (City: 'Co韒bra'; Country: 'Portugal'; Population: 96100), (City: 'Craiova'; Country: 'Romania'; Population: 313530), (City: 'Crato'; Country: 'Brazil'; Population: 98965), (City: 'Crawley'; Country: 'United Kingdom'; Population: 97000), (City: 'Crici鷐a'; Country: 'Brazil'; Population: 167661), (City: 'Cuauht閙oc'; Country: 'Mexico'; Population: 124279), (City: 'Cuautitl醤 Izcalli'; Country: 'Mexico'; Population: 452976), (City: 'Cuautla'; Country: 'Mexico'; Population: 153132), (City: 'Cubat鉶'; Country: 'Brazil'; Population: 102372), (City: 'Cuddalore'; Country: 'India'; Population: 153086), (City: 'Cuddapah'; Country: 'India'; Population: 121463), (City: 'Cuenca'; Country: 'Ecuador'; Population: 270353), (City: 'Cuernavaca'; Country: 'Mexico'; Population: 337966), (City: 'Cuiab'; Country: 'Brazil'; Population: 453813), (City: 'Culiac醤'; Country: 'Mexico'; Population: 744859), (City: 'Cuman'; Country: 'Venezuela'; Population: 293105), (City: 'Cunduac醤'; Country: 'Mexico'; Population: 104164), (City: 'Curic'; Country: 'Chile'; Population: 115766), (City: 'Curitiba'; Country: 'Brazil'; Population: 1584232), (City: 'Cusco'; Country: 'Peru'; Population: 291000), (City: 'Czestochowa'; Country: 'Poland'; Population: 257812), (City: 'C醖iz'; Country: 'Spain'; Population: 142449), (City: 'C醨denas'; Country: 'Mexico'; Population: 216903), (City: 'C髍doba'; Country: 'Argentina'; Population: 1157507), (City: 'C髍doba'; Country: 'Spain'; Population: 311708), (City: 'C髍doba'; Country: 'Mexico'; Population: 176952), (City: 'C鷆uta'; Country: 'Colombia'; Population: 606932), (City: 'Da Lat'; Country: 'Vietnam'; Population: 106409), (City: 'Da Nang'; Country: 'Vietnam'; Population: 382674), (City: 'Dabgram'; Country: 'India'; Population: 147217), (City: 'Dabrowa G髍nicza'; Country: 'Poland'; Population: 131037), (City: 'Dadu'; Country: 'Pakistan'; Population: 98600), (City: 'Dagupan'; Country: 'Philippines'; Population: 130328), (City: 'Daito'; Country: 'Japan'; Population: 130594), (City: 'Dakar'; Country: 'Senegal'; Population: 785071), (City: 'Dalap-Uliga-Darrit'; Country: 'Marshall Islands'; Population: 28000), (City: 'Dali'; Country: 'China'; Population: 136554), (City: 'Dalian'; Country: 'China'; Population: 2697000), (City: 'Dallas'; Country: 'United States'; Population: 1188580), (City: 'Daloa'; Country: 'C魌e d扞voire'; Population: 121842), (City: 'Daly City'; Country: 'United States'; Population: 103621), (City: 'Damanhur'; Country: 'Egypt'; Population: 212203), (City: 'Damascus'; Country: 'Syria'; Population: 1347000), (City: 'Damoh'; Country: 'India'; Population: 95661), (City: 'Danao'; Country: 'Philippines'; Population: 98781), (City: 'Dandong'; Country: 'China'; Population: 520000), (City: 'Danjiangkou'; Country: 'China'; Population: 103211), (City: 'Danyang'; Country: 'China'; Population: 169603), (City: 'Daqing'; Country: 'China'; Population: 660000), (City: 'Dar es Salaam'; Country: 'Tanzania'; Population: 1747000), (City: 'Daraga (Locsin)'; Country: 'Philippines'; Population: 101031), (City: 'Darbhanga'; Country: 'India'; Population: 218391), (City: 'Darmstadt'; Country: 'Germany'; Population: 137776), (City: 'Dashhowuz'; Country: 'Turkmenistan'; Population: 141800), (City: 'Daska'; Country: 'Pakistan'; Population: 101500), (City: 'Dasmari馻s'; Country: 'Philippines'; Population: 379520), (City: 'Datong'; Country: 'China'; Population: 800000), (City: 'Daugavpils'; Country: 'Latvia'; Population: 114829), (City: 'Davangere'; Country: 'India'; Population: 266082), (City: 'Davao'; Country: 'Philippines'; Population: 1147116), (City: 'Davenport'; Country: 'United States'; Population: 98256), (City: 'Daxian'; Country: 'China'; Population: 188101), (City: 'Dayr al-Zawr'; Country: 'Syria'; Population: 140459), (City: 'Dayton'; Country: 'United States'; Population: 166179), (City: 'Da碼n'; Country: 'China'; Population: 138963), (City: 'Deba Habe'; Country: 'Nigeria'; Population: 138600), (City: 'Debrecen'; Country: 'Hungary'; Population: 203648), (City: 'Dehiwala'; Country: 'Sri Lanka'; Population: 203000), (City: 'Dehra Dun'; Country: 'India'; Population: 270159), (City: 'Dehri'; Country: 'India'; Population: 94526), (City: 'Delft'; Country: 'Netherlands'; Population: 95268), (City: 'Delhi'; Country: 'India'; Population: 7206704), (City: 'Delhi Cantonment'; Country: 'India'; Population: 94326), (City: 'Delicias'; Country: 'Mexico'; Population: 116132), (City: 'Delmas'; Country: 'Haiti'; Population: 240429), (City: 'Delta'; Country: 'Canada'; Population: 95411), (City: 'Denizli'; Country: 'Turkey'; Population: 253848), (City: 'Denpasar'; Country: 'Indonesia'; Population: 435000), (City: 'Denver'; Country: 'United States'; Population: 554636), (City: 'Depok'; Country: 'Indonesia'; Population: 365200), (City: 'Depok'; Country: 'Indonesia'; Population: 106800), (City: 'Dera Ghazi Khan'; Country: 'Pakistan'; Population: 188100), (City: 'Dera Ismail Khan'; Country: 'Pakistan'; Population: 90400), (City: 'Derbent'; Country: 'Russian Federation'; Population: 92300), (City: 'Derby'; Country: 'United Kingdom'; Population: 236000), (City: 'Des Moines'; Country: 'United States'; Population: 198682), (City: 'Dese'; Country: 'Ethiopia'; Population: 97314), (City: 'Detroit'; Country: 'United States'; Population: 951270), (City: 'Dewas'; Country: 'India'; Population: 164364), (City: 'Deyang'; Country: 'China'; Population: 182488), (City: 'Dezful'; Country: 'Iran'; Population: 202639), (City: 'Dezhou'; Country: 'China'; Population: 195485), (City: 'Dhaka'; Country: 'Bangladesh'; Population: 3612850), (City: 'Dhanbad'; Country: 'India'; Population: 151789), (City: 'Dhule (Dhulia)'; Country: 'India'; Population: 278317), (City: 'Diadema'; Country: 'Brazil'; Population: 335078), (City: 'Dibrugarh'; Country: 'India'; Population: 120127), (City: 'Digos'; Country: 'Philippines'; Population: 125171), (City: 'Dijon'; Country: 'France'; Population: 149867), (City: 'Dili'; Country: 'East Timor'; Population: 47900), (City: 'Dimitrovgrad'; Country: 'Russian Federation'; Population: 137000), (City: 'Dinajpur'; Country: 'Bangladesh'; Population: 127815), (City: 'Dindigul'; Country: 'India'; Population: 182477), (City: 'Diourbel'; Country: 'Senegal'; Population: 99400), (City: 'Dipolog'; Country: 'Philippines'; Population: 99862), (City: 'Dire Dawa'; Country: 'Ethiopia'; Population: 164851), (City: 'Disuq'; Country: 'Egypt'; Population: 91300), (City: 'Divin髉olis'; Country: 'Brazil'; Population: 185047), (City: 'Diyarbakir'; Country: 'Turkey'; Population: 479884), (City: 'Djibouti'; Country: 'Djibouti'; Population: 383000), (City: 'Djougou'; Country: 'Benin'; Population: 134099), (City: 'Dniprodzerzynsk'; Country: 'Ukraine'; Population: 270000), (City: 'Dnipropetrovsk'; Country: 'Ukraine'; Population: 1103000), (City: 'Dobric'; Country: 'Bulgaria'; Population: 100399), (City: 'Dodoma'; Country: 'Tanzania'; Population: 189000), (City: 'Doha'; Country: 'Qatar'; Population: 355000), (City: 'Dolores Hidalgo'; Country: 'Mexico'; Population: 128675), (City: 'Donetsk'; Country: 'Ukraine'; Population: 1050000), (City: 'Dongtai'; Country: 'China'; Population: 192247), (City: 'Dongwan'; Country: 'China'; Population: 308669), (City: 'Dongying'; Country: 'China'; Population: 281728), (City: 'Donostia-San Sebasti醤'; Country: 'Spain'; Population: 179208), (City: 'Dordrecht'; Country: 'Netherlands'; Population: 119811), (City: 'Dortmund'; Country: 'Germany'; Population: 590213), (City: 'Dos Hermanas'; Country: 'Spain'; Population: 94591), (City: 'Dos Quebradas'; Country: 'Colombia'; Population: 159363), (City: 'Douala'; Country: 'Cameroon'; Population: 1448300), (City: 'Douglas'; Country: 'United Kingdom'; Population: 23487), (City: 'Dourados'; Country: 'Brazil'; Population: 164716), (City: 'Downey'; Country: 'United States'; Population: 107323), (City: 'Dresden'; Country: 'Germany'; Population: 476668), (City: 'Drobeta-Turnu Severin'; Country: 'Romania'; Population: 117865), (City: 'Dubai'; Country: 'United Arab Emirates'; Population: 669181), (City: 'Dublin'; Country: 'Ireland'; Population: 481854), (City: 'Dudley'; Country: 'United Kingdom'; Population: 192171), (City: 'Duisburg'; Country: 'Germany'; Population: 519793), (City: 'Dujiangyan'; Country: 'China'; Population: 123357), (City: 'Duma'; Country: 'Syria'; Population: 131158), (City: 'Dumaguete'; Country: 'Philippines'; Population: 102265), (City: 'Dundee'; Country: 'United Kingdom'; Population: 146690), (City: 'Dunedin'; Country: 'New Zealand'; Population: 119600), (City: 'Dunhua'; Country: 'China'; Population: 235100), (City: 'Duque de Caxias'; Country: 'Brazil'; Population: 746758), (City: 'Duran [Eloy Alfaro]'; Country: 'Ecuador'; Population: 152514), (City: 'Durango'; Country: 'Mexico'; Population: 490524), (City: 'Durban'; Country: 'South Africa'; Population: 566120), (City: 'Durg'; Country: 'India'; Population: 150645), (City: 'Durgapur'; Country: 'India'; Population: 425836), (City: 'Durham'; Country: 'United States'; Population: 187035), (City: 'Dushanbe'; Country: 'Tajikistan'; Population: 524000), (City: 'Duyun'; Country: 'China'; Population: 132971), (City: 'Dzerzinsk'; Country: 'Russian Federation'; Population: 277100), (City: 'D黵en'; Country: 'Germany'; Population: 91092), (City: 'D黶seldorf'; Country: 'Germany'; Population: 568855), (City: 'East London'; Country: 'South Africa'; Population: 221047), (City: 'East Los Angeles'; Country: 'United States'; Population: 126379), (City: 'East York'; Country: 'Canada'; Population: 114034), (City: 'Eastbourne'; Country: 'United Kingdom'; Population: 90000), (City: 'Ebetsu'; Country: 'Japan'; Population: 118805), (City: 'Ebina'; Country: 'Japan'; Population: 115571), (City: 'Ecatepec de Morelos'; Country: 'Mexico'; Population: 1620303), (City: 'Ech-Chleff (el-Asnam)'; Country: 'Algeria'; Population: 96794), (City: 'Ede'; Country: 'Netherlands'; Population: 101574), (City: 'Ede'; Country: 'Nigeria'; Population: 307100), (City: 'Edinburgh'; Country: 'United Kingdom'; Population: 450180), (City: 'Edirne'; Country: 'Turkey'; Population: 123383), (City: 'Edmonton'; Country: 'Canada'; Population: 616306), (City: 'Effon-Alaiye'; Country: 'Nigeria'; Population: 153100), (City: 'Eindhoven'; Country: 'Netherlands'; Population: 201843), (City: 'Ejigbo'; Country: 'Nigeria'; Population: 105900), (City: 'Ekibastuz'; Country: 'Kazakstan'; Population: 127200), (City: 'El Alto'; Country: 'Bolivia'; Population: 534466), (City: 'El Araich'; Country: 'Morocco'; Population: 90400), (City: 'El Cajon'; Country: 'United States'; Population: 94578), (City: 'El Fuerte'; Country: 'Mexico'; Population: 89556), (City: 'El Jadida'; Country: 'Morocco'; Population: 119083), (City: 'El Lim髇'; Country: 'Venezuela'; Population: 90000), (City: 'El Mante'; Country: 'Mexico'; Population: 112453), (City: 'El Monte'; Country: 'United States'; Population: 115965), (City: 'El Paso'; Country: 'United States'; Population: 563662), (City: 'El Tigre'; Country: 'Venezuela'; Population: 116256), (City: 'El-Aai鷑'; Country: 'Western Sahara'; Population: 169000), (City: 'Elblag'; Country: 'Poland'; Population: 129782), (City: 'Elche [Elx]'; Country: 'Spain'; Population: 193174), (City: 'Eldoret'; Country: 'Kenya'; Population: 111882), (City: 'Elektrostal'; Country: 'Russian Federation'; Population: 147000), (City: 'Elgin'; Country: 'United States'; Population: 89408), (City: 'Elista'; Country: 'Russian Federation'; Population: 103300), (City: 'Elizabeth'; Country: 'United States'; Population: 120568), (City: 'Eluru'; Country: 'India'; Population: 212866), (City: 'El鈠ig'; Country: 'Turkey'; Population: 228815), (City: 'Embu'; Country: 'Brazil'; Population: 222223), (City: 'Emeishan'; Country: 'China'; Population: 94000), (City: 'Emmen'; Country: 'Netherlands'; Population: 105853), (City: 'Engels'; Country: 'Russian Federation'; Population: 189000), (City: 'Enschede'; Country: 'Netherlands'; Population: 149544), (City: 'Ensenada'; Country: 'Mexico'; Population: 369573), (City: 'Enshi'; Country: 'China'; Population: 93056), (City: 'Enugu'; Country: 'Nigeria'; Population: 316100), (City: 'Envigado'; Country: 'Colombia'; Population: 135848), (City: 'Epe'; Country: 'Nigeria'; Population: 101000), (City: 'Erfurt'; Country: 'Germany'; Population: 201267), (City: 'Erie'; Country: 'United States'; Population: 103717), (City: 'Erlangen'; Country: 'Germany'; Population: 100750), (City: 'Erode'; Country: 'India'; Population: 159232), (City: 'Erzincan'; Country: 'Turkey'; Population: 102304), (City: 'Erzurum'; Country: 'Turkey'; Population: 246535), (City: 'Escobar'; Country: 'Argentina'; Population: 116675), (City: 'Escondido'; Country: 'United States'; Population: 133559), (City: 'Esfahan'; Country: 'Iran'; Population: 1266072), (City: 'Eskisehir'; Country: 'Turkey'; Population: 470781), (City: 'Eslamshahr'; Country: 'Iran'; Population: 265450), (City: 'Esmeraldas'; Country: 'Ecuador'; Population: 123045), (City: 'Espoo'; Country: 'Finland'; Population: 213271), (City: 'Essen'; Country: 'Germany'; Population: 599515), (City: 'Esslingen am Neckar'; Country: 'Germany'; Population: 89667), (City: 'Esteban Echeverr韆'; Country: 'Argentina'; Population: 235760), (City: 'Etawah'; Country: 'India'; Population: 124072), (City: 'Etobicoke'; Country: 'Canada'; Population: 348845), (City: 'Ettadhamen'; Country: 'Tunisia'; Population: 178600), (City: 'Eugene'; Country: 'United States'; Population: 137893), (City: 'Eun醦olis'; Country: 'Brazil'; Population: 96610), (City: 'Evansville'; Country: 'United States'; Population: 121582), (City: 'Exeter'; Country: 'United Kingdom'; Population: 111000), (City: 'Ezeiza'; Country: 'Argentina'; Population: 99578), (City: 'Ezhou'; Country: 'China'; Population: 190123), (City: 'Faaa'; Country: 'French Polynesia'; Population: 25888), (City: 'Fagatogo'; Country: 'American Samoa'; Population: 2323), (City: 'Fairfield'; Country: 'United States'; Population: 92256), (City: 'Faisalabad'; Country: 'Pakistan'; Population: 1977246), (City: 'Faizabad'; Country: 'India'; Population: 124437), (City: 'Fakaofo'; Country: 'Tokelau'; Population: 300), (City: 'Fall River'; Country: 'United States'; Population: 90555), (City: 'Fargona'; Country: 'Uzbekistan'; Population: 180500), (City: 'Faridabad'; Country: 'India'; Population: 703592), (City: 'Farrukhabad-cum-Fatehgarh'; Country: 'India'; Population: 194567), (City: 'Fatehpur'; Country: 'India'; Population: 117675), (City: 'Fayetteville'; Country: 'United States'; Population: 121015), (City: 'Feira de Santana'; Country: 'Brazil'; Population: 479992), (City: 'Fengcheng'; Country: 'China'; Population: 193784), (City: 'Fengshan'; Country: 'Taiwan'; Population: 318562), (City: 'Fengyuan'; Country: 'Taiwan'; Population: 161032), (City: 'Fernando de la Mora'; Country: 'Paraguay'; Population: 95287), (City: 'Ferrara'; Country: 'Italy'; Population: 132127), (City: 'Ferraz de Vasconcelos'; Country: 'Brazil'; Population: 139283), (City: 'Fianarantsoa'; Country: 'Madagascar'; Population: 99005), (City: 'Firenze'; Country: 'Italy'; Population: 376662), (City: 'Firozabad'; Country: 'India'; Population: 215128), (City: 'Flint'; Country: 'United States'; Population: 124943), (City: 'Florencia'; Country: 'Colombia'; Population: 108574), (City: 'Florencio Varela'; Country: 'Argentina'; Population: 315432), (City: 'Florian髉olis'; Country: 'Brazil'; Population: 281928), (City: 'Floridablanca'; Country: 'Colombia'; Population: 221913), (City: 'Flying Fish Cove'; Country: 'Christmas Island'; Population: 700), (City: 'Focsani'; Country: 'Romania'; Population: 98979), (City: 'Foggia'; Country: 'Italy'; Population: 154891), (City: 'Fontana'; Country: 'United States'; Population: 128929), (City: 'Forl'; Country: 'Italy'; Population: 107475), (City: 'Formosa'; Country: 'Argentina'; Population: 147636), (City: 'Fort Collins'; Country: 'United States'; Population: 118652), (City: 'Fort Lauderdale'; Country: 'United States'; Population: 152397), (City: 'Fort Wayne'; Country: 'United States'; Population: 205727), (City: 'Fort Worth'; Country: 'United States'; Population: 534694), (City: 'Fort-de-France'; Country: 'Martinique'; Population: 94050), (City: 'Fortaleza'; Country: 'Brazil'; Population: 2097757), (City: 'Foshan'; Country: 'China'; Population: 303160), (City: 'Foz do Igua鐄'; Country: 'Brazil'; Population: 259425), (City: 'Franca'; Country: 'Brazil'; Population: 290139), (City: 'Francisco Morato'; Country: 'Brazil'; Population: 121197), (City: 'Francistown'; Country: 'Botswana'; Population: 101805), (City: 'Franco da Rocha'; Country: 'Brazil'; Population: 108964), (City: 'Frankfurt am Main'; Country: 'Germany'; Population: 643821), (City: 'Frederiksberg'; Country: 'Denmark'; Population: 90327), (City: 'Freetown'; Country: 'Sierra Leone'; Population: 850000), (City: 'Freiburg im Breisgau'; Country: 'Germany'; Population: 202455), (City: 'Fremont'; Country: 'United States'; Population: 203413), (City: 'Fresnillo'; Country: 'Mexico'; Population: 182744), (City: 'Fresno'; Country: 'United States'; Population: 427652), (City: 'Fuchu'; Country: 'Japan'; Population: 220576), (City: 'Fuenlabrada'; Country: 'Spain'; Population: 171173), (City: 'Fuji'; Country: 'Japan'; Population: 231527), (City: 'Fujieda'; Country: 'Japan'; Population: 126897), (City: 'Fujimi'; Country: 'Japan'; Population: 96972), (City: 'Fujin'; Country: 'China'; Population: 103104), (City: 'Fujinomiya'; Country: 'Japan'; Population: 119714), (City: 'Fujisawa'; Country: 'Japan'; Population: 372840), (City: 'Fukaya'; Country: 'Japan'; Population: 102156), (City: 'Fukui'; Country: 'Japan'; Population: 254818), (City: 'Fukuoka'; Country: 'Japan'; Population: 1308379), (City: 'Fukushima'; Country: 'Japan'; Population: 287525), (City: 'Fukuyama'; Country: 'Japan'; Population: 376921), (City: 'Fuling'; Country: 'China'; Population: 173878), (City: 'Fullerton'; Country: 'United States'; Population: 126003), (City: 'Funabashi'; Country: 'Japan'; Population: 545299), (City: 'Funafuti'; Country: 'Tuvalu'; Population: 4600), (City: 'Fuqing'; Country: 'China'; Population: 99193), (City: 'Fushun'; Country: 'China'; Population: 1200000), (City: 'Fuxin'; Country: 'China'; Population: 640000), (City: 'Fuyang'; Country: 'China'; Population: 179572), (City: 'Fuyu'; Country: 'China'; Population: 192981), (City: 'Fuzhou'; Country: 'China'; Population: 1593800), (City: 'Fu碼n'; Country: 'China'; Population: 105265), (City: 'F鑣'; Country: 'Morocco'; Population: 541162), (City: 'F黵th'; Country: 'Germany'; Population: 109771), (City: 'Gaborone'; Country: 'Botswana'; Population: 213017), (City: 'Gab鑣'; Country: 'Tunisia'; Population: 106600), (City: 'Gadag Betigeri'; Country: 'India'; Population: 134051), (City: 'Gainesville'; Country: 'United States'; Population: 92291), (City: 'Galati'; Country: 'Romania'; Population: 330276), (City: 'Gandhidham'; Country: 'India'; Population: 104585), (City: 'Gandhinagar'; Country: 'India'; Population: 123359), (City: 'Ganganagar'; Country: 'India'; Population: 161482), (City: 'Ganzhou'; Country: 'China'; Population: 220129), (City: 'Garanhuns'; Country: 'Brazil'; Population: 114603), (City: 'Garapan'; Country: 'Northern Mariana Islands'; Population: 9200), (City: 'Garden Grove'; Country: 'United States'; Population: 165196), (City: 'Garland'; Country: 'United States'; Population: 215768), (City: 'Garoua'; Country: 'Cameroon'; Population: 177000), (City: 'Garut'; Country: 'Indonesia'; Population: 95800), (City: 'Gary'; Country: 'United States'; Population: 102746), (City: 'Gatineau'; Country: 'Canada'; Population: 100702), (City: 'Gaya'; Country: 'India'; Population: 291675), (City: 'Gaza'; Country: 'Palestine'; Population: 353632), (City: 'Gaziantep'; Country: 'Turkey'; Population: 789056), (City: 'Gazipur'; Country: 'Bangladesh'; Population: 96717), (City: 'Gdansk'; Country: 'Poland'; Population: 458988), (City: 'Gdynia'; Country: 'Poland'; Population: 253521), (City: 'Gebze'; Country: 'Turkey'; Population: 264170), (City: 'Geelong'; Country: 'Australia'; Population: 125382), (City: 'Gejiu'; Country: 'China'; Population: 214294), (City: 'Gelsenkirchen'; Country: 'Germany'; Population: 281979), (City: 'General Escobedo'; Country: 'Mexico'; Population: 232961), (City: 'General Mariano Alvarez'; Country: 'Philippines'; Population: 112446), (City: 'General San Mart韓'; Country: 'Argentina'; Population: 422542), (City: 'General Santos'; Country: 'Philippines'; Population: 411822), (City: 'General Trias'; Country: 'Philippines'; Population: 107691), (City: 'Geneve'; Country: 'Switzerland'; Population: 173500), (City: 'Genova'; Country: 'Italy'; Population: 636104), (City: 'Gent'; Country: 'Belgium'; Population: 224180), (City: 'George'; Country: 'South Africa'; Population: 93818), (City: 'George Town'; Country: 'Cayman Islands'; Population: 19600), (City: 'Georgetown'; Country: 'Guyana'; Population: 254000), (City: 'Gera'; Country: 'Germany'; Population: 114718), (City: 'Germiston'; Country: 'South Africa'; Population: 164252), (City: 'Getafe'; Country: 'Spain'; Population: 145371), (City: 'Gharda颽'; Country: 'Algeria'; Population: 89415), (City: 'Ghaziabad'; Country: 'India'; Population: 454156), (City: 'Ghulja'; Country: 'China'; Population: 177193), (City: 'Gibraltar'; Country: 'Gibraltar'; Population: 27025), (City: 'Gifu'; Country: 'Japan'; Population: 408007), (City: 'Gij髇'; Country: 'Spain'; Population: 267980), (City: 'Gilbert'; Country: 'United States'; Population: 109697), (City: 'Gillingham'; Country: 'United Kingdom'; Population: 92000), (City: 'Gingoog'; Country: 'Philippines'; Population: 102379), (City: 'Girardot'; Country: 'Colombia'; Population: 110963), (City: 'Giron'; Country: 'Colombia'; Population: 90688), (City: 'Giugliano in Campania'; Country: 'Italy'; Population: 93286), (City: 'Giza'; Country: 'Egypt'; Population: 2221868), (City: 'Gjumri'; Country: 'Armenia'; Population: 211700), (City: 'Glasgow'; Country: 'United Kingdom'; Population: 619680), (City: 'Glazov'; Country: 'Russian Federation'; Population: 106300), (City: 'Glendale'; Country: 'United States'; Population: 218812), (City: 'Glendale'; Country: 'United States'; Population: 194973), (City: 'Gliwice'; Country: 'Poland'; Population: 212164), (City: 'Gloucester'; Country: 'United Kingdom'; Population: 107000), (City: 'Gloucester'; Country: 'Canada'; Population: 107314), (City: 'Godhra'; Country: 'India'; Population: 96813), (City: 'Godoy Cruz'; Country: 'Argentina'; Population: 206998), (City: 'Goi鈔ia'; Country: 'Brazil'; Population: 1056330), (City: 'Gojra'; Country: 'Pakistan'; Population: 115000), (City: 'Gold Coast'; Country: 'Australia'; Population: 311932), (City: 'Goma'; Country: 'Congo, The Democratic Republic of the'; Population: 109094), (City: 'Gombe'; Country: 'Nigeria'; Population: 107800), (City: 'Gomel'; Country: 'Belarus'; Population: 475000), (City: 'Gonbad-e Qabus'; Country: 'Iran'; Population: 111253), (City: 'Gonda'; Country: 'India'; Population: 106078), (City: 'Gonder'; Country: 'Ethiopia'; Population: 112249), (City: 'Gondiya'; Country: 'India'; Population: 109470), (City: 'Gongziling'; Country: 'China'; Population: 226569), (City: 'Gorakhpur'; Country: 'India'; Population: 505566), (City: 'Gorgan'; Country: 'Iran'; Population: 188710), (City: 'Gorlivka'; Country: 'Ukraine'; Population: 299000), (City: 'Gorontalo'; Country: 'Indonesia'; Population: 94058), (City: 'Gorz體 Wielkopolski'; Country: 'Poland'; Population: 126019), (City: 'Gothenburg [G鰐eborg]'; Country: 'Sweden'; Population: 466990), (City: 'Governador Valadares'; Country: 'Brazil'; Population: 231724), (City: 'Granada'; Country: 'Spain'; Population: 244767), (City: 'Grand Prairie'; Country: 'United States'; Population: 127427), (City: 'Grand Rapids'; Country: 'United States'; Population: 197800), (City: 'Gravata'; Country: 'Brazil'; Population: 223011), (City: 'Graz'; Country: 'Austria'; Population: 240967), (City: 'Green Bay'; Country: 'United States'; Population: 102313), (City: 'Greensboro'; Country: 'United States'; Population: 223891), (City: 'Grenoble'; Country: 'France'; Population: 153317), (City: 'Grimsby'; Country: 'United Kingdom'; Population: 89000), (City: 'Grodno'; Country: 'Belarus'; Population: 302000), (City: 'Groningen'; Country: 'Netherlands'; Population: 172701), (City: 'Grozny'; Country: 'Russian Federation'; Population: 186000), (City: 'Grudziadz'; Country: 'Poland'; Population: 102434), (City: 'Guacara'; Country: 'Venezuela'; Population: 131334), (City: 'Guadalajara'; Country: 'Mexico'; Population: 1647720), (City: 'Guadalupe'; Country: 'Mexico'; Population: 668780), (City: 'Guadalupe'; Country: 'Mexico'; Population: 108881), (City: 'Guagua'; Country: 'Philippines'; Population: 96858), (City: 'Guanajuato'; Country: 'Mexico'; Population: 141215), (City: 'Guanare'; Country: 'Venezuela'; Population: 125621), (City: 'Guangshui'; Country: 'China'; Population: 102770), (City: 'Guangyuan'; Country: 'China'; Population: 182241), (City: 'Guant醤amo'; Country: 'Cuba'; Population: 205078), (City: 'Guarapuava'; Country: 'Brazil'; Population: 160510), (City: 'Guaratinguet'; Country: 'Brazil'; Population: 103433), (City: 'Guarenas'; Country: 'Venezuela'; Population: 165889), (City: 'Guaruj'; Country: 'Brazil'; Population: 237206), (City: 'Guarulhos'; Country: 'Brazil'; Population: 1095874), (City: 'Guasave'; Country: 'Mexico'; Population: 277201), (City: 'Guatire'; Country: 'Venezuela'; Population: 109121), (City: 'Guayaquil'; Country: 'Ecuador'; Population: 2070040), (City: 'Guaymall閚'; Country: 'Argentina'; Population: 200595), (City: 'Guaymas'; Country: 'Mexico'; Population: 130108), (City: 'Guaynabo'; Country: 'Puerto Rico'; Population: 100053), (City: 'Gua韇a'; Country: 'Brazil'; Population: 92224), (City: 'Gudivada'; Country: 'India'; Population: 101656), (City: 'Guelph'; Country: 'Canada'; Population: 103593), (City: 'Guigang'; Country: 'China'; Population: 114025), (City: 'Guilin'; Country: 'China'; Population: 364130), (City: 'Guiyang'; Country: 'China'; Population: 1465200), (City: 'Gujranwala'; Country: 'Pakistan'; Population: 1124749), (City: 'Gujrat'; Country: 'Pakistan'; Population: 250121), (City: 'Gulbarga'; Country: 'India'; Population: 304099), (City: 'Guna'; Country: 'India'; Population: 100490), (City: 'Guntakal'; Country: 'India'; Population: 107592), (City: 'Guntur'; Country: 'India'; Population: 471051), (City: 'Gurgaon'; Country: 'India'; Population: 128608), (City: 'Gurue'; Country: 'Mozambique'; Population: 99300), (City: 'Gusau'; Country: 'Nigeria'; Population: 158000), (City: 'Guwahati (Gauhati)'; Country: 'India'; Population: 584342), (City: 'Gwalior'; Country: 'India'; Population: 690765), (City: 'Gweru'; Country: 'Zimbabwe'; Population: 128037), (City: 'Gy鰎'; Country: 'Hungary'; Population: 127119), (City: 'G鋘c'; Country: 'Azerbaijan'; Population: 299300), (City: 'G鋠le'; Country: 'Sweden'; Population: 90742), (City: 'G髆ez Palacio'; Country: 'Mexico'; Population: 272806), (City: 'G鰐tingen'; Country: 'Germany'; Population: 124775), (City: 'G黷ersloh'; Country: 'Germany'; Population: 95028), (City: 'Haag'; Country: 'Netherlands'; Population: 440900), (City: 'Haarlem'; Country: 'Netherlands'; Population: 148772), (City: 'Haarlemmermeer'; Country: 'Netherlands'; Population: 110722), (City: 'Habarovsk'; Country: 'Russian Federation'; Population: 609400), (City: 'Habikino'; Country: 'Japan'; Population: 118968), (City: 'Habra'; Country: 'India'; Population: 100223), (City: 'Hachinohe'; Country: 'Japan'; Population: 242979), (City: 'Hachioji'; Country: 'Japan'; Population: 513451), (City: 'Hadano'; Country: 'Japan'; Population: 166512), (City: 'Haeju'; Country: 'North Korea'; Population: 229172), (City: 'Hafar al-Batin'; Country: 'Saudi Arabia'; Population: 137800), (City: 'Hafizabad'; Country: 'Pakistan'; Population: 130200), (City: 'Hagen'; Country: 'Germany'; Population: 205201), (City: 'Hagonoy'; Country: 'Philippines'; Population: 111425), (City: 'Haicheng'; Country: 'China'; Population: 205560), (City: 'Haifa'; Country: 'Israel'; Population: 265700), (City: 'Haikou'; Country: 'China'; Population: 454300), (City: 'Hail'; Country: 'Saudi Arabia'; Population: 176800), (City: 'Hailar'; Country: 'China'; Population: 180650), (City: 'Hailun'; Country: 'China'; Population: 133565), (City: 'Haining'; Country: 'China'; Population: 100478), (City: 'Haiphong'; Country: 'Vietnam'; Population: 783133), (City: 'Hakodate'; Country: 'Japan'; Population: 294788), (City: 'Haldia'; Country: 'India'; Population: 100347), (City: 'Haldwani-cum-Kathgodam'; Country: 'India'; Population: 104195), (City: 'Halifax'; Country: 'United Kingdom'; Population: 91069), (City: 'Halifax'; Country: 'Canada'; Population: 113910), (City: 'Halisahar'; Country: 'India'; Population: 114028), (City: 'Halle/Saale'; Country: 'Germany'; Population: 254360), (City: 'Hama'; Country: 'Syria'; Population: 343361), (City: 'Hamadan'; Country: 'Iran'; Population: 401281), (City: 'Hamamatsu'; Country: 'Japan'; Population: 568796), (City: 'Hamburg'; Country: 'Germany'; Population: 1704735), (City: 'Hamhung'; Country: 'North Korea'; Population: 709730), (City: 'Hami'; Country: 'China'; Population: 161315), (City: 'Hamilton'; Country: 'Bermuda'; Population: 1200), (City: 'Hamilton'; Country: 'Canada'; Population: 335614), (City: 'Hamilton'; Country: 'New Zealand'; Population: 117100), (City: 'Hamm'; Country: 'Germany'; Population: 181804), (City: 'Hampton'; Country: 'United States'; Population: 146437), (City: 'Hanam'; Country: 'South Korea'; Population: 115812), (City: 'Handa'; Country: 'Japan'; Population: 108600), (City: 'Handan'; Country: 'China'; Population: 840000), (City: 'Hangzhou'; Country: 'China'; Population: 2190500), (City: 'Hannover'; Country: 'Germany'; Population: 514718), (City: 'Hanoi'; Country: 'Vietnam'; Population: 1410000), (City: 'Hanzhong'; Country: 'China'; Population: 169930), (City: 'Haora (Howrah)'; Country: 'India'; Population: 950435), (City: 'Hapur'; Country: 'India'; Population: 146262), (City: 'Harare'; Country: 'Zimbabwe'; Population: 1410000), (City: 'Harbin'; Country: 'China'; Population: 4289800), (City: 'Hardwar (Haridwar)'; Country: 'India'; Population: 147305), (City: 'Hargeysa'; Country: 'Somalia'; Population: 90000), (City: 'Harkova [Harkiv]'; Country: 'Ukraine'; Population: 1500000), (City: 'Hartford'; Country: 'United States'; Population: 121578), (City: 'Hartlepool'; Country: 'United Kingdom'; Population: 92000), (City: 'Hassan'; Country: 'India'; Population: 90803), (City: 'Hat Yai'; Country: 'Thailand'; Population: 148632), (City: 'Hatay (Antakya)'; Country: 'Turkey'; Population: 143982), (City: 'Hathras'; Country: 'India'; Population: 113285), (City: 'Hayward'; Country: 'United States'; Population: 140030), (City: 'Hazaribag'; Country: 'India'; Population: 97712), (City: 'Hebi'; Country: 'China'; Population: 212976), (City: 'Hebron'; Country: 'Palestine'; Population: 119401), (City: 'Heerlen'; Country: 'Netherlands'; Population: 95052), (City: 'Hefei'; Country: 'China'; Population: 1369100), (City: 'Hegang'; Country: 'China'; Population: 520000), (City: 'Heidelberg'; Country: 'Germany'; Population: 139672), (City: 'Heilbronn'; Country: 'Germany'; Population: 119526), (City: 'Helsingborg'; Country: 'Sweden'; Population: 117737), (City: 'Helsinki [Helsingfors]'; Country: 'Finland'; Population: 555474), (City: 'Henderson'; Country: 'United States'; Population: 175381), (City: 'Hengshui'; Country: 'China'; Population: 104269), (City: 'Hengyang'; Country: 'China'; Population: 487148), (City: 'Henzada (Hinthada)'; Country: 'Myanmar'; Population: 104700), (City: 'Herakleion'; Country: 'Greece'; Population: 116178), (City: 'Herat'; Country: 'Afghanistan'; Population: 186800), (City: 'Hermosillo'; Country: 'Mexico'; Population: 608697), (City: 'Herne'; Country: 'Germany'; Population: 175661), (City: 'Herson'; Country: 'Ukraine'; Population: 353000), (City: 'Heyuan'; Country: 'China'; Population: 120101), (City: 'Heze'; Country: 'China'; Population: 189293), (City: 'Hialeah'; Country: 'United States'; Population: 226419), (City: 'Hidalgo'; Country: 'Mexico'; Population: 106198), (City: 'Hidalgo del Parral'; Country: 'Mexico'; Population: 100881), (City: 'Higashihiroshima'; Country: 'Japan'; Population: 119166), (City: 'Higashikurume'; Country: 'Japan'; Population: 111666), (City: 'Higashimatsuyama'; Country: 'Japan'; Population: 93342), (City: 'Higashimurayama'; Country: 'Japan'; Population: 136970), (City: 'Higashiosaka'; Country: 'Japan'; Population: 517785), (City: 'Hikone'; Country: 'Japan'; Population: 105508), (City: 'Hildesheim'; Country: 'Germany'; Population: 104013), (City: 'Himeji'; Country: 'Japan'; Population: 475167), (City: 'Himki'; Country: 'Russian Federation'; Population: 133700), (City: 'Hims'; Country: 'Syria'; Population: 507404), (City: 'Hindupur'; Country: 'India'; Population: 104651), (City: 'Hino'; Country: 'Japan'; Population: 166770), (City: 'Hirakata'; Country: 'Japan'; Population: 403151), (City: 'Hiratsuka'; Country: 'Japan'; Population: 254207), (City: 'Hirosaki'; Country: 'Japan'; Population: 177522), (City: 'Hiroshima'; Country: 'Japan'; Population: 1119117), (City: 'Hisar (Hissar)'; Country: 'India'; Population: 172677), (City: 'Hitachi'; Country: 'Japan'; Population: 196622), (City: 'Hitachinaka'; Country: 'Japan'; Population: 148006), (City: 'Hmelnytskyi'; Country: 'Ukraine'; Population: 262000), (City: 'Ho Chi Minh City'; Country: 'Vietnam'; Population: 3980000), (City: 'Hobart'; Country: 'Australia'; Population: 126118), (City: 'Hodeida'; Country: 'Yemen'; Population: 298500), (City: 'Hofu'; Country: 'Japan'; Population: 118751), (City: 'Hohhot'; Country: 'China'; Population: 916700), (City: 'Holgu韓'; Country: 'Cuba'; Population: 249492), (City: 'Hollywood'; Country: 'United States'; Population: 139357), (City: 'Holon'; Country: 'Israel'; Population: 163100), (City: 'Hong Gai'; Country: 'Vietnam'; Population: 127484), (City: 'Honghu'; Country: 'China'; Population: 190772), (City: 'Hongjiang'; Country: 'China'; Population: 116188), (City: 'Honiara'; Country: 'Solomon Islands'; Population: 50100), (City: 'Honolulu'; Country: 'United States'; Population: 371657), (City: 'Hortol鈔dia'; Country: 'Brazil'; Population: 135755), (City: 'Hoshiarpur'; Country: 'India'; Population: 122705), (City: 'Hospet'; Country: 'India'; Population: 96322), (City: 'Houston'; Country: 'United States'; Population: 1953631), (City: 'Hoya'; Country: 'Japan'; Population: 100313), (City: 'Hradec Kr醠ov'; Country: 'Czech Republic'; Population: 98080), (City: 'Hsichuh'; Country: 'Taiwan'; Population: 154976), (City: 'Hsinchu'; Country: 'Taiwan'; Population: 361958), (City: 'Hsinchuang'; Country: 'Taiwan'; Population: 365048), (City: 'Hsintien'; Country: 'Taiwan'; Population: 263603), (City: 'Huadian'; Country: 'China'; Population: 175873), (City: 'Huaibei'; Country: 'China'; Population: 366549), (City: 'Huaihua'; Country: 'China'; Population: 126785), (City: 'Huainan'; Country: 'China'; Population: 700000), (City: 'Huaiyin'; Country: 'China'; Population: 239675), (City: 'Huai碼n'; Country: 'China'; Population: 131149), (City: 'Hualien'; Country: 'Taiwan'; Population: 108407), (City: 'Huambo'; Country: 'Angola'; Population: 163100), (City: 'Huancayo'; Country: 'Peru'; Population: 327000), (City: 'Huangshan'; Country: 'China'; Population: 102628), (City: 'Huangshi'; Country: 'China'; Population: 457601), (City: 'Huangyan'; Country: 'China'; Population: 89288), (City: 'Huaying'; Country: 'China'; Population: 89400), (City: 'Hubli-Dharwad'; Country: 'India'; Population: 648298), (City: 'Huddersfield'; Country: 'United Kingdom'; Population: 143726), (City: 'Hue'; Country: 'Vietnam'; Population: 219149), (City: 'Huejutla de Reyes'; Country: 'Mexico'; Population: 108017), (City: 'Huelva'; Country: 'Spain'; Population: 140583), (City: 'Hugli-Chinsurah'; Country: 'India'; Population: 151806), (City: 'Huimanguillo'; Country: 'Mexico'; Population: 158335), (City: 'Huixquilucan'; Country: 'Mexico'; Population: 193156), (City: 'Huizhou'; Country: 'China'; Population: 161023), (City: 'Hunjiang'; Country: 'China'; Population: 482043), (City: 'Huntington Beach'; Country: 'United States'; Population: 189594), (City: 'Huntsville'; Country: 'United States'; Population: 158216), (City: 'Hurlingham'; Country: 'Argentina'; Population: 170028), (City: 'Huzhou'; Country: 'China'; Population: 218071), (City: 'Hu醤uco'; Country: 'Peru'; Population: 129688), (City: 'Hyderabad'; Country: 'India'; Population: 2964638), (City: 'Hyderabad'; Country: 'Pakistan'; Population: 1151274), (City: 'Hyesan'; Country: 'North Korea'; Population: 178020), (City: 'Iasi'; Country: 'Romania'; Population: 348070), (City: 'Ibadan'; Country: 'Nigeria'; Population: 1432000), (City: 'Ibagu'; Country: 'Colombia'; Population: 393664), (City: 'Ibaraki'; Country: 'Japan'; Population: 261020), (City: 'Ibarra'; Country: 'Ecuador'; Population: 130643), (City: 'Ibb'; Country: 'Yemen'; Population: 103300), (City: 'Ibirit'; Country: 'Brazil'; Population: 125982), (City: 'Ica'; Country: 'Peru'; Population: 194820), (City: 'Ichalkaranji'; Country: 'India'; Population: 214950), (City: 'Ichihara'; Country: 'Japan'; Population: 279280), (City: 'Ichikawa'; Country: 'Japan'; Population: 441893), (City: 'Ichinomiya'; Country: 'Japan'; Population: 270828), (City: 'Ichon'; Country: 'South Korea'; Population: 155332), (City: 'Idfu'; Country: 'Egypt'; Population: 94200), (City: 'Idlib'; Country: 'Syria'; Population: 91081), (City: 'Ife'; Country: 'Nigeria'; Population: 296800), (City: 'Igboho'; Country: 'Nigeria'; Population: 106800), (City: 'Iguala de la Independencia'; Country: 'Mexico'; Population: 123883), (City: 'Iida'; Country: 'Japan'; Population: 107583), (City: 'Ijebu-Ode'; Country: 'Nigeria'; Population: 156400), (City: 'Ikare'; Country: 'Nigeria'; Population: 140800), (City: 'Ikeda'; Country: 'Japan'; Population: 102710), (City: 'Ikerre'; Country: 'Nigeria'; Population: 244600), (City: 'Ikire'; Country: 'Nigeria'; Population: 123300), (City: 'Ikirun'; Country: 'Nigeria'; Population: 181400), (City: 'Ikoma'; Country: 'Japan'; Population: 111645), (City: 'Ikorodu'; Country: 'Nigeria'; Population: 184900), (City: 'Iksan'; Country: 'South Korea'; Population: 322685), (City: 'Ila'; Country: 'Nigeria'; Population: 264000), (City: 'Ilagan'; Country: 'Philippines'; Population: 119990), (City: 'Ilam'; Country: 'Iran'; Population: 126346), (City: 'Ilan'; Country: 'Taiwan'; Population: 92000), (City: 'Ilawe-Ekiti'; Country: 'Nigeria'; Population: 184500), (City: 'Ilesha'; Country: 'Nigeria'; Population: 378400), (City: 'Ilh閡s'; Country: 'Brazil'; Population: 254970), (City: 'Iligan'; Country: 'Philippines'; Population: 285061), (City: 'Ilobu'; Country: 'Nigeria'; Population: 199000), (City: 'Iloilo'; Country: 'Philippines'; Population: 365820), (City: 'Ilorin'; Country: 'Nigeria'; Population: 475800), (City: 'Imabari'; Country: 'Japan'; Population: 119357), (City: 'Imperatriz'; Country: 'Brazil'; Population: 224564), (City: 'Imphal'; Country: 'India'; Population: 198535), (City: 'Imus'; Country: 'Philippines'; Population: 195482), (City: 'Inanda'; Country: 'South Africa'; Population: 634065), (City: 'Inazawa'; Country: 'Japan'; Population: 98746), (City: 'Inchon'; Country: 'South Korea'; Population: 2559424), (City: 'Indaiatuba'; Country: 'Brazil'; Population: 135968), (City: 'Independence'; Country: 'United States'; Population: 113288), (City: 'Indianapolis'; Country: 'United States'; Population: 791926), (City: 'Indore'; Country: 'India'; Population: 1091674), (City: 'Ineg鰈'; Country: 'Turkey'; Population: 90500), (City: 'Inglewood'; Country: 'United States'; Population: 112580), (City: 'Ingolstadt'; Country: 'Germany'; Population: 114826), (City: 'Ingraj Bazar (English Bazar)'; Country: 'India'; Population: 139204), (City: 'Inisa'; Country: 'Nigeria'; Population: 119800), (City: 'Innsbruck'; Country: 'Austria'; Population: 111752), (City: 'Ipatinga'; Country: 'Brazil'; Population: 206338), (City: 'Ipoh'; Country: 'Malaysia'; Population: 382853), (City: 'Ipswich'; Country: 'United Kingdom'; Population: 114000), (City: 'Iquique'; Country: 'Chile'; Population: 177892), (City: 'Iquitos'; Country: 'Peru'; Population: 367000), (City: 'Irapuato'; Country: 'Mexico'; Population: 440039), (City: 'Irbid'; Country: 'Jordan'; Population: 231511), (City: 'Irbil'; Country: 'Iraq'; Population: 485968), (City: 'Irkutsk'; Country: 'Russian Federation'; Population: 593700), (City: 'Iruma'; Country: 'Japan'; Population: 145922), (City: 'Irvine'; Country: 'United States'; Population: 143072), (City: 'Irving'; Country: 'United States'; Population: 191615), (City: 'Isahaya'; Country: 'Japan'; Population: 93058), (City: 'Ise'; Country: 'Japan'; Population: 101732), (City: 'Ise-Ekiti'; Country: 'Nigeria'; Population: 103400), (City: 'Isehara'; Country: 'Japan'; Population: 98123), (City: 'Iserlohn'; Country: 'Germany'; Population: 99474), (City: 'Isesaki'; Country: 'Japan'; Population: 123285), (City: 'Iseyin'; Country: 'Nigeria'; Population: 217300), (City: 'Ishinomaki'; Country: 'Japan'; Population: 120963), (City: 'Iskenderun'; Country: 'Turkey'; Population: 153022), (City: 'Islamabad'; Country: 'Pakistan'; Population: 524500), (City: 'Ismailia'; Country: 'Egypt'; Population: 254477), (City: 'Isparta'; Country: 'Turkey'; Population: 121911), (City: 'Istanbul'; Country: 'Turkey'; Population: 8787958), (City: 'Itabira'; Country: 'Brazil'; Population: 102217), (City: 'Itabora'; Country: 'Brazil'; Population: 173977), (City: 'Itabuna'; Country: 'Brazil'; Population: 182148), (City: 'Itag'; Country: 'Colombia'; Population: 228985), (City: 'Itaituba'; Country: 'Brazil'; Population: 101320), (City: 'Itaja'; Country: 'Brazil'; Population: 145197), (City: 'Itami'; Country: 'Japan'; Population: 190886), (City: 'Itapecerica da Serra'; Country: 'Brazil'; Population: 126672), (City: 'Itapetininga'; Country: 'Brazil'; Population: 119391), (City: 'Itapevi'; Country: 'Brazil'; Population: 150664), (City: 'Itaquaquecetuba'; Country: 'Brazil'; Population: 270874), (City: 'Itu'; Country: 'Brazil'; Population: 132736), (City: 'Ituiutaba'; Country: 'Brazil'; Population: 90507), (City: 'Ituzaing'; Country: 'Argentina'; Population: 158197), (City: 'Ivano-Frankivsk'; Country: 'Ukraine'; Population: 237000), (City: 'Ivanovo'; Country: 'Russian Federation'; Population: 459200), (City: 'Iwaki'; Country: 'Japan'; Population: 361737), (City: 'Iwakuni'; Country: 'Japan'; Population: 106647), (City: 'Iwatsuki'; Country: 'Japan'; Population: 110034), (City: 'Iwo'; Country: 'Nigeria'; Population: 362000), (City: 'Ixtapaluca'; Country: 'Mexico'; Population: 293160), (City: 'Ixtlahuaca'; Country: 'Mexico'; Population: 115548), (City: 'Izevsk'; Country: 'Russian Federation'; Population: 652800), (City: 'Izmajil'; Country: 'Ukraine'; Population: 90000), (City: 'Izmir'; Country: 'Turkey'; Population: 2130359), (City: 'Izmit (Kocaeli)'; Country: 'Turkey'; Population: 210068), (City: 'Izumi'; Country: 'Japan'; Population: 166979), (City: 'Izumisano'; Country: 'Japan'; Population: 92583), (City: 'Jabaliya'; Country: 'Palestine'; Population: 113901), (City: 'Jabalpur'; Country: 'India'; Population: 741927), (City: 'Jaboat鉶 dos Guararapes'; Country: 'Brazil'; Population: 558680), (City: 'Jacare'; Country: 'Brazil'; Population: 170356), (City: 'Jackson'; Country: 'United States'; Population: 184256), (City: 'Jacksonville'; Country: 'United States'; Population: 735167), (City: 'Jacobabad'; Country: 'Pakistan'; Population: 137700), (City: 'Jacobina'; Country: 'Brazil'; Population: 96131), (City: 'Jaffna'; Country: 'Sri Lanka'; Population: 149000), (City: 'Jahrom'; Country: 'Iran'; Population: 94200), (City: 'Jaipur'; Country: 'India'; Population: 1458483), (City: 'Jakarta'; Country: 'Indonesia'; Population: 9604900), (City: 'Jakutsk'; Country: 'Russian Federation'; Population: 195400), (City: 'Jalandhar (Jullundur)'; Country: 'India'; Population: 509510), (City: 'Jalgaon'; Country: 'India'; Population: 242193), (City: 'Jalib al-Shuyukh'; Country: 'Kuwait'; Population: 102178), (City: 'Jalna'; Country: 'India'; Population: 174985), (City: 'Jamalpur'; Country: 'Bangladesh'; Population: 103556), (City: 'Jambi'; Country: 'Indonesia'; Population: 385201), (City: 'Jamestown'; Country: 'Saint Helena'; Population: 1500), (City: 'Jammu'; Country: 'India'; Population: 214737), (City: 'Jamnagar'; Country: 'India'; Population: 341637), (City: 'Jamshedpur'; Country: 'India'; Population: 460577), (City: 'Jaragu?do Sul'; Country: 'Brazil'; Population: 102580), (City: 'Jaramana'; Country: 'Syria'; Population: 138469), (City: 'Jaranwala'; Country: 'Pakistan'; Population: 103300), (City: 'Jaroslavl'; Country: 'Russian Federation'; Population: 616700), (City: 'Jastrzebie-Zdr骿'; Country: 'Poland'; Population: 102294), (City: 'Jaunpur'; Country: 'India'; Population: 136062), (City: 'Jaworzno'; Country: 'Poland'; Population: 97929), (City: 'Jaya Pura'; Country: 'Indonesia'; Population: 94700), (City: 'Ja閚'; Country: 'Spain'; Population: 109247), (City: 'Ja'; Country: 'Brazil'; Population: 109965), (City: 'Jedda'; Country: 'Saudi Arabia'; Population: 2046300), (City: 'Jekaterinburg'; Country: 'Russian Federation'; Population: 1266300), (City: 'Jelenia G髍a'; Country: 'Poland'; Population: 93901), (City: 'Jelets'; Country: 'Russian Federation'; Population: 119400), (City: 'Jember'; Country: 'Indonesia'; Population: 218500), (City: 'Jena'; Country: 'Germany'; Population: 99779), (City: 'Jenakijeve'; Country: 'Ukraine'; Population: 105000), (City: 'Jequi'; Country: 'Brazil'; Population: 179128), (City: 'Jerez de la Frontera'; Country: 'Spain'; Population: 182660), (City: 'Jersey City'; Country: 'United States'; Population: 240055), (City: 'Jerusalem'; Country: 'Israel'; Population: 633700), (City: 'Jessentuki'; Country: 'Russian Federation'; Population: 97900), (City: 'Jessore'; Country: 'Bangladesh'; Population: 139710), (City: 'Jevpatorija'; Country: 'Ukraine'; Population: 112000), (City: 'Jhang'; Country: 'Pakistan'; Population: 292214), (City: 'Jhansi'; Country: 'India'; Population: 300850), (City: 'Jhelum'; Country: 'Pakistan'; Population: 145800), (City: 'Ji-Paran'; Country: 'Brazil'; Population: 93346), (City: 'Jiamusi'; Country: 'China'; Population: 493409), (City: 'Jiangmen'; Country: 'China'; Population: 230587), (City: 'Jiangyin'; Country: 'China'; Population: 213659), (City: 'Jiangyou'; Country: 'China'; Population: 175753), (City: 'Jiaohe'; Country: 'China'; Population: 176367), (City: 'Jiaonan'; Country: 'China'; Population: 121397), (City: 'Jiaozhou'; Country: 'China'; Population: 153364), (City: 'Jiaozuo'; Country: 'China'; Population: 409100), (City: 'Jiaxing'; Country: 'China'; Population: 211526), (City: 'Jieyang'; Country: 'China'; Population: 98531), (City: 'Jilin'; Country: 'China'; Population: 1040000), (City: 'Jinan'; Country: 'China'; Population: 2278100), (City: 'Jinchang'; Country: 'China'; Population: 105287), (City: 'Jincheng'; Country: 'China'; Population: 136396), (City: 'Jingdezhen'; Country: 'China'; Population: 281183), (City: 'Jinhua'; Country: 'China'; Population: 144280), (City: 'Jining'; Country: 'China'; Population: 265248), (City: 'Jining'; Country: 'China'; Population: 163552), (City: 'Jinmen'; Country: 'China'; Population: 160794), (City: 'Jinxi'; Country: 'China'; Population: 357052), (City: 'Jinzhou'; Country: 'China'; Population: 570000), (City: 'Jinzhou'; Country: 'China'; Population: 95761), (City: 'Jirja'; Country: 'Egypt'; Population: 95400), (City: 'Jiujiang'; Country: 'China'; Population: 291187), (City: 'Jiutai'; Country: 'China'; Population: 180130), (City: 'Jiutepec'; Country: 'Mexico'; Population: 170428), (City: 'Jixi'; Country: 'China'; Population: 683885), (City: 'Ji碼n'; Country: 'China'; Population: 148583), (City: 'Jodhpur'; Country: 'India'; Population: 666279), (City: 'Joetsu'; Country: 'Japan'; Population: 133505), (City: 'Johannesburg'; Country: 'South Africa'; Population: 756653), (City: 'Johor Baharu'; Country: 'Malaysia'; Population: 328436), (City: 'Joinville'; Country: 'Brazil'; Population: 428011), (City: 'Jokohama [Yokohama]'; Country: 'Japan'; Population: 3339594), (City: 'Joliet'; Country: 'United States'; Population: 106221), (City: 'Jombang'; Country: 'Indonesia'; Population: 92600), (City: 'Jos'; Country: 'Nigeria'; Population: 206300), (City: 'Jos?Azueta'; Country: 'Mexico'; Population: 95448), (City: 'Jos?C. Paz'; Country: 'Argentina'; Population: 221754), (City: 'Jo鉶 Pessoa'; Country: 'Brazil'; Population: 584029), (City: 'Jo歬ar-Ola'; Country: 'Russian Federation'; Population: 249200), (City: 'Juazeiro'; Country: 'Brazil'; Population: 201073), (City: 'Juazeiro do Norte'; Country: 'Brazil'; Population: 199636), (City: 'Juba'; Country: 'Sudan'; Population: 114980), (City: 'Jubayl'; Country: 'Saudi Arabia'; Population: 140800), (City: 'Juiz de Fora'; Country: 'Brazil'; Population: 450288), (City: 'Juliaca'; Country: 'Peru'; Population: 142576), (City: 'Junagadh'; Country: 'India'; Population: 130484), (City: 'Junan'; Country: 'China'; Population: 90222), (City: 'Jund韆'; Country: 'Brazil'; Population: 296127), (City: 'Juzno-Sahalinsk'; Country: 'Russian Federation'; Population: 179200), (City: 'Ju醨ez'; Country: 'Mexico'; Population: 1217818), (City: 'J鰊k鰌ing'; Country: 'Sweden'; Population: 117095), (City: 'Kabankalan'; Country: 'Philippines'; Population: 149769), (City: 'Kabul'; Country: 'Afghanistan'; Population: 1780000), (City: 'Kabwe'; Country: 'Zambia'; Population: 154300), (City: 'Kadoma'; Country: 'Japan'; Population: 138953), (City: 'Kaduna'; Country: 'Nigeria'; Population: 342200), (City: 'Kaesong'; Country: 'North Korea'; Population: 171500), (City: 'Kafr al-Dawwar'; Country: 'Egypt'; Population: 231978), (City: 'Kafr al-Shaykh'; Country: 'Egypt'; Population: 124819), (City: 'Kagoshima'; Country: 'Japan'; Population: 549977), (City: 'Kahramanmaras'; Country: 'Turkey'; Population: 245772), (City: 'Kaifeng'; Country: 'China'; Population: 510000), (City: 'Kaili'; Country: 'China'; Population: 113958), (City: 'Kairouan'; Country: 'Tunisia'; Population: 113100), (City: 'Kaiserslautern'; Country: 'Germany'; Population: 100025), (City: 'Kaiyuan'; Country: 'China'; Population: 124219), (City: 'Kaiyuan'; Country: 'China'; Population: 91999), (City: 'Kakamigahara'; Country: 'Japan'; Population: 131831), (City: 'Kakinada'; Country: 'India'; Population: 279980), (City: 'Kakogawa'; Country: 'Japan'; Population: 266281), (City: 'Kalemie'; Country: 'Congo, The Democratic Republic of the'; Population: 101309), (City: 'Kaliningrad'; Country: 'Russian Federation'; Population: 424400), (City: 'Kalisz'; Country: 'Poland'; Population: 106641), (City: 'Kallithea'; Country: 'Greece'; Population: 114233), (City: 'Kalookan'; Country: 'Philippines'; Population: 1177604), (City: 'Kaluga'; Country: 'Russian Federation'; Population: 339300), (City: 'Kalyan'; Country: 'India'; Population: 1014557), (City: 'Kamagaya'; Country: 'Japan'; Population: 100821), (City: 'Kamakura'; Country: 'Japan'; Population: 167661), (City: 'Kamalia'; Country: 'Pakistan'; Population: 95300), (City: 'Kamarhati'; Country: 'India'; Population: 266889), (City: 'Kamensk-Uralski'; Country: 'Russian Federation'; Population: 190600), (City: 'Kameoka'; Country: 'Japan'; Population: 92398), (City: 'Kamjanets-Podilskyi'; Country: 'Ukraine'; Population: 109000), (City: 'Kamoke'; Country: 'Pakistan'; Population: 151000), (City: 'Kampala'; Country: 'Uganda'; Population: 890800), (City: 'Kamy歩n'; Country: 'Russian Federation'; Population: 124600), (City: 'Kananga'; Country: 'Congo, The Democratic Republic of the'; Population: 393030), (City: 'Kanazawa'; Country: 'Japan'; Population: 455386), (City: 'Kanchipuram'; Country: 'India'; Population: 150100), (City: 'Kanchrapara'; Country: 'India'; Population: 100194), (City: 'Kandy'; Country: 'Sri Lanka'; Population: 140000), (City: 'Kanggye'; Country: 'North Korea'; Population: 223410), (City: 'Kangnung'; Country: 'South Korea'; Population: 220403), (City: 'Kangshan'; Country: 'Taiwan'; Population: 92200), (City: 'Kano'; Country: 'Nigeria'; Population: 674100), (City: 'Kanpur'; Country: 'India'; Population: 1874409), (City: 'Kanpur Cantonment'; Country: 'India'; Population: 93109), (City: 'Kansas City'; Country: 'United States'; Population: 441545), (City: 'Kansas City'; Country: 'United States'; Population: 146866), (City: 'Kansk'; Country: 'Russian Federation'; Population: 107400), (City: 'Kanton [Guangzhou]'; Country: 'China'; Population: 4256300), (City: 'Kanuma'; Country: 'Japan'; Population: 93053), (City: 'Kaohsiung'; Country: 'Taiwan'; Population: 1475505), (City: 'Kaolack'; Country: 'Senegal'; Population: 199000), (City: 'Karab黭'; Country: 'Turkey'; Population: 118285), (City: 'Karachi'; Country: 'Pakistan'; Population: 9269265), (City: 'Karaj'; Country: 'Iran'; Population: 940968), (City: 'Karaman'; Country: 'Turkey'; Population: 104200), (City: 'Karawang'; Country: 'Indonesia'; Population: 145000), (City: 'Karbala'; Country: 'Iraq'; Population: 296705), (City: 'Karimnagar'; Country: 'India'; Population: 148583), (City: 'Kariya'; Country: 'Japan'; Population: 127969), (City: 'Karlsruhe'; Country: 'Germany'; Population: 277204), (City: 'Karnal'; Country: 'India'; Population: 173751), (City: 'Kars'; Country: 'Turkey'; Population: 93000), (City: 'Karsi'; Country: 'Uzbekistan'; Population: 194100), (City: 'Kashan'; Country: 'Iran'; Population: 201372), (City: 'Kashihara'; Country: 'Japan'; Population: 124013), (City: 'Kashiwa'; Country: 'Japan'; Population: 320296), (City: 'Kashiwazaki'; Country: 'Japan'; Population: 91229), (City: 'Kassala'; Country: 'Sudan'; Population: 234622), (City: 'Kassel'; Country: 'Germany'; Population: 196211), (City: 'Kasuga'; Country: 'Japan'; Population: 101344), (City: 'Kasugai'; Country: 'Japan'; Population: 282348), (City: 'Kasukabe'; Country: 'Japan'; Population: 201838), (City: 'Kasur'; Country: 'Pakistan'; Population: 241649), (City: 'Kataka (Cuttack)'; Country: 'India'; Population: 403418), (City: 'Kathmandu'; Country: 'Nepal'; Population: 591835), (City: 'Katihar'; Country: 'India'; Population: 154367), (City: 'Katowice'; Country: 'Poland'; Population: 345934), (City: 'Katsina'; Country: 'Nigeria'; Population: 206500), (City: 'Kaunas'; Country: 'Lithuania'; Population: 412639), (City: 'Kawachinagano'; Country: 'Japan'; Population: 119666), (City: 'Kawagoe'; Country: 'Japan'; Population: 327211), (City: 'Kawaguchi'; Country: 'Japan'; Population: 452155), (City: 'Kawanishi'; Country: 'Japan'; Population: 149794), (City: 'Kawasaki'; Country: 'Japan'; Population: 1217359), (City: 'Kayseri'; Country: 'Turkey'; Population: 475657), (City: 'Kazan'; Country: 'Russian Federation'; Population: 1101000), (City: 'Kecskem閠'; Country: 'Hungary'; Population: 105606), (City: 'Kediri'; Country: 'Indonesia'; Population: 253760), (City: 'Keelung (Chilung)'; Country: 'Taiwan'; Population: 385201), (City: 'Kelang'; Country: 'Malaysia'; Population: 243355), (City: 'Kelowna'; Country: 'Canada'; Population: 89442), (City: 'Kemerovo'; Country: 'Russian Federation'; Population: 492700), (City: 'Kempton Park'; Country: 'South Africa'; Population: 442633), (City: 'Kendari'; Country: 'Indonesia'; Population: 94800), (City: 'Kenosha'; Country: 'United States'; Population: 89447), (City: 'Kerman'; Country: 'Iran'; Population: 384991), (City: 'Kermanshah'; Country: 'Iran'; Population: 692986), (City: 'Kert'; Country: 'Ukraine'; Population: 162000), (City: 'Khairpur'; Country: 'Pakistan'; Population: 102200), (City: 'Khamis Mushayt'; Country: 'Saudi Arabia'; Population: 217900), (City: 'Khammam'; Country: 'India'; Population: 127992), (City: 'Khan Yunis'; Country: 'Palestine'; Population: 123175), (City: 'Khandwa'; Country: 'India'; Population: 145133), (City: 'Khanewal'; Country: 'Pakistan'; Population: 133000), (City: 'Khanpur'; Country: 'Pakistan'; Population: 117800), (City: 'Kharagpur'; Country: 'India'; Population: 177989), (City: 'Khartum'; Country: 'Sudan'; Population: 947483), (City: 'Khomeynishahr'; Country: 'Iran'; Population: 165888), (City: 'Khon Kaen'; Country: 'Thailand'; Population: 126500), (City: 'Khorramabad'; Country: 'Iran'; Population: 272815), (City: 'Khorramshahr'; Country: 'Iran'; Population: 105636), (City: 'Khouribga'; Country: 'Morocco'; Population: 152090), (City: 'Khoy'; Country: 'Iran'; Population: 148944), (City: 'Khujand'; Country: 'Tajikistan'; Population: 161500), (City: 'Khulna'; Country: 'Bangladesh'; Population: 663340), (City: 'Khuzdar'; Country: 'Pakistan'; Population: 93100), (City: 'Kidapawan'; Country: 'Philippines'; Population: 101205), (City: 'Kiel'; Country: 'Germany'; Population: 233795), (City: 'Kielce'; Country: 'Poland'; Population: 212383), (City: 'Kigali'; Country: 'Rwanda'; Population: 286000), (City: 'Kikwit'; Country: 'Congo, The Democratic Republic of the'; Population: 182142), (City: 'Kilis'; Country: 'Turkey'; Population: 118245), (City: 'Kimberley'; Country: 'South Africa'; Population: 197254), (City: 'Kimchaek'; Country: 'North Korea'; Population: 179000), (City: 'Kimchon'; Country: 'South Korea'; Population: 147027), (City: 'Kimhae'; Country: 'South Korea'; Population: 256370), (City: 'Kimitsu'; Country: 'Japan'; Population: 93216), (City: 'Kimje'; Country: 'South Korea'; Population: 115427), (City: 'Kine歮a'; Country: 'Russian Federation'; Population: 100000), (City: 'Kingston'; Country: 'Jamaica'; Population: 103962), (City: 'Kingston'; Country: 'Norfolk Island'; Population: 800), (City: 'Kingston upon Hull'; Country: 'United Kingdom'; Population: 262000), (City: 'Kingstown'; Country: 'Saint Vincent and the Grenadines'; Population: 17100), (City: 'Kinshasa'; Country: 'Congo, The Democratic Republic of the'; Population: 5064000), (City: 'Kioto'; Country: 'Japan'; Population: 1461974), (City: 'Kirikkale'; Country: 'Turkey'; Population: 142044), (City: 'Kirkuk'; Country: 'Iraq'; Population: 418624), (City: 'Kirov'; Country: 'Russian Federation'; Population: 466200), (City: 'Kirovo-T歟petsk'; Country: 'Russian Federation'; Population: 91600), (City: 'Kirovograd'; Country: 'Ukraine'; Population: 265000), (City: 'Kiryu'; Country: 'Japan'; Population: 118326), (City: 'Kisangani'; Country: 'Congo, The Democratic Republic of the'; Population: 417517), (City: 'Kisarazu'; Country: 'Japan'; Population: 121967), (City: 'Kiseljovsk'; Country: 'Russian Federation'; Population: 110000), (City: 'Kishiwada'; Country: 'Japan'; Population: 197276), (City: 'Kislovodsk'; Country: 'Russian Federation'; Population: 120400), (City: 'Kismaayo'; Country: 'Somalia'; Population: 90000), (City: 'Kisumu'; Country: 'Kenya'; Population: 192733), (City: 'Kitakyushu'; Country: 'Japan'; Population: 1016264), (City: 'Kitami'; Country: 'Japan'; Population: 111295), (City: 'Kitchener'; Country: 'Canada'; Population: 189959), (City: 'Kitwe'; Country: 'Zambia'; Population: 288600), (City: 'Kiziltepe'; Country: 'Turkey'; Population: 112000), (City: 'Klagenfurt'; Country: 'Austria'; Population: 91141), (City: 'Klaipeda'; Country: 'Lithuania'; Population: 202451), (City: 'Klaten'; Country: 'Indonesia'; Population: 103300), (City: 'Klerksdorp'; Country: 'South Africa'; Population: 261911), (City: 'Klin'; Country: 'Russian Federation'; Population: 90000), (City: 'Knoxville'; Country: 'United States'; Population: 173890), (City: 'Kobe'; Country: 'Japan'; Population: 1425139), (City: 'Koblenz'; Country: 'Germany'; Population: 108003), (City: 'Kochi'; Country: 'Japan'; Population: 324710), (City: 'Kodaira'; Country: 'Japan'; Population: 174984), (City: 'Kofu'; Country: 'Japan'; Population: 199753), (City: 'Koganei'; Country: 'Japan'; Population: 110969), (City: 'Kohat'; Country: 'Pakistan'; Population: 125300), (City: 'Koje'; Country: 'South Korea'; Population: 147562), (City: 'Kokubunji'; Country: 'Japan'; Population: 106996), (City: 'Kolhapur'; Country: 'India'; Population: 406370), (City: 'Kollam (Quilon)'; Country: 'India'; Population: 139852), (City: 'Kolomna'; Country: 'Russian Federation'; Population: 150700), (City: 'Kolpino'; Country: 'Russian Federation'; Population: 141200), (City: 'Kolwezi'; Country: 'Congo, The Democratic Republic of the'; Population: 417810), (City: 'Komaki'; Country: 'Japan'; Population: 139827), (City: 'Komatsu'; Country: 'Japan'; Population: 107937), (City: 'Komsomolsk-na-Amure'; Country: 'Russian Federation'; Population: 291600), (City: 'Konan'; Country: 'Japan'; Population: 95521), (City: 'Kongju'; Country: 'South Korea'; Population: 131229), (City: 'Konotop'; Country: 'Ukraine'; Population: 96000), (City: 'Konya'; Country: 'Turkey'; Population: 628364), (City: 'Korba'; Country: 'India'; Population: 124501), (City: 'Korhogo'; Country: 'C魌e d扞voire'; Population: 109445), (City: 'Koriyama'; Country: 'Japan'; Population: 330335), (City: 'Korla'; Country: 'China'; Population: 159344), (City: 'Korolev'; Country: 'Russian Federation'; Population: 132400), (City: 'Koronadal'; Country: 'Philippines'; Population: 133786), (City: 'Koror'; Country: 'Palau'; Population: 12000), (City: 'Koshigaya'; Country: 'Japan'; Population: 301446), (City: 'Kostjantynivka'; Country: 'Ukraine'; Population: 95000), (City: 'Kostroma'; Country: 'Russian Federation'; Population: 288100), (City: 'Koszalin'; Country: 'Poland'; Population: 112375), (City: 'Kota'; Country: 'India'; Population: 537371), (City: 'Kota Bharu'; Country: 'Malaysia'; Population: 219582), (City: 'Koudougou'; Country: 'Burkina Faso'; Population: 105000), (City: 'Kovrov'; Country: 'Russian Federation'; Population: 159900), (City: 'Kowloon and New Kowloon'; Country: 'Hong Kong'; Population: 1987996), (City: 'Koyang'; Country: 'South Korea'; Population: 518282), (City: 'Ko歩ce'; Country: 'Slovakia'; Population: 241874), (City: 'Kragujevac'; Country: 'Yugoslavia'; Population: 147305), (City: 'Krak體'; Country: 'Poland'; Population: 738150), (City: 'Kramatorsk'; Country: 'Ukraine'; Population: 186000), (City: 'Krasnodar'; Country: 'Russian Federation'; Population: 639000), (City: 'Krasnogorsk'; Country: 'Russian Federation'; Population: 91000), (City: 'Krasnojarsk'; Country: 'Russian Federation'; Population: 875500), (City: 'Krasnyi Lut'; Country: 'Ukraine'; Population: 101000), (City: 'Krefeld'; Country: 'Germany'; Population: 241769), (City: 'Krement歶k'; Country: 'Ukraine'; Population: 239000), (City: 'Krishnanagar'; Country: 'India'; Population: 121110), (City: 'Krugersdorp'; Country: 'South Africa'; Population: 181503), (City: 'Kryvyi Rig'; Country: 'Ukraine'; Population: 703000), (City: 'Ksar el Kebir'; Country: 'Morocco'; Population: 107065), (City: 'Kuala Lumpur'; Country: 'Malaysia'; Population: 1297526), (City: 'Kuala Terengganu'; Country: 'Malaysia'; Population: 228119), (City: 'Kuantan'; Country: 'Malaysia'; Population: 199484), (City: 'Kuching'; Country: 'Malaysia'; Population: 148059), (City: 'Kudus'; Country: 'Indonesia'; Population: 95300), (City: 'Kueishan'; Country: 'Taiwan'; Population: 112195), (City: 'Kukatpalle'; Country: 'India'; Population: 185378), (City: 'Kulti-Barakar'; Country: 'India'; Population: 108518), (City: 'Kumagaya'; Country: 'Japan'; Population: 157171), (City: 'Kumamoto'; Country: 'Japan'; Population: 656734), (City: 'Kumasi'; Country: 'Ghana'; Population: 385192), (City: 'Kumbakonam'; Country: 'India'; Population: 139483), (City: 'Kumi'; Country: 'South Korea'; Population: 311431), (City: 'Kumo'; Country: 'Nigeria'; Population: 148000), (City: 'Kunming'; Country: 'China'; Population: 1829500), (City: 'Kunpo'; Country: 'South Korea'; Population: 235233), (City: 'Kunsan'; Country: 'South Korea'; Population: 266569), (City: 'Kunshan'; Country: 'China'; Population: 102052), (City: 'Kupang'; Country: 'Indonesia'; Population: 129300), (City: 'Kurashiki'; Country: 'Japan'; Population: 425103), (City: 'Kure'; Country: 'Japan'; Population: 206504), (City: 'Kurgan'; Country: 'Russian Federation'; Population: 364700), (City: 'Kuri'; Country: 'South Korea'; Population: 142173), (City: 'Kurnool'; Country: 'India'; Population: 236800), (City: 'Kursk'; Country: 'Russian Federation'; Population: 443500), (City: 'Kurume'; Country: 'Japan'; Population: 235611), (City: 'Kusatsu'; Country: 'Japan'; Population: 106232), (City: 'Kushiro'; Country: 'Japan'; Population: 197608), (City: 'Kusti'; Country: 'Sudan'; Population: 173599), (City: 'Kutaisi'; Country: 'Georgia'; Population: 240900), (City: 'Kuwait'; Country: 'Kuwait'; Population: 28859), (City: 'Kuwana'; Country: 'Japan'; Population: 106121), (City: 'Kuytun'; Country: 'China'; Population: 118553), (City: 'Kuznetsk'; Country: 'Russian Federation'; Population: 98200), (City: 'Kwang-yang'; Country: 'South Korea'; Population: 122052), (City: 'Kwangju'; Country: 'South Korea'; Population: 1368341), (City: 'Kwangmyong'; Country: 'South Korea'; Population: 350914), (City: 'Kyiv'; Country: 'Ukraine'; Population: 2624000), (City: 'Kyongju'; Country: 'South Korea'; Population: 272968), (City: 'Kyongsan'; Country: 'South Korea'; Population: 173746), (City: 'Kyzyl'; Country: 'Russian Federation'; Population: 101100), (City: 'K閚itra'; Country: 'Morocco'; Population: 292600), (City: 'K鰇shetau'; Country: 'Kazakstan'; Population: 123400), (City: 'K鰈n'; Country: 'Germany'; Population: 962507), (City: 'K鴅enhavn'; Country: 'Denmark'; Population: 495699), (City: 'K黭on'; Country: 'Uzbekistan'; Population: 190100), (City: 'K黷ahya'; Country: 'Turkey'; Population: 144761), (City: 'La Ceiba'; Country: 'Honduras'; Population: 89200), (City: 'La Habana'; Country: 'Cuba'; Population: 2256000), (City: 'La Matanza'; Country: 'Argentina'; Population: 1266461), (City: 'La Paz'; Country: 'Bolivia'; Population: 758141), (City: 'La Paz'; Country: 'Mexico'; Population: 213045), (City: 'La Paz'; Country: 'Mexico'; Population: 196708), (City: 'La Plata'; Country: 'Argentina'; Population: 521936), (City: 'La Rioja'; Country: 'Argentina'; Population: 138117), (City: 'La Romana'; Country: 'Dominican Republic'; Population: 140204), (City: 'La Serena'; Country: 'Chile'; Population: 137409), (City: 'La Spezia'; Country: 'Italy'; Population: 95504), (City: 'Ladysmith'; Country: 'South Africa'; Population: 89292), (City: 'Lafayette'; Country: 'United States'; Population: 110257), (City: 'Lafia'; Country: 'Nigeria'; Population: 122500), (City: 'Lages'; Country: 'Brazil'; Population: 139570), (City: 'Lagos'; Country: 'Nigeria'; Population: 1518000), (City: 'Lagos de Moreno'; Country: 'Mexico'; Population: 127949), (City: 'Lahore'; Country: 'Pakistan'; Population: 5063499), (City: 'Lahti'; Country: 'Finland'; Population: 96921), (City: 'Laiwu'; Country: 'China'; Population: 246833), (City: 'Laiyang'; Country: 'China'; Population: 137080), (City: 'Laizhou'; Country: 'China'; Population: 198664), (City: 'Lakewood'; Country: 'United States'; Population: 144126), (City: 'Lalbahadur Nagar'; Country: 'India'; Population: 155500), (City: 'Lalitapur'; Country: 'Nepal'; Population: 145847), (City: 'Lambar'; Country: 'Paraguay'; Population: 99681), (City: 'Lancaster'; Country: 'United States'; Population: 118718), (City: 'Langfang'; Country: 'China'; Population: 148105), (City: 'Lansing'; Country: 'United States'; Population: 119128), (City: 'Lanzhou'; Country: 'China'; Population: 1565800), (City: 'Lan鷖'; Country: 'Argentina'; Population: 469735), (City: 'Laoag'; Country: 'Philippines'; Population: 94466), (City: 'Laohekou'; Country: 'China'; Population: 123366), (City: 'Lapu-Lapu'; Country: 'Philippines'; Population: 217019), (City: 'Laredo'; Country: 'United States'; Population: 176576), (City: 'Larisa'; Country: 'Greece'; Population: 113090), (City: 'Larkana'; Country: 'Pakistan'; Population: 270366), (City: 'Las Heras'; Country: 'Argentina'; Population: 145823), (City: 'Las Margaritas'; Country: 'Mexico'; Population: 97389), (City: 'Las Palmas de Gran Canaria'; Country: 'Spain'; Population: 354757), (City: 'Las Pi馻s'; Country: 'Philippines'; Population: 472780), (City: 'Las Vegas'; Country: 'United States'; Population: 478434), (City: 'Lashio (Lasho)'; Country: 'Myanmar'; Population: 107600), (City: 'Latakia'; Country: 'Syria'; Population: 264563), (City: 'Latina'; Country: 'Italy'; Population: 114099), (City: 'Latur'; Country: 'India'; Population: 197408), (City: 'Lauro de Freitas'; Country: 'Brazil'; Population: 109236), (City: 'Lausanne'; Country: 'Switzerland'; Population: 114500), (City: 'Laval'; Country: 'Canada'; Population: 330393), (City: 'Le Havre'; Country: 'France'; Population: 190905), (City: 'Le Mans'; Country: 'France'; Population: 146105), (City: 'Le-Cap-Ha飔ien'; Country: 'Haiti'; Population: 102233), (City: 'Lecce'; Country: 'Italy'; Population: 98208), (City: 'Leeds'; Country: 'United Kingdom'; Population: 424194), (City: 'Legan閟'; Country: 'Spain'; Population: 173163), (City: 'Legazpi'; Country: 'Philippines'; Population: 157010), (City: 'Legnica'; Country: 'Poland'; Population: 109335), (City: 'Leicester'; Country: 'United Kingdom'; Population: 294000), (City: 'Leiden'; Country: 'Netherlands'; Population: 117196), (City: 'Leipzig'; Country: 'Germany'; Population: 489532), (City: 'Leiyang'; Country: 'China'; Population: 130115), (City: 'Lengshuijiang'; Country: 'China'; Population: 137994), (City: 'Leninsk-Kuznetski'; Country: 'Russian Federation'; Population: 113800), (City: 'Lerdo'; Country: 'Mexico'; Population: 112272), (City: 'Lerma'; Country: 'Mexico'; Population: 99714), (City: 'Les Abymes'; Country: 'Guadeloupe'; Population: 62947), (City: 'Leshan'; Country: 'China'; Population: 341128), (City: 'Leverkusen'; Country: 'Germany'; Population: 160841), (City: 'Lexington-Fayette'; Country: 'United States'; Population: 260512), (City: 'Le髇'; Country: 'Spain'; Population: 139809), (City: 'Le髇'; Country: 'Mexico'; Population: 1133576), (City: 'Le髇'; Country: 'Nicaragua'; Population: 123865), (City: 'Lhasa'; Country: 'China'; Population: 120000), (City: 'Lhokseumawe'; Country: 'Indonesia'; Population: 109600), (City: 'Liangcheng'; Country: 'China'; Population: 156307), (City: 'Lianyuan'; Country: 'China'; Population: 118858), (City: 'Lianyungang'; Country: 'China'; Population: 354139), (City: 'Liaocheng'; Country: 'China'; Population: 207844), (City: 'Liaoyang'; Country: 'China'; Population: 492559), (City: 'Liaoyuan'; Country: 'China'; Population: 354141), (City: 'Liberec'; Country: 'Czech Republic'; Population: 99155), (City: 'Libreville'; Country: 'Gabon'; Population: 419000), (City: 'Lida'; Country: 'Belarus'; Population: 101000), (City: 'Liepaja'; Country: 'Latvia'; Population: 89439), (City: 'Ligao'; Country: 'Philippines'; Population: 90603), (City: 'Likasi'; Country: 'Congo, The Democratic Republic of the'; Population: 299118), (City: 'Liling'; Country: 'China'; Population: 108504), (City: 'Lille'; Country: 'France'; Population: 184657), (City: 'Lilongwe'; Country: 'Malawi'; Population: 435964), (City: 'Lima'; Country: 'Peru'; Population: 6464693), (City: 'Limassol'; Country: 'Cyprus'; Population: 154400), (City: 'Limeira'; Country: 'Brazil'; Population: 245497), (City: 'Limoges'; Country: 'France'; Population: 133968), (City: 'Linchuan'; Country: 'China'; Population: 121949), (City: 'Lincoln'; Country: 'United States'; Population: 225581), (City: 'Linfen'; Country: 'China'; Population: 187309), (City: 'Linhai'; Country: 'China'; Population: 90870), (City: 'Linhares'; Country: 'Brazil'; Population: 106278), (City: 'Linhe'; Country: 'China'; Population: 133183), (City: 'Link鰌ing'; Country: 'Sweden'; Population: 133168), (City: 'Linqing'; Country: 'China'; Population: 123958), (City: 'Linyi'; Country: 'China'; Population: 324720), (City: 'Linz'; Country: 'Austria'; Population: 188022), (City: 'Lipa'; Country: 'Philippines'; Population: 218447), (City: 'Lipetsk'; Country: 'Russian Federation'; Population: 521000), (City: 'Lisboa'; Country: 'Portugal'; Population: 563210), (City: 'Little Rock'; Country: 'United States'; Population: 183133), (City: 'Liupanshui'; Country: 'China'; Population: 363954), (City: 'Liuzhou'; Country: 'China'; Population: 610000), (City: 'Liu碼n'; Country: 'China'; Population: 144248), (City: 'Liverpool'; Country: 'United Kingdom'; Population: 461000), (City: 'Livonia'; Country: 'United States'; Population: 100545), (City: 'Livorno'; Country: 'Italy'; Population: 161673), (City: 'Liyang'; Country: 'China'; Population: 109520), (City: 'Li鑗e'; Country: 'Belgium'; Population: 185639), (City: 'Ljubertsy'; Country: 'Russian Federation'; Population: 163900), (City: 'Ljubljana'; Country: 'Slovenia'; Population: 270986), (City: 'Lleida (L閞ida)'; Country: 'Spain'; Population: 112207), (City: 'Lobito'; Country: 'Angola'; Population: 130000), (City: 'Logro駉'; Country: 'Spain'; Population: 127093), (City: 'Loja'; Country: 'Ecuador'; Population: 123875), (City: 'Lomas de Zamora'; Country: 'Argentina'; Population: 622013), (City: 'Lom'; Country: 'Togo'; Population: 375000), (City: 'London'; Country: 'United Kingdom'; Population: 7285000), (City: 'London'; Country: 'Canada'; Population: 339917), (City: 'Londrina'; Country: 'Brazil'; Population: 432257), (City: 'Long Beach'; Country: 'United States'; Population: 461522), (City: 'Long Xuyen'; Country: 'Vietnam'; Population: 132681), (City: 'Longjing'; Country: 'China'; Population: 139417), (City: 'Longkou'; Country: 'China'; Population: 148362), (City: 'Longueuil'; Country: 'Canada'; Population: 127977), (City: 'Longyan'; Country: 'China'; Population: 134481), (City: 'Longyearbyen'; Country: 'Svalbard and Jan Mayen'; Population: 1438), (City: 'Los Angeles'; Country: 'Chile'; Population: 158215), (City: 'Los Angeles'; Country: 'United States'; Population: 3694820), (City: 'Los Cabos'; Country: 'Mexico'; Population: 105199), (City: 'Los Teques'; Country: 'Venezuela'; Population: 178784), (City: 'Loudi'; Country: 'China'; Population: 128418), (City: 'Louisville'; Country: 'United States'; Population: 256231), (City: 'Lowell'; Country: 'United States'; Population: 105167), (City: 'Lower Hutt'; Country: 'New Zealand'; Population: 98100), (City: 'Luanda'; Country: 'Angola'; Population: 2022000), (City: 'Luanshya'; Country: 'Zambia'; Population: 118100), (City: 'Lubao'; Country: 'Philippines'; Population: 125699), (City: 'Lubbock'; Country: 'United States'; Population: 199564), (City: 'Lublin'; Country: 'Poland'; Population: 356251), (City: 'Lubumbashi'; Country: 'Congo, The Democratic Republic of the'; Population: 851381), (City: 'Lucena'; Country: 'Philippines'; Population: 196075), (City: 'Luchou'; Country: 'Taiwan'; Population: 160516), (City: 'Lucknow'; Country: 'India'; Population: 1619115), (City: 'Ludhiana'; Country: 'India'; Population: 1042740), (City: 'Ludwigshafen am Rhein'; Country: 'Germany'; Population: 163771), (City: 'Lugansk'; Country: 'Ukraine'; Population: 469000), (City: 'Lund'; Country: 'Sweden'; Population: 98948), (City: 'Lungtan'; Country: 'Taiwan'; Population: 103088), (City: 'Luohe'; Country: 'China'; Population: 126438), (City: 'Luoyang'; Country: 'China'; Population: 760000), (City: 'Lusaka'; Country: 'Zambia'; Population: 1317000), (City: 'Luton'; Country: 'United Kingdom'; Population: 183000), (City: 'Lutsk'; Country: 'Ukraine'; Population: 217000), (City: 'Luxembourg [Luxemburg/L雝zebuerg]'; Country: 'Luxembourg'; Population: 80700), (City: 'Luxor'; Country: 'Egypt'; Population: 360503), (City: 'Luzhou'; Country: 'China'; Population: 262892), (City: 'Luzi鈔ia'; Country: 'Brazil'; Population: 125597), (City: 'Lviv'; Country: 'Ukraine'; Population: 788000), (City: 'Lyon'; Country: 'France'; Population: 445452), (City: 'Lysyt歛nsk'; Country: 'Ukraine'; Population: 116000), (City: 'L碒ospitalet de Llobregat'; Country: 'Spain'; Population: 247986), (City: 'L醶aro C醨denas'; Country: 'Mexico'; Population: 170878), (City: 'L骴z'; Country: 'Poland'; Population: 800110), (City: 'L黚eck'; Country: 'Germany'; Population: 213326), (City: 'L黱en'; Country: 'Germany'; Population: 92044), (City: 'Maastricht'; Country: 'Netherlands'; Population: 122087), (City: 'Mabalacat'; Country: 'Philippines'; Population: 171045), (City: 'Macao'; Country: 'Macao'; Population: 437500), (City: 'Macap'; Country: 'Brazil'; Population: 256033), (City: 'Maca'; Country: 'Brazil'; Population: 125597), (City: 'Macei'; Country: 'Brazil'; Population: 786288), (City: 'Machakos'; Country: 'Kenya'; Population: 116293), (City: 'Machala'; Country: 'Ecuador'; Population: 210368), (City: 'Machida'; Country: 'Japan'; Population: 364197), (City: 'Machilipatnam (Masulipatam)'; Country: 'India'; Population: 159110), (City: 'Macon'; Country: 'United States'; Population: 113336), (City: 'Macuspana'; Country: 'Mexico'; Population: 133795), (City: 'Madison'; Country: 'United States'; Population: 208054), (City: 'Madiun'; Country: 'Indonesia'; Population: 171532), (City: 'Madrid'; Country: 'Spain'; Population: 2879052), (City: 'Madurai'; Country: 'India'; Population: 977856), (City: 'Maebashi'; Country: 'Japan'; Population: 284473), (City: 'Magadan'; Country: 'Russian Federation'; Population: 121000), (City: 'Magdeburg'; Country: 'Germany'; Population: 235073), (City: 'Magelang'; Country: 'Indonesia'; Population: 123800), (City: 'Magnitogorsk'; Country: 'Russian Federation'; Population: 427900), (City: 'Mag'; Country: 'Brazil'; Population: 196147), (City: 'Mahabad'; Country: 'Iran'; Population: 107799), (City: 'Mahajanga'; Country: 'Madagascar'; Population: 100807), (City: 'Mahat歬ala'; Country: 'Russian Federation'; Population: 332800), (City: 'Mahbubnagar'; Country: 'India'; Population: 116833), (City: 'Maicao'; Country: 'Colombia'; Population: 108053), (City: 'Maidstone'; Country: 'United Kingdom'; Population: 90878), (City: 'Maiduguri'; Country: 'Nigeria'; Population: 320000), (City: 'Maikop'; Country: 'Russian Federation'; Population: 167300), (City: 'Mainz'; Country: 'Germany'; Population: 183134), (City: 'Maizuru'; Country: 'Japan'; Population: 94784), (City: 'Majalaya'; Country: 'Indonesia'; Population: 93200), (City: 'Makati'; Country: 'Philippines'; Population: 444867), (City: 'Makijivka'; Country: 'Ukraine'; Population: 384000), (City: 'Makurdi'; Country: 'Nigeria'; Population: 123100), (City: 'Malabo'; Country: 'Equatorial Guinea'; Population: 40000), (City: 'Malabon'; Country: 'Philippines'; Population: 338855), (City: 'Malang'; Country: 'Indonesia'; Population: 716862), (City: 'Malasiqui'; Country: 'Philippines'; Population: 113190), (City: 'Malatya'; Country: 'Turkey'; Population: 330312), (City: 'Malaybalay'; Country: 'Philippines'; Population: 123672), (City: 'Malayer'; Country: 'Iran'; Population: 144373), (City: 'Male'; Country: 'Maldives'; Population: 71000), (City: 'Malegaon'; Country: 'India'; Population: 342595), (City: 'Malita'; Country: 'Philippines'; Population: 100000), (City: 'Malkajgiri'; Country: 'India'; Population: 126066), (City: 'Mallawi'; Country: 'Egypt'; Population: 119283), (City: 'Malm'; Country: 'Sweden'; Population: 259579), (City: 'Malolos'; Country: 'Philippines'; Population: 175291), (City: 'Malungon'; Country: 'Philippines'; Population: 93232), (City: 'Malvinas Argentinas'; Country: 'Argentina'; Population: 290335), (City: 'Mamoutzou'; Country: 'Mayotte'; Population: 12000), (City: 'Manado'; Country: 'Indonesia'; Population: 332288), (City: 'Managua'; Country: 'Nicaragua'; Population: 959000), (City: 'Manaus'; Country: 'Brazil'; Population: 1255049), (City: 'Manchester'; Country: 'United Kingdom'; Population: 430000), (City: 'Manchester'; Country: 'United States'; Population: 107006), (City: 'Mandalay'; Country: 'Myanmar'; Population: 885300), (City: 'Mandaluyong'; Country: 'Philippines'; Population: 278474), (City: 'Mandasor'; Country: 'India'; Population: 95758), (City: 'Mandaue'; Country: 'Philippines'; Population: 259728), (City: 'Mandi Bahauddin'; Country: 'Pakistan'; Population: 97300), (City: 'Mandi Burewala'; Country: 'Pakistan'; Population: 149900), (City: 'Mandya'; Country: 'India'; Population: 120265), (City: 'Mangalore'; Country: 'India'; Population: 273304), (City: 'Mango'; Country: 'India'; Population: 110024), (City: 'Manila'; Country: 'Philippines'; Population: 1581082), (City: 'Manisa'; Country: 'Turkey'; Population: 207148), (City: 'Manizales'; Country: 'Colombia'; Population: 337580), (City: 'Mannheim'; Country: 'Germany'; Population: 307730), (City: 'Manta'; Country: 'Ecuador'; Population: 164739), (City: 'Manukau'; Country: 'New Zealand'; Population: 281800), (City: 'Manzanillo'; Country: 'Cuba'; Population: 109350), (City: 'Manzanillo'; Country: 'Mexico'; Population: 124014), (City: 'Manzhouli'; Country: 'China'; Population: 120023), (City: 'Maoming'; Country: 'China'; Population: 178683), (City: 'Maputo'; Country: 'Mozambique'; Population: 1018938), (City: 'Mar del Plata'; Country: 'Argentina'; Population: 512880), (City: 'Marab'; Country: 'Brazil'; Population: 167795), (City: 'Maracana'; Country: 'Brazil'; Population: 162022), (City: 'Maracay'; Country: 'Venezuela'; Population: 444443), (City: 'Maraca韇o'; Country: 'Venezuela'; Population: 1304776), (City: 'Maradi'; Country: 'Niger'; Population: 112965), (City: 'Maragheh'; Country: 'Iran'; Population: 132318), (City: 'Marand'; Country: 'Iran'; Population: 96400), (City: 'Marawi'; Country: 'Philippines'; Population: 131090), (City: 'Marbella'; Country: 'Spain'; Population: 101144), (City: 'Mardan'; Country: 'Pakistan'; Population: 244511), (City: 'Margilon'; Country: 'Uzbekistan'; Population: 140800), (City: 'Maribor'; Country: 'Slovenia'; Population: 115532), (City: 'Marikina'; Country: 'Philippines'; Population: 391170), (City: 'Marilao'; Country: 'Philippines'; Population: 101017), (City: 'Maring'; Country: 'Brazil'; Population: 286461), (City: 'Mariupol'; Country: 'Ukraine'; Population: 490000), (City: 'Markham'; Country: 'Canada'; Population: 189098), (City: 'Marl'; Country: 'Germany'; Population: 93735), (City: 'Maroua'; Country: 'Cameroon'; Population: 143000), (City: 'Marrakech'; Country: 'Morocco'; Population: 621914), (City: 'Marseille'; Country: 'France'; Population: 798430), (City: 'Mart韓ez de la Torre'; Country: 'Mexico'; Population: 118815), (City: 'Marv Dasht'; Country: 'Iran'; Population: 103579), (City: 'Mary'; Country: 'Turkmenistan'; Population: 101000), (City: 'Mar韑ia'; Country: 'Brazil'; Population: 188691), (City: 'Masan'; Country: 'South Korea'; Population: 441242), (City: 'Masaya'; Country: 'Nicaragua'; Population: 88971), (City: 'Maseru'; Country: 'Lesotho'; Population: 297000), (City: 'Mashhad'; Country: 'Iran'; Population: 1887405), (City: 'Masjed-e-Soleyman'; Country: 'Iran'; Population: 116883), (City: 'Masqat'; Country: 'Oman'; Population: 51969), (City: 'Mata-Utu'; Country: 'Wallis and Futuna'; Population: 1137), (City: 'Matadi'; Country: 'Congo, The Democratic Republic of the'; Population: 172730), (City: 'Matamoros'; Country: 'Mexico'; Population: 416428), (City: 'Matamoros'; Country: 'Mexico'; Population: 91858), (City: 'Matanzas'; Country: 'Cuba'; Population: 123273), (City: 'Mataram'; Country: 'Indonesia'; Population: 306600), (City: 'Matar'; Country: 'Spain'; Population: 104095), (City: 'Mathura'; Country: 'India'; Population: 226691), (City: 'Mati'; Country: 'Philippines'; Population: 105908), (City: 'Matola'; Country: 'Mozambique'; Population: 424662), (City: 'Matsubara'; Country: 'Japan'; Population: 135010), (City: 'Matsudo'; Country: 'Japan'; Population: 461126), (City: 'Matsue'; Country: 'Japan'; Population: 149821), (City: 'Matsumoto'; Country: 'Japan'; Population: 206801), (City: 'Matsusaka'; Country: 'Japan'; Population: 123582), (City: 'Matsuyama'; Country: 'Japan'; Population: 466133), (City: 'Matur韓'; Country: 'Venezuela'; Population: 319726), (City: 'Maunath Bhanjan'; Country: 'India'; Population: 136697), (City: 'Mau'; Country: 'Brazil'; Population: 375055), (City: 'Maxixe'; Country: 'Mozambique'; Population: 93985), (City: 'Mayag黣z'; Country: 'Puerto Rico'; Population: 98434), (City: 'Mazar-e-Sharif'; Country: 'Afghanistan'; Population: 127800), (City: 'Mazatl醤'; Country: 'Mexico'; Population: 380265), (City: 'Ma碼nshan'; Country: 'China'; Population: 305421), (City: 'Mbabane'; Country: 'Swaziland'; Population: 61000), (City: 'Mbandaka'; Country: 'Congo, The Democratic Republic of the'; Population: 169841), (City: 'Mbeya'; Country: 'Tanzania'; Population: 130800), (City: 'Mbour'; Country: 'Senegal'; Population: 109300), (City: 'Mbuji-Mayi'; Country: 'Congo, The Democratic Republic of the'; Population: 806475), (City: 'McAllen'; Country: 'United States'; Population: 106414), (City: 'Mdantsane'; Country: 'South Africa'; Population: 182639), (City: 'Medan'; Country: 'Indonesia'; Population: 1843919), (City: 'Medell韓'; Country: 'Colombia'; Population: 1861265), (City: 'Medina'; Country: 'Saudi Arabia'; Population: 608300), (City: 'Meerut'; Country: 'India'; Population: 753778), (City: 'Meerut Cantonment'; Country: 'India'; Population: 94876), (City: 'Meihekou'; Country: 'China'; Population: 209038), (City: 'Meikhtila'; Country: 'Myanmar'; Population: 129700), (City: 'Meixian'; Country: 'China'; Population: 132156), (City: 'Mejicanos'; Country: 'El Salvador'; Population: 138800), (City: 'Mekele'; Country: 'Ethiopia'; Population: 96938), (City: 'Mekka'; Country: 'Saudi Arabia'; Population: 965700), (City: 'Mekn鑣'; Country: 'Morocco'; Population: 460000), (City: 'Melbourne'; Country: 'Australia'; Population: 2865329), (City: 'Melipilla'; Country: 'Chile'; Population: 91056), (City: 'Melitopol'; Country: 'Ukraine'; Population: 169000), (City: 'Memphis'; Country: 'United States'; Population: 650100), (City: 'Mendoza'; Country: 'Argentina'; Population: 123027), (City: 'Mergui (Myeik)'; Country: 'Myanmar'; Population: 122700), (City: 'Merlo'; Country: 'Argentina'; Population: 463846), (City: 'Mersin (I鏴l)'; Country: 'Turkey'; Population: 587212), (City: 'Meru'; Country: 'Kenya'; Population: 94947), (City: 'Mesa'; Country: 'United States'; Population: 396375), (City: 'Mesquite'; Country: 'United States'; Population: 124523), (City: 'Messina'; Country: 'Italy'; Population: 259156), (City: 'Metairie'; Country: 'United States'; Population: 149428), (City: 'Metepec'; Country: 'Mexico'; Population: 194265), (City: 'Metz'; Country: 'France'; Population: 123776), (City: 'Mexicali'; Country: 'Mexico'; Population: 764902), (City: 'Mexico'; Country: 'Philippines'; Population: 109481), (City: 'Meycauayan'; Country: 'Philippines'; Population: 163037), (City: 'Mezduret歟nsk'; Country: 'Russian Federation'; Population: 104400), (City: 'Miami'; Country: 'United States'; Population: 362470), (City: 'Miami Beach'; Country: 'United States'; Population: 97855), (City: 'Miandoab'; Country: 'Iran'; Population: 90100), (City: 'Mianyang'; Country: 'China'; Population: 262947), (City: 'Miaoli'; Country: 'Taiwan'; Population: 90000), (City: 'Miass'; Country: 'Russian Federation'; Population: 166200), (City: 'Middlesbrough'; Country: 'United Kingdom'; Population: 145000), (City: 'Midland'; Country: 'United States'; Population: 98293), (City: 'Midnapore (Medinipur)'; Country: 'India'; Population: 125498), (City: 'Midsayap'; Country: 'Philippines'; Population: 105760), (City: 'Milagro'; Country: 'Ecuador'; Population: 124177), (City: 'Milano'; Country: 'Italy'; Population: 1300977), (City: 'Milwaukee'; Country: 'United States'; Population: 596974), (City: 'Minatitl醤'; Country: 'Mexico'; Population: 152983), (City: 'Mingora'; Country: 'Pakistan'; Population: 174500), (City: 'Ming溏evir'; Country: 'Azerbaijan'; Population: 93900), (City: 'Minna'; Country: 'Nigeria'; Population: 136900), (City: 'Minneapolis'; Country: 'United States'; Population: 382618), (City: 'Minoo'; Country: 'Japan'; Population: 127026), (City: 'Minsk'; Country: 'Belarus'; Population: 1674000), (City: 'Mira Bhayandar'; Country: 'India'; Population: 175372), (City: 'Miraj'; Country: 'India'; Population: 125407), (City: 'Mirpur Khas'; Country: 'Pakistan'; Population: 184500), (City: 'Miryang'; Country: 'South Korea'; Population: 121501), (City: 'Mirzapur-cum-Vindhyachal'; Country: 'India'; Population: 169336), (City: 'Misato'; Country: 'Japan'; Population: 132957), (City: 'Mishan'; Country: 'China'; Population: 132744), (City: 'Mishima'; Country: 'Japan'; Population: 109699), (City: 'Miskolc'; Country: 'Hungary'; Population: 172357), (City: 'Misrata'; Country: 'Libyan Arab Jamahiriya'; Population: 121669), (City: 'Mission Viejo'; Country: 'United States'; Population: 98049), (City: 'Mississauga'; Country: 'Canada'; Population: 608072), (City: 'Mit Ghamr'; Country: 'Egypt'; Population: 101801), (City: 'Mitaka'; Country: 'Japan'; Population: 167268), (City: 'Mito'; Country: 'Japan'; Population: 246559), (City: 'Mit歶rinsk'; Country: 'Russian Federation'; Population: 120700), (City: 'Mixco'; Country: 'Guatemala'; Population: 209791), (City: 'Miyakonojo'; Country: 'Japan'; Population: 133183), (City: 'Miyazaki'; Country: 'Japan'; Population: 303784), (City: 'Mobara'; Country: 'Japan'; Population: 91664), (City: 'Mobile'; Country: 'United States'; Population: 198915), (City: 'Mocuba'; Country: 'Mozambique'; Population: 124700), (City: 'Modena'; Country: 'Italy'; Population: 176022), (City: 'Modesto'; Country: 'United States'; Population: 188856), (City: 'Modinagar'; Country: 'India'; Population: 101660), (City: 'Moers'; Country: 'Germany'; Population: 106837), (City: 'Moga'; Country: 'India'; Population: 108304), (City: 'Mogadishu'; Country: 'Somalia'; Population: 997000), (City: 'Mogiljov'; Country: 'Belarus'; Population: 356000), (City: 'Mohammedia'; Country: 'Morocco'; Population: 154706), (City: 'Moji das Cruzes'; Country: 'Brazil'; Population: 339194), (City: 'Moji-Gua鐄'; Country: 'Brazil'; Population: 123782), (City: 'Mojokerto'; Country: 'Indonesia'; Population: 96626), (City: 'Mokpo'; Country: 'South Korea'; Population: 247452), (City: 'Molodet歯o'; Country: 'Belarus'; Population: 97000), (City: 'Mombasa'; Country: 'Kenya'; Population: 461753), (City: 'Monaco-Ville'; Country: 'Monaco'; Population: 1234), (City: 'Monclova'; Country: 'Mexico'; Population: 193657), (City: 'Monrovia'; Country: 'Liberia'; Population: 850000), (City: 'Mons'; Country: 'Belgium'; Population: 90935), (City: 'Monte-Carlo'; Country: 'Monaco'; Population: 13154), (City: 'Monterrey'; Country: 'Mexico'; Population: 1108499), (City: 'Monter韆'; Country: 'Colombia'; Population: 248245), (City: 'Montes Claros'; Country: 'Brazil'; Population: 286058), (City: 'Montevideo'; Country: 'Uruguay'; Population: 1236000), (City: 'Montgomery'; Country: 'United States'; Population: 201568), (City: 'Montpellier'; Country: 'France'; Population: 225392), (City: 'Montreuil'; Country: 'France'; Population: 90674), (City: 'Montr閍l'; Country: 'Canada'; Population: 1016376), (City: 'Monywa'; Country: 'Myanmar'; Population: 138600), (City: 'Monza'; Country: 'Italy'; Population: 119516), (City: 'Moradabad'; Country: 'India'; Population: 429214), (City: 'Moratuwa'; Country: 'Sri Lanka'; Population: 190000), (City: 'Morelia'; Country: 'Mexico'; Population: 619958), (City: 'Morena'; Country: 'India'; Population: 147124), (City: 'Moreno'; Country: 'Argentina'; Population: 356993), (City: 'Moreno Valley'; Country: 'United States'; Population: 142381), (City: 'Moriguchi'; Country: 'Japan'; Population: 155941), (City: 'Morioka'; Country: 'Japan'; Population: 287353), (City: 'Morogoro'; Country: 'Tanzania'; Population: 117800), (City: 'Moroni'; Country: 'Comoros'; Population: 36000), (City: 'Morvi'; Country: 'India'; Population: 90357), (City: 'Mor髇'; Country: 'Argentina'; Population: 349246), (City: 'Moscow'; Country: 'Russian Federation'; Population: 8389200), (City: 'Moshi'; Country: 'Tanzania'; Population: 96800), (City: 'Mossor'; Country: 'Brazil'; Population: 214901), (City: 'Mostaganem'; Country: 'Algeria'; Population: 115212), (City: 'Mosul'; Country: 'Iraq'; Population: 879000), (City: 'Moulmein (Mawlamyine)'; Country: 'Myanmar'; Population: 307900), (City: 'Moundou'; Country: 'Chad'; Population: 99500), (City: 'Mount Darwin'; Country: 'Zimbabwe'; Population: 164362), (City: 'Mozyr'; Country: 'Belarus'; Population: 110000), (City: 'Mudanjiang'; Country: 'China'; Population: 570000), (City: 'Mufulira'; Country: 'Zambia'; Population: 123900), (City: 'Mukat歟ve'; Country: 'Ukraine'; Population: 89000), (City: 'Mulhouse'; Country: 'France'; Population: 110359), (City: 'Multan'; Country: 'Pakistan'; Population: 1182441), (City: 'Mumbai (Bombay)'; Country: 'India'; Population: 10500000), (City: 'Mun-gyong'; Country: 'South Korea'; Population: 92239), (City: 'Munger (Monghyr)'; Country: 'India'; Population: 150112), (City: 'Munich [M黱chen]'; Country: 'Germany'; Population: 1194560), (City: 'Muntinlupa'; Country: 'Philippines'; Population: 379310), (City: 'Murcia'; Country: 'Spain'; Population: 353504), (City: 'Muridke'; Country: 'Pakistan'; Population: 108600), (City: 'Murmansk'; Country: 'Russian Federation'; Population: 376300), (City: 'Murom'; Country: 'Russian Federation'; Population: 142400), (City: 'Muroran'; Country: 'Japan'; Population: 108275), (City: 'Murwara (Katni)'; Country: 'India'; Population: 163431), (City: 'Musashino'; Country: 'Japan'; Population: 134426), (City: 'Mushin'; Country: 'Nigeria'; Population: 333200), (City: 'Mutare'; Country: 'Zimbabwe'; Population: 131367), (City: 'Muzaffargarh'; Country: 'Pakistan'; Population: 121600), (City: 'Muzaffarnagar'; Country: 'India'; Population: 240609), (City: 'Muzaffarpur'; Country: 'India'; Population: 241107), (City: 'Mwanza'; Country: 'Tanzania'; Population: 172300), (City: 'Mwene-Ditu'; Country: 'Congo, The Democratic Republic of the'; Population: 137459), (City: 'My Tho'; Country: 'Vietnam'; Population: 108404), (City: 'Myingyan'; Country: 'Myanmar'; Population: 103600), (City: 'Mykolajiv'; Country: 'Ukraine'; Population: 508000), (City: 'Mymensingh'; Country: 'Bangladesh'; Population: 188713), (City: 'Mysore'; Country: 'India'; Population: 480692), (City: 'Myti歵歩'; Country: 'Russian Federation'; Population: 155700), (City: 'M醠aga'; Country: 'Spain'; Population: 530553), (City: 'M閞ida'; Country: 'Mexico'; Population: 703324), (City: 'M閞ida'; Country: 'Venezuela'; Population: 224887), (City: 'M髎toles'; Country: 'Spain'; Population: 195351), (City: 'M鰊chengladbach'; Country: 'Germany'; Population: 263697), (City: 'M黮heim an der Ruhr'; Country: 'Germany'; Population: 173895), (City: 'M黱ster'; Country: 'Germany'; Population: 264670), (City: 'Nabereznyje T歟lny'; Country: 'Russian Federation'; Population: 514700), (City: 'Nablus'; Country: 'Palestine'; Population: 100231), (City: 'Nadiad'; Country: 'India'; Population: 167051), (City: 'Nador'; Country: 'Morocco'; Population: 112450), (City: 'Naga'; Country: 'Philippines'; Population: 137810), (City: 'Nagano'; Country: 'Japan'; Population: 361391), (City: 'Nagaoka'; Country: 'Japan'; Population: 192407), (City: 'Nagaon'; Country: 'India'; Population: 93350), (City: 'Nagar Coil'; Country: 'India'; Population: 190084), (City: 'Nagareyama'; Country: 'Japan'; Population: 147738), (City: 'Nagasaki'; Country: 'Japan'; Population: 432759), (City: 'Nagoya'; Country: 'Japan'; Population: 2154376), (City: 'Nagpur'; Country: 'India'; Population: 1624752), (City: 'Naha'; Country: 'Japan'; Population: 299851), (City: 'Nahodka'; Country: 'Russian Federation'; Population: 157700), (City: 'Naihati'; Country: 'India'; Population: 132701), (City: 'Nairobi'; Country: 'Kenya'; Population: 2290000), (City: 'Najafabad'; Country: 'Iran'; Population: 178498), (City: 'Najran'; Country: 'Saudi Arabia'; Population: 91000), (City: 'Naju'; Country: 'South Korea'; Population: 107831), (City: 'Nakhon Pathom'; Country: 'Thailand'; Population: 94100), (City: 'Nakhon Ratchasima'; Country: 'Thailand'; Population: 181400), (City: 'Nakhon Sawan'; Country: 'Thailand'; Population: 123800), (City: 'Nakuru'; Country: 'Kenya'; Population: 163927), (City: 'Nalt歩k'; Country: 'Russian Federation'; Population: 233400), (City: 'Nam Dinh'; Country: 'Vietnam'; Population: 171699), (City: 'Namangan'; Country: 'Uzbekistan'; Population: 370500), (City: 'Namibe'; Country: 'Angola'; Population: 118200), (City: 'Nampo'; Country: 'North Korea'; Population: 566200), (City: 'Nampula'; Country: 'Mozambique'; Population: 303346), (City: 'Namur'; Country: 'Belgium'; Population: 105419), (City: 'Namwon'; Country: 'South Korea'; Population: 103544), (City: 'Namyangju'; Country: 'South Korea'; Population: 229060), (City: 'Nanchang'; Country: 'China'; Population: 1691600), (City: 'Nanchong'; Country: 'China'; Population: 180273), (City: 'Nancy'; Country: 'France'; Population: 103605), (City: 'Nanded (Nander)'; Country: 'India'; Population: 275083), (City: 'Nandyal'; Country: 'India'; Population: 119813), (City: 'Nanking [Nanjing]'; Country: 'China'; Population: 2870300), (City: 'Nanning'; Country: 'China'; Population: 1161800), (City: 'Nanping'; Country: 'China'; Population: 195064), (City: 'Nantes'; Country: 'France'; Population: 270251), (City: 'Nantong'; Country: 'China'; Population: 343341), (City: 'Nantou'; Country: 'Taiwan'; Population: 104723), (City: 'Nanyang'; Country: 'China'; Population: 243303), (City: 'Naogaon'; Country: 'Bangladesh'; Population: 101266), (City: 'Naperville'; Country: 'United States'; Population: 128358), (City: 'Napoli'; Country: 'Italy'; Population: 1002619), (City: 'Nara'; Country: 'Japan'; Population: 362812), (City: 'Narashino'; Country: 'Japan'; Population: 152849), (City: 'Narayanganj'; Country: 'Bangladesh'; Population: 202134), (City: 'Narita'; Country: 'Japan'; Population: 91470), (City: 'Narsinghdi'; Country: 'Bangladesh'; Population: 98342), (City: 'Nashik (Nasik)'; Country: 'India'; Population: 656925), (City: 'Nashville-Davidson'; Country: 'United States'; Population: 569891), (City: 'Nassau'; Country: 'Bahamas'; Population: 172000), (City: 'Nasugbu'; Country: 'Philippines'; Population: 96113), (City: 'Natal'; Country: 'Brazil'; Population: 688955), (City: 'Naucalpan de Ju醨ez'; Country: 'Mexico'; Population: 857511), (City: 'Navadwip'; Country: 'India'; Population: 125037), (City: 'Navoi'; Country: 'Uzbekistan'; Population: 116300), (City: 'Navojoa'; Country: 'Mexico'; Population: 140495), (City: 'Navolato'; Country: 'Mexico'; Population: 145396), (City: 'Navotas'; Country: 'Philippines'; Population: 230403), (City: 'Navsari'; Country: 'India'; Population: 126089), (City: 'Nawabganj'; Country: 'Bangladesh'; Population: 130577), (City: 'Nawabshah'; Country: 'Pakistan'; Population: 183100), (City: 'Nazilli'; Country: 'Turkey'; Population: 99900), (City: 'Nazret'; Country: 'Ethiopia'; Population: 127842), (City: 'Na鏰la-Porto'; Country: 'Mozambique'; Population: 158248), (City: 'Ndola'; Country: 'Zambia'; Population: 329200), (City: 'Neftejugansk'; Country: 'Russian Federation'; Population: 97400), (City: 'Neftekamsk'; Country: 'Russian Federation'; Population: 115700), (City: 'Negombo'; Country: 'Sri Lanka'; Population: 100000), (City: 'Neijiang'; Country: 'China'; Population: 256012), (City: 'Neiva'; Country: 'Colombia'; Population: 300052), (City: 'Nellore'; Country: 'India'; Population: 316606), (City: 'Nepean'; Country: 'Canada'; Population: 115100), (City: 'Netanya'; Country: 'Israel'; Population: 154900), (City: 'Neuqu閚'; Country: 'Argentina'; Population: 167296), (City: 'Neuss'; Country: 'Germany'; Population: 149702), (City: 'Nevinnomyssk'; Country: 'Russian Federation'; Population: 132600), (City: 'New Bedford'; Country: 'United States'; Population: 94780), (City: 'New Bombay'; Country: 'India'; Population: 307297), (City: 'New Delhi'; Country: 'India'; Population: 301297), (City: 'New Haven'; Country: 'United States'; Population: 123626), (City: 'New Orleans'; Country: 'United States'; Population: 484674), (City: 'New York'; Country: 'United States'; Population: 8008278), (City: 'Newark'; Country: 'United States'; Population: 273546), (City: 'Newcastle'; Country: 'Australia'; Population: 270324), (City: 'Newcastle'; Country: 'South Africa'; Population: 222993), (City: 'Newcastle upon Tyne'; Country: 'United Kingdom'; Population: 189150), (City: 'Newport'; Country: 'United Kingdom'; Population: 139000), (City: 'Newport News'; Country: 'United States'; Population: 180150), (City: 'Neyagawa'; Country: 'Japan'; Population: 257315), (City: 'Neyshabur'; Country: 'Iran'; Population: 158847), (City: 'Neyveli'; Country: 'India'; Population: 118080), (City: 'Nezahualc髖otl'; Country: 'Mexico'; Population: 1224924), (City: 'Nha Trang'; Country: 'Vietnam'; Population: 221331), (City: 'Niamey'; Country: 'Niger'; Population: 420000), (City: 'Nice'; Country: 'France'; Population: 342738), (City: 'Nicol醩 Romero'; Country: 'Mexico'; Population: 269393), (City: 'Nicosia'; Country: 'Cyprus'; Population: 195000), (City: 'Nigel'; Country: 'South Africa'; Population: 96734), (City: 'Niigata'; Country: 'Japan'; Population: 497464), (City: 'Niihama'; Country: 'Japan'; Population: 127207), (City: 'Niiza'; Country: 'Japan'; Population: 147744), (City: 'Nijmegen'; Country: 'Netherlands'; Population: 152463), (City: 'Nikopol'; Country: 'Ukraine'; Population: 149000), (City: 'Nil髉olis'; Country: 'Brazil'; Population: 153383), (City: 'Ningbo'; Country: 'China'; Population: 1371200), (City: 'Nishinomiya'; Country: 'Japan'; Population: 397618), (City: 'Nishio'; Country: 'Japan'; Population: 100032), (City: 'Niter骾'; Country: 'Brazil'; Population: 459884), (City: 'Nizamabad'; Country: 'India'; Population: 241034), (City: 'Niznekamsk'; Country: 'Russian Federation'; Population: 223400), (City: 'Niznevartovsk'; Country: 'Russian Federation'; Population: 233900), (City: 'Nizni Novgorod'; Country: 'Russian Federation'; Population: 1357000), (City: 'Nizni Tagil'; Country: 'Russian Federation'; Population: 390900), (City: 'Ni'; Country: 'Yugoslavia'; Population: 175391), (City: 'Nkongsamba'; Country: 'Cameroon'; Population: 112454), (City: 'Nobeoka'; Country: 'Japan'; Population: 125547), (City: 'Noda'; Country: 'Japan'; Population: 121030), (City: 'Nogales'; Country: 'Mexico'; Population: 159103), (City: 'Noginsk'; Country: 'Russian Federation'; Population: 117200), (City: 'Noida'; Country: 'India'; Population: 146514), (City: 'Nojabrsk'; Country: 'Russian Federation'; Population: 97300), (City: 'Nonsan'; Country: 'South Korea'; Population: 146619), (City: 'Nonthaburi'; Country: 'Thailand'; Population: 292100), (City: 'Norfolk'; Country: 'United States'; Population: 234403), (City: 'Norilsk'; Country: 'Russian Federation'; Population: 140800), (City: 'Norman'; Country: 'United States'; Population: 94193), (City: 'Norrk鰌ing'; Country: 'Sweden'; Population: 122199), (City: 'North Barrackpur'; Country: 'India'; Population: 100513), (City: 'North Dum Dum'; Country: 'India'; Population: 149965), (City: 'North Las Vegas'; Country: 'United States'; Population: 115488), (City: 'North Shore'; Country: 'New Zealand'; Population: 187700), (City: 'North York'; Country: 'Canada'; Population: 622632), (City: 'Northampton'; Country: 'United Kingdom'; Population: 196000), (City: 'Norwalk'; Country: 'United States'; Population: 103298), (City: 'Norwich'; Country: 'United Kingdom'; Population: 124000), (City: 'Nossa Senhora do Socorro'; Country: 'Brazil'; Population: 131351), (City: 'Nottingham'; Country: 'United Kingdom'; Population: 287000), (City: 'Nouakchott'; Country: 'Mauritania'; Population: 667300), (City: 'Noum閍'; Country: 'New Caledonia'; Population: 76293), (City: 'Nou鈊hibou'; Country: 'Mauritania'; Population: 97600), (City: 'Nova Friburgo'; Country: 'Brazil'; Population: 170697), (City: 'Nova Igua鐄'; Country: 'Brazil'; Population: 862225), (City: 'Novara'; Country: 'Italy'; Population: 102037), (City: 'Novi Sad'; Country: 'Yugoslavia'; Population: 179626), (City: 'Novo Hamburgo'; Country: 'Brazil'; Population: 239940), (City: 'Novokuiby歟vsk'; Country: 'Russian Federation'; Population: 116200), (City: 'Novokuznetsk'; Country: 'Russian Federation'; Population: 561600), (City: 'Novomoskovsk'; Country: 'Russian Federation'; Population: 138100), (City: 'Novopolotsk'; Country: 'Belarus'; Population: 106000), (City: 'Novorossijsk'; Country: 'Russian Federation'; Population: 203300), (City: 'Novosibirsk'; Country: 'Russian Federation'; Population: 1398800), (City: 'Novotroitsk'; Country: 'Russian Federation'; Population: 109600), (City: 'Novot歟boksarsk'; Country: 'Russian Federation'; Population: 123400), (City: 'Novot歟rkassk'; Country: 'Russian Federation'; Population: 184400), (City: 'Novouralsk'; Country: 'Russian Federation'; Population: 93300), (City: 'Novo歛htinsk'; Country: 'Russian Federation'; Population: 101900), (City: 'Novyi Urengoi'; Country: 'Russian Federation'; Population: 89800), (City: 'Nowshera'; Country: 'Pakistan'; Population: 89400), (City: 'Nueva San Salvador'; Country: 'El Salvador'; Population: 98400), (City: 'Nuevo Laredo'; Country: 'Mexico'; Population: 310277), (City: 'Nukus'; Country: 'Uzbekistan'; Population: 194100), (City: 'Nuku碼lofa'; Country: 'Tonga'; Population: 22400), (City: 'Numazu'; Country: 'Japan'; Population: 211382), (City: 'Nuuk'; Country: 'Greenland'; Population: 13445), (City: 'Nyala'; Country: 'Sudan'; Population: 227183), (City: 'Nyeri'; Country: 'Kenya'; Population: 91258), (City: 'Nyiregyh醶a'; Country: 'Hungary'; Population: 112419), (City: 'N碊jam閚a'; Country: 'Chad'; Population: 530965), (City: 'N頼es'; Country: 'France'; Population: 133424), (City: 'N黵nberg'; Country: 'Germany'; Population: 486628), (City: 'Oakland'; Country: 'United States'; Population: 399484), (City: 'Oakville'; Country: 'Canada'; Population: 139192), (City: 'Oaxaca de Ju醨ez'; Country: 'Mexico'; Population: 256848), (City: 'Obeid'; Country: 'Sudan'; Population: 229425), (City: 'Oberhausen'; Country: 'Germany'; Population: 222349), (City: 'Oberholzer'; Country: 'South Africa'; Population: 164367), (City: 'Obihiro'; Country: 'Japan'; Population: 173685), (City: 'Obninsk'; Country: 'Russian Federation'; Population: 108300), (City: 'Oceanside'; Country: 'United States'; Population: 161029), (City: 'Ocosingo'; Country: 'Mexico'; Population: 171495), (City: 'Ocumare del Tuy'; Country: 'Venezuela'; Population: 97168), (City: 'Odawara'; Country: 'Japan'; Population: 200171), (City: 'Odense'; Country: 'Denmark'; Population: 183912), (City: 'Odesa'; Country: 'Ukraine'; Population: 1011000), (City: 'Odessa'; Country: 'United States'; Population: 89293), (City: 'Odintsovo'; Country: 'Russian Federation'; Population: 127400), (City: 'Offa'; Country: 'Nigeria'; Population: 197200), (City: 'Offenbach am Main'; Country: 'Germany'; Population: 116627), (City: 'Ogaki'; Country: 'Japan'; Population: 151758), (City: 'Ogbomosho'; Country: 'Nigeria'; Population: 730000), (City: 'Oita'; Country: 'Japan'; Population: 433401), (City: 'Oka-Akoko'; Country: 'Nigeria'; Population: 142900), (City: 'Okara'; Country: 'Pakistan'; Population: 200901), (City: 'Okayama'; Country: 'Japan'; Population: 624269), (City: 'Okazaki'; Country: 'Japan'; Population: 328711), (City: 'Okinawa'; Country: 'Japan'; Population: 117748), (City: 'Oklahoma City'; Country: 'United States'; Population: 506132), (City: 'Oktjabrski'; Country: 'Russian Federation'; Population: 111500), (City: 'Oldbury/Smethwick (Warley)'; Country: 'United Kingdom'; Population: 145542), (City: 'Oldenburg'; Country: 'Germany'; Population: 154125), (City: 'Oldham'; Country: 'United Kingdom'; Population: 103931), (City: 'Oleksandrija'; Country: 'Ukraine'; Population: 99000), (City: 'Olinda'; Country: 'Brazil'; Population: 354732), (City: 'Olmalik'; Country: 'Uzbekistan'; Population: 114900), (City: 'Olomouc'; Country: 'Czech Republic'; Population: 102702), (City: 'Olongapo'; Country: 'Philippines'; Population: 194260), (City: 'Olsztyn'; Country: 'Poland'; Population: 170904), (City: 'Omaha'; Country: 'United States'; Population: 390007), (City: 'Omdurman'; Country: 'Sudan'; Population: 1271403), (City: 'Ome'; Country: 'Japan'; Population: 139216), (City: 'Omiya'; Country: 'Japan'; Population: 441649), (City: 'Omsk'; Country: 'Russian Federation'; Population: 1148900), (City: 'Omuta'; Country: 'Japan'; Population: 142889), (City: 'Ondo'; Country: 'Nigeria'; Population: 173600), (City: 'Ongole'; Country: 'India'; Population: 100836), (City: 'Onitsha'; Country: 'Nigeria'; Population: 371900), (City: 'Onomichi'; Country: 'Japan'; Population: 93756), (City: 'Ontario'; Country: 'United States'; Population: 158007), (City: 'Opole'; Country: 'Poland'; Population: 129553), (City: 'Oradea'; Country: 'Romania'; Population: 222239), (City: 'Orai'; Country: 'India'; Population: 98640), (City: 'Oral'; Country: 'Kazakstan'; Population: 195500), (City: 'Oran'; Country: 'Algeria'; Population: 609823), (City: 'Orange'; Country: 'United States'; Population: 128821), (City: 'Oranjestad'; Country: 'Aruba'; Population: 29034), (City: 'Ordu'; Country: 'Turkey'; Population: 133642), (City: 'Orehovo-Zujevo'; Country: 'Russian Federation'; Population: 124900), (City: 'Orenburg'; Country: 'Russian Federation'; Population: 523600), (City: 'Orizaba'; Country: 'Mexico'; Population: 118488), (City: 'Orjol'; Country: 'Russian Federation'; Population: 344500), (City: 'Orlando'; Country: 'United States'; Population: 185951), (City: 'Orl閍ns'; Country: 'France'; Population: 113126), (City: 'Ormoc'; Country: 'Philippines'; Population: 154297), (City: 'Orsk'; Country: 'Russian Federation'; Population: 273900), (City: 'Oruro'; Country: 'Bolivia'; Population: 223553), (City: 'Or歛'; Country: 'Belarus'; Population: 124000), (City: 'Osaka'; Country: 'Japan'; Population: 2595674), (City: 'Osasco'; Country: 'Brazil'; Population: 659604), (City: 'Osh'; Country: 'Kyrgyzstan'; Population: 222700), (City: 'Oshawa'; Country: 'Canada'; Population: 140173), (City: 'Oshogbo'; Country: 'Nigeria'; Population: 476800), (City: 'Osijek'; Country: 'Croatia'; Population: 104761), (City: 'Oslo'; Country: 'Norway'; Population: 508726), (City: 'Osmaniye'; Country: 'Turkey'; Population: 146003), (City: 'Osnabr點k'; Country: 'Germany'; Population: 164539), (City: 'Osorno'; Country: 'Chile'; Population: 141468), (City: 'Ostrava'; Country: 'Czech Republic'; Population: 320041), (City: 'Ota'; Country: 'Japan'; Population: 145317), (City: 'Otaru'; Country: 'Japan'; Population: 155784), (City: 'Oth髇 P. Blanco (Chetumal)'; Country: 'Mexico'; Population: 208014), (City: 'Otsu'; Country: 'Japan'; Population: 282070), (City: 'Ottawa'; Country: 'Canada'; Population: 335277), (City: 'Ouagadougou'; Country: 'Burkina Faso'; Population: 824000), (City: 'Oujda'; Country: 'Morocco'; Population: 365382), (City: 'Oulu'; Country: 'Finland'; Population: 120753), (City: 'Ourense (Orense)'; Country: 'Spain'; Population: 109120), (City: 'Ourinhos'; Country: 'Brazil'; Population: 96291), (City: 'Ovalle'; Country: 'Chile'; Population: 94854), (City: 'Overland Park'; Country: 'United States'; Population: 149080), (City: 'Oviedo'; Country: 'Spain'; Population: 200453), (City: 'Owo'; Country: 'Nigeria'; Population: 183500), (City: 'Oxford'; Country: 'United Kingdom'; Population: 144000), (City: 'Oxnard'; Country: 'United States'; Population: 170358), (City: 'Oyama'; Country: 'Japan'; Population: 152820), (City: 'Oyo'; Country: 'Nigeria'; Population: 256400), (City: 'Ozamis'; Country: 'Philippines'; Population: 110420), (City: 'Paarl'; Country: 'South Africa'; Population: 105768), (City: 'Pabna'; Country: 'Bangladesh'; Population: 103277), (City: 'Pachuca de Soto'; Country: 'Mexico'; Population: 244688), (City: 'Padang'; Country: 'Indonesia'; Population: 534474), (City: 'Padang Sidempuan'; Country: 'Indonesia'; Population: 91200), (City: 'Paderborn'; Country: 'Germany'; Population: 137647), (City: 'Padova'; Country: 'Italy'; Population: 211391), (City: 'Pagadian'; Country: 'Philippines'; Population: 142515), (City: 'Pagakku (Pakokku)'; Country: 'Myanmar'; Population: 94800), (City: 'Paju'; Country: 'South Korea'; Population: 163379), (City: 'Pak Kret'; Country: 'Thailand'; Population: 126055), (City: 'Pak Pattan'; Country: 'Pakistan'; Population: 107800), (City: 'Palangka Raya'; Country: 'Indonesia'; Population: 99693), (City: 'Palayankottai'; Country: 'India'; Population: 97662), (City: 'Palembang'; Country: 'Indonesia'; Population: 1222764), (City: 'Palermo'; Country: 'Italy'; Population: 683794), (City: 'Palghat (Palakkad)'; Country: 'India'; Population: 123289), (City: 'Palho鏰'; Country: 'Brazil'; Population: 89465), (City: 'Pali'; Country: 'India'; Population: 136842), (City: 'Palikir'; Country: 'Micronesia, Federated States of'; Population: 8600), (City: 'Pallavaram'; Country: 'India'; Population: 111866), (City: 'Palma de Mallorca'; Country: 'Spain'; Population: 326993), (City: 'Palmas'; Country: 'Brazil'; Population: 121919), (City: 'Palmdale'; Country: 'United States'; Population: 116670), (City: 'Palmira'; Country: 'Colombia'; Population: 226509), (City: 'Palu'; Country: 'Indonesia'; Population: 142800), (City: 'Pamplona [Iru馻]'; Country: 'Spain'; Population: 180483), (City: 'Panabo'; Country: 'Philippines'; Population: 133950), (City: 'Panchiao'; Country: 'Taiwan'; Population: 523850), (City: 'Panevezys'; Country: 'Lithuania'; Population: 133695), (City: 'Pangkal Pinang'; Country: 'Indonesia'; Population: 124000), (City: 'Panihati'; Country: 'India'; Population: 275990), (City: 'Panipat'; Country: 'India'; Population: 215218), (City: 'Panjin'; Country: 'China'; Population: 362773), (City: 'Panzhihua'; Country: 'China'; Population: 415466), (City: 'Papantla'; Country: 'Mexico'; Population: 170123), (City: 'Papeete'; Country: 'French Polynesia'; Population: 25553), (City: 'Paradise'; Country: 'United States'; Population: 124682), (City: 'Parakou'; Country: 'Benin'; Population: 103577), (City: 'Paramaribo'; Country: 'Suriname'; Population: 112000), (City: 'Paranagu'; Country: 'Brazil'; Population: 126076), (City: 'Paran'; Country: 'Argentina'; Population: 207041), (City: 'Para馻que'; Country: 'Philippines'; Population: 449811), (City: 'Parbhani'; Country: 'India'; Population: 190255), (City: 'Pardubice'; Country: 'Czech Republic'; Population: 91309), (City: 'Paris'; Country: 'France'; Population: 2125246), (City: 'Parma'; Country: 'Italy'; Population: 168717), (City: 'Parnamirim'; Country: 'Brazil'; Population: 96210), (City: 'Parna韇a'; Country: 'Brazil'; Population: 129756), (City: 'Pasadena'; Country: 'United States'; Population: 141674), (City: 'Pasadena'; Country: 'United States'; Population: 133936), (City: 'Pasay'; Country: 'Philippines'; Population: 354908), (City: 'Pasig'; Country: 'Philippines'; Population: 505058), (City: 'Passo Fundo'; Country: 'Brazil'; Population: 166343), (City: 'Passos'; Country: 'Brazil'; Population: 98570), (City: 'Pasto'; Country: 'Colombia'; Population: 332396), (City: 'Pasuruan'; Country: 'Indonesia'; Population: 134019), (City: 'Patan'; Country: 'India'; Population: 96109), (City: 'Pate'; Country: 'Taiwan'; Population: 161700), (City: 'Paterson'; Country: 'United States'; Population: 149222), (City: 'Pathankot'; Country: 'India'; Population: 123930), (City: 'Patiala'; Country: 'India'; Population: 238368), (City: 'Patna'; Country: 'India'; Population: 917243), (City: 'Patos'; Country: 'Brazil'; Population: 90519), (City: 'Patos de Minas'; Country: 'Brazil'; Population: 119262), (City: 'Patras'; Country: 'Greece'; Population: 153344), (City: 'Paulista'; Country: 'Brazil'; Population: 248473), (City: 'Paulo Afonso'; Country: 'Brazil'; Population: 97291), (City: 'Pavlodar'; Country: 'Kazakstan'; Population: 300500), (City: 'Pavlograd'; Country: 'Ukraine'; Population: 127000), (City: 'Pegu (Bago)'; Country: 'Myanmar'; Population: 190900), (City: 'Pekalongan'; Country: 'Indonesia'; Population: 301504), (City: 'Pekan Baru'; Country: 'Indonesia'; Population: 438638), (City: 'Peking'; Country: 'China'; Population: 7472000), (City: 'Pelotas'; Country: 'Brazil'; Population: 315415), (City: 'Pemalang'; Country: 'Indonesia'; Population: 103500), (City: 'Pematang Siantar'; Country: 'Indonesia'; Population: 203056), (City: 'Pembroke Pines'; Country: 'United States'; Population: 137427), (City: 'Penza'; Country: 'Russian Federation'; Population: 532200), (City: 'Peoria'; Country: 'United States'; Population: 112936), (City: 'Peoria'; Country: 'United States'; Population: 108364), (City: 'Percut Sei Tuan'; Country: 'Indonesia'; Population: 129000), (City: 'Pereira'; Country: 'Colombia'; Population: 381725), (City: 'Peristerion'; Country: 'Greece'; Population: 137288), (City: 'Perm'; Country: 'Russian Federation'; Population: 1009700), (City: 'Perpignan'; Country: 'France'; Population: 105115), (City: 'Perth'; Country: 'Australia'; Population: 1096829), (City: 'Perugia'; Country: 'Italy'; Population: 156673), (City: 'Pervouralsk'; Country: 'Russian Federation'; Population: 136100), (City: 'Pesaro'; Country: 'Italy'; Population: 88987), (City: 'Pescara'; Country: 'Italy'; Population: 115698), (City: 'Peshawar'; Country: 'Pakistan'; Population: 988005), (City: 'Petah Tiqwa'; Country: 'Israel'; Population: 159400), (City: 'Petaling Jaya'; Country: 'Malaysia'; Population: 254350), (City: 'Petare'; Country: 'Venezuela'; Population: 488868), (City: 'Peterborough'; Country: 'United Kingdom'; Population: 156000), (City: 'Petrolina'; Country: 'Brazil'; Population: 210540), (City: 'Petropavl'; Country: 'Kazakstan'; Population: 203500), (City: 'Petropavlovsk-Kamt歛tski'; Country: 'Russian Federation'; Population: 194100), (City: 'Petroskoi'; Country: 'Russian Federation'; Population: 282100), (City: 'Petr髉olis'; Country: 'Brazil'; Population: 279183), (City: 'Pforzheim'; Country: 'Germany'; Population: 117227), (City: 'Phan Thi阾'; Country: 'Vietnam'; Population: 114236), (City: 'Philadelphia'; Country: 'United States'; Population: 1517550), (City: 'Phnom Penh'; Country: 'Cambodia'; Population: 570155), (City: 'Phoenix'; Country: 'United States'; Population: 1321045), (City: 'Phyongsong'; Country: 'North Korea'; Population: 272934), (City: 'Piacenza'; Country: 'Italy'; Population: 98384), (City: 'Piatra Neamt'; Country: 'Romania'; Population: 125070), (City: 'Piedras Negras'; Country: 'Mexico'; Population: 127898), (City: 'Pietermaritzburg'; Country: 'South Africa'; Population: 370190), (City: 'Pihkova'; Country: 'Russian Federation'; Population: 201500), (City: 'Pikine'; Country: 'Senegal'; Population: 855287), (City: 'Pilar'; Country: 'Argentina'; Population: 113428), (City: 'Pilibhit'; Country: 'India'; Population: 106605), (City: 'Pimpri-Chinchwad'; Country: 'India'; Population: 517083), (City: 'Pinang'; Country: 'Malaysia'; Population: 219603), (City: 'Pinar del R韔'; Country: 'Cuba'; Population: 142100), (City: 'Pindamonhangaba'; Country: 'Brazil'; Population: 121904), (City: 'Pinetown'; Country: 'South Africa'; Population: 378810), (City: 'Pingchen'; Country: 'Taiwan'; Population: 188344), (City: 'Pingdingshan'; Country: 'China'; Population: 410775), (City: 'Pingdu'; Country: 'China'; Population: 150123), (City: 'Pingliang'; Country: 'China'; Population: 99265), (City: 'Pingtung'; Country: 'Taiwan'; Population: 214727), (City: 'Pingxiang'; Country: 'China'; Population: 425579), (City: 'Pingyi'; Country: 'China'; Population: 89373), (City: 'Pinhais'; Country: 'Brazil'; Population: 98198), (City: 'Pinsk'; Country: 'Belarus'; Population: 130000), (City: 'Piracicaba'; Country: 'Brazil'; Population: 319104), (City: 'Pireus'; Country: 'Greece'; Population: 182671), (City: 'Pisa'; Country: 'Italy'; Population: 92379), (City: 'Pitesti'; Country: 'Romania'; Population: 187170), (City: 'Pittsburgh'; Country: 'United States'; Population: 334563), (City: 'Piura'; Country: 'Peru'; Population: 325000), (City: 'Pjatigorsk'; Country: 'Russian Federation'; Population: 132500), (City: 'Plano'; Country: 'United States'; Population: 222030), (City: 'Pleven'; Country: 'Bulgaria'; Population: 121952), (City: 'Plock'; Country: 'Poland'; Population: 131011), (City: 'Ploiesti'; Country: 'Romania'; Population: 251348), (City: 'Plovdiv'; Country: 'Bulgaria'; Population: 342584), (City: 'Plymouth'; Country: 'United Kingdom'; Population: 253000), (City: 'Plymouth'; Country: 'Montserrat'; Population: 2000), (City: 'Plzen'; Country: 'Czech Republic'; Population: 166759), (City: 'Podgorica'; Country: 'Yugoslavia'; Population: 135000), (City: 'Podolsk'; Country: 'Russian Federation'; Population: 194300), (City: 'Pohang'; Country: 'South Korea'; Population: 508899), (City: 'Pointe-Noire'; Country: 'Congo'; Population: 500000), (City: 'Pokhara'; Country: 'Nepal'; Population: 146318), (City: 'Polomolok'; Country: 'Philippines'; Population: 110709), (City: 'Pomona'; Country: 'United States'; Population: 149473), (City: 'Ponce'; Country: 'Puerto Rico'; Population: 186475), (City: 'Pondicherry'; Country: 'India'; Population: 203065), (City: 'Pondok Aren'; Country: 'Indonesia'; Population: 92700), (City: 'Pondokgede'; Country: 'Indonesia'; Population: 263200), (City: 'Ponta Grossa'; Country: 'Brazil'; Population: 268013), (City: 'Pontianak'; Country: 'Indonesia'; Population: 409632), (City: 'Poole'; Country: 'United Kingdom'; Population: 141000), (City: 'Popay醤'; Country: 'Colombia'; Population: 200719), (City: 'Porbandar'; Country: 'India'; Population: 116671), (City: 'Port Elizabeth'; Country: 'South Africa'; Population: 752319), (City: 'Port Harcourt'; Country: 'Nigeria'; Population: 410000), (City: 'Port Moresby'; Country: 'Papua New Guinea'; Population: 247000), (City: 'Port Said'; Country: 'Egypt'; Population: 469533), (City: 'Port Sudan'; Country: 'Sudan'; Population: 308195), (City: 'Port-Louis'; Country: 'Mauritius'; Population: 138200), (City: 'Port-Vila'; Country: 'Vanuatu'; Population: 33700), (City: 'Port-au-Prince'; Country: 'Haiti'; Population: 884472), (City: 'Port-of-Spain'; Country: 'Trinidad and Tobago'; Population: 43396), (City: 'Portland'; Country: 'United States'; Population: 529121), (City: 'Portmore'; Country: 'Jamaica'; Population: 99799), (City: 'Porto'; Country: 'Portugal'; Population: 273060), (City: 'Porto Alegre'; Country: 'Brazil'; Population: 1314032), (City: 'Porto Velho'; Country: 'Brazil'; Population: 309750), (City: 'Porto-Novo'; Country: 'Benin'; Population: 194000), (City: 'Portoviejo'; Country: 'Ecuador'; Population: 176413), (City: 'Portsmouth'; Country: 'United Kingdom'; Population: 190000), (City: 'Portsmouth'; Country: 'United States'; Population: 100565), (City: 'Poryong'; Country: 'South Korea'; Population: 122604), (City: 'Posadas'; Country: 'Argentina'; Population: 201273), (City: 'Potchefstroom'; Country: 'South Africa'; Population: 101817), (City: 'Potos'; Country: 'Bolivia'; Population: 140642), (City: 'Potsdam'; Country: 'Germany'; Population: 128983), (City: 'Pouso Alegre'; Country: 'Brazil'; Population: 100028), (City: 'Poza Rica de Hidalgo'; Country: 'Mexico'; Population: 152678), (City: 'Poznan'; Country: 'Poland'; Population: 576899), (City: 'Pozuelos'; Country: 'Venezuela'; Population: 105690), (City: 'Po'; Country: 'Brazil'; Population: 89236), (City: 'Po鏾s de Caldas'; Country: 'Brazil'; Population: 129683), (City: 'Praha'; Country: 'Czech Republic'; Population: 1181126), (City: 'Praia'; Country: 'Cape Verde'; Population: 94800), (City: 'Praia Grande'; Country: 'Brazil'; Population: 168434), (City: 'Prato'; Country: 'Italy'; Population: 172473), (City: 'Presidente Prudente'; Country: 'Brazil'; Population: 185340), (City: 'Preston'; Country: 'United Kingdom'; Population: 135000), (City: 'Pretoria'; Country: 'South Africa'; Population: 658630), (City: 'Pre歰v'; Country: 'Slovakia'; Population: 93977), (City: 'Prizren'; Country: 'Yugoslavia'; Population: 92303), (City: 'Pri歵ina'; Country: 'Yugoslavia'; Population: 155496), (City: 'Probolinggo'; Country: 'Indonesia'; Population: 120770), (City: 'Proddatur'; Country: 'India'; Population: 133914), (City: 'Prokopjevsk'; Country: 'Russian Federation'; Population: 237300), (City: 'Prome (Pyay)'; Country: 'Myanmar'; Population: 105700), (City: 'Providence'; Country: 'United States'; Population: 173618), (City: 'Provo'; Country: 'United States'; Population: 105166), (City: 'Pucallpa'; Country: 'Peru'; Population: 220866), (City: 'Puchon'; Country: 'South Korea'; Population: 779412), (City: 'Pudukkottai'; Country: 'India'; Population: 98619), (City: 'Puebla'; Country: 'Mexico'; Population: 1346176), (City: 'Pueblo'; Country: 'United States'; Population: 102121), (City: 'Puente Alto'; Country: 'Chile'; Population: 386236), (City: 'Puerto Cabello'; Country: 'Venezuela'; Population: 187722), (City: 'Puerto La Cruz'; Country: 'Venezuela'; Population: 155700), (City: 'Puerto Montt'; Country: 'Chile'; Population: 152194), (City: 'Puerto Princesa'; Country: 'Philippines'; Population: 161912), (City: 'Puerto Vallarta'; Country: 'Mexico'; Population: 183741), (City: 'Pultava [Poltava]'; Country: 'Ukraine'; Population: 313000), (City: 'Pune'; Country: 'India'; Population: 1566651), (City: 'Puno'; Country: 'Peru'; Population: 101578), (City: 'Punta Arenas'; Country: 'Chile'; Population: 125631), (City: 'Punto Fijo'; Country: 'Venezuela'; Population: 167215), (City: 'Puqi'; Country: 'China'; Population: 117264), (City: 'Puri'; Country: 'India'; Population: 125199), (City: 'Purnea (Purnia)'; Country: 'India'; Population: 114912), (City: 'Purulia'; Country: 'India'; Population: 92574), (City: 'Purwakarta'; Country: 'Indonesia'; Population: 95900), (City: 'Purwokerto'; Country: 'Indonesia'; Population: 202500), (City: 'Pusan'; Country: 'South Korea'; Population: 3804522), (City: 'Putian'; Country: 'China'; Population: 91030), (City: 'Puyang'; Country: 'China'; Population: 175988), (City: 'Pu歬in'; Country: 'Russian Federation'; Population: 92900), (City: 'Pyongtaek'; Country: 'South Korea'; Population: 312927), (City: 'Pyongyang'; Country: 'North Korea'; Population: 2484000), (City: 'P醤uco'; Country: 'Mexico'; Population: 90551), (City: 'P閏s'; Country: 'Hungary'; Population: 157332), (City: 'P閚jamo'; Country: 'Mexico'; Population: 143927), (City: 'Qaemshahr'; Country: 'Iran'; Population: 143286), (City: 'Qalyub'; Country: 'Egypt'; Population: 97200), (City: 'Qandahar'; Country: 'Afghanistan'; Population: 237500), (City: 'Qaraghandy'; Country: 'Kazakstan'; Population: 436900), (City: 'Qaramay'; Country: 'China'; Population: 197602), (City: 'Qarchak'; Country: 'Iran'; Population: 142690), (City: 'Qashqar'; Country: 'China'; Population: 174570), (City: 'Qazvin'; Country: 'Iran'; Population: 291117), (City: 'Qianjiang'; Country: 'China'; Population: 205504), (City: 'Qidong'; Country: 'China'; Population: 126872), (City: 'Qina'; Country: 'Egypt'; Population: 171275), (City: 'Qingdao'; Country: 'China'; Population: 2596000), (City: 'Qingyuan'; Country: 'China'; Population: 164641), (City: 'Qingzhou'; Country: 'China'; Population: 128258), (City: 'Qinhuangdao'; Country: 'China'; Population: 364972), (City: 'Qinzhou'; Country: 'China'; Population: 114586), (City: 'Qiqihar'; Country: 'China'; Population: 1070000), (City: 'Qitaihe'; Country: 'China'; Population: 214957), (City: 'Qods'; Country: 'Iran'; Population: 138278), (City: 'Qom'; Country: 'Iran'; Population: 777677), (City: 'Qomsheh'; Country: 'Iran'; Population: 89800), (City: 'Qostanay'; Country: 'Kazakstan'; Population: 221400), (City: 'Quanzhou'; Country: 'China'; Population: 185154), (City: 'Queimados'; Country: 'Brazil'; Population: 115020), (City: 'Quelimane'; Country: 'Mozambique'; Population: 150116), (City: 'Quer閠aro'; Country: 'Mexico'; Population: 639839), (City: 'Quetta'; Country: 'Pakistan'; Population: 560307), (City: 'Quetzaltenango'; Country: 'Guatemala'; Population: 90801), (City: 'Quevedo'; Country: 'Ecuador'; Population: 129631), (City: 'Quezon'; Country: 'Philippines'; Population: 2173831), (City: 'Quilmes'; Country: 'Argentina'; Population: 559249), (City: 'Quilpu'; Country: 'Chile'; Population: 118857), (City: 'Quito'; Country: 'Ecuador'; Population: 1573458), (City: 'Qujing'; Country: 'China'; Population: 178669), (City: 'Qutubullapur'; Country: 'India'; Population: 105380), (City: 'Quy Nhon'; Country: 'Vietnam'; Population: 163385), (City: 'Quzhou'; Country: 'China'; Population: 112373), (City: 'Qu閎ec'; Country: 'Canada'; Population: 167264), (City: 'Qyzylorda'; Country: 'Kazakstan'; Population: 157400), (City: 'Rabat'; Country: 'Morocco'; Population: 623457), (City: 'Rach Gia'; Country: 'Vietnam'; Population: 141132), (City: 'Radom'; Country: 'Poland'; Population: 232262), (City: 'Rae Bareli'; Country: 'India'; Population: 129904), (City: 'Rafah'; Country: 'Palestine'; Population: 92020), (City: 'Rafsanjan'; Country: 'Iran'; Population: 98300), (City: 'Rahim Yar Khan'; Country: 'Pakistan'; Population: 228479), (City: 'Raichur'; Country: 'India'; Population: 157551), (City: 'Raiganj'; Country: 'India'; Population: 151045), (City: 'Raigarh'; Country: 'India'; Population: 89166), (City: 'Raipur'; Country: 'India'; Population: 438639), (City: 'Raj Nandgaon'; Country: 'India'; Population: 125371), (City: 'Rajahmundry'; Country: 'India'; Population: 324851), (City: 'Rajapalaiyam'; Country: 'India'; Population: 114202), (City: 'Rajkot'; Country: 'India'; Population: 559407), (City: 'Rajshahi'; Country: 'Bangladesh'; Population: 294056), (City: 'Raleigh'; Country: 'United States'; Population: 276093), (City: 'Ramagundam'; Country: 'India'; Population: 214384), (City: 'Ramat Gan'; Country: 'Israel'; Population: 126900), (City: 'Rampur'; Country: 'India'; Population: 243742), (City: 'Rancagua'; Country: 'Chile'; Population: 212977), (City: 'Ranchi'; Country: 'India'; Population: 599306), (City: 'Rancho Cucamonga'; Country: 'United States'; Population: 127743), (City: 'Randburg'; Country: 'South Africa'; Population: 341288), (City: 'Randfontein'; Country: 'South Africa'; Population: 120838), (City: 'Rangoon (Yangon)'; Country: 'Myanmar'; Population: 3361700), (City: 'Rangpur'; Country: 'Bangladesh'; Population: 191398), (City: 'Rasht'; Country: 'Iran'; Population: 417748), (City: 'Ratingen'; Country: 'Germany'; Population: 90951), (City: 'Ratlam'; Country: 'India'; Population: 183375), (City: 'Raurkela'; Country: 'India'; Population: 215489), (City: 'Raurkela Civil Township'; Country: 'India'; Population: 140408), (City: 'Ravenna'; Country: 'Italy'; Population: 138418), (City: 'Rawalpindi'; Country: 'Pakistan'; Population: 1406214), (City: 'Reading'; Country: 'United Kingdom'; Population: 148000), (City: 'Recife'; Country: 'Brazil'; Population: 1378087), (City: 'Recklinghausen'; Country: 'Germany'; Population: 125022), (City: 'Regensburg'; Country: 'Germany'; Population: 125236), (City: 'Reggio di Calabria'; Country: 'Italy'; Population: 179617), (City: 'Reggio nell?Emilia'; Country: 'Italy'; Population: 143664), (City: 'Regina'; Country: 'Canada'; Population: 180400), (City: 'Rehovot'; Country: 'Israel'; Population: 90300), (City: 'Reims'; Country: 'France'; Population: 187206), (City: 'Remscheid'; Country: 'Germany'; Population: 120125), (City: 'Rennes'; Country: 'France'; Population: 206229), (City: 'Reno'; Country: 'United States'; Population: 180480), (City: 'Renqiu'; Country: 'China'; Population: 114256), (City: 'Resende'; Country: 'Brazil'; Population: 100627), (City: 'Resistencia'; Country: 'Argentina'; Population: 229212), (City: 'Resita'; Country: 'Romania'; Population: 93976), (City: 'Reutlingen'; Country: 'Germany'; Population: 110343), (City: 'Rewa'; Country: 'India'; Population: 128981), (City: 'Reykjav韐'; Country: 'Iceland'; Population: 109184), (City: 'Reynosa'; Country: 'Mexico'; Population: 419776), (City: 'Ribeir鉶 Pires'; Country: 'Brazil'; Population: 108121), (City: 'Ribeir鉶 Preto'; Country: 'Brazil'; Population: 473276), (City: 'Ribeir鉶 das Neves'; Country: 'Brazil'; Population: 232685), (City: 'Richmond'; Country: 'Canada'; Population: 148867), (City: 'Richmond'; Country: 'United States'; Population: 197790), (City: 'Richmond'; Country: 'United States'; Population: 94100), (City: 'Richmond Hill'; Country: 'Canada'; Population: 116428), (City: 'Riga'; Country: 'Latvia'; Population: 764328), (City: 'Rijeka'; Country: 'Croatia'; Population: 167964), (City: 'Rimini'; Country: 'Italy'; Population: 131062), (City: 'Rio Branco'; Country: 'Brazil'; Population: 259537), (City: 'Rio Claro'; Country: 'Brazil'; Population: 163551), (City: 'Rio Grande'; Country: 'Brazil'; Population: 182222), (City: 'Rio Verde'; Country: 'Brazil'; Population: 107755), (City: 'Rio de Janeiro'; Country: 'Brazil'; Population: 5598953), (City: 'Rishon Le Ziyyon'; Country: 'Israel'; Population: 188200), (City: 'Rishra'; Country: 'India'; Population: 102649), (City: 'Riverside'; Country: 'United States'; Population: 255166), (City: 'Rivne'; Country: 'Ukraine'; Population: 245000), (City: 'Riyadh'; Country: 'Saudi Arabia'; Population: 3324000), (City: 'Rizhao'; Country: 'China'; Population: 185048), (City: 'Rjazan'; Country: 'Russian Federation'; Population: 529900), (City: 'Road Town'; Country: 'Virgin Islands, British'; Population: 8000), (City: 'Roanoke'; Country: 'United States'; Population: 93357), (City: 'Rochdale'; Country: 'United Kingdom'; Population: 94313), (City: 'Rochester'; Country: 'United States'; Population: 219773), (City: 'Rockford'; Country: 'United States'; Population: 150115), (City: 'Rodriguez (Montalban)'; Country: 'Philippines'; Population: 115167), (City: 'Rohtak'; Country: 'India'; Population: 233400), (City: 'Roma'; Country: 'Italy'; Population: 2643581), (City: 'Rondon髉olis'; Country: 'Brazil'; Population: 155115), (City: 'Roodepoort'; Country: 'South Africa'; Population: 279340), (City: 'Rosario'; Country: 'Argentina'; Population: 907718), (City: 'Roseau'; Country: 'Dominica'; Population: 16243), (City: 'Rostock'; Country: 'Germany'; Population: 203279), (City: 'Rostov-na-Donu'; Country: 'Russian Federation'; Population: 1012700), (City: 'Rotherham'; Country: 'United Kingdom'; Population: 121380), (City: 'Rotterdam'; Country: 'Netherlands'; Population: 593321), (City: 'Roubaix'; Country: 'France'; Population: 96984), (City: 'Rouen'; Country: 'France'; Population: 106592), (City: 'Roxas'; Country: 'Philippines'; Population: 126352), (City: 'Rubtsovsk'; Country: 'Russian Federation'; Population: 162600), (City: 'Ruda Slaska'; Country: 'Poland'; Population: 159665), (City: 'Rudnyy'; Country: 'Kazakstan'; Population: 109500), (City: 'Rufisque'; Country: 'Senegal'; Population: 150000), (City: 'Rui碼n'; Country: 'China'; Population: 156468), (City: 'Ruse'; Country: 'Bulgaria'; Population: 166467), (City: 'Rustavi'; Country: 'Georgia'; Population: 155400), (City: 'Rustenburg'; Country: 'South Africa'; Population: 97008), (City: 'Rybinsk'; Country: 'Russian Federation'; Population: 239600), (City: 'Rybnik'; Country: 'Poland'; Population: 144582), (City: 'Rzesz體'; Country: 'Poland'; Population: 162049), (City: 'R鈓nicu V鈒cea'; Country: 'Romania'; Population: 119741), (City: 'R韔 Bravo'; Country: 'Mexico'; Population: 103901), (City: 'R韔 Cuarto'; Country: 'Argentina'; Population: 134355), (City: 'R韔bamba'; Country: 'Ecuador'; Population: 123163), (City: 'Saanich'; Country: 'Canada'; Population: 101388), (City: 'Saarbr點ken'; Country: 'Germany'; Population: 183836), (City: 'Sabadell'; Country: 'Spain'; Population: 184859), (City: 'Sabar'; Country: 'Brazil'; Population: 107781), (City: 'Sabzevar'; Country: 'Iran'; Population: 170738), (City: 'Sachon'; Country: 'South Korea'; Population: 113494), (City: 'Sacramento'; Country: 'United States'; Population: 407018), (City: 'Sadiqabad'; Country: 'Pakistan'; Population: 141500), (City: 'Safi'; Country: 'Morocco'; Population: 262300), (City: 'Saga'; Country: 'Japan'; Population: 170034), (City: 'Sagamihara'; Country: 'Japan'; Population: 586300), (City: 'Sagar'; Country: 'India'; Population: 195346), (City: 'Sagay'; Country: 'Philippines'; Population: 129765), (City: 'Saharanpur'; Country: 'India'; Population: 374945), (City: 'Sahiwal'; Country: 'Pakistan'; Population: 207388), (City: 'Saidpur'; Country: 'Bangladesh'; Population: 96777), (City: 'Saint Catharines'; Country: 'Canada'; Population: 136216), (City: 'Saint George'; Country: 'Bermuda'; Population: 1800), (City: 'Saint George磗'; Country: 'Grenada'; Population: 4621), (City: 'Saint Helens'; Country: 'United Kingdom'; Population: 106293), (City: 'Saint Helier'; Country: 'United Kingdom'; Population: 27523), (City: 'Saint John磗'; Country: 'Antigua and Barbuda'; Population: 24000), (City: 'Saint John磗'; Country: 'Canada'; Population: 101936), (City: 'Saint Louis'; Country: 'United States'; Population: 348189), (City: 'Saint Paul'; Country: 'United States'; Population: 287151), (City: 'Saint Petersburg'; Country: 'United States'; Population: 248232), (City: 'Saint-Denis'; Country: 'R閡nion'; Population: 131480), (City: 'Saint-Louis'; Country: 'Senegal'; Population: 132400), (City: 'Saint-Pierre'; Country: 'Saint Pierre and Miquelon'; Population: 5808), (City: 'Sakado'; Country: 'Japan'; Population: 98221), (City: 'Sakai'; Country: 'Japan'; Population: 797735), (City: 'Sakarya (Adapazari)'; Country: 'Turkey'; Population: 190641), (City: 'Sakata'; Country: 'Japan'; Population: 101651), (City: 'Sakura'; Country: 'Japan'; Population: 168072), (City: 'Salala'; Country: 'Oman'; Population: 131813), (City: 'Salamanca'; Country: 'Spain'; Population: 158720), (City: 'Salamanca'; Country: 'Mexico'; Population: 226864), (City: 'Salatiga'; Country: 'Indonesia'; Population: 103000), (City: 'Salavat'; Country: 'Russian Federation'; Population: 156800), (City: 'Salem'; Country: 'India'; Population: 366712), (City: 'Salem'; Country: 'United States'; Population: 136924), (City: 'Salerno'; Country: 'Italy'; Population: 142055), (City: 'Salinas'; Country: 'United States'; Population: 151060), (City: 'Salt Lake City'; Country: 'United States'; Population: 181743), (City: 'Salta'; Country: 'Argentina'; Population: 367550), (City: 'Saltillo'; Country: 'Mexico'; Population: 577352), (City: 'Salto'; Country: 'Brazil'; Population: 96348), (City: 'Salvador'; Country: 'Brazil'; Population: 2302832), (City: 'Salvatierra'; Country: 'Mexico'; Population: 94322), (City: 'Salzburg'; Country: 'Austria'; Population: 144247), (City: 'Salzgitter'; Country: 'Germany'; Population: 112934), (City: 'Sal'; Country: 'Morocco'; Population: 504420), (City: 'Samara'; Country: 'Russian Federation'; Population: 1156100), (City: 'Samarinda'; Country: 'Indonesia'; Population: 399175), (City: 'Samarkand'; Country: 'Uzbekistan'; Population: 361800), (City: 'Sambalpur'; Country: 'India'; Population: 131138), (City: 'Sambhal'; Country: 'India'; Population: 150869), (City: 'Samsun'; Country: 'Turkey'; Population: 339871), (City: 'San Andr閟 Tuxtla'; Country: 'Mexico'; Population: 142251), (City: 'San Antonio'; Country: 'United States'; Population: 1144646), (City: 'San Bernardino'; Country: 'United States'; Population: 185401), (City: 'San Bernardo'; Country: 'Chile'; Population: 241910), (City: 'San Buenaventura'; Country: 'United States'; Population: 100916), (City: 'San Carlos'; Country: 'Philippines'; Population: 154264), (City: 'San Carlos'; Country: 'Philippines'; Population: 118259), (City: 'San Crist骲al'; Country: 'Venezuela'; Population: 319373), (City: 'San Crist骲al de las Casas'; Country: 'Mexico'; Population: 132317), (City: 'San Diego'; Country: 'United States'; Population: 1223400), (City: 'San Felipe'; Country: 'Mexico'; Population: 95305), (City: 'San Felipe'; Country: 'Venezuela'; Population: 90940), (City: 'San Felipe de Puerto Plata'; Country: 'Dominican Republic'; Population: 89423), (City: 'San Felipe del Progreso'; Country: 'Mexico'; Population: 177330), (City: 'San Fernando'; Country: 'Argentina'; Population: 153036), (City: 'San Fernando'; Country: 'Philippines'; Population: 221857), (City: 'San Fernando'; Country: 'Philippines'; Population: 102082), (City: 'San Fernando de Apure'; Country: 'Venezuela'; Population: 93809), (City: 'San Fernando del Valle de Cata'; Country: 'Argentina'; Population: 134935), (City: 'San Francisco'; Country: 'United States'; Population: 776733), (City: 'San Francisco de Macor韘'; Country: 'Dominican Republic'; Population: 108485), (City: 'San Francisco del Rinc髇'; Country: 'Mexico'; Population: 100149), (City: 'San Isidro'; Country: 'Argentina'; Population: 306341), (City: 'San Jose'; Country: 'Philippines'; Population: 111009), (City: 'San Jose'; Country: 'Philippines'; Population: 108254), (City: 'San Jose'; Country: 'United States'; Population: 894943), (City: 'San Jos'; Country: 'Costa Rica'; Population: 339131), (City: 'San Jos?del Monte'; Country: 'Philippines'; Population: 315807), (City: 'San Juan'; Country: 'Argentina'; Population: 119152), (City: 'San Juan'; Country: 'Puerto Rico'; Population: 434374), (City: 'San Juan Bautista Tuxtepec'; Country: 'Mexico'; Population: 133675), (City: 'San Juan del Monte'; Country: 'Philippines'; Population: 117680), (City: 'San Juan del R韔'; Country: 'Mexico'; Population: 179300), (City: 'San Lorenzo'; Country: 'Paraguay'; Population: 133395), (City: 'San Luis'; Country: 'Argentina'; Population: 110136), (City: 'San Luis Potos'; Country: 'Mexico'; Population: 669353), (City: 'San Luis R韔 Colorado'; Country: 'Mexico'; Population: 145276), (City: 'San Luis de la Paz'; Country: 'Mexico'; Population: 96763), (City: 'San Marino'; Country: 'San Marino'; Population: 2294), (City: 'San Mart韓 Texmelucan'; Country: 'Mexico'; Population: 121093), (City: 'San Mateo'; Country: 'Philippines'; Population: 135603), (City: 'San Mateo'; Country: 'United States'; Population: 91799), (City: 'San Miguel'; Country: 'Argentina'; Population: 248700), (City: 'San Miguel'; Country: 'El Salvador'; Population: 127696), (City: 'San Miguel'; Country: 'Philippines'; Population: 123824), (City: 'San Miguel de Tucum醤'; Country: 'Argentina'; Population: 470809), (City: 'San Miguelito'; Country: 'Panama'; Population: 315382), (City: 'San Nicol醩 de los Arroyos'; Country: 'Argentina'; Population: 119302), (City: 'San Nicol醩 de los Garza'; Country: 'Mexico'; Population: 495540), (City: 'San Pablo'; Country: 'Philippines'; Population: 207927), (City: 'San Pedro'; Country: 'Philippines'; Population: 231403), (City: 'San Pedro Cholula'; Country: 'Mexico'; Population: 99734), (City: 'San Pedro Garza Garc韆'; Country: 'Mexico'; Population: 126147), (City: 'San Pedro Sula'; Country: 'Honduras'; Population: 383900), (City: 'San Pedro de Macor韘'; Country: 'Dominican Republic'; Population: 124735), (City: 'San Pedro de la Paz'; Country: 'Chile'; Population: 91684), (City: 'San Rafael'; Country: 'Argentina'; Population: 94651), (City: 'San Salvador'; Country: 'El Salvador'; Population: 415346), (City: 'San Salvador de Jujuy'; Country: 'Argentina'; Population: 178748), (City: 'Sanaa'; Country: 'Yemen'; Population: 503600), (City: 'Sanandaj'; Country: 'Iran'; Population: 277808), (City: 'Sanchung'; Country: 'Taiwan'; Population: 380084), (City: 'Sancti-Sp韗itus'; Country: 'Cuba'; Population: 100751), (City: 'Sanda'; Country: 'Japan'; Population: 105643), (City: 'Sandakan'; Country: 'Malaysia'; Population: 125841), (City: 'Sandy'; Country: 'United States'; Population: 101853), (City: 'Sangju'; Country: 'South Korea'; Population: 124116), (City: 'Sangli'; Country: 'India'; Population: 193197), (City: 'Sanliurfa'; Country: 'Turkey'; Population: 405905), (City: 'Sanmenxia'; Country: 'China'; Population: 120523), (City: 'Sanming'; Country: 'China'; Population: 160691), (City: 'Santa Ana'; Country: 'El Salvador'; Population: 139389), (City: 'Santa Ana'; Country: 'United States'; Population: 337977), (City: 'Santa Ana de Coro'; Country: 'Venezuela'; Population: 185766), (City: 'Santa B醨bara d碠este'; Country: 'Brazil'; Population: 171657), (City: 'Santa Catarina'; Country: 'Mexico'; Population: 226573), (City: 'Santa Clara'; Country: 'Cuba'; Population: 207350), (City: 'Santa Clara'; Country: 'United States'; Population: 102361), (City: 'Santa Clarita'; Country: 'United States'; Population: 151088), (City: 'Santa Coloma de Gramenet'; Country: 'Spain'; Population: 120802), (City: 'Santa Cruz'; Country: 'Philippines'; Population: 92694), (City: 'Santa Cruz de Tenerife'; Country: 'Spain'; Population: 213050), (City: 'Santa Cruz de la Sierra'; Country: 'Bolivia'; Population: 935361), (City: 'Santa Cruz do Sul'; Country: 'Brazil'; Population: 106734), (City: 'Santa F'; Country: 'Argentina'; Population: 353063), (City: 'Santa Luzia'; Country: 'Brazil'; Population: 164704), (City: 'Santa Maria'; Country: 'Brazil'; Population: 238473), (City: 'Santa Maria'; Country: 'Philippines'; Population: 144282), (City: 'Santa Marta'; Country: 'Colombia'; Population: 359147), (City: 'Santa Monica'; Country: 'United States'; Population: 91084), (City: 'Santa Rita'; Country: 'Brazil'; Population: 113135), (City: 'Santa Rosa'; Country: 'Philippines'; Population: 185633), (City: 'Santa Rosa'; Country: 'United States'; Population: 147595), (City: 'Santaf?de Bogot'; Country: 'Colombia'; Population: 6260862), (City: 'Santana do Livramento'; Country: 'Brazil'; Population: 91779), (City: 'Santander'; Country: 'Spain'; Population: 184165), (City: 'Santar閙'; Country: 'Brazil'; Population: 241771), (City: 'Santiago'; Country: 'Philippines'; Population: 110531), (City: 'Santiago Ixcuintla'; Country: 'Mexico'; Population: 95311), (City: 'Santiago de Chile'; Country: 'Chile'; Population: 4703954), (City: 'Santiago de Compostela'; Country: 'Spain'; Population: 93745), (City: 'Santiago de Cuba'; Country: 'Cuba'; Population: 433180), (City: 'Santiago de los Caballeros'; Country: 'Dominican Republic'; Population: 365463), (City: 'Santiago del Estero'; Country: 'Argentina'; Population: 189947), (City: 'Santipur'; Country: 'India'; Population: 109956), (City: 'Santo Andr'; Country: 'Brazil'; Population: 630073), (City: 'Santo Domingo de Guzm醤'; Country: 'Dominican Republic'; Population: 1609966), (City: 'Santo Domingo de los Colorados'; Country: 'Ecuador'; Population: 202111), (City: 'Santos'; Country: 'Brazil'; Population: 408748), (City: 'Sanya'; Country: 'China'; Population: 102820), (City: 'Sapele'; Country: 'Nigeria'; Population: 139200), (City: 'Sapporo'; Country: 'Japan'; Population: 1790886), (City: 'Sapucaia do Sul'; Country: 'Brazil'; Population: 120217), (City: 'Saqqez'; Country: 'Iran'; Population: 115394), (City: 'Sarajevo'; Country: 'Bosnia and Herzegovina'; Population: 360000), (City: 'Saransk'; Country: 'Russian Federation'; Population: 314800), (City: 'Sarapul'; Country: 'Russian Federation'; Population: 105700), (City: 'Saratov'; Country: 'Russian Federation'; Population: 874000), (City: 'Sargodha'; Country: 'Pakistan'; Population: 455360), (City: 'Sari'; Country: 'Iran'; Population: 195882), (City: 'Sariaya'; Country: 'Philippines'; Population: 114568), (City: 'Sariwon'; Country: 'North Korea'; Population: 254146), (City: 'Sasaram'; Country: 'India'; Population: 98220), (City: 'Sasebo'; Country: 'Japan'; Population: 244240), (City: 'Saskatoon'; Country: 'Canada'; Population: 193647), (City: 'Sassari'; Country: 'Italy'; Population: 120803), (City: 'Satara'; Country: 'India'; Population: 95133), (City: 'Satna'; Country: 'India'; Population: 156630), (City: 'Satu Mare'; Country: 'Romania'; Population: 130059), (City: 'Savannah'; Country: 'United States'; Population: 131510), (City: 'Savannakhet'; Country: 'Laos'; Population: 96652), (City: 'Saveh'; Country: 'Iran'; Population: 111245), (City: 'Sawangan'; Country: 'Indonesia'; Population: 91100), (City: 'Sawhaj'; Country: 'Egypt'; Population: 170125), (City: 'Sayama'; Country: 'Japan'; Population: 162472), (City: 'Scarborough'; Country: 'Canada'; Population: 594501), (City: 'Schaan'; Country: 'Liechtenstein'; Population: 5346), (City: 'Schaerbeek'; Country: 'Belgium'; Population: 105692), (City: 'Schwerin'; Country: 'Germany'; Population: 102878), (City: 'Scottsdale'; Country: 'United States'; Population: 202705), (City: 'Seattle'; Country: 'United States'; Population: 563374), (City: 'Secunderabad'; Country: 'India'; Population: 167461), (City: 'Sekondi-Takoradi'; Country: 'Ghana'; Population: 103653), (City: 'Selayang Baru'; Country: 'Malaysia'; Population: 124228), (City: 'Semarang'; Country: 'Indonesia'; Population: 1104405), (City: 'Semey'; Country: 'Kazakstan'; Population: 269600), (City: 'Semnan'; Country: 'Iran'; Population: 91045), (City: 'Sendai'; Country: 'Japan'; Population: 989975), (City: 'Seoul'; Country: 'South Korea'; Population: 9981619), (City: 'Serampore'; Country: 'India'; Population: 137028), (City: 'Serang'; Country: 'Indonesia'; Population: 122400), (City: 'Serekunda'; Country: 'Gambia'; Population: 102600), (City: 'Seremban'; Country: 'Malaysia'; Population: 182869), (City: 'Sergijev Posad'; Country: 'Russian Federation'; Population: 111100), (City: 'Serov'; Country: 'Russian Federation'; Population: 100400), (City: 'Serpuhov'; Country: 'Russian Federation'; Population: 132000), (City: 'Serra'; Country: 'Brazil'; Population: 302666), (City: 'Serravalle'; Country: 'San Marino'; Population: 4802), (City: 'Sert鉶zinho'; Country: 'Brazil'; Population: 98140), (City: 'Sete Lagoas'; Country: 'Brazil'; Population: 182984), (City: 'Seto'; Country: 'Japan'; Population: 130470), (City: 'Settat'; Country: 'Morocco'; Population: 96200), (City: 'Sevastopol'; Country: 'Ukraine'; Population: 348000), (City: 'Severodvinsk'; Country: 'Russian Federation'; Population: 229300), (City: 'Seversk'; Country: 'Russian Federation'; Population: 118600), (City: 'Sevilla'; Country: 'Spain'; Population: 701927), (City: 'Sfax'; Country: 'Tunisia'; Population: 257800), (City: 'Shagamu'; Country: 'Nigeria'; Population: 117200), (City: 'Shah Alam'; Country: 'Malaysia'; Population: 102019), (City: 'Shahjahanpur'; Country: 'India'; Population: 237713), (City: 'Shahr-e Kord'; Country: 'Iran'; Population: 100477), (City: 'Shahrud'; Country: 'Iran'; Population: 104765), (City: 'Shaki'; Country: 'Nigeria'; Population: 174500), (City: 'Shambajinagar (Aurangabad)'; Country: 'India'; Population: 573272), (City: 'Shanghai'; Country: 'China'; Population: 9696300), (City: 'Shangqiu'; Country: 'China'; Population: 164880), (City: 'Shangrao'; Country: 'China'; Population: 132455), (City: 'Shangzi'; Country: 'China'; Population: 215373), (City: 'Shantou'; Country: 'China'; Population: 580000), (City: 'Shanwei'; Country: 'China'; Population: 107847), (City: 'Shaoguan'; Country: 'China'; Population: 350043), (City: 'Shaowu'; Country: 'China'; Population: 90286), (City: 'Shaoxing'; Country: 'China'; Population: 179818), (City: 'Shaoyang'; Country: 'China'; Population: 247227), (City: 'Sharja'; Country: 'United Arab Emirates'; Population: 320095), (City: 'Sharq al-Nil'; Country: 'Sudan'; Population: 700887), (City: 'Shashi'; Country: 'China'; Population: 281352), (City: 'Sheffield'; Country: 'United Kingdom'; Population: 431607), (City: 'Sheikhupura'; Country: 'Pakistan'; Population: 271875), (City: 'Shenyang'; Country: 'China'; Population: 4265200), (City: 'Shenzhen'; Country: 'China'; Population: 950500), (City: 'Shibin al-Kawm'; Country: 'Egypt'; Population: 159909), (City: 'Shihezi'; Country: 'China'; Population: 299676), (City: 'Shihung'; Country: 'South Korea'; Population: 133443), (City: 'Shijiazhuang'; Country: 'China'; Population: 2041500), (City: 'Shikarpur'; Country: 'Pakistan'; Population: 133300), (City: 'Shillong'; Country: 'India'; Population: 131719), (City: 'Shimizu'; Country: 'Japan'; Population: 239123), (City: 'Shimoga'; Country: 'India'; Population: 179258), (City: 'Shimonoseki'; Country: 'Japan'; Population: 257263), (City: 'Shiraz'; Country: 'Iran'; Population: 1053025), (City: 'Shishou'; Country: 'China'; Population: 104571), (City: 'Shivapuri'; Country: 'India'; Population: 108277), (City: 'Shiyan'; Country: 'China'; Population: 273786), (City: 'Shizuishan'; Country: 'China'; Population: 257862), (City: 'Shizuoka'; Country: 'Japan'; Population: 473854), (City: 'Shomolu'; Country: 'Nigeria'; Population: 147700), (City: 'Shreveport'; Country: 'United States'; Population: 200145), (City: 'Shuangcheng'; Country: 'China'; Population: 142659), (City: 'Shuangyashan'; Country: 'China'; Population: 386081), (City: 'Shubra al-Khayma'; Country: 'Egypt'; Population: 870716), (City: 'Shulin'; Country: 'Taiwan'; Population: 151260), (City: 'Shymkent'; Country: 'Kazakstan'; Population: 360100), (City: 'Sialkot'; Country: 'Pakistan'; Population: 417597), (City: 'Sibiu'; Country: 'Romania'; Population: 169611), (City: 'Sibu'; Country: 'Malaysia'; Population: 126381), (City: 'Sidi Bel Abb鑣'; Country: 'Algeria'; Population: 153106), (City: 'Siegen'; Country: 'Germany'; Population: 109225), (City: 'Siem Reap'; Country: 'Cambodia'; Population: 105100), (City: 'Siirt'; Country: 'Turkey'; Population: 107100), (City: 'Sikar'; Country: 'India'; Population: 148272), (City: 'Silang'; Country: 'Philippines'; Population: 156137), (City: 'Silao'; Country: 'Mexico'; Population: 134037), (City: 'Silay'; Country: 'Philippines'; Population: 107722), (City: 'Silchar'; Country: 'India'; Population: 115483), (City: 'Siliguri (Shiliguri)'; Country: 'India'; Population: 216950), (City: 'Simferopol'; Country: 'Ukraine'; Population: 339000), (City: 'Simi Valley'; Country: 'United States'; Population: 111351), (City: 'Sincelejo'; Country: 'Colombia'; Population: 220704), (City: 'Singapore'; Country: 'Singapore'; Population: 4017733), (City: 'Sinuiju'; Country: 'North Korea'; Population: 326011), (City: 'Sioux Falls'; Country: 'United States'; Population: 123975), (City: 'Siping'; Country: 'China'; Population: 317223), (City: 'Sirajganj'; Country: 'Bangladesh'; Population: 99669), (City: 'Sirjan'; Country: 'Iran'; Population: 135024), (City: 'Sirsa'; Country: 'India'; Population: 125000), (City: 'Sitapur'; Country: 'India'; Population: 121842), (City: 'Sittwe (Akyab)'; Country: 'Myanmar'; Population: 137600), (City: 'Sivas'; Country: 'Turkey'; Population: 246642), (City: 'Sjeverodonetsk'; Country: 'Ukraine'; Population: 127000), (City: 'Skikda'; Country: 'Algeria'; Population: 128747), (City: 'Skopje'; Country: 'Macedonia'; Population: 444299), (City: 'Sliven'; Country: 'Bulgaria'; Population: 105530), (City: 'Slough'; Country: 'United Kingdom'; Population: 112000), (City: 'Slovjansk'; Country: 'Ukraine'; Population: 127000), (City: 'Slupsk'; Country: 'Poland'; Population: 102370), (City: 'Smolensk'; Country: 'Russian Federation'; Population: 353400), (City: 'Soacha'; Country: 'Colombia'; Population: 272058), (City: 'Sobral'; Country: 'Brazil'; Population: 146005), (City: 'Sofija'; Country: 'Bulgaria'; Population: 1122302), (City: 'Sogamoso'; Country: 'Colombia'; Population: 107728), (City: 'Sohumi'; Country: 'Georgia'; Population: 111700), (City: 'Soka'; Country: 'Japan'; Population: 222768), (City: 'Sokoto'; Country: 'Nigeria'; Population: 204900), (City: 'Solapur (Sholapur)'; Country: 'India'; Population: 604215), (City: 'Soledad'; Country: 'Colombia'; Population: 295058), (City: 'Soledad de Graciano S醤chez'; Country: 'Mexico'; Population: 179956), (City: 'Soligorsk'; Country: 'Belarus'; Population: 101000), (City: 'Solihull'; Country: 'United Kingdom'; Population: 94531), (City: 'Solikamsk'; Country: 'Russian Federation'; Population: 106000), (City: 'Solingen'; Country: 'Germany'; Population: 165583), (City: 'Songkhla'; Country: 'Thailand'; Population: 94900), (City: 'Songnam'; Country: 'South Korea'; Population: 869094), (City: 'Sonipat (Sonepat)'; Country: 'India'; Population: 143922), (City: 'Sorocaba'; Country: 'Brazil'; Population: 466823), (City: 'Sorsogon'; Country: 'Philippines'; Population: 92512), (City: 'Sosan'; Country: 'South Korea'; Population: 134746), (City: 'Soshanguve'; Country: 'South Africa'; Population: 242727), (City: 'Sosnowiec'; Country: 'Poland'; Population: 244102), (City: 'Sot歩'; Country: 'Russian Federation'; Population: 358600), (City: 'Sousse'; Country: 'Tunisia'; Population: 145900), (City: 'South Bend'; Country: 'United States'; Population: 107789), (City: 'South Dum Dum'; Country: 'India'; Population: 232811), (City: 'South Hill'; Country: 'Anguilla'; Population: 961), (City: 'Southampton'; Country: 'United Kingdom'; Population: 216000), (City: 'Southend-on-Sea'; Country: 'United Kingdom'; Population: 176000), (City: 'Southport'; Country: 'United Kingdom'; Population: 90959), (City: 'Soweto'; Country: 'South Africa'; Population: 904165), (City: 'Soyapango'; Country: 'El Salvador'; Population: 129800), (City: 'Spanish Town'; Country: 'Jamaica'; Population: 110379), (City: 'Split'; Country: 'Croatia'; Population: 189388), (City: 'Spokane'; Country: 'United States'; Population: 195629), (City: 'Springfield'; Country: 'United States'; Population: 152082), (City: 'Springfield'; Country: 'United States'; Population: 151580), (City: 'Springfield'; Country: 'United States'; Population: 111454), (City: 'Springs'; Country: 'South Africa'; Population: 162072), (City: 'Sri Jayawardenepura Kotte'; Country: 'Sri Lanka'; Population: 118000), (City: 'Srinagar'; Country: 'India'; Population: 892506), (City: 'St Petersburg'; Country: 'Russian Federation'; Population: 4694000), (City: 'St-蓆ienne'; Country: 'France'; Population: 180210), (City: 'Stahanov'; Country: 'Ukraine'; Population: 101000), (City: 'Stamford'; Country: 'United States'; Population: 117083), (City: 'Stanley'; Country: 'Falkland Islands'; Population: 1636), (City: 'Stara Zagora'; Country: 'Bulgaria'; Population: 147939), (City: 'Staryi Oskol'; Country: 'Russian Federation'; Population: 213800), (City: 'Stavanger'; Country: 'Norway'; Population: 108848), (City: 'Stavropol'; Country: 'Russian Federation'; Population: 343300), (City: 'Sterling Heights'; Country: 'United States'; Population: 124471), (City: 'Sterlitamak'; Country: 'Russian Federation'; Population: 265200), (City: 'Stockholm'; Country: 'Sweden'; Population: 750348), (City: 'Stockport'; Country: 'United Kingdom'; Population: 132813), (City: 'Stockton'; Country: 'United States'; Population: 243771), (City: 'Stoke-on-Trent'; Country: 'United Kingdom'; Population: 252000), (City: 'Strasbourg'; Country: 'France'; Population: 264115), (City: 'Stuttgart'; Country: 'Germany'; Population: 582443), (City: 'Subotica'; Country: 'Yugoslavia'; Population: 100386), (City: 'Suceava'; Country: 'Romania'; Population: 118549), (City: 'Sucre'; Country: 'Bolivia'; Population: 178426), (City: 'Sudbury'; Country: 'Canada'; Population: 92686), (City: 'Suez'; Country: 'Egypt'; Population: 417610), (City: 'Suhar'; Country: 'Oman'; Population: 90814), (City: 'Suihua'; Country: 'China'; Population: 227881), (City: 'Suining'; Country: 'China'; Population: 146086), (City: 'Suita'; Country: 'Japan'; Population: 345750), (City: 'Suizhou'; Country: 'China'; Population: 142302), (City: 'Sukabumi'; Country: 'Indonesia'; Population: 125766), (City: 'Sukkur'; Country: 'Pakistan'; Population: 329176), (City: 'Sullana'; Country: 'Peru'; Population: 147361), (City: 'Sultan Kudarat'; Country: 'Philippines'; Population: 94861), (City: 'Sultanbeyli'; Country: 'Turkey'; Population: 211068), (City: 'Sumar'; Country: 'Brazil'; Population: 186205), (City: 'Sumqayit'; Country: 'Azerbaijan'; Population: 283000), (City: 'Sumy'; Country: 'Ukraine'; Population: 294000), (City: 'Sunchon'; Country: 'South Korea'; Population: 249263), (City: 'Sunderland'; Country: 'United Kingdom'; Population: 183310), (City: 'Sundsvall'; Country: 'Sweden'; Population: 93126), (City: 'Sungai Petani'; Country: 'Malaysia'; Population: 114763), (City: 'Sunggal'; Country: 'Indonesia'; Population: 92300), (City: 'Sunnyvale'; Country: 'United States'; Population: 131760), (City: 'Sunrise Manor'; Country: 'United States'; Population: 95362), (City: 'Suqian'; Country: 'China'; Population: 105021), (City: 'Surabaya'; Country: 'Indonesia'; Population: 2663820), (City: 'Surakarta'; Country: 'Indonesia'; Population: 518600), (City: 'Surat'; Country: 'India'; Population: 1498817), (City: 'Surendranagar'; Country: 'India'; Population: 105973), (City: 'Surgut'; Country: 'Russian Federation'; Population: 274900), (City: 'Surigao'; Country: 'Philippines'; Population: 118534), (City: 'Surrey'; Country: 'Canada'; Population: 304477), (City: 'Sutton Coldfield'; Country: 'United Kingdom'; Population: 106001), (City: 'Suva'; Country: 'Fiji Islands'; Population: 77366), (City: 'Suwon'; Country: 'South Korea'; Population: 755550), (City: 'Suzano'; Country: 'Brazil'; Population: 195434), (City: 'Suzhou'; Country: 'China'; Population: 710000), (City: 'Suzhou'; Country: 'China'; Population: 151862), (City: 'Suzuka'; Country: 'Japan'; Population: 184061), (City: 'Swansea'; Country: 'United Kingdom'; Population: 230000), (City: 'Swindon'; Country: 'United Kingdom'; Population: 180000), (City: 'Sydney'; Country: 'Australia'; Population: 3276207), (City: 'Syktyvkar'; Country: 'Russian Federation'; Population: 229700), (City: 'Sylhet'; Country: 'Bangladesh'; Population: 117396), (City: 'Syracuse'; Country: 'United States'; Population: 147306), (City: 'Syrakusa'; Country: 'Italy'; Population: 126282), (City: 'Syzran'; Country: 'Russian Federation'; Population: 186900), (City: 'Szczecin'; Country: 'Poland'; Population: 416988), (City: 'Szeged'; Country: 'Hungary'; Population: 158158), (City: 'Sz閗esfeh閞v醨'; Country: 'Hungary'; Population: 105119), (City: 'S鉶 Bernardo do Campo'; Country: 'Brazil'; Population: 723132), (City: 'S鉶 Caetano do Sul'; Country: 'Brazil'; Population: 133321), (City: 'S鉶 Carlos'; Country: 'Brazil'; Population: 187122), (City: 'S鉶 Gon鏰lo'; Country: 'Brazil'; Population: 869254), (City: 'S鉶 Jos'; Country: 'Brazil'; Population: 155105), (City: 'S鉶 Jos?de Ribamar'; Country: 'Brazil'; Population: 98318), (City: 'S鉶 Jos?do Rio Preto'; Country: 'Brazil'; Population: 351944), (City: 'S鉶 Jos?dos Campos'; Country: 'Brazil'; Population: 515553), (City: 'S鉶 Jos?dos Pinhais'; Country: 'Brazil'; Population: 196884), (City: 'S鉶 Jo鉶 de Meriti'; Country: 'Brazil'; Population: 440052), (City: 'S鉶 Leopoldo'; Country: 'Brazil'; Population: 189258), (City: 'S鉶 Louren鏾 da Mata'; Country: 'Brazil'; Population: 91999), (City: 'S鉶 Lu韘'; Country: 'Brazil'; Population: 837588), (City: 'S鉶 Paulo'; Country: 'Brazil'; Population: 9968485), (City: 'S鉶 Tom'; Country: 'Sao Tome and Principe'; Population: 49541), (City: 'S鉶 Vicente'; Country: 'Brazil'; Population: 286848), (City: 'S閠if'; Country: 'Algeria'; Population: 179055), (City: 'Tabaco'; Country: 'Philippines'; Population: 107166), (City: 'Tabora'; Country: 'Tanzania'; Population: 92800), (City: 'Tabo鉶 da Serra'; Country: 'Brazil'; Population: 197550), (City: 'Tabriz'; Country: 'Iran'; Population: 1191043), (City: 'Tabuk'; Country: 'Saudi Arabia'; Population: 292600), (City: 'Tachikawa'; Country: 'Japan'; Population: 159430), (City: 'Tacloban'; Country: 'Philippines'; Population: 178639), (City: 'Tacna'; Country: 'Peru'; Population: 215683), (City: 'Tacoma'; Country: 'United States'; Population: 193556), (City: 'Taegu'; Country: 'South Korea'; Population: 2548568), (City: 'Taejon'; Country: 'South Korea'; Population: 1425835), (City: 'Tafuna'; Country: 'American Samoa'; Population: 5200), (City: 'Taganrog'; Country: 'Russian Federation'; Population: 284400), (City: 'Taguig'; Country: 'Philippines'; Population: 467375), (City: 'Tagum'; Country: 'Philippines'; Population: 179531), (City: 'Taichung'; Country: 'Taiwan'; Population: 940589), (City: 'Tainan'; Country: 'Taiwan'; Population: 728060), (City: 'Taipei'; Country: 'Taiwan'; Population: 2641312), (City: 'Taiping'; Country: 'Malaysia'; Population: 183261), (City: 'Taiping'; Country: 'Taiwan'; Population: 165524), (City: 'Taitung'; Country: 'Taiwan'; Population: 111039), (City: 'Taiyuan'; Country: 'China'; Population: 1968400), (City: 'Taizhou'; Country: 'China'; Population: 152442), (City: 'Taizz'; Country: 'Yemen'; Population: 317600), (City: 'Tai碼n'; Country: 'China'; Population: 350696), (City: 'Tajimi'; Country: 'Japan'; Population: 103171), (City: 'Takamatsu'; Country: 'Japan'; Population: 332471), (City: 'Takaoka'; Country: 'Japan'; Population: 174380), (City: 'Takarazuka'; Country: 'Japan'; Population: 205993), (City: 'Takasago'; Country: 'Japan'; Population: 97632), (City: 'Takasaki'; Country: 'Japan'; Population: 239124), (City: 'Takatsuki'; Country: 'Japan'; Population: 361747), (City: 'Talavera'; Country: 'Philippines'; Population: 97329), (City: 'Talca'; Country: 'Chile'; Population: 187557), (City: 'Talcahuano'; Country: 'Chile'; Population: 277752), (City: 'Taldyqorghan'; Country: 'Kazakstan'; Population: 98000), (City: 'Tali'; Country: 'Taiwan'; Population: 171940), (City: 'Taliao'; Country: 'Taiwan'; Population: 115897), (City: 'Talisay'; Country: 'Philippines'; Population: 148110), (City: 'Talkha'; Country: 'Egypt'; Population: 97700), (City: 'Tallahassee'; Country: 'United States'; Population: 150624), (City: 'Tallinn'; Country: 'Estonia'; Population: 403981), (City: 'Tama'; Country: 'Japan'; Population: 146712), (City: 'Tamale'; Country: 'Ghana'; Population: 151069), (City: 'Taman'; Country: 'Indonesia'; Population: 107000), (City: 'Tambaram'; Country: 'India'; Population: 107187), (City: 'Tambov'; Country: 'Russian Federation'; Population: 312000), (City: 'Tampa'; Country: 'United States'; Population: 303447), (City: 'Tampere'; Country: 'Finland'; Population: 195468), (City: 'Tampico'; Country: 'Mexico'; Population: 294789), (City: 'Tamuning'; Country: 'Guam'; Population: 9500), (City: 'Tanauan'; Country: 'Philippines'; Population: 117539), (City: 'Tandil'; Country: 'Argentina'; Population: 91101), (City: 'Tando Adam'; Country: 'Pakistan'; Population: 103400), (City: 'Tanga'; Country: 'Tanzania'; Population: 137400), (City: 'Tangail'; Country: 'Bangladesh'; Population: 106004), (City: 'Tanger'; Country: 'Morocco'; Population: 521735), (City: 'Tangerang'; Country: 'Indonesia'; Population: 1198300), (City: 'Tangshan'; Country: 'China'; Population: 1040000), (City: 'Tanjung Pinang'; Country: 'Indonesia'; Population: 89900), (City: 'Tanshui'; Country: 'Taiwan'; Population: 111882), (City: 'Tanta'; Country: 'Egypt'; Population: 371010), (City: 'Tantoyuca'; Country: 'Mexico'; Population: 94709), (City: 'Tanza'; Country: 'Philippines'; Population: 110517), (City: 'Taonan'; Country: 'China'; Population: 150168), (City: 'Taoyuan'; Country: 'Taiwan'; Population: 316438), (City: 'Tapachula'; Country: 'Mexico'; Population: 271141), (City: 'Taranto'; Country: 'Italy'; Population: 208214), (City: 'Taraz'; Country: 'Kazakstan'; Population: 330100), (City: 'Tarija'; Country: 'Bolivia'; Population: 125255), (City: 'Tarlac'; Country: 'Philippines'; Population: 262481), (City: 'Tarn體'; Country: 'Poland'; Population: 121494), (City: 'Tarragona'; Country: 'Spain'; Population: 113016), (City: 'Tarsus'; Country: 'Turkey'; Population: 246206), (City: 'Tartu'; Country: 'Estonia'; Population: 101246), (City: 'Tasikmalaya'; Country: 'Indonesia'; Population: 179800), (City: 'Tatu'; Country: 'Brazil'; Population: 93897), (City: 'Taubat'; Country: 'Brazil'; Population: 229130), (City: 'Taunggyi (Taunggye)'; Country: 'Myanmar'; Population: 131500), (City: 'Tavoy (Dawei)'; Country: 'Myanmar'; Population: 96800), (City: 'Taxco de Alarc髇'; Country: 'Mexico'; Population: 99907), (City: 'Taytay'; Country: 'Philippines'; Population: 198183), (City: 'Taza'; Country: 'Morocco'; Population: 92700), (City: 'Tbilisi'; Country: 'Georgia'; Population: 1235200), (City: 'Tebing Tinggi'; Country: 'Indonesia'; Population: 129300), (City: 'Tecom醤'; Country: 'Mexico'; Population: 99296), (City: 'Tec醡ac'; Country: 'Mexico'; Population: 172410), (City: 'Tegal'; Country: 'Indonesia'; Population: 289744), (City: 'Tegucigalpa'; Country: 'Honduras'; Population: 813900), (City: 'Teheran'; Country: 'Iran'; Population: 6758845), (City: 'Tehuac醤'; Country: 'Mexico'; Population: 225943), (City: 'Teixeira de Freitas'; Country: 'Brazil'; Population: 108441), (City: 'Tejupilco'; Country: 'Mexico'; Population: 94934), (City: 'Tekirdag'; Country: 'Turkey'; Population: 106077), (City: 'Tel Aviv-Jaffa'; Country: 'Israel'; Population: 348100), (City: 'Tellicherry (Thalassery)'; Country: 'India'; Population: 103579), (City: 'Tema'; Country: 'Ghana'; Population: 109975), (City: 'Temapache'; Country: 'Mexico'; Population: 102824), (City: 'Temirtau'; Country: 'Kazakstan'; Population: 170500), (City: 'Temixco'; Country: 'Mexico'; Population: 92686), (City: 'Tempe'; Country: 'United States'; Population: 158625), (City: 'Temuco'; Country: 'Chile'; Population: 233041), (City: 'Tenali'; Country: 'India'; Population: 143726), (City: 'Tengzhou'; Country: 'China'; Population: 315083), (City: 'Tepatitl醤 de Morelos'; Country: 'Mexico'; Population: 118948), (City: 'Tepic'; Country: 'Mexico'; Population: 305025), (City: 'Teresina'; Country: 'Brazil'; Population: 691942), (City: 'Teres髉olis'; Country: 'Brazil'; Population: 128079), (City: 'Termiz'; Country: 'Uzbekistan'; Population: 109500), (City: 'Terni'; Country: 'Italy'; Population: 107770), (City: 'Ternopil'; Country: 'Ukraine'; Population: 236000), (City: 'Terrassa'; Country: 'Spain'; Population: 168695), (City: 'Tete'; Country: 'Mozambique'; Population: 101984), (City: 'Texcoco'; Country: 'Mexico'; Population: 203681), (City: 'Te骹ilo Otoni'; Country: 'Brazil'; Population: 124489), (City: 'Thai Nguyen'; Country: 'Vietnam'; Population: 127643), (City: 'Thane (Thana)'; Country: 'India'; Population: 803389), (City: 'Thanjavur'; Country: 'India'; Population: 202013), (City: 'The Valley'; Country: 'Anguilla'; Population: 595), (City: 'Thessaloniki'; Country: 'Greece'; Population: 383967), (City: 'Thimphu'; Country: 'Bhutan'; Population: 22000), (City: 'Thiruvananthapuram (Trivandrum'; Country: 'India'; Population: 524006), (City: 'Thi鑣'; Country: 'Senegal'; Population: 248000), (City: 'Thousand Oaks'; Country: 'United States'; Population: 117005), (City: 'Thunder Bay'; Country: 'Canada'; Population: 115913), (City: 'Tianjin'; Country: 'China'; Population: 5286800), (City: 'Tianmen'; Country: 'China'; Population: 186332), (City: 'Tianshui'; Country: 'China'; Population: 244974), (City: 'Tiaret'; Country: 'Algeria'; Population: 100118), (City: 'Tiefa'; Country: 'China'; Population: 131807), (City: 'Tieli'; Country: 'China'; Population: 265683), (City: 'Tieling'; Country: 'China'; Population: 254842), (City: 'Tierra Blanca'; Country: 'Mexico'; Population: 89143), (City: 'Tigre'; Country: 'Argentina'; Population: 296226), (City: 'Tijuana'; Country: 'Mexico'; Population: 1212232), (City: 'Tilburg'; Country: 'Netherlands'; Population: 193238), (City: 'Timisoara'; Country: 'Romania'; Population: 324304), (City: 'Timkur'; Country: 'India'; Population: 138903), (City: 'Timon'; Country: 'Brazil'; Population: 125812), (City: 'Tirana'; Country: 'Albania'; Population: 270000), (City: 'Tiraspol'; Country: 'Moldova'; Population: 194300), (City: 'Tiruchirapalli'; Country: 'India'; Population: 387223), (City: 'Tirunelveli'; Country: 'India'; Population: 135825), (City: 'Tirupati'; Country: 'India'; Population: 174369), (City: 'Tiruppur (Tirupper)'; Country: 'India'; Population: 235661), (City: 'Tiruvannamalai'; Country: 'India'; Population: 109196), (City: 'Tiruvottiyur'; Country: 'India'; Population: 172562), (City: 'Titagarh'; Country: 'India'; Population: 114085), (City: 'Tjumen'; Country: 'Russian Federation'; Population: 503400), (City: 'Tlajomulco de Ziga'; Country: 'Mexico'; Population: 123220), (City: 'Tlalnepantla de Baz'; Country: 'Mexico'; Population: 720755), (City: 'Tlaquepaque'; Country: 'Mexico'; Population: 475472), (City: 'Tlemcen (Tilimsen)'; Country: 'Algeria'; Population: 110242), (City: 'Toa Baja'; Country: 'Puerto Rico'; Population: 94085), (City: 'Toamasina'; Country: 'Madagascar'; Population: 127441), (City: 'Tobolsk'; Country: 'Russian Federation'; Population: 97600), (City: 'Toda'; Country: 'Japan'; Population: 103969), (City: 'Tokai'; Country: 'Japan'; Population: 99738), (City: 'Tokat'; Country: 'Turkey'; Population: 99500), (City: 'Tokorozawa'; Country: 'Japan'; Population: 325809), (City: 'Tokushima'; Country: 'Japan'; Population: 269649), (City: 'Tokuyama'; Country: 'Japan'; Population: 107078), (City: 'Tokyo'; Country: 'Japan'; Population: 7980230), (City: 'Toledo'; Country: 'Brazil'; Population: 99387), (City: 'Toledo'; Country: 'Philippines'; Population: 141174), (City: 'Toledo'; Country: 'United States'; Population: 313619), (City: 'Toljatti'; Country: 'Russian Federation'; Population: 722900), (City: 'Toluca'; Country: 'Mexico'; Population: 665617), (City: 'Tomakomai'; Country: 'Japan'; Population: 171958), (City: 'Tomsk'; Country: 'Russian Federation'; Population: 482100), (City: 'Tonal'; Country: 'Mexico'; Population: 336109), (City: 'Tondabayashi'; Country: 'Japan'; Population: 125094), (City: 'Tong Xian'; Country: 'China'; Population: 97168), (City: 'Tong-yong'; Country: 'South Korea'; Population: 131717), (City: 'Tongchuan'; Country: 'China'; Population: 280657), (City: 'Tonghae'; Country: 'South Korea'; Population: 95472), (City: 'Tonghua'; Country: 'China'; Population: 324600), (City: 'Tongliao'; Country: 'China'; Population: 255129), (City: 'Tongling'; Country: 'China'; Population: 228017), (City: 'Tonk'; Country: 'India'; Population: 100079), (City: 'Topeka'; Country: 'United States'; Population: 122377), (City: 'Torbat-e Heydariyeh'; Country: 'Iran'; Population: 94600), (City: 'Torino'; Country: 'Italy'; Population: 903705), (City: 'Toronto'; Country: 'Canada'; Population: 688275), (City: 'Torrance'; Country: 'United States'; Population: 137946), (City: 'Torre del Greco'; Country: 'Italy'; Population: 94505), (City: 'Torrej髇 de Ardoz'; Country: 'Spain'; Population: 92262), (City: 'Torre髇'; Country: 'Mexico'; Population: 529093), (City: 'Torun'; Country: 'Poland'; Population: 206158), (City: 'Toskent'; Country: 'Uzbekistan'; Population: 2117500), (City: 'Tottori'; Country: 'Japan'; Population: 147523), (City: 'Touliu'; Country: 'Taiwan'; Population: 98900), (City: 'Toulon'; Country: 'France'; Population: 160639), (City: 'Toulouse'; Country: 'France'; Population: 390350), (City: 'Tourcoing'; Country: 'France'; Population: 93540), (City: 'Tours'; Country: 'France'; Population: 132820), (City: 'Townsville'; Country: 'Australia'; Population: 109914), (City: 'Toyama'; Country: 'Japan'; Population: 325790), (City: 'Toyohashi'; Country: 'Japan'; Population: 360066), (City: 'Toyokawa'; Country: 'Japan'; Population: 115781), (City: 'Toyonaka'; Country: 'Japan'; Population: 396689), (City: 'Toyota'; Country: 'Japan'; Population: 346090), (City: 'Trabzon'; Country: 'Turkey'; Population: 138234), (City: 'Trento'; Country: 'Italy'; Population: 104906), (City: 'Tres de Febrero'; Country: 'Argentina'; Population: 352311), (City: 'Trier'; Country: 'Germany'; Population: 99891), (City: 'Trieste'; Country: 'Italy'; Population: 216459), (City: 'Tripoli'; Country: 'Lebanon'; Population: 240000), (City: 'Tripoli'; Country: 'Libyan Arab Jamahiriya'; Population: 1682000), (City: 'Trondheim'; Country: 'Norway'; Population: 150166), (City: 'Trujillo'; Country: 'Peru'; Population: 652000), (City: 'Tsaotun'; Country: 'Taiwan'; Population: 96800), (City: 'Tshikapa'; Country: 'Congo, The Democratic Republic of the'; Population: 180860), (City: 'Tsu'; Country: 'Japan'; Population: 164543), (City: 'Tsuchiura'; Country: 'Japan'; Population: 134072), (City: 'Tsukuba'; Country: 'Japan'; Population: 160768), (City: 'Tsuruoka'; Country: 'Japan'; Population: 100713), (City: 'Tsuyama'; Country: 'Japan'; Population: 91170), (City: 'Tucheng'; Country: 'Taiwan'; Population: 224897), (City: 'Tucson'; Country: 'United States'; Population: 486699), (City: 'Tuguegarao'; Country: 'Philippines'; Population: 120645), (City: 'Tula'; Country: 'Russian Federation'; Population: 506100), (City: 'Tulancingo de Bravo'; Country: 'Mexico'; Population: 121946), (City: 'Tulcea'; Country: 'Romania'; Population: 96278), (City: 'Tulsa'; Country: 'United States'; Population: 393049), (City: 'Tultepec'; Country: 'Mexico'; Population: 93364), (City: 'Tultitl醤'; Country: 'Mexico'; Population: 432411), (City: 'Tulu'; Country: 'Colombia'; Population: 152488), (City: 'Tumen'; Country: 'China'; Population: 91471), (City: 'Tungi'; Country: 'Bangladesh'; Population: 168702), (City: 'Tunis'; Country: 'Tunisia'; Population: 690600), (City: 'Tunja'; Country: 'Colombia'; Population: 109740), (City: 'Turku [舃o]'; Country: 'Finland'; Population: 172561), (City: 'Turmero'; Country: 'Venezuela'; Population: 217499), (City: 'Tuticorin'; Country: 'India'; Population: 199854), (City: 'Tuxtla Guti閞rez'; Country: 'Mexico'; Population: 433544), (City: 'Tver'; Country: 'Russian Federation'; Population: 454900), (City: 'Tychy'; Country: 'Poland'; Population: 133178), (City: 'T鈘goviste'; Country: 'Romania'; Population: 98980), (City: 'T鈘gu Jiu'; Country: 'Romania'; Population: 98524), (City: 'T鈘gu Mures'; Country: 'Romania'; Population: 165153), (City: 'T閎essa'; Country: 'Algeria'; Population: 112007), (City: 'T閙ara'; Country: 'Morocco'; Population: 126303), (City: 'T閠ouan'; Country: 'Morocco'; Population: 277516), (City: 'T髍shavn'; Country: 'Faroe Islands'; Population: 14542), (City: 'T鷛pam'; Country: 'Mexico'; Population: 126475), (City: 'T歛ikovski'; Country: 'Russian Federation'; Population: 90000), (City: 'T歟boksary'; Country: 'Russian Federation'; Population: 459200), (City: 'T歟ljabinsk'; Country: 'Russian Federation'; Population: 1083200), (City: 'T歟repovets'; Country: 'Russian Federation'; Population: 324400), (City: 'T歟rkasy'; Country: 'Ukraine'; Population: 309000), (City: 'T歟rkessk'; Country: 'Russian Federation'; Population: 121700), (City: 'T歟rnigiv'; Country: 'Ukraine'; Population: 313000), (City: 'T歟rnivtsi'; Country: 'Ukraine'; Population: 259000), (City: 'T歩ta'; Country: 'Russian Federation'; Population: 309900), (City: 'Ube'; Country: 'Japan'; Population: 175206), (City: 'Uberaba'; Country: 'Brazil'; Population: 249225), (City: 'Uberl鈔dia'; Country: 'Brazil'; Population: 487222), (City: 'Ubon Ratchathani'; Country: 'Thailand'; Population: 116300), (City: 'Udaipur'; Country: 'India'; Population: 308571), (City: 'Udine'; Country: 'Italy'; Population: 94932), (City: 'Udon Thani'; Country: 'Thailand'; Population: 158100), (City: 'Ueda'; Country: 'Japan'; Population: 124217), (City: 'Ufa'; Country: 'Russian Federation'; Population: 1091200), (City: 'Ugep'; Country: 'Nigeria'; Population: 102600), (City: 'Uhta'; Country: 'Russian Federation'; Population: 98000), (City: 'Uijongbu'; Country: 'South Korea'; Population: 276111), (City: 'Uitenhage'; Country: 'South Africa'; Population: 192120), (City: 'Uiwang'; Country: 'South Korea'; Population: 108788), (City: 'Uji'; Country: 'Japan'; Population: 188735), (City: 'Ujjain'; Country: 'India'; Population: 362266), (City: 'Ujung Pandang'; Country: 'Indonesia'; Population: 1060257), (City: 'Ulan Bator'; Country: 'Mongolia'; Population: 773700), (City: 'Ulan-Ude'; Country: 'Russian Federation'; Population: 370400), (City: 'Ulanhot'; Country: 'China'; Population: 159538), (City: 'Ulhasnagar'; Country: 'India'; Population: 369077), (City: 'Uljanovsk'; Country: 'Russian Federation'; Population: 667400), (City: 'Ulm'; Country: 'Germany'; Population: 116103), (City: 'Ulsan'; Country: 'South Korea'; Population: 1084891), (City: 'Uluberia'; Country: 'India'; Population: 155172), (City: 'Uman'; Country: 'Ukraine'; Population: 90000), (City: 'Ume'; Country: 'Sweden'; Population: 104512), (City: 'Umlazi'; Country: 'South Africa'; Population: 339233), (City: 'Unayza'; Country: 'Saudi Arabia'; Population: 91100), (City: 'Unnao'; Country: 'India'; Population: 107425), (City: 'Uppsala'; Country: 'Sweden'; Population: 189569), (City: 'Urasoe'; Country: 'Japan'; Population: 96002), (City: 'Urawa'; Country: 'Japan'; Population: 469675), (City: 'Urayasu'; Country: 'Japan'; Population: 127550), (City: 'Urdaneta'; Country: 'Philippines'; Population: 111582), (City: 'Urmia'; Country: 'Iran'; Population: 435200), (City: 'Uruapan'; Country: 'Mexico'; Population: 265211), (City: 'Uruguaiana'; Country: 'Brazil'; Population: 126305), (City: 'Urumt歩 [躵黰qi]'; Country: 'China'; Population: 1310100), (City: 'Usak'; Country: 'Turkey'; Population: 128162), (City: 'Usolje-Sibirskoje'; Country: 'Russian Federation'; Population: 103500), (City: 'Ussurijsk'; Country: 'Russian Federation'; Population: 157300), (City: 'Ust-Ilimsk'; Country: 'Russian Federation'; Population: 105200), (City: 'Utrecht'; Country: 'Netherlands'; Population: 234323), (City: 'Utsunomiya'; Country: 'Japan'; Population: 440353), (City: 'Uttarpara-Kotrung'; Country: 'India'; Population: 100867), (City: 'Uvira'; Country: 'Congo, The Democratic Republic of the'; Population: 115590), (City: 'Uzgorod'; Country: 'Ukraine'; Population: 127000), (City: 'Vacoas-Phoenix'; Country: 'Mauritius'; Population: 98464), (City: 'Vadodara (Baroda)'; Country: 'India'; Population: 1031346), (City: 'Vaduz'; Country: 'Liechtenstein'; Population: 5043), (City: 'Valdivia'; Country: 'Chile'; Population: 133106), (City: 'Valencia'; Country: 'Spain'; Population: 739412), (City: 'Valencia'; Country: 'Philippines'; Population: 147924), (City: 'Valencia'; Country: 'Venezuela'; Population: 794246), (City: 'Valenzuela'; Country: 'Philippines'; Population: 485433), (City: 'Valera'; Country: 'Venezuela'; Population: 130281), (City: 'Valladolid'; Country: 'Spain'; Population: 319998), (City: 'Valle de Chalco Solidaridad'; Country: 'Mexico'; Population: 323113), (City: 'Valle de Santiago'; Country: 'Mexico'; Population: 130557), (City: 'Valle de la Pascua'; Country: 'Venezuela'; Population: 95927), (City: 'Valledupar'; Country: 'Colombia'; Population: 263247), (City: 'Vallejo'; Country: 'United States'; Population: 116760), (City: 'Valletta'; Country: 'Malta'; Population: 7073), (City: 'Valparai'; Country: 'India'; Population: 106523), (City: 'Valpara韘o'; Country: 'Chile'; Population: 293800), (City: 'Van'; Country: 'Turkey'; Population: 219319), (City: 'Vanadzor'; Country: 'Armenia'; Population: 172700), (City: 'Vancouver'; Country: 'Canada'; Population: 514008), (City: 'Vancouver'; Country: 'United States'; Population: 143560), (City: 'Vanderbijlpark'; Country: 'South Africa'; Population: 468931), (City: 'Vantaa'; Country: 'Finland'; Population: 178471), (City: 'Varamin'; Country: 'Iran'; Population: 107233), (City: 'Varanasi (Benares)'; Country: 'India'; Population: 929270), (City: 'Varginha'; Country: 'Brazil'; Population: 108314), (City: 'Varna'; Country: 'Bulgaria'; Population: 299801), (City: 'Vaughan'; Country: 'Canada'; Population: 147889), (City: 'Vejalpur'; Country: 'India'; Population: 89053), (City: 'Velbert'; Country: 'Germany'; Population: 89881), (City: 'Veliki Novgorod'; Country: 'Russian Federation'; Population: 299500), (City: 'Velikije Luki'; Country: 'Russian Federation'; Population: 116300), (City: 'Vellore'; Country: 'India'; Population: 175061), (City: 'Venezia'; Country: 'Italy'; Population: 277305), (City: 'Ventanilla'; Country: 'Peru'; Population: 101056), (City: 'Veracruz'; Country: 'Mexico'; Population: 457119), (City: 'Veraval'; Country: 'India'; Population: 123000), (City: 'Vereeniging'; Country: 'South Africa'; Population: 328535), (City: 'Verona'; Country: 'Italy'; Population: 255268), (City: 'Viam鉶'; Country: 'Brazil'; Population: 207557), (City: 'Vicente L髉ez'; Country: 'Argentina'; Population: 288341), (City: 'Vicenza'; Country: 'Italy'; Population: 109738), (City: 'Victoria'; Country: 'Hong Kong'; Population: 1312637), (City: 'Victoria'; Country: 'Mexico'; Population: 262686), (City: 'Victoria'; Country: 'Seychelles'; Population: 41000), (City: 'Victoria de las Tunas'; Country: 'Cuba'; Population: 132350), (City: 'Vidisha'; Country: 'India'; Population: 92917), (City: 'Vientiane'; Country: 'Laos'; Population: 531800), (City: 'Vigo'; Country: 'Spain'; Population: 283670), (City: 'Vihari'; Country: 'Pakistan'; Population: 92300), (City: 'Vijayawada'; Country: 'India'; Population: 701827), (City: 'Vila Velha'; Country: 'Brazil'; Population: 318758), (City: 'Villa Nueva'; Country: 'Guatemala'; Population: 101295), (City: 'Villavicencio'; Country: 'Colombia'; Population: 273140), (City: 'Villeurbanne'; Country: 'France'; Population: 124215), (City: 'Vilnius'; Country: 'Lithuania'; Population: 577969), (City: 'Vinh'; Country: 'Vietnam'; Population: 112455), (City: 'Vinnytsja'; Country: 'Ukraine'; Population: 391000), (City: 'Viransehir'; Country: 'Turkey'; Population: 106400), (City: 'Virginia Beach'; Country: 'United States'; Population: 425257), (City: 'Visalia'; Country: 'United States'; Population: 91762), (City: 'Vishakhapatnam'; Country: 'India'; Population: 752037), (City: 'Vitebsk'; Country: 'Belarus'; Population: 340000), (City: 'Vitoria-Gasteiz'; Country: 'Spain'; Population: 217154), (City: 'Vit髍ia'; Country: 'Brazil'; Population: 270626), (City: 'Vit髍ia da Conquista'; Country: 'Brazil'; Population: 253587), (City: 'Vit髍ia de Santo Ant鉶'; Country: 'Brazil'; Population: 113595), (City: 'Vizianagaram'; Country: 'India'; Population: 160359), (City: 'Vi馻 del Mar'; Country: 'Chile'; Population: 312493), (City: 'Vladikavkaz'; Country: 'Russian Federation'; Population: 310100), (City: 'Vladimir'; Country: 'Russian Federation'; Population: 337100), (City: 'Vladivostok'; Country: 'Russian Federation'; Population: 606200), (City: 'Volgodonsk'; Country: 'Russian Federation'; Population: 178200), (City: 'Volgograd'; Country: 'Russian Federation'; Population: 993400), (City: 'Vologda'; Country: 'Russian Federation'; Population: 302500), (City: 'Volta Redonda'; Country: 'Brazil'; Population: 240315), (City: 'Volzski'; Country: 'Russian Federation'; Population: 286900), (City: 'Vorkuta'; Country: 'Russian Federation'; Population: 92600), (City: 'Voronez'; Country: 'Russian Federation'; Population: 907700), (City: 'Votkinsk'; Country: 'Russian Federation'; Population: 101700), (City: 'Votorantim'; Country: 'Brazil'; Population: 91777), (City: 'Vung Tau'; Country: 'Vietnam'; Population: 145145), (City: 'V醨zea Grande'; Country: 'Brazil'; Population: 214435), (City: 'V鋝ter錽'; Country: 'Sweden'; Population: 126328), (City: 'Waco'; Country: 'United States'; Population: 113726), (City: 'Wad Madani'; Country: 'Sudan'; Population: 211362), (City: 'Wadi al-Sir'; Country: 'Jordan'; Population: 89104), (City: 'Wafangdian'; Country: 'China'; Population: 251733), (City: 'Wah'; Country: 'Pakistan'; Population: 198400), (City: 'Waitakere'; Country: 'New Zealand'; Population: 170600), (City: 'Wakayama'; Country: 'Japan'; Population: 391233), (City: 'Walbrzych'; Country: 'Poland'; Population: 136923), (City: 'Walsall'; Country: 'United Kingdom'; Population: 174739), (City: 'Wanxian'; Country: 'China'; Population: 156823), (City: 'Warangal'; Country: 'India'; Population: 447657), (City: 'Wardha'; Country: 'India'; Population: 102985), (City: 'Warraq al-Arab'; Country: 'Egypt'; Population: 127108), (City: 'Warren'; Country: 'United States'; Population: 138247), (City: 'Warri'; Country: 'Nigeria'; Population: 126100), (City: 'Warszawa'; Country: 'Poland'; Population: 1615369), (City: 'Waru'; Country: 'Indonesia'; Population: 124300), (City: 'Washington'; Country: 'United States'; Population: 572059), (City: 'Waterbury'; Country: 'United States'; Population: 107271), (City: 'Watford'; Country: 'United Kingdom'; Population: 113080), (City: 'Wazirabad'; Country: 'Pakistan'; Population: 89700), (City: 'Weifang'; Country: 'China'; Population: 428522), (City: 'Weihai'; Country: 'China'; Population: 128888), (City: 'Weinan'; Country: 'China'; Population: 140169), (City: 'Welkom'; Country: 'South Africa'; Population: 203296), (City: 'Wellington'; Country: 'New Zealand'; Population: 166700), (City: 'Wendeng'; Country: 'China'; Population: 133910), (City: 'Weno'; Country: 'Micronesia, Federated States of'; Population: 22000), (City: 'Wenzhou'; Country: 'China'; Population: 401871), (City: 'West Bromwich'; Country: 'United Kingdom'; Population: 146386), (City: 'West Covina'; Country: 'United States'; Population: 105080), (City: 'West Island'; Country: 'Cocos (Keeling) Islands'; Population: 167), (City: 'West Valley City'; Country: 'United States'; Population: 108896), (City: 'Westminster'; Country: 'United States'; Population: 100940), (City: 'Westonaria'; Country: 'South Africa'; Population: 159632), (City: 'Wichita'; Country: 'United States'; Population: 344284), (City: 'Wichita Falls'; Country: 'United States'; Population: 104197), (City: 'Wien'; Country: 'Austria'; Population: 1608144), (City: 'Wiesbaden'; Country: 'Germany'; Population: 268716), (City: 'Willemstad'; Country: 'Netherlands Antilles'; Population: 2345), (City: 'Windhoek'; Country: 'Namibia'; Population: 169000), (City: 'Windsor'; Country: 'Canada'; Population: 207588), (City: 'Winnipeg'; Country: 'Canada'; Population: 618477), (City: 'Winston-Salem'; Country: 'United States'; Population: 185776), (City: 'Witbank'; Country: 'South Africa'; Population: 167183), (City: 'Witten'; Country: 'Germany'; Population: 103384), (City: 'Wloclawek'; Country: 'Poland'; Population: 123373), (City: 'Woking/Byfleet'; Country: 'United Kingdom'; Population: 92000), (City: 'Wolfsburg'; Country: 'Germany'; Population: 121954), (City: 'Wollongong'; Country: 'Australia'; Population: 219761), (City: 'Wolverhampton'; Country: 'United Kingdom'; Population: 242000), (City: 'Wonderboom'; Country: 'South Africa'; Population: 283289), (City: 'Wonju'; Country: 'South Korea'; Population: 237460), (City: 'Wonsan'; Country: 'North Korea'; Population: 300148), (City: 'Worcester'; Country: 'United Kingdom'; Population: 95000), (City: 'Worcester'; Country: 'United States'; Population: 172648), (City: 'Worthing'; Country: 'United Kingdom'; Population: 100000), (City: 'Wroclaw'; Country: 'Poland'; Population: 636765), (City: 'Wuhai'; Country: 'China'; Population: 264081), (City: 'Wuhan'; Country: 'China'; Population: 4344600), (City: 'Wuhu'; Country: 'China'; Population: 425740), (City: 'Wuppertal'; Country: 'Germany'; Population: 368993), (City: 'Wuwei'; Country: 'China'; Population: 133101), (City: 'Wuxi'; Country: 'China'; Population: 830000), (City: 'Wuzhou'; Country: 'China'; Population: 210452), (City: 'W黵zburg'; Country: 'Germany'; Population: 127350), (City: 'Xai-Xai'; Country: 'Mozambique'; Population: 99442), (City: 'Xalapa'; Country: 'Mexico'; Population: 390058), (City: 'Xiangfan'; Country: 'China'; Population: 410407), (City: 'Xiangtan'; Country: 'China'; Population: 441968), (City: 'Xianning'; Country: 'China'; Population: 136811), (City: 'Xiantao'; Country: 'China'; Population: 222884), (City: 'Xianyang'; Country: 'China'; Population: 352125), (City: 'Xiaogan'; Country: 'China'; Population: 166280), (City: 'Xiaoshan'; Country: 'China'; Population: 162930), (City: 'Xichang'; Country: 'China'; Population: 134419), (City: 'Xilin Hot'; Country: 'China'; Population: 90646), (City: 'Xingcheng'; Country: 'China'; Population: 102384), (City: 'Xinghua'; Country: 'China'; Population: 161910), (City: 'Xingtai'; Country: 'China'; Population: 302789), (City: 'Xining'; Country: 'China'; Population: 700200), (City: 'Xintai'; Country: 'China'; Population: 281248), (City: 'Xinxiang'; Country: 'China'; Population: 473762), (City: 'Xinyang'; Country: 'China'; Population: 192509), (City: 'Xinyu'; Country: 'China'; Population: 173524), (City: 'Xinzhou'; Country: 'China'; Population: 98667), (City: 'Xi碼n'; Country: 'China'; Population: 2761400), (City: 'Xuangzhou'; Country: 'China'; Population: 112673), (City: 'Xuchang'; Country: 'China'; Population: 208815), (City: 'Xuzhou'; Country: 'China'; Population: 810000), (City: 'Yachiyo'; Country: 'Japan'; Population: 161222), (City: 'Yaizu'; Country: 'Japan'; Population: 117258), (City: 'Yakeshi'; Country: 'China'; Population: 377869), (City: 'Yamagata'; Country: 'Japan'; Population: 255617), (City: 'Yamaguchi'; Country: 'Japan'; Population: 138210), (City: 'Yamato'; Country: 'Japan'; Population: 208234), (City: 'Yamatokoriyama'; Country: 'Japan'; Population: 95165), (City: 'Yamoussoukro'; Country: 'C魌e d扞voire'; Population: 130000), (City: 'Yamuna Nagar'; Country: 'India'; Population: 144346), (City: 'Yanbu'; Country: 'Saudi Arabia'; Population: 119800), (City: 'Yancheng'; Country: 'China'; Population: 296831), (City: 'Yangjiang'; Country: 'China'; Population: 215196), (City: 'Yangmei'; Country: 'Taiwan'; Population: 126323), (City: 'Yangor'; Country: 'Nauru'; Population: 4050), (City: 'Yangquan'; Country: 'China'; Population: 362268), (City: 'Yangsan'; Country: 'South Korea'; Population: 163351), (City: 'Yangzhou'; Country: 'China'; Population: 312892), (City: 'Yanji'; Country: 'China'; Population: 230892), (City: 'Yantai'; Country: 'China'; Population: 452127), (City: 'Yan碼n'; Country: 'China'; Population: 113277), (City: 'Yao'; Country: 'Japan'; Population: 276421), (City: 'Yaound'; Country: 'Cameroon'; Population: 1372800), (City: 'Yaren'; Country: 'Nauru'; Population: 559), (City: 'Yatsushiro'; Country: 'Japan'; Population: 107661), (City: 'Yazd'; Country: 'Iran'; Population: 326776), (City: 'Ya碼n'; Country: 'China'; Population: 95900), (City: 'Yeotmal (Yavatmal)'; Country: 'India'; Population: 108578), (City: 'Yerevan'; Country: 'Armenia'; Population: 1248700), (City: 'Yibin'; Country: 'China'; Population: 241019), (City: 'Yichang'; Country: 'China'; Population: 371601), (City: 'Yichun'; Country: 'China'; Population: 800000), (City: 'Yichun'; Country: 'China'; Population: 151585), (City: 'Yinchuan'; Country: 'China'; Population: 544500), (City: 'Yingkou'; Country: 'China'; Population: 421589), (City: 'Yixing'; Country: 'China'; Population: 200824), (City: 'Yiyang'; Country: 'China'; Population: 185818), (City: 'Yizheng'; Country: 'China'; Population: 109268), (City: 'Yogyakarta'; Country: 'Indonesia'; Population: 418944), (City: 'Yokkaichi'; Country: 'Japan'; Population: 288173), (City: 'Yokosuka'; Country: 'Japan'; Population: 430200), (City: 'Yonago'; Country: 'Japan'; Population: 136461), (City: 'Yonezawa'; Country: 'Japan'; Population: 95592), (City: 'Yong-in'; Country: 'South Korea'; Population: 242643), (City: 'Yongchon'; Country: 'South Korea'; Population: 113511), (City: 'Yongju'; Country: 'South Korea'; Population: 131097), (City: 'Yong碼n'; Country: 'China'; Population: 111762), (City: 'Yonkers'; Country: 'United States'; Population: 196086), (City: 'York'; Country: 'United Kingdom'; Population: 104425), (City: 'York'; Country: 'Canada'; Population: 154980), (City: 'Yosu'; Country: 'South Korea'; Population: 183596), (City: 'Yuanjiang'; Country: 'China'; Population: 107004), (City: 'Yuanlin'; Country: 'Taiwan'; Population: 126402), (City: 'Yuci'; Country: 'China'; Population: 191356), (City: 'Yueyang'; Country: 'China'; Population: 302800), (City: 'Yulin'; Country: 'China'; Population: 144467), (City: 'Yumen'; Country: 'China'; Population: 109234), (City: 'Yuncheng'; Country: 'China'; Population: 108359), (City: 'Yungho'; Country: 'Taiwan'; Population: 227700), (City: 'Yungkang'; Country: 'Taiwan'; Population: 193005), (City: 'Yushu'; Country: 'China'; Population: 131861), (City: 'Yuyao'; Country: 'China'; Population: 114065), (City: 'Yuzhou'; Country: 'China'; Population: 92889), (City: 'Zaanstad'; Country: 'Netherlands'; Population: 135621), (City: 'Zabol'; Country: 'Iran'; Population: 100887), (City: 'Zabrze'; Country: 'Poland'; Population: 200177), (City: 'Zacatecas'; Country: 'Mexico'; Population: 123700), (City: 'Zagazig'; Country: 'Egypt'; Population: 267351), (City: 'Zagreb'; Country: 'Croatia'; Population: 706770), (City: 'Zahedan'; Country: 'Iran'; Population: 419518), (City: 'Zalantun'; Country: 'China'; Population: 130031), (City: 'Zama'; Country: 'Japan'; Population: 122046), (City: 'Zamboanga'; Country: 'Philippines'; Population: 601794), (City: 'Zamora'; Country: 'Mexico'; Population: 161191), (City: 'Zanjan'; Country: 'Iran'; Population: 286295), (City: 'Zanzibar'; Country: 'Tanzania'; Population: 157634), (City: 'Zaoyang'; Country: 'China'; Population: 162198), (City: 'Zaozhuang'; Country: 'China'; Population: 380846), (City: 'Zapopan'; Country: 'Mexico'; Population: 1002239), (City: 'Zaporizzja'; Country: 'Ukraine'; Population: 848000), (City: 'Zaragoza'; Country: 'Spain'; Population: 603367), (City: 'Zaria'; Country: 'Nigeria'; Population: 379200), (City: 'Zelenodolsk'; Country: 'Russian Federation'; Population: 100200), (City: 'Zelenograd'; Country: 'Russian Federation'; Population: 207100), (City: 'Zeleznodoroznyi'; Country: 'Russian Federation'; Population: 100100), (City: 'Zeleznogorsk'; Country: 'Russian Federation'; Population: 96900), (City: 'Zeleznogorsk'; Country: 'Russian Federation'; Population: 94000), (City: 'Zenica'; Country: 'Bosnia and Herzegovina'; Population: 96027), (City: 'Zhangjiagang'; Country: 'China'; Population: 97994), (City: 'Zhangjiakou'; Country: 'China'; Population: 530000), (City: 'Zhangjiang'; Country: 'China'; Population: 400997), (City: 'Zhangzhou'; Country: 'China'; Population: 181424), (City: 'Zhaodong'; Country: 'China'; Population: 179976), (City: 'Zhaoqing'; Country: 'China'; Population: 194784), (City: 'Zhengzhou'; Country: 'China'; Population: 2107200), (City: 'Zhenjiang'; Country: 'China'; Population: 368316), (City: 'Zhezqazghan'; Country: 'Kazakstan'; Population: 90000), (City: 'Zhongshan'; Country: 'China'; Population: 278829), (City: 'Zhoukou'; Country: 'China'; Population: 146288), (City: 'Zhoushan'; Country: 'China'; Population: 156317), (City: 'Zhucheng'; Country: 'China'; Population: 102134), (City: 'Zhuhai'; Country: 'China'; Population: 164747), (City: 'Zhumadian'; Country: 'China'; Population: 123232), (City: 'Zhuzhou'; Country: 'China'; Population: 409924), (City: 'Zibo'; Country: 'China'; Population: 1140000), (City: 'Zielona G髍a'; Country: 'Poland'; Population: 118182), (City: 'Zigong'; Country: 'China'; Population: 393184), (City: 'Ziguinchor'; Country: 'Senegal'; Population: 192000), (City: 'Zinacantepec'; Country: 'Mexico'; Population: 121715), (City: 'Zinder'; Country: 'Niger'; Population: 120892), (City: 'Zit醕uaro'; Country: 'Mexico'; Population: 137970), (City: 'Zixing'; Country: 'China'; Population: 110048), (City: 'Zlatoust'; Country: 'Russian Federation'; Population: 196900), (City: 'Zoetermeer'; Country: 'Netherlands'; Population: 110214), (City: 'Zonguldak'; Country: 'Turkey'; Population: 111542), (City: 'Zukovski'; Country: 'Russian Federation'; Population: 96500), (City: 'Zumpango'; Country: 'Mexico'; Population: 99781), (City: 'Zunyi'; Country: 'China'; Population: 261862), (City: 'Zwickau'; Country: 'Germany'; Population: 104146), (City: 'Zwolle'; Country: 'Netherlands'; Population: 105819), (City: 'Zytomyr'; Country: 'Ukraine'; Population: 297000), (City: 'Z黵ich'; Country: 'Switzerland'; Population: 336800), (City: '[San Crist骲al de] la Laguna'; Country: 'Spain'; Population: 127945), (City: 'al-Amara'; Country: 'Iraq'; Population: 208797), (City: 'al-Arish'; Country: 'Egypt'; Population: 100447), (City: 'al-Ayn'; Country: 'United Arab Emirates'; Population: 225970), (City: 'al-Dammam'; Country: 'Saudi Arabia'; Population: 482300), (City: 'al-Diwaniya'; Country: 'Iraq'; Population: 196519), (City: 'al-Faiyum'; Country: 'Egypt'; Population: 260964), (City: 'al-Fashir'; Country: 'Sudan'; Population: 141884), (City: 'al-Hawamidiya'; Country: 'Egypt'; Population: 91700), (City: 'al-Hawiya'; Country: 'Saudi Arabia'; Population: 93900), (City: 'al-Hilla'; Country: 'Iraq'; Population: 268834), (City: 'al-Hufuf'; Country: 'Saudi Arabia'; Population: 225800), (City: 'al-Kharj'; Country: 'Saudi Arabia'; Population: 152100), (City: 'al-Khubar'; Country: 'Saudi Arabia'; Population: 141700), (City: 'al-Kut'; Country: 'Iraq'; Population: 183183), (City: 'al-Mahallat al-Kubra'; Country: 'Egypt'; Population: 395402), (City: 'al-Manama'; Country: 'Bahrain'; Population: 148000), (City: 'al-Mansura'; Country: 'Egypt'; Population: 369621), (City: 'al-Minya'; Country: 'Egypt'; Population: 201360), (City: 'al-Mubarraz'; Country: 'Saudi Arabia'; Population: 219100), (City: 'al-Mukalla'; Country: 'Yemen'; Population: 122400), (City: 'al-Najaf'; Country: 'Iraq'; Population: 309010), (City: 'al-Nasiriya'; Country: 'Iraq'; Population: 265937), (City: 'al-Qadarif'; Country: 'Sudan'; Population: 191164), (City: 'al-Qamishliya'; Country: 'Syria'; Population: 144286), (City: 'al-Qatif'; Country: 'Saudi Arabia'; Population: 98900), (City: 'al-Ramadi'; Country: 'Iraq'; Population: 192556), (City: 'al-Raqqa'; Country: 'Syria'; Population: 108020), (City: 'al-Rusayfa'; Country: 'Jordan'; Population: 137247), (City: 'al-Salimiya'; Country: 'Kuwait'; Population: 130215), (City: 'al-Sib'; Country: 'Oman'; Population: 155000), (City: 'al-Sulaymaniya'; Country: 'Iraq'; Population: 364096), (City: 'al-Taif'; Country: 'Saudi Arabia'; Population: 416100), (City: 'al-Tuqba'; Country: 'Saudi Arabia'; Population: 125700), (City: 'al-Zarqa'; Country: 'Jordan'; Population: 389815), (City: 'al-Zawiya'; Country: 'Libyan Arab Jamahiriya'; Population: 89338), (City: '磗-Hertogenbosch'; Country: 'Netherlands'; Population: 129170), (City: '羐uas Lindas de Goi醩'; Country: 'Brazil'; Population: 89200), (City: '舝hus'; Country: 'Denmark'; Population: 284846), (City: '莖rlu'; Country: 'Turkey'; Population: 123300), (City: '莖rum'; Country: 'Turkey'; Population: 145495), (City: '謗ebro'; Country: 'Sweden'; Population: 124207), (City: '謘kemen'; Country: 'Kazakstan'; Population: 311000), (City: '趕t?nad Labem'; Country: 'Czech Republic'; Population: 95491), (City: '躵genc'; Country: 'Uzbekistan'; Population: 138900), (City: '奱hty'; Country: 'Russian Federation'; Population: 221800), (City: '奿auliai'; Country: 'Lithuania'; Population: 146563), (City: '妎stka'; Country: 'Ukraine'; Population: 90000), (City: '妕歰lkovo'; Country: 'Russian Federation'; Population: 104900), (City: '妘men'; Country: 'Bulgaria'; Population: 94686) ); implementation end.
{ [===========================================] [?]uDllFromMem - Loading a DLL from Memory[?] [v] Version 1.0 [v] [c] Hamtaro aka CorVu5 [c] [@] hamtaro.6x.to OR corvu5.6x.to [@] [================Description================] [With this Code, you can load a DLL in your ] [application directly from Memory, the file ] [doesnt have to be present on your Harddrive] [===================Note====================] [ This example doesnt work with Bound ] [ Import Tables at this time ] [==================thx to===================] [ CDW, Cryptocrack ] [ & Joachim Bauch for his ] [ GetSectionProtection function ] [===========================================] [ there must be 50 ways to learn to hover ] [===========================================] MODIFIED BY ARTHURPRS for 1clickmusic - fixed some bugs - human readable code - remove garbage - added some compiler directives } unit uDllfromMem; interface {$DEBUGINFO OFF} {$WARNINGS OFF} {$HINTS OFF} uses Windows; type PImageBaseRelocation = ^TImageBaseRelocation; _IMAGE_BASE_RELOCATION = packed record VirtualAddress: DWORD; SizeOfBlock: DWORD; end; {$EXTERNALSYM _IMAGE_BASE_RELOCATION} TImageBaseRelocation = _IMAGE_BASE_RELOCATION; IMAGE_BASE_RELOCATION = _IMAGE_BASE_RELOCATION; {$EXTERNALSYM IMAGE_BASE_RELOCATION} type PImageImportDescriptor = ^TImageImportDescriptor; TImageImportDescriptor = packed record OriginalFirstThunk: dword; TimeDateStamp: dword; ForwarderChain: dword; Name: dword; FirstThunk: dword; end; type PImageImportByName = ^TImageImportByName; TImageImportByName = packed record Hint: WORD; Name: array[0..255] of Char; end; type PImageThunkData = ^TImageThunkData; TImageThunkData = packed record case integer of 0: (ForwarderString: PBYTE); 1: (FunctionPtr: PDWORD); 2: (Ordinal: DWORD); 3: (AddressOfData: PImageImportByName); end; type TDllEntryProc = function(hinstdll: THandle; fdwReason: DWORD; lpReserved: Pointer): BOOL; stdcall; function memLoadLibrary(FileBase: Pointer): Pointer; function memGetProcAddress(Physbase: Pointer; NameOfFunction: string): Pointer; function memFreeLibrary(physbase: Pointer): Boolean; const IMAGE_REL_BASED_HIGHLOW = 3; IMAGE_ORDINAL_FLAG32 = DWORD($80000000); implementation function GetSectionProtection(ImageScn: cardinal): cardinal; begin Result := 0; if (ImageScn and IMAGE_SCN_MEM_NOT_CACHED) <> 0 then begin Result := Result or PAGE_NOCACHE; end; if (ImageScn and IMAGE_SCN_MEM_EXECUTE) <> 0 then begin if (ImageScn and IMAGE_SCN_MEM_READ) <> 0 then begin if (ImageScn and IMAGE_SCN_MEM_WRITE) <> 0 then begin Result := Result or PAGE_EXECUTE_READWRITE end else begin Result := Result or PAGE_EXECUTE_READ end; end else if (ImageScn and IMAGE_SCN_MEM_WRITE) <> 0 then begin Result := Result or PAGE_EXECUTE_WRITECOPY end else begin Result := Result or PAGE_EXECUTE end; end else if (ImageScn and IMAGE_SCN_MEM_READ) <> 0 then begin if (ImageScn and IMAGE_SCN_MEM_WRITE) <> 0 then begin Result := Result or PAGE_READWRITE end else begin Result := Result or PAGE_READONLY end end else if (ImageScn and IMAGE_SCN_MEM_WRITE) <> 0 then begin Result := Result or PAGE_WRITECOPY end else begin Result := Result or PAGE_NOACCESS; end; end; function memLoadLibrary(FileBase: Pointer): Pointer; var pfilentheader: PImageNtHeaders; pfiledosheader: PImageDosHeader; pphysntheader: PImageNtHeaders; pphysdosheader: PImageDosHeader; physbase: Pointer; pphyssectionheader: PImageSectionHeader; i: Integer; importsDir: PImageDataDirectory; importsBase: Pointer; importDesc: PImageImportDescriptor; importThunk: PImageThunkData; dll_handle: Cardinal; importbyname: pimageimportbyname; relocbase: Pointer; relocdata: PIMAGeBaseRElocation; relocitem: PWORD; reloccount: Integer; dllproc: TDLLEntryProc; begin try pfiledosheader := filebase; pfilentheader := Pointer(Cardinal(filebase) + pfiledosheader^._lfanew); ////////////////////// ///////////allozieren/ {physbase := VirtualAlloc(Pointer(pfilentheader^.OptionalHeader.ImageBase), pfilentheader^.OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_READWRITE); if physbase = nil then begin physbase := VirtualAlloc(nil, pfilentheader^.OptionalHeader.SizeOfImage, MEM_RESERVE or MEM_COMMIT, PAGE_READWRITE); end;} // above code does not work, this work physbase := VirtualAlloc(nil, pfilentheader^.OptionalHeader.SizeOfImage, MEM_RESERVE or MEM_COMMIT, PAGE_READWRITE); /////////////////////////// ///////////header kopieren/ Move(filebase^, physbase^, pfilentheader^.OptionalHeader.SizeOfHeaders); //header im memory finden & anpassen pphysdosheader := physbase; pphysntheader := Pointer(Cardinal(physbase) + pphysdosheader^._lfanew); pphysntheader^.OptionalHeader.ImageBase := Cardinal(physbase); /////////////////////////////// /////////////sections kopieren/ pphyssectionheader := Pointer(Cardinal(pphysntheader) + SizeOf(TIMAGENTHEADERS)); for i := 0 to (pphysntheader^.FileHeader.NumberOfSections - 1) do begin if (pphyssectionheader^.SizeOfRawData = 0) then //keine raw data FillChar(Pointer(Cardinal(physbase) + pphyssectionheader^.VirtualAddress)^, pphyssectionheader^.Misc.VirtualSize, 0) else //raw data vorhanden Move(Pointer(Cardinal(filebase) + pphyssectionheader^.PointerToRawData)^, Pointer(Cardinal(physbase) + pphyssectionheader^.VirtualAddress)^, pphyssectionheader^.SizeOfRawData); pphyssectionheader^.Misc.PhysicalAddress := Cardinal(physbase) + pphyssectionheader^.VirtualAddress; Inc(pphyssectionheader); //next one please // same as above //pphyssectionheader := Pointer(Cardinal(pphyssectionheader) + SizeOf(TIMAGESECTIONHEADER)); end; ///////////////////// /////////////relocs/ relocbase := Pointer(Cardinal(physbase) + pphysntheader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress); relocData := relocbase; while (Cardinal(relocdata) - Cardinal(relocbase)) < pphysntheader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size do begin reloccount := ((relocdata.SizeOfBlock - 8) div 2); relocitem := Pointer(Cardinal(relocdata) + 8); for i := 0 to (reloccount - 1) do begin if (relocitem^ shr 12) = IMAGE_REL_BASED_HIGHLOW then begin Inc(PDWord(Cardinal(physbase) + relocdata.VirtualAddress + (relocitem^ and $FFF))^, (Cardinal(physbase) - pfilentheader.OptionalHeader.ImageBase)); end; Inc(relocitem); //relocitem := Pointer(Cardinal(relocitem) + SizeOf(WORD)); end; Inc(PByte(relocdata), relocdata.SizeOfBlock); // same as above //next one please //relocdata := Pointer(Cardinal(relocdata) + relocdata.SizeOfBlock); end; ////////////////////// /////////////imports/ importsBase := Pointer(Cardinal(physbase) + pphysntheader^.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); importDesc := importsBase; while (importDesc.Name) <> 0 do begin dll_handle := LoadLibrary(pchar(Cardinal(physbase) + importdesc.Name)); importDesc.ForwarderChain := dll_handle; importThunk := Pointer(Cardinal(physbase) + importDesc.FirstThunk); while (importThunk.Ordinal <> 0) do begin importbyname := Pointer(Cardinal(physbase) + importThunk.Ordinal); //Später noch überprüfen ob OriginalFirstThunk = 0 if (importThunk.Ordinal and IMAGE_ORDINAL_FLAG32) <> 0 then //ordinal importThunk.FunctionPtr := GetProcaddress(dll_handle, pchar(importThunk.Ordinal and $FFFF)) else //normal importThunk.FunctionPtr := GetProcAddress(dll_handle, importByname.name); Inc(importThunk); // same as above //next one, please //importThunk := Pointer(Cardinal(importThunk) + SizeOf(TIMAGETHUNKDATA)); end; Inc(importDesc); //next one, please // same as above //importDesc := Pointer(Cardinal(importDesc) + sizeOf(TIMAGEIMPORTDESCRIPTOR)); end; ///////////////////////////////// ////////Section protection & so/ pphyssectionheader := Pointer(Cardinal(pphysntheader) + SizeOf(TIMAGENTHEADERS)); for i := 0 to (pphysntheader^.FileHeader.NumberOfSections - 1) do begin VirtualProtect(Pointer(Cardinal(physbase) + pphyssectionheader^.VirtualAddress), pphyssectionheader^.Misc.VirtualSize, GetSectionProtection(pphyssectionheader.Characteristics), nil); Inc(pphyssectionheader); //pphyssectionheader := Pointer(Cardinal(pphyssectionheader) + SizeOf(TIMAGESECTIONHEADER)); end; //////////////////////////////// ////////////////Dll entry proc/ dllproc := Pointer(Cardinal(physbase) + pphysntheader.OptionalHeader.AddressOfEntryPoint); dllproc(cardinal(physbase), DLL_PROCESS_ATTACH, nil); Result := physbase; except Result := nil; end; end; function memGetProcAddress(Physbase: Pointer; NameOfFunction: string): Pointer; var pdosheader: PImageDosHeader; pntheader: PImageNtHeaders; pexportdir: PImageExportDirectory; i: Integer; pexportname: PDWORD; //pexportordinal: PWORD; pexportFunction: PDWORD; begin Result := nil; pdosheader := physbase; pntheader := Pointer(Cardinal(physbase) + pdosheader._lfanew); pexportdir := Pointer(Cardinal(physbase) + pntheader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); if pexportdir.NumberOfFunctions or pexportdir.NumberOfNames = 0 then exit; pexportName := Pointer(Cardinal(physbase) + Cardinal(pexportDir.AddressOfNames)); //pexportordinal := Pointer(Cardinal(physbase) + Cardinal(pexportDir.AddressOfNameOrdinals)); pexportFunction := Pointer(Cardinal(physbase) + Cardinal(pexportDir.AddressOfFunctions)); for i := 0 to (pexportdir.NumberOfNames - 1) do begin if string(PChar(Pointer(Cardinal(physbase) + pexportName^))) = NameOfFunction then begin Result := Pointer(Cardinal(physbase) + pexportFunction^); Break; end; //next one, please Inc(pexportFunction); Inc(pexportName); //Inc(pexportOrdinal); end; end; function memFreeLibrary(physbase: Pointer): Boolean; var dllproc: TDllEntryProc; begin try Result := True; // ugly code to avoid needing the globalvariable dllproc := TDllEntryProc(Cardinal(physbase) + PImageNtHeaders(Cardinal(physbase) + PImageDosHeader(physbase)^._lfanew)^.OptionalHeader.AddressOfEntryPoint); dllproc(Cardinal(physbase), DLL_PROCESS_DETACH, nil); VirtualFree(physbase, 0, MEM_RELEASE); except Result := False; end; end; end.
unit UExemploIni; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IniFiles; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; ListBox1: TListBox; Button5: TButton; Button6: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); private FCaminho: String; FIni: TiniFile; public property Caminho: String read FCaminho write FCaminho; property Ini: TiniFile read FIni write FIni; constructor Create(AOwner: TComponent); override; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin try FIni := TiniFile.Create(Caminho); FIni.WriteString('sessao1', 'variavel1', 'valor1'); FIni.WriteString('sessao2', 'variavel1', 'valor1'); FIni.WriteString('sessao3', 'variavel1', 'valor1'); finally FreeAndNil(FIni); end; end; procedure TForm1.Button2Click(Sender: TObject); var S: String; begin if FileExists(Caminho) then begin try FIni := TiniFile.Create(Caminho); S := Ini.ReadString('sessao1', 'variavel1', ''); if (S <> EmptyStr) then ShowMessage(S); finally FreeAndNil(FIni); end; end; end; procedure TForm1.Button3Click(Sender: TObject); var St: TStringList; begin try FIni := TiniFile.Create(Caminho); St := TStringList.Create; FIni.ReadSections(St); ShowMessage(inttostr(St.Count)); finally FreeAndNil(FIni); FreeAndNil(St); end; end; procedure TForm1.Button4Click(Sender: TObject); begin try FIni := TiniFile.Create(Caminho); if FIni.SectionExists('sessao1') then ShowMessage('existe sessao') else ShowMessage('nao existe sessao'); finally FreeAndNil(FIni); end; end; procedure TForm1.Button5Click(Sender: TObject); begin try FIni := TiniFile.Create(Caminho); FIni.ReadSectionValues('sessao1', ListBox1.Items); // FIni.ReadSubSections('sessao1', ListBox1.Items); finally FreeAndNil(FIni); end; end; procedure TForm1.Button6Click(Sender: TObject); begin try FIni := TiniFile.Create(Caminho); FIni.EraseSection('sessao1'); FIni.EraseSection('sessao2'); finally FreeAndNil(FIni); end; end; constructor TForm1.Create(AOwner: TComponent); begin inherited; Caminho := ExtractFilePath(ParamStr(0)) + '\meu_ini.ini'; end; end.
object MainForm: TMainForm Left = 219 Top = 129 ActiveControl = FileList BorderIcons = [biSystemMenu, biMinimize] BorderStyle = bsSingle Caption = 'LEA-128 from files' ClientHeight = 313 ClientWidth = 657 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -14 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter OnClose = FormClose OnCreate = FormCreate PixelsPerInch = 120 TextHeight = 16 object InfoLbl: TLabel Left = 8 Top = 36 Width = 505 Height = 17 AutoSize = False Caption = 'Des fichiers d'#39'exemple, presque semblables sont fournis dans le ' + 'dossier "Samples".' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -15 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False WordWrap = True end object AddBtn: TButton Left = 8 Top = 8 Width = 537 Height = 25 Caption = 'Open file ...' TabOrder = 0 OnClick = AddBtnClick end object ClearBtn: TButton Left = 552 Top = 8 Width = 97 Height = 25 Caption = 'Clear' TabOrder = 1 OnClick = ClearBtnClick end object FileList: TListView Left = 8 Top = 56 Width = 641 Height = 249 Columns = < item Caption = 'Name' Width = 140 end item Caption = 'Size' Width = 90 end item Caption = 'Hash' Width = 310 end item Alignment = taCenter Caption = 'Time' Width = 80 end> Font.Charset = RUSSIAN_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Courier New' Font.Style = [] ReadOnly = True RowSelect = True ParentFont = False TabOrder = 2 ViewStyle = vsReport end object OpenDlg: TOpenDialog Filter = 'Tous les fichiers|*.*' Options = [ofHideReadOnly, ofAllowMultiSelect, ofEnableSizing] Title = 'Ajouter un fichier ...' Left = 24 Top = 72 end end
unit FGeradorDeSQL; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TfrmGeradorDeSql = class(TForm) memColunas: TMemo; memTabelas: TMemo; memCondicoes: TMemo; btnGerarSql: TButton; memSQL: TMemo; lblColunas: TLabel; lblTabelas: TLabel; lblCondicoes: TLabel; lblSQL: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnGerarSqlClick(Sender: TObject); private fListaColunas: TStringList; fListaTabelas: TStringList; fListaCondicoes: TStringList; procedure ValidarMemosPreenchidos; public procedure LimparListas; procedure AdicionarColuna(psColuna: String); procedure AdicionarTabela(psTabela: String); procedure AdicionarCondicao(psCondicao: String); function GerarSQL: String; end; var frmGeradorDeSql: TfrmGeradorDeSql; implementation uses UConstantes; {$R *.dfm} procedure TfrmGeradorDeSql.AdicionarColuna(psColuna: String); begin fListaColunas.Add(psColuna); end; procedure TfrmGeradorDeSql.AdicionarCondicao(psCondicao: String); begin fListaCondicoes.Add(psCondicao); end; procedure TfrmGeradorDeSql.AdicionarTabela(psTabela: String); begin fListaTabelas.Add(psTabela); end; procedure TfrmGeradorDeSql.btnGerarSqlClick(Sender: TObject); var lsAux: String; begin memSQL.Clear; ValidarMemosPreenchidos; LimparListas; for lsAux in memColunas.Lines do AdicionarColuna(lsAux); for lsAux in memTabelas.Lines do AdicionarTabela(lsAux); for lsAux in memCondicoes.Lines do AdicionarCondicao(lsAux); memSQL.Lines.Text := GerarSQL; end; procedure TfrmGeradorDeSql.FormCreate(Sender: TObject); begin fListaColunas := TStringList.Create; fListaTabelas := TStringList.Create; fListaCondicoes := TStringList.Create; end; procedure TfrmGeradorDeSql.FormDestroy(Sender: TObject); begin FreeAndNil(fListaColunas); FreeAndNil(fListaTabelas); FreeAndNil(fListaCondicoes); end; function TfrmGeradorDeSql.GerarSQL: String; var lsAux: String; begin result := constSELECTClause; for lsAux in fListaColunas do result := result + ' ' + lsAux + ','; Delete(result, result.Length, 1); result := result + constCRLF + constFROMClause; for lsAux in fListaTabelas do result := result + ' ' + lsAux + ','; Delete(result, result.Length, 1); result := result + constCRLF + constWHEREClause; for lsAux in fListaCondicoes do result := result + ' ' + lsAux + ' ' + constANDClause; Delete(result, result.Length-2, 3); end; procedure TfrmGeradorDeSql.LimparListas; begin fListaColunas.Clear; fListaTabelas.Clear; fListaCondicoes.Clear; end; procedure TfrmGeradorDeSql.ValidarMemosPreenchidos; begin if memColunas.Lines.Text.IsEmpty or memTabelas.Lines.Text.IsEmpty or memCondicoes.Lines.Text.IsEmpty then raise Exception.Create('Atenção! Preencha todos as informações para gerar o SQL.'); end; end.
unit uCefDomVisitFunc; interface uses Classes, System.SysUtils, System.Types, System.IoUtils, System.Generics.Collections, // uCEFInterfaces, uCEFTypes, // uCefUtilFunc; type TCefDomNodeFilterProc = function(const ANode: ICefDomNode): Boolean; function CefVisitGetElementsRoot(const ARoot: ICefDomNode; const AElement: TElementParams; const AFilter: TCefDomNodeFilterProc; const ALimit: Integer): TArray<ICefDomNode>; function CefVisitGetElements(const ADocument: ICefDomDocument; const AElement: TElementParams; const AFilter: TCefDomNodeFilterProc; const ALimit: Integer): TArray<ICefDomNode>; function CefVisitGetElementRoot(const ARoot: ICefDomNode; const AElement: TElementParams; const AFilter: TCefDomNodeFilterProc): ICefDomNode; function CefVisitGetElement(const ADocument: ICefDomDocument; const AElement: TElementParams; const AFilter: TCefDomNodeFilterProc = nil): ICefDomNode; function CefVisitGetElementByName(const ADocument: ICefDomDocument; const AName: string): ICefDomNode; implementation uses // uRegExprFunc, uStringUtils; function CefVisitGetElementsRoot(const ARoot: ICefDomNode; const AElement: TElementParams; const AFilter: TCefDomNodeFilterProc; const ALimit: Integer): TArray<ICefDomNode>; var l_elem: ICefDomNode; l_arr: TList<ICefDomNode>; l_class, l_name, l_tag: string; function TestTag(const AElem: ICefDomNode): Boolean; begin Result := l_tag.IsEmpty or (l_tag = LowerCase(Trim(AElem.ElementTagName))) end; function TestName(const AElem: ICefDomNode): Boolean; begin Result := l_name.IsEmpty or (l_name = LowerCase(Trim(AElem.GetElementAttribute('name')))) end; function TestClass(const AElem: ICefDomNode): Boolean; var elclass, z: string; begin if l_class.IsEmpty then Exit(True); elclass := LowerCase(Trim(AElem.GetElementAttribute('class'))); while elclass <> '' do begin z := Trim(StrCut(elclass, [#0..#32])); if z = l_class then Exit(True); elclass := Trim(elclass); end; Exit(False); end; function TestAttr(const AElem: ICefDomNode): Boolean; var attrval: string; begin if AElement.AttrName.IsEmpty or AElement.AttrValue.IsEmpty then Exit(True); attrval := LowerCase(Trim((AElem.GetElementAttribute(AElement.AttrName)))); Result := YesRegExpr(attrval, AElement.AttrValue) end; function TestText(const AElem: ICefDomNode): Boolean; var val: string; begin if AElement.Text.IsEmpty then Exit(True); if not AElem.HasChildren then Exit(False); if AElem.FirstChild = nil then Exit(False); if not AElem.FirstChild.IsSame(AElem.LastChild) then // there is one child Exit(False); if not AElem.FirstChild.IsText then Exit(False); val := AElem.FirstChild.AsMarkup; Result := YesRegExpr(val, AElement.Text); end; function TestFilter(const AElem: ICefDomNode): Boolean; begin if Assigned(AElem) then if AElem.IsElement then if TestTag(AElem) then if TestName(AElem) then if TestClass(AElem) then if not Assigned(AFilter) or AFilter(AElem) then if TestAttr(aElem) then if TestText(aElem) then Exit(True); Exit(False); end; function ProcessNode(const ANode: ICefDomNode; const AList: TList<ICefDomNode>; const ALevel: Integer): Boolean; var Node: ICefDomNode; begin if Assigned(ANode) then begin Node := ANode.FirstChild; while Assigned(Node) do begin if TestFilter(Node) then begin AList.Add(Node); if AList.Count >= ALimit then Exit(True); end; if ProcessNode(Node, AList, ALevel + 1) then Exit(True); Node := Node.NextSibling; end; end; Exit(False) end; begin Result := nil; if ARoot = nil then Exit; l_class := LowerCase(Trim(AElement.Class_)); l_name := LowerCase(Trim(AElement.Name)); l_tag := LowerCase(Trim(AElement.Tag)); if AElement.Id <> '' then begin l_elem := ARoot.Document.getElementById(AElement.Id); if TestFilter(l_elem) then begin SetLength(Result, 1); Result[0] := l_elem; end; Exit; end; l_arr := TList<ICefDomNode>.Create; try ProcessNode(ARoot, l_arr, 0); Result := l_arr.ToArray; finally l_arr.Free end; end; function CefVisitGetElements(const ADocument: ICefDomDocument; const AElement: TElementParams; const AFilter: TCefDomNodeFilterProc; const ALimit: Integer): TArray<ICefDomNode>; begin Result := nil; if ADocument = nil then Exit; Result := CefVisitGetElementsRoot(ADocument.Document, AElement, AFilter, ALimit) end; function CefVisitGetElement(const ADocument: ICefDomDocument; const AElement: TElementParams; const AFilter: TCefDomNodeFilterProc): ICefDomNode; var arr: TArray<ICefDomNode>; begin arr := CefVisitGetElements(ADocument, AElement, AFilter, 1); if Length(arr) > 0 then Exit(arr[0]); Exit(nil) end; function CefVisitGetElementRoot(const ARoot: ICefDomNode; const AElement: TElementParams; const AFilter: TCefDomNodeFilterProc): ICefDomNode; var arr: TArray<ICefDomNode>; begin arr := CefVisitGetElementsRoot(ARoot, AElement, AFilter, 1); if Length(arr) > 0 then Exit(arr[0]); Exit(nil) end; function CefVisitGetElementByName(const ADocument: ICefDomDocument; const AName: string): ICefDomNode; begin Result := CefVisitGetElement(ADocument, TElementParams.CreateTagName('', AName), nil) end; end.
{$include kode.inc} unit kode_filter_allpass; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- type KFilter_Allpass = class private a : Single; x0,x1,x2 : Single; y0,y1,y2 : single; public constructor create(ACoefficient:Single); //destructor destroy; override; function process(AInput:Single) : Single; inline; //function process0 : single; inline; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses kode_math; // KKillDenorm //---------- constructor KFilter_Allpass.create(ACoefficient:Single); begin inherited create; a := ACoefficient; x0 := 0; x1 := 0; x2 := 0; y0 := 0; y1 := 0; y2 := 0; end; //---------- //destructor KFilter_allPass.destroy; //begin // inherited; //end; //---------- function KFilter_Allpass.process(AInput:single) : single; inline; //var // output : Single; begin x2 := x1; x1 := x0; x0 := AInput; y2 := y1; y1 := y0; //output := x2 + ( (AInput-y2) * a ); //output := KKillDenorm(output); //y0 := output; y0 := x2 + ( (AInput-y2) * a ); y0 := KKillDenorm(y0); result := y0; end; //---------- {function KFilter_Allpass.Process0 : single; inline; var output : Single; begin x2 := x1; x1 := x0; x0 := 0; //AInput; y2 := y1; y1 := y0; output := x2 + ( {AInput} -y2 * a ); output := KKillDenorm(output); y0 := output; result := output; end;} //---------------------------------------------------------------------- end.
(* Д) Вращение строки вправо. Напишите процедуру, перемещающую 1-й символ строки на место 2-го, 2-й - на место 3-го и т.д. Последний символ должен занять 1-е место. Примените средства обработки строк. *) procedure RotateRight(var s : string); var rChar : char; len : word; begin len := Length(s); rChar := s[len]; Delete(s, len, 1); Insert(rChar, s, 1); end; var str : string; begin str := 'pascal'; Writeln(str); RotateRight(str); Writeln(str); end.
unit U_Files; { Unit: U_Files.pas By: H@PPyZERŲ5 E-mail: happy05@programmer.net } interface uses Winapi.windows, System.UITypes, System.SysUtils, Winapi.ShellAPI; function GetFileSize(const APath: string): int64; function CopyFile(Source, Destination: String ) : boolean; implementation function GetFileSize(const APath: string): int64; var Sr : TSearchRec; begin if FindFirst(APath,faAnyFile,Sr)=0 then try Result := Int64(Sr.FindData.nFileSizeHigh) shl 32 + Sr.FindData.nFileSizeLow; finally FindClose(Sr); end else Result := 0; end; function CopyFile(Source, Destination: String ) : boolean; var fos : TSHFileOpStruct; begin FillChar(fos, SizeOf(fos),0); with fos do begin wFunc := FO_COPY; pFrom := PChar(Source+#0); pTo := PChar(Destination+#0); fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT; end; result := (0 = ShFileOperation(fos)); end; end.
unit fmEditNOtes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls; type TfrmEditNotes = class(TForm) meNotes: TRichEdit; btOK: TButton; btCancel: TButton; chkUpdateManifest: TCheckBox; private procedure SetNotes(Value :string); function GetNotes :string; public property Notes :string read GetNotes write SetNotes; end; var frmEditNotes: TfrmEditNotes; implementation {$R *.dfm} function TfrmEditNotes.GetNotes: string; begin result := meNotes.Lines.Text; end; procedure TfrmEditNotes.SetNotes(Value: string); var stringStream :TStringStream; begin stringStream := TStringStream.Create(Value); try meNotes.Lines.LoadFromStream(stringStream); finally stringStream.Free; end; end; end.
program Conexus; {$mode objfpc}{$H+} {$MACRO ON} {____________________________________________________________ | _______________________________________________________ | | | | | | | Remote for Frontier Silicon based devices | | | | (c) 2018 Alexander Feuster (alexander.feuster@web.de) | | | | http://www.github.com/feuster | | | |_______________________________________________________| | |___________________________________________________________} //define program basics {$DEFINE PROGVERSION:='2.4'} //{$DEFINE PROG_DEBUG} {___________________________________________________________} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp { you can add units after this }, StrUtils, FrontierSiliconAPI; type { TApp } TApp = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; procedure HelpHint; virtual; procedure WaitPrint; virtual; procedure WaitClear; virtual; end; const //program title STR_Title: String = ' __________________________________________________ '+#13#10+ '| ______________________________________________ |'+#13#10+ '| | | |'+#13#10+ '| |**********************************************| |'+#13#10+ '| | Remote for Frontier Silicon based devices | |'+#13#10+ '| | (c) 2018 Alexander Feuster | |'+#13#10+ '| | http://www.github.com/feuster | |'+#13#10+ '| |______________________________________________| |'+#13#10+ '|__________________________________________________|'+#13#10; //program version STR_Version: String = PROGVERSION; //CPU architecture STR_CPU: String = {$I %FPCTARGETCPU%}; //Build info STR_Build: String = {$I %FPCTARGETOS%}+' '+{$I %FPCTARGETCPU%}+' '+{$I %DATE%}+' '+{$I %TIME%}; {$WARNINGS OFF} STR_User: String = {$I %USER%}; {$WARNINGS ON} STR_Date: String = {$I %DATE%}; //Message strings STR_Info: String = 'Info: '; STR_Error: String = 'Error: '; STR_Space: String = ' '; STR_Warning: String = 'Warning: '; STR_WaitingMsg: String = 'Please wait...'; {$IFDEF PROG_DEBUG} STR_Debug: String = 'Debug: '; {$ENDIF} //Timeout INT_Timeout: Integer = 1500; var STR_Title_Banner: String; { Conexus } procedure TApp.DoRun; var ErrorMsg: String; URL: String; PIN: String; Command: String; Value: String; Buffer: String; Buffer2: Byte; Buffer3: TStringList; Buffer4: TStringList; Buffer5: Integer; begin //add CPU architecture info to title if STR_CPU='x86_64' then {$IFDEF PROG_DEBUG} STR_Title_Banner:=StringReplace(STR_Title,'**********************************************',' Conexus V'+STR_Version+' Debug (64Bit) ',[]) {$ELSE} STR_Title_Banner:=StringReplace(STR_Title,'**********************************************',' Conexus V'+STR_Version+' (64Bit) ',[]) {$ENDIF} else if STR_CPU='i386' then {$IFDEF PROG_DEBUG} STR_Title_Banner:=StringReplace(STR_Title,'**********************************************',' Conexus V'+STR_Version+' Debug (32Bit) ',[]) {$ELSE} STR_Title_Banner:=StringReplace(STR_Title,'**********************************************',' Conexus V'+STR_Version+' (32Bit) ',[]) {$ENDIF} else {$IFDEF PROG_DEBUG} STR_Title_Banner:=StringReplace(STR_Title,'**********************************************',' Conexus V'+STR_Version+' Debug ',[]); {$ELSE} STR_Title_Banner:=StringReplace(STR_Title,'**********************************************',' Conexus V'+STR_Version+' ',[]); {$ENDIF} // quick check parameters ErrorMsg:=CheckOptions('hbadlnsu:p:r:w:f:c:', 'help build api devicelist license nobanner showbanner url: pin: read: write: fullraw: command: icondownload: coverdownload:'); if ErrorMsg<>'' then begin //write title banner WriteLn(STR_Title_Banner); WriteLn(STR_Error+ErrorMsg); HelpHint; Terminate; Exit; end; // parse parameters //show banner if not surpressed if (HasOption('n', 'nobanner')=false) or (HasOption('s', 'showbanner')=true) then WriteLn(STR_Title_Banner); //exit if showbanner is called if HasOption('s', 'showbanner')=true then begin Terminate; Exit; end; //show help if HasOption('h', 'help') then begin WriteHelp; Terminate; Exit; end; //show build info if HasOption('b', 'build') then begin if STR_User<>'' then {$IFDEF PROG_DEBUG} WriteLn(STR_Info,'Build "V'+STR_Version+' '+STR_Build+'" (DEBUG) compiled by "'+STR_User+'"') {$ELSE} WriteLn(STR_Info,'Build "V'+STR_Version+' '+STR_Build+'" compiled by "'+STR_User+'"') {$ENDIF} else {$IFDEF PROG_DEBUG} WriteLn(STR_Info,'Build "V'+STR_Version+' (DEBUG) '+STR_Build+'"'); {$ELSE} WriteLn(STR_Info,'Build "V'+STR_Version+' '+STR_Build+'"'); {$ENDIF} Terminate; Exit; end; //show API info if HasOption('a', 'api') then begin if FSAPI_DEBUG then WriteLn(STR_Info,'Frontier Silicon API V'+API_Version+' (Debug)') else WriteLn(STR_Info,'Frontier Silicon API V'+API_Version); Terminate; Exit; end; //show license info if HasOption('l', 'license') then begin //show Conexus license WriteLn('Conexus V'+STR_Version+' (c) '+STR_Date[1..4]+' Alexander Feuster (alexander.feuster@web.de)'+#13#10+ 'http://www.github.com/feuster'+#13#10+ 'This program is provided "as-is" without any warranties for any data loss,'+#13#10+ 'device defects etc. Use at own risk!'+#13#10+ 'Free for personal use. Commercial use is prohibited without permission.'+#13#10); //show API license Write(API_License); Terminate; Exit; end; //list in network available Frontier Silicon devices if HasOption('d', 'devicelist') then begin WriteLn(STR_Info,'UPnP network scan for available Frontier Silicon devices'); WaitPrint; Buffer3:=TStringList.Create; Buffer3:=fsapi_Info_DeviceList(INT_Timeout,true); WaitClear; if Buffer3.Count=0 then begin WriteLn(STR_Info,'First try did not found any available devices. Starting second try.'); Buffer3:=fsapi_Info_DeviceList(INT_Timeout,true); WaitClear; if Buffer3.Count=0 then begin WriteLn(STR_Info,'No devices available!') end else begin if Buffer3.Count>0 then begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; WriteLn(''); WriteLn(' IP | Name | UUID'); WriteLn('---------------|------------------------------------|------------------------------------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-15s',[Buffer4.Strings[0]]):15,'|',Format('%0:-36s',[Buffer4.Strings[1]]):36,'|',Format('%0:-36s',[Buffer4.Strings[2]]):36); end; WriteLn(''); WriteLn(' IP | Icon URL'); WriteLn('---------------|-------------------------------------------------------------------------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-15s',[Buffer4.Strings[0]]):15,'|',Format('%0:-73s',[Buffer4.Strings[3]]):73); end; end; end; end else begin if Buffer3.Count>0 then begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; WriteLn(''); WriteLn(' IP | Name | UUID'); WriteLn('---------------|------------------------------------|------------------------------------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-15s',[Buffer4.Strings[0]]):15,'|',Format('%0:-36s',[Buffer4.Strings[1]]):36,'|',Format('%0:-36s',[Buffer4.Strings[2]]):36); end; WriteLn(''); WriteLn(' IP | Icon URL'); WriteLn('---------------|-------------------------------------------------------------------------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-15s',[Buffer4.Strings[0]]):15,'|',Format('%0:-73s',[Buffer4.Strings[3]]):73); end; end; end; Terminate; Exit; end; { add your program here } //check URL if HasOption('u', 'url') then begin URL:=(GetOptionValue('u', 'url')); if AnsiPos(LowerCase('http://'),URL)<>1 then URL:='http://'+URL; end else begin WriteLn(STR_Error+'No URL specified'); HelpHint; Terminate; Exit; end; //start icon download (since no PIN is needed function is started before PIN check) if HasOption('icondownload') then begin Buffer:=(GetOptionValue('icondownload')); if DirectoryExists(ExtractFilePath(Buffer))=true then begin if fsapi_Info_DeviceFileDownload(URL,Buffer)=true then WriteLn(STR_Info+'Icon saved to "'+Buffer+'"') else WriteLn(STR_Error+'Icon not saved'); end else WriteLn(STR_Error+'Folder "'+ExtractFilePath(Buffer)+'" does not exist'); Terminate; Exit; end; //PIN check if HasOption('p', 'pin') then begin PIN:=(GetOptionValue('p', 'pin')); end else begin for Buffer5:=0 to ParamCount do begin Buffer:=Buffer+ParamStr(Buffer5); end; //additional PIN check for fullraw command if Pos('pin=',LowerCase(Buffer))=0 then begin WriteLn(STR_Error+'No PIN specified'); WriteLn(STR_Warning+'Trying default PIN "1234"'); PIN:='1234'; end; Buffer:=''; Buffer5:=0; end; //start cover download if HasOption('coverdownload') then begin Buffer:=(GetOptionValue('coverdownload')); if DirectoryExists(ExtractFilePath(Buffer))=true then begin URL:=fsapi_Info_graphicUri(URL,PIN); if (RightStr(Buffer,1)='\') or (RightStr(Buffer,1)='/') then Buffer:=Buffer+ExtractFileName(URL) else Buffer:=Buffer+'/'+ExtractFileName(URL); if (URL<>'') and (Buffer<>'') then begin if fsapi_Info_DeviceFileDownload(URL,Buffer)=true then WriteLn(STR_Info+'Cover saved to "'+Buffer+'"') else WriteLn(STR_Error+'Cover not saved'); end else WriteLn(STR_Error+'Cover not saved'); end else WriteLn(STR_Error+'Folder "'+ExtractFilePath(Buffer)+'" does not exist'); Terminate; Exit; end; //check for read command if HasOption('r', 'read') then begin Command:=GetOptionValue('r', 'read'); WriteLn(STR_Info+'read by raw sending GET command '+#13#10+STR_Space+'"'+Command+'"'); Buffer:=fsapi_RAW(URL,PIN,COMMAND); if Buffer<>'' then begin WriteLn(STR_Info+'XML output:'); WriteLn('--------------------------------------------------------------------------------'); Write(Buffer); WriteLn('--------------------------------------------------------------------------------'); end else WriteLn(STR_Error+'read command "'+Command+'" failed'); Terminate; Exit; end; //check for write command if HasOption('w', 'write') then begin Command:=GetOptionValue('w', 'write'); Value:=MidStr(Command,AnsiPos(':',Command)+1,Length(Command)-AnsiPos(':',Command)); Command:=StringReplace(Command,':'+Value,'',[rfReplaceAll,rfIgnoreCase]); WriteLn(STR_Info+'write by raw sending SET command '+#13#10+STR_Space+'"'+Command+'" with value "'+value+'"'); Buffer:=fsapi_RAW(URL,PIN,COMMAND,true,Value); if Buffer<>'' then begin WriteLn(STR_Info+'XML output:'); WriteLn('--------------------------------------------------------------------------------'); Write(Buffer); WriteLn('--------------------------------------------------------------------------------'); end else WriteLn(STR_Error+'write command "'+Command+'" failed'); Terminate; Exit; end; //check for fullraw command if HasOption('f', 'fullraw') then begin Command:=GetOptionValue('f', 'fullraw'); Value:=MidStr(Command,AnsiPos(':',Command)+1,Length(Command)-AnsiPos(':',Command)); Command:=StringReplace(Command,':'+Value,'',[rfReplaceAll,rfIgnoreCase]); //adding PIN and SID only when no fsapi "?" arguments are given if Pos('?',Command)=0 then Command:=Command+'?pin='+PIN else begin if Pos('pin=',LowerCase(Command))=0 then Command:=Command+'&pin='+PIN; end; if Pos('&sid=',LowerCase(Command))=0 then begin Buffer:=fsapi_CreateSession(URL,PIN); if Buffer<>'' then Command:=Command+'&sid='+Buffer; end; WriteLn(STR_Info+'sending full raw HTTP command '+#13#10+STR_Space+'"'+URL+Command+'"'); Buffer:=fsapi_RAW_URL(URL+Command); if Buffer<>'' then begin WriteLn(STR_Info+'XML output:'); WriteLn('--------------------------------------------------------------------------------'); Write(Buffer); WriteLn('--------------------------------------------------------------------------------'); end else WriteLn(STR_Error+'sending full raw HTTP command '+#13#10+STR_Space+'"'+URL+Command+'" failed'); Terminate; Exit; end; //check for existing command if HasOption('c', 'command') then begin Command:=UpperCase((GetOptionValue('c', 'command'))); end else begin WriteLn(STR_Error+'No command specified'); HelpHint; Terminate; Exit; end; //check and execute command //Standby on if Command='ON' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Standby_On(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Standy off else if Command='OFF' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Standby_Off(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Standy on/off else if Command='STANDBY' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Standby(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Standy state else if Command='STANDBYSTATE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Standby_State(URL,PIN)=true then WriteLn(STR_Info+'device active') else WriteLn(STR_Info+'device in Standby or disconnected'); end //Image version else if Command='VERSION' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_ImageVersion(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'image version "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Get notifies else if Command='GETNOTIFIES' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer3:=fsapi_Info_GetNotifies(URL,PIN); if Buffer3.Count>0 then begin WriteLn(STR_Info+'command "'+Command+'" successful'); WriteLn(''); WriteLn(' Notify | Value '); WriteLn('--------------------------------------------------|------------------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-50s',[Buffer4.Strings[0]]):50,'|',Format('%0:-18s',[Buffer4.Strings[1]]):18); end; end else WriteLn(STR_Error+'command "'+Command+'" failed or no notifies available'); end //Friendly name else if (Command='FRIENDLYNAME') or (Command='NAME') or (Command='DEVICENAME') then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_FriendlyName(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'friendly name "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //ID else if (Command='ID') or (Command='RADIOID') then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_RadioID(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'ID "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Mute on else if Command='MUTEON' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Mute_On(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Mute off else if Command='MUTEOFF' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Mute_Off(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Mute on/off else if Command='MUTE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Mute(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Mute state else if Command='MUTESTATE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Mute_State(URL,PIN)=true then WriteLn(STR_Info+'device muted') else WriteLn(STR_Info+'device not muted or disconnected'); end //PLAYPAUSE else if Command='PLAYPAUSE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_PlayControl_PlayPause(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //PLAY else if Command='PLAY' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_PlayControl_Play(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //PAUSE else if Command='PAUSE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_PlayControl_Pause(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //NEXT else if Command='NEXT' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_PlayControl_Next(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //PREVIOUS else if Command='PREVIOUS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_PlayControl_Previous(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Repeat on else if Command='REPEATON' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Repeat_On(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Repeat off else if Command='REPEATOFF' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Repeat_Off(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Repeat on/off else if Command='REPEAT' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Repeat(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Repeat state else if Command='REPEATSTATE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Repeat_State(URL,PIN)=true then WriteLn(STR_Info+'repeat mode active') else WriteLn(STR_Info+'repeat mode not active or device disconnected'); end //Shuffle on else if Command='SHUFFLEON' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Shuffle_On(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Shuffle off else if Command='SHUFFLEOFF' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Shuffle_Off(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Shuffle on/off else if Command='SHUFFLE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Shuffle(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Shuffle state else if Command='SHUFFLESTATE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Shuffle_State(URL,PIN)=true then WriteLn(STR_Info+'shuffle mode active') else WriteLn(STR_Info+'shuffle mode not active or device disconnected'); end //Scrobble on else if Command='SCROBBLEON' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Scrobble_On(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Scrobble off else if Command='SCROBBLEOFF' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Scrobble_Off(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Scrobble on/off else if Command='SCROBBLE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Scrobble(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Scrobble state else if Command='SCROBBLESTATE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Shuffle_State(URL,PIN)=true then WriteLn(STR_Info+'scrobble mode active') else WriteLn(STR_Info+'scrobble mode not active or device disconnected'); end //Set new position in ms else if LeftStr(Command,14)='SETPOSITIONMS:' then begin try Buffer5:=StrToInt(StringReplace(Command,'SETPOSITIONMS:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect volume value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "SETPOSITIONMS:'+IntToStr(Buffer5)+'"'); if fsapi_PlayControl_SetPositionMS(URL,PIN,Buffer5)=true then WriteLn(STR_Info+'command "SETPOSITIONMS:'+IntToStr(Buffer5)+'" successful') else WriteLn(STR_Error+'command "SETPOSITIONMS:'+IntToStr(Buffer5)+'" failed'); end //Set new position in time format hh:mm:ss else if LeftStr(Command,12)='SETPOSITION:' then begin try Buffer:=StringReplace(Command,'SETPOSITION:','',[rfReplaceAll,rfIgnoreCase]); if not ((MidStr(Buffer,3,1)=':') and (MidStr(Buffer,6,1)=':') and (Length(Buffer)=8)) then begin WriteLn(STR_Error+'command "'+Command+'" incorrect time format') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "SETPOSITION:'+Buffer+'"'); if fsapi_PlayControl_SetPosition(URL,PIN,Buffer)=true then WriteLn(STR_Info+'command "SETPOSITION:'+Buffer+'" successful') else WriteLn(STR_Error+'command "SETPOSITION:'+Buffer+'" failed'); except WriteLn(STR_Error+'command "SETPOSITION:'+Buffer+'" failed'); end; end //Artist else if Command='GETARTIST' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_Artist(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'artist "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Name else if Command='GETNAME' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_Name(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'name "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Text else if Command='GETTEXT' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_Text(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'text "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Graphic URI else if Command='GETGRAPHICURI' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_graphicUri(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'graphic URI "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Get duration else if Command='GETDURATION' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Info_Duration(URL,PIN); if Buffer5<>0 then WriteLn(STR_Info+'duration '+TimeToStr(Buffer5/MSecsPerDay)) else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Get position else if Command='GETPOSITION' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Info_Position(URL,PIN); if Buffer5<>0 then WriteLn(STR_Info+'position '+TimeToStr(Buffer5/MSecsPerDay)) else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Play info else if Command='GETPLAYINFO' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_PlayInfo(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'actually playing "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Play status else if Command='GETPLAYSTATUS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer2:=fsapi_Info_PlayStatus(URL,PIN); if Buffer2=1 then WriteLn(STR_Info+'play status "buffering/loading"') else if Buffer2=2 then WriteLn(STR_Info+'play status "playing"') else if Buffer2=3 then WriteLn(STR_Info+'play status "paused"') else if Buffer2=255 then WriteLn(STR_Error+'command "'+Command+'" failed') else WriteLn(STR_Info+'play status unknown') ; end //Play error else if Command='GETPLAYERROR' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_PlayError(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'play error "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed or no play error available'); end //Time else if Command='TIME' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_Time(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'time "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Date else if Command='DATE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_Date(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'date "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Date & Time else if Command='DATETIME' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_DateTime(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'date&time "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //LAN MAC address else if Command='LANMAC' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_LAN_MAC(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'LAN MAC address "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //WLAN MAC address else if Command='WLANMAC' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_WLAN_MAC(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'WLAN MAC address "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //WLAN RSSI value else if Command='WLANRSSI' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_WLAN_RSSI(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'WLAN RSSI value "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed or zero RSSI signal strength'); end //WLAN Connected SSID else if Command='WLANSSID' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_WLAN_ConnectedSSID(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'WLAN connected AP SSID "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed or no connected WLAN AP SSID available'); end //Volume value else if Command='GETVOLVALUE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer2:=fsapi_Volume_Get(URL,PIN); if Buffer2=255 then WriteLn(STR_Error+'command "'+Command+'" failed') else WriteLn(STR_Info+'volume is set to "'+IntToStr(Buffer2)+'"'); end //Get maximum supported volume steps value else if Command='GETVOLSTEPS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer2:=fsapi_Volume_GetSteps(URL,PIN); if Buffer2=255 then WriteLn(STR_Error+'command "'+Command+'" failed') else WriteLn(STR_Info+'maximum supported volume is "'+IntToStr(Buffer2)+'"'); end //Volume set new value else if LeftStr(Command,4)='VOL:' then begin if (Length(Command)>6) or (Length(Command)<5)then begin WriteLn(STR_Error+'command "'+Command+'" incorrect') ; Terminate; Exit; end; try Buffer2:=StrToInt(StringReplace(Command,'VOL:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect volume value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "VOL:'+IntToStr(Buffer2)+'"'); if fsapi_Volume_Set(URL,PIN,Buffer2)=true then WriteLn(STR_Info+'command "VOL:'+IntToStr(Buffer2)+'" successful') else WriteLn(STR_Error+'command "VOL:'+IntToStr(Buffer2)+'" failed'); end //Volume up else if ((Command='VOLUP') or (Command='VOL+'))then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Volume_Up(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Volume down else if ((Command='VOLDOWN') or (Command='VOL-'))then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Volume_Down(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Mode list else if ((Command='MODELIST') or (Command='MODES'))then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer3:=TStringList.Create; Buffer3:=fsapi_Modes_Get(URL,PIN); if Buffer3.Count>0 then begin WriteLn(STR_Info+'command "'+Command+'" successful'); WriteLn(''); WriteLn(' Mode | Label | ID '); WriteLn('------|------------------|------------------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-6s',[Buffer4.Strings[0]]):6,'|',Format('%0:-18s',[Buffer4.Strings[1]]):18,'|',Format('%0:-18s',[Buffer4.Strings[2]]):18); end; end else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Modes: set new active mode else if LeftStr(Command,5)='MODE:' then begin try //mode as numeric value Buffer2:=StrToInt(StringReplace(Command,'MODE:','',[rfReplaceAll,rfIgnoreCase])); WriteLn(STR_Info+'sending command "MODE:'+IntToStr(Buffer2)+'"'); if fsapi_Modes_Set(URL,PIN,Buffer2)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); except //mode as text value WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Modes_SetModeByAlias(URL,PIN,StringReplace(Command,'MODE:','',[rfReplaceAll,rfIgnoreCase]))=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end; end //Modes: get mode value by label or ID else if LeftStr(Command,8)='GETMODE:' then begin Buffer2:=fsapi_Modes_GetModeByIdLabel(URL,PIN,StringReplace(Command,'GETMODE:','',[rfReplaceAll,rfIgnoreCase])); if Buffer2<255 then WriteLn(STR_Info+'command "'+Command+'" successful returned value "'+IntToStr(Buffer2)+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Get active mode else if Command='ACTIVEMODE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Modes_ActiveModeLabel(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'active mode "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Get active mode ID else if Command='ACTIVEMODEID' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Modes_ActiveMode(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'active mode "'+IntToStr(Buffer5)+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //switch to next available mode else if Command='NEXTMODE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Modes_NextMode(URL,PIN)=true then WriteLn(STR_Info+'switched to next mode') else WriteLn(STR_Info+'could not switch to next mode'); end //switch to previous available mode else if Command='PREVIOUSMODE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Modes_PreviousMode(URL,PIN)=true then WriteLn(STR_Info+'switched to previous mode') else WriteLn(STR_Info+'could not switch to previous mode'); end //DAB scan else if Command='DABSCAN' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_DAB_Scan(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //DAB prune else if Command='DABPRUNE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_DAB_Prune(URL,PIN)=true then WriteLn(STR_Info+'command "'+Command+'" successful') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //DAB frequency list else if (Command='DABFREQ') or (Command='DABFREQUENCIES') then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer3:=TStringList.Create; Buffer3:=fsapi_DAB_FrequencyList(URL,PIN); if Buffer3.Count>0 then begin WriteLn(STR_Info+'command "'+Command+'" successful'); WriteLn(''); WriteLn(' ID | Frequency | Label '); WriteLn('----|-----------|-------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-4s',[Buffer4.Strings[0]]):4,'|',Format('%0:-11s',[Buffer4.Strings[1]]):11,'|',Format('%0:-7s',[Buffer4.Strings[2]]):7); end; end else WriteLn(STR_Error+'command "'+Command+'" failed or no preset list available'); end //Preset list else if (Command='PRESETLIST') or (Command='PRESETS') then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer3:=TStringList.Create; Buffer3:=fsapi_Presets_List(URL,PIN); if Buffer3.Count>0 then begin WriteLn(STR_Info+'command "'+Command+'" successful'); WriteLn(''); WriteLn(' ID | Name'); WriteLn('----|------------------------------------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-4s',[Buffer4.Strings[0]]):4,'|',Format('%0:-36s',[Buffer4.Strings[1]]):36); end; end else WriteLn(STR_Error+'command "'+Command+'" failed or no preset list available'); end //select Preset else if (LeftStr(Command,13)='PRESETSELECT:') or (LeftStr(Command,7)='PRESET:') then begin try Command:=StringReplace(Command,'PRESETSELECT:','',[rfReplaceAll,rfIgnoreCase]); Command:=StringReplace(Command,'PRESET:','',[rfReplaceAll,rfIgnoreCase]); Buffer2:=StrToInt(Command); except WriteLn(STR_Error+'command "'+Command+'" incorrect preset value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "PRESETSELECT:'+IntToStr(Buffer2)+'"'); if fsapi_Presets_Set(URL,PIN,Buffer2)=true then WriteLn(STR_Info+'command "PRESETSELECT:'+IntToStr(Buffer2)+'" successful') else WriteLn(STR_Error+'command "PRESETSELECT:'+IntToStr(Buffer2)+'" failed'); end //add Preset else if LeftStr(Command,10)='PRESETADD:' then begin try Command:=StringReplace(Command,'PRESETADD:','',[rfReplaceAll,rfIgnoreCase]); Buffer2:=StrToInt(Command); except WriteLn(STR_Error+'command "'+Command+'" incorrect preset value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "PRESETADD:'+IntToStr(Buffer2)+'"'); if fsapi_Presets_Add(URL,PIN,Buffer2)=true then WriteLn(STR_Info+'command "PRESETADD:'+IntToStr(Buffer2)+'" successful') else WriteLn(STR_Error+'command "PRESETADD:'+IntToStr(Buffer2)+'" failed'); end //switch to next available Preset else if Command='NEXTPRESET' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Presets_NextPreset(URL,PIN)=true then WriteLn(STR_Info+'switched to next preset') else WriteLn(STR_Info+'could not switch to next preset'); end //switch to previous available Preset else if Command='PREVIOUSPRESET' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Presets_PreviousPreset(URL,PIN)=true then WriteLn(STR_Info+'switched to previous preset') else WriteLn(STR_Info+'could not switch to previous Preset'); end //Update info else if Command='UPDATEINFO' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_DeviceUpdateInfo(URL,PIN); if Buffer<>'' then begin WriteLn(STR_Info+'command "'+Command+'" successful'); WriteLn(STR_Info+'XML output:'); WriteLn('--------------------------------------------------------------------------------'); Write(Buffer); WriteLn('--------------------------------------------------------------------------------'); end else WriteLn(STR_Info+'No update available or command "'+Command+'" failed'); end //LAN interface enabled info else if Command='LANSTATUS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Info_LAN_Enabled(URL,PIN)=true then WriteLn(STR_Info+'LAN interface enabled') else WriteLn(STR_Info+'LAN interface not enabled or command failed'); end //WLAN interface enabled info else if Command='WLANSTATUS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Info_WLAN_Enabled(URL,PIN)=true then WriteLn(STR_Info+'WLAN interface enabled') else WriteLn(STR_Info+'WLAN interface not enabled or command failed'); end //Update info else if Command='INTERFACES' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_Network_Interfaces(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'enabled network interfaces: "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Factory reset else if Command='FACTORYRESET' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_FACTORY_RESET(URL,PIN)=true then begin WriteLn(STR_Info+'Factory reset activated. Your device should be in Setup mode now.'); WriteLn(STR_Info+'Use your default app to setup your device again.') end else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Device ID else if Command='DEVICEID' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer:=fsapi_Info_DeviceID(URL,PIN); if Buffer<>'' then WriteLn(STR_Info+'device ID "'+Buffer+'"') else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Navigation list else if Command='NAVLIST' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer3:=TStringList.Create; Buffer3:=fsapi_Nav_List(URL,PIN); if Buffer3.Count>0 then begin WriteLn(STR_Info+'command "'+Command+'" successful'); WriteLn(''); WriteLn(' ID | Name | Type | Subtype '); WriteLn('----|------------------------------------|---------|---------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-4s',[Buffer4.Strings[0]]):4,'|',Format('%0:-36s',[Buffer4.Strings[1]]):36,'|',Format('%0:-9s',[Buffer4.Strings[2]]):9,'|',Format('%0:-9s',[Buffer4.Strings[3]]):9); end; end else WriteLn(STR_Error+'command "'+Command+'" failed or no list available'); end //select navigation item (must be type = 0) else if LeftStr(Command,16)='NAVITEMNAVIGATE:' then begin try Buffer2:=StrToInt(StringReplace(Command,'NAVITEMNAVIGATE:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect navigation item value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "NAVITEMNAVIGATE:'+IntToStr(Buffer2)+'"'); if fsapi_Nav_Navigate(URL,PIN,Buffer2)=true then WriteLn(STR_Info+'command "NAVITEMNAVIGATE:'+IntToStr(Buffer2)+'" successful') else WriteLn(STR_Error+'command "NAVITEMNAVIGATE:'+IntToStr(Buffer2)+'" failed'); end //select navigation item (must be type > 0) else if LeftStr(Command,14)='NAVITEMSELECT:' then begin try Buffer2:=StrToInt(StringReplace(Command,'NAVITEMSELECT:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect navigation item value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "NAVITEMSELECT:'+IntToStr(Buffer2)+'"'); if fsapi_Nav_SelectItem(URL,PIN,Buffer2)=true then WriteLn(STR_Info+'command "NAVITEMSELECT:'+IntToStr(Buffer2)+'" successful') else WriteLn(STR_Error+'command "NAVITEMSELECT:'+IntToStr(Buffer2)+'" failed'); end //Get navigation caps else if Command='NAVCAPS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Nav_Caps(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'caps "'+IntToStr(Buffer5)+'"') else WriteLn(STR_Error+'command "'+Command+'" failed or no caps available'); end //Get navigation item count else if Command='NAVNUMITEMS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Nav_NumItems(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'number of navigation items "'+IntToStr(Buffer5)+'"') else WriteLn(STR_Error+'command "'+Command+'" failed or no items available'); end //Navigation status else if Command='NAVSTATUS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Nav_Status(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'navigation status "'+IntToStr(Buffer5)+'"') else WriteLn(STR_Error+'command "'+Command+'" failed or navigation status not available'); end //Get FM highest allowed frequency else if Command='FMUPPERCAP' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_FM_FreqRange_UpperCap(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'highest allowed FM frequency "'+IntToStr(Buffer5)+'" kHz') else WriteLn(STR_Error+'command "'+Command+'" failed or no items available'); end //Get FM lowest allowed frequency else if Command='FMLOWERCAP' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_FM_FreqRange_LowerCap(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'lowest allowed FM frequency "'+IntToStr(Buffer5)+'" kHz') else WriteLn(STR_Error+'command "'+Command+'" failed or no items available'); end //Get FM allowed frequency steps else if Command='FMSTEPS' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_FM_FreqRange_Steps(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'allowed FM frequency step size "'+IntToStr(Buffer5)+'" kHz') else WriteLn(STR_Error+'command "'+Command+'" failed or no items available'); end //System state else if Command='SYSSTATE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Sys_State(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'system state "'+IntToStr(Buffer5)+'"') else WriteLn(STR_Info+'command "'+Command+'" failed or system state not available'); end //set new frequency else if LeftStr(Command,10)='FMSETFREQ:' then begin try Buffer5:=StrToInt(StringReplace(Command,'FMSETFREQ:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect navigation item value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "FMSETFREQ:'+IntToStr(Buffer5)+'"'); if fsapi_FM_SetFrequency(URL,PIN,Buffer5)=true then WriteLn(STR_Info+'command "FMSETFREQ:'+IntToStr(Buffer5)+'" successful') else WriteLn(STR_Error+'command "FMSETFREQ:'+IntToStr(Buffer5)+'" failed'); end //get frequency else if Command='FMGETFREQ' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_FM_GetFrequency(URL,PIN); if Buffer5>-1 then WriteLn(STR_Info+'actual FM frequency "'+IntToStr(Buffer5)+'"') else WriteLn(STR_Info+'command "'+Command+'" failed or actual FM frequency not available'); end //set new sleeptimer else if LeftStr(Command,14)='SETSLEEPTIMER:' then begin try Buffer5:=StrToInt(StringReplace(Command,'SETSLEEPTIMER:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect seconds value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "SETSLEEPTIMER:'+IntToStr(Buffer5)+'"'); if fsapi_Sys_SetSleepTimer(URL,PIN,Buffer5)=true then WriteLn(STR_Info+'command "SETSLEEPTIMER:'+IntToStr(Buffer5)+'" successful') else WriteLn(STR_Error+'command "SETSLEEPTIMER:'+IntToStr(Buffer5)+'" failed'); end //get sleeptimer time else if Command='GETSLEEPTIMER' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Sys_GetSleepTimer(URL,PIN); if Buffer5>-1 then begin if Buffer5>0 then WriteLn(STR_Info+'sleeptimer in "'+IntToStr(Buffer5)+'" seconds') else WriteLn(STR_Info+'sleeptimer is "off"') end else WriteLn(STR_Error+'command "'+Command+'" failed'); end //Equalizer preset list else if (Command='EQPRESETLIST') or (Command='EQPRESETS') then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer3:=TStringList.Create; Buffer3:=fsapi_Equalizer_Presets_List(URL,PIN); if Buffer3.Count>0 then begin WriteLn(STR_Info+'command "'+Command+'" successful'); WriteLn(''); WriteLn(' ID | Equalizer Preset Name'); WriteLn('----|------------------------------------'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-4s',[Buffer4.Strings[0]]):4,'|',Format('%0:-36s',[Buffer4.Strings[1]]):36); end; end else WriteLn(STR_Error+'command "'+Command+'" failed or no equalizer preset list available'); end //Equalizer bands list else if (Command='EQBANDSLIST') or (Command='EQBANDS') then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer3:=TStringList.Create; Buffer3:=fsapi_Equalizer_Bands_List(URL,PIN); if Buffer3.Count>0 then begin WriteLn(STR_Info+'command "'+Command+'" successful'); WriteLn(''); WriteLn(' ID | Equalizer Preset Name | Min | Max '); WriteLn('----|------------------------------------|-----|-----'); for Buffer2:=0 to Buffer3.Count-1 do begin Buffer4:=TStringList.Create; Buffer4.StrictDelimiter:=true; Buffer4.Delimiter:='|'; Buffer4.DelimitedText:=Buffer3.Strings[Buffer2]; WriteLn(Format('%0:-4s',[Buffer4.Strings[0]]):4,'|',Format('%0:-36s',[Buffer4.Strings[1]]):36,'|',Format('%0:-5s',[Buffer4.Strings[2]]):5,'|',Format('%0:-5s',[Buffer4.Strings[3]]):5); end; end else WriteLn(STR_Error+'command "'+Command+'" failed or no equalizer preset list available'); end //get active equalizer ID else if Command='GETEQUALIZER' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer2:=fsapi_Equalizer_Get(URL,PIN); if Buffer2<255 then begin WriteLn(STR_Info+'active equalizer "'+IntToStr(Buffer2)+'"') end else WriteLn(STR_Error+'command "'+Command+'" failed or no equalizer value available'); end //set new equalizer mode else if LeftStr(Command,13)='SETEQUALIZER:' then begin try Buffer5:=StrToInt(StringReplace(Command,'SETEQUALIZER:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect ID value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "SETEQUALIZER:'+IntToStr(Buffer5)+'"'); if fsapi_Equalizer_Set(URL,PIN,Buffer5)=true then WriteLn(STR_Info+'command "SETEQUALIZER:'+IntToStr(Buffer5)+'" successful') else WriteLn(STR_Error+'command "SETEQUALIZER:'+IntToStr(Buffer5)+'" failed'); end //get custom equalizer 0 value else if Command='GETCUSTOMEQ0' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Equalizer_CustomParam0_Get(URL,PIN); if Buffer5<255 then begin WriteLn(STR_Info+'custom equalizer 0 value "'+IntToStr(Buffer5)+'"') end else WriteLn(STR_Error+'command "'+Command+'" failed or no custom equalizer 0 value available'); end //set custom equalizer 0 value else if LeftStr(Command,13)='SETCUSTOMEQ0:' then begin try Buffer5:=StrToInt(StringReplace(Command,'SETCUSTOMEQ0:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "SETCUSTOMEQ0:'+IntToStr(Buffer5)+'"'); if fsapi_Equalizer_CustomParam0_Set(URL,PIN,Buffer5)=true then WriteLn(STR_Info+'command "SETCUSTOMEQ0:'+IntToStr(Buffer5)+'" successful') else WriteLn(STR_Error+'command "SETCUSTOMEQ0:'+IntToStr(Buffer5)+'" failed'); end //get custom equalizer 1 value else if Command='GETCUSTOMEQ1' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); Buffer5:=fsapi_Equalizer_CustomParam1_Get(URL,PIN); if Buffer5<255 then begin WriteLn(STR_Info+'custom equalizer 1 value "'+IntToStr(Buffer5)+'"') end else WriteLn(STR_Error+'command "'+Command+'" failed or no custom equalizer 1 value available'); end //set custom equalizer 1 value else if LeftStr(Command,13)='SETCUSTOMEQ1:' then begin try Buffer5:=StrToInt(StringReplace(Command,'SETCUSTOMEQ1:','',[rfReplaceAll,rfIgnoreCase])); except WriteLn(STR_Error+'command "'+Command+'" incorrect value') ; Terminate; Exit; end; WriteLn(STR_Info+'sending command "SETCUSTOMEQ1:'+IntToStr(Buffer5)+'"'); if fsapi_Equalizer_CustomParam1_Set(URL,PIN,Buffer5)=true then WriteLn(STR_Info+'command "SETCUSTOMEQ1:'+IntToStr(Buffer5)+'" successful') else WriteLn(STR_Error+'command "SETCUSTOMEQ1:'+IntToStr(Buffer5)+'" failed'); end //Enable navigation else if Command='NAVENABLE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Nav_State(URL,PIN,true)=true then WriteLn(STR_Info+'navigation enabled') else WriteLn(STR_Info+'command "'+Command+'" failed or navigation not enabled'); end //Disable navigation else if Command='NAVDISABLE' then begin WriteLn(STR_Info+'sending command "'+Command+'"'); if fsapi_Nav_State(URL,PIN,false)=true then WriteLn(STR_Info+'navigation disabled') else WriteLn(STR_Info+'command "'+Command+'" failed or navigation not disabled'); end //unknown command else begin WriteLn(STR_Error+'Unknown command "'+Command+'" set'); HelpHint; end; //clean up {$IFDEF PROG_DEBUG} if fsapi_SessionID<>'' then begin Write(STR_Debug+'Deletion of session ID "'+fsapi_SessionID+'"'); if fsapi_DeleteSession(URL,PIN)=true then WriteLn(' succeeded') else WriteLn(' failed'); end; {$ELSE} if fsapi_SessionID<>'' then fsapi_DeleteSession(URL,PIN); {$ENDIF} Terminate; end; constructor TApp.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TApp.Destroy; begin inherited Destroy; end; procedure TApp.WriteHelp; begin { add your help code here } WriteLn('General usage: ', ExtractFileName(ExeName), ' --url=[IP or LOCAL DOMAIN] --pin=[DEVICE PIN] --command=[COMMAND]'); WriteLn(' or'); WriteLn(' ', ExtractFileName(ExeName), ' -u [IP or LOCAL DOMAIN] -p [DEVICE PIN] -c [COMMAND]'); WriteLn(''); WriteLn('General usage examples: ', ExtractFileName(ExeName), ' --url=192.168.0.34 --pin=1234 --command=on'); WriteLn(' ', ExtractFileName(ExeName), ' -u AudioMaster.fritz.box -p 9999 -c off'); WriteLn(' ', ExtractFileName(ExeName), ' --url=192.168.0.34 -p 1234 -c mode:1'); WriteLn(''); WriteLn('Usage hints: Some commands need additional values. These values are added with ":" after the command.'); WriteLn(' If a value contains one or more spaces the value must be quoted with ".'); WriteLn(' Examples:'); WriteLn(' --command="COMMAND:VALUE"'); WriteLn(' -w "netRemote.sys.info.friendlyName:DigitRadio 360 CD"'); WriteLn(''); WriteLn('List of commands:'); WriteLn('ON switch device on'); WriteLn('OFF switch device off'); WriteLn('STANDBY toggle device state from on to off and vice versa'); WriteLn('STANDBYSTATE show device power state'); WriteLn('VERSION show the version of the installed image'); WriteLn('GETNOTIFIES list device notifies if available'); WriteLn('FRIENDLYNAME show the device friendly name (alternative commands: NAME, DEVICENAME)'); WriteLn('ID show the device (alternative command: RADIOID)'); WriteLn('TIME show device time'); WriteLn('DATE show device date'); WriteLn('DATETIME show device date&time'); WriteLn('LANMAC show device LAN MAC address'); WriteLn('LANSTATUS show status if LAN interface is enabled or not'); WriteLn('WLANMAC show device WLAN MAC address'); WriteLn('WLANSTATUS show status if WLAN interface is enabled or not'); WriteLn('WLANRSSI show device WLAN Received Signal Strength Indicator (RSSI)'); WriteLn('WLANSSID show the SSID (Service Set Identifier) of the connected Wireless Access Point'); WriteLn('INTERFACES shows which network interface is enabled ("LAN", "WLAN" or "NONE").'); WriteLn('MUTEON activate mute function'); WriteLn('MUTEOFF deactivate mute function'); WriteLn('MUTE toggle muting state from on to off and vice versa'); WriteLn('MUTESTATE show device muting state'); WriteLn('PLAY start playback'); WriteLn('PAUSE pause playback'); WriteLn('PLAYPAUSE toggle playback state from play to pause and vice versa'); WriteLn('NEXT play next item or track'); WriteLn('PREVIOUS play previous item or track'); WriteLn('REPEATON activate repeat function'); WriteLn('REPEATOFF deactivate repeat function'); WriteLn('REPEAT toggle repeat function state from on to off and vice versa'); WriteLn('REPEATSTATE show device repeat state'); WriteLn('SHUFFLEON activate shuffle function'); WriteLn('SHUFFLEOFF deactivate shuffle function'); WriteLn('SHUFFLE toggle shuffle function state from on to off and vice versa'); WriteLn('SHUFFLESTATE show shuffle function state'); WriteLn('SCROBBLEON activate scrobble function'); WriteLn('SCROBBLEOFF deactivate scrobble function'); WriteLn('SCROBBLE toggle scrobble function state from on to off and vice versa'); WriteLn('SCROBBLESTATE show scrobble function state'); WriteLn('SETPOSITIONMS set new play position in milliseconds'); WriteLn('SETPOSITION set new play position in time format hh:mm:ss'); WriteLn('GETARTIST show artist'); WriteLn('GETNAME show name(title)'); WriteLn('GETTEXT show text'); WriteLn('GETGRAPHICURI show URI for graphic (the actual cover or logo)'); WriteLn('GETDURATION show duration'); WriteLn('GETPOSITION show actual play position'); WriteLn('GETPLAYINFO show artist/name(title)/position/duration'); WriteLn('GETPLAYSTATUS show actual play status'); WriteLn('GETPLAYERROR show play error if available'); WriteLn('GETVOLVALUE show the actual set volume value'); WriteLn('GETVOLSTEPS show the volume step count. The maximum supported volume value should be "steps - 1".'); WriteLn('VOL:[VALUE] set volume to [VALUE] (allowed value range: 0-max / for max see GETMAXVOLVALUE)'); WriteLn('VOLUP increase volume value (alternative command: VOL+)'); WriteLn('VOLDOWN decrease volume value (alternative command: VOL-)'); WriteLn('MODELIST show the available device modes and their aliases (alternative command: MODES)'); WriteLn('MODE:[VALUE] set mode to [VALUE] (allowed values: mode number, ID or label)'); WriteLn('NEXTMODE switch to the next available mode'); WriteLn('PREVIOUSMODE switch to the previous available mode'); WriteLn('ACTIVEMODE get mode label for active mode'); WriteLn('ACTIVEMODEID get mode ID number for active mode'); WriteLn('GETMODE:[VALUE] get mode number for [VALUE] (allowed values: ID or label)'); WriteLn('PRESETLIST list stored presets (alternative command: PRESETS)'); WriteLn('PRESETSELECT:[VALUE] select stored preset [VALUE] (alternative command: PRESET))'); WriteLn('PRESETADD:[VALUE] store actual running service as preset [VALUE]'); WriteLn('NEXTPRESET switch to the next available preset'); WriteLn('PREVIOUSPRESET switch to the previous available preset'); WriteLn('NAVENABLE enable navigation (this must be called before navigation related commands)'); WriteLn('NAVDISABLE disable/end navigation (this must be called to end the actual navigation session)'); WriteLn('NAVSTATUS show navigation status'); WriteLn('NAVLIST list available navigation items'); WriteLn('NAVITEMNAVIGATE:[VALUE] select [VALUE] navigation item (must be type = 0 see NAVLIST)'); WriteLn('NAVITEMSELECT:[VALUE] select [VALUE] navigation item (must be type > 0 see NAVLIST)'); WriteLn('NAVCAPS show navigation caps'); WriteLn('NAVNUMITEMS show navigation item count'); WriteLn('UPDATEINFO check if an update is available for the device and print XML output'); WriteLn('DEVICEID show device id (unique)'); WriteLn('FACTORYRESET CAUTION: this does activate the factory reset! Use your default app to setup the device again'); WriteLn('DABSCAN start DAB scan'); WriteLn('DABPRUNE start DAB prune'); WriteLn('DABFREQ show available DAB frequencies/channels (alternative command: DABFREQUENCIES)'); WriteLn('FMUPPERCAP show highest allowed FM frequency in kHz'); WriteLn('FMLOWERCAP show lowest allowed FM frequency in kHz'); WriteLn('FMSTEPS show allowed FM step size in kHz'); WriteLn('FMSETFREQ set new FM frequency'); WriteLn('FMGETFREQ show actual FM frequency'); WriteLn('SYSSTATE show system state'); WriteLn('GETSLEEPTIMER show time until sleep starts (0 = sleeptimer off)'); WriteLn('SETSLEEPTIMER:[VALUE] show time until sleep starts ([VALUE] in seconds)'); WriteLn('EQPRESETLIST list stored equalizer presets (alternative command: EQPRESETS)'); WriteLn('EQBANDSLIST list stored custom equalizer settings (alternative command: EQBANDS)'); WriteLn('GETEQUALIZER show the actual active equalizer'); WriteLn('SETEQUALIZER:[VALUE] set an equalizer mode ([VALUE] equalizer preset ID)'); WriteLn('GETCUSTOMEQ0 show the value for the custom equalizer 0 (in most cases this is BASS see EQBANDSLIST)'); WriteLn('SETCUSTOMEQ0:[VALUE] set new custom equalizer 0 [VALUE]'); WriteLn('GETCUSTOMEQ1 show the value for the custom equalizer 1 (in most cases this is TREBLE see EQBANDSLIST)'); WriteLn('SETCUSTOMEQ1:[VALUE] set new custom equalizer 1 [VALUE]'); WriteLn(''); WriteLn('Commands hint: not all commands are supported by all modes'); WriteLn(''); WriteLn('Mode aliases:'); WriteLn('Additional to the original mode label/IDs it is possible to use optional aliases for the same mode'); WriteLn('Example for music mode: ', ExtractFileName(ExeName), ' --url=192.168.0.34 --pin=1234 --command=mode:MUSIC'); WriteLn(' ', ExtractFileName(ExeName), ' --url=192.168.0.34 --pin=1234 --command=mode:MP3'); WriteLn(' ', ExtractFileName(ExeName), ' --url=192.168.0.34 --pin=1234 --command=mode:MP'); WriteLn(''); WriteLn('List of supported mode aliases:'); WriteLn('BLUETOOTH BLUETOOTH, BLUE, BT'); WriteLn('AUXIN "AUX EINGANG", AUXIN, AUX'); WriteLn('FM FM, UKW, UKWRADIO'); WriteLn('DAB DAB, RADIO, DABRADIO, DIGITALRADIO'); WriteLn('MP "MUSIK ABSPIELEN", MUSIK, MUSIC, MP3, MP'); WriteLn('IR "INTERNET RADIO", INTERNETRADIO, INTERNET, "WEB RADIO", WEBRADIO, WEB, IR'); WriteLn('SPOTIFY SPOTIFY, "SPOTIFY CONNECT", SPOT'); WriteLn('CD CD, CDROM, CD-ROM, DISC, COMPACTDISC'); WriteLn(' for a list of default modes see command "MODELIST"'); WriteLn(''); WriteLn('Additional program functions:'); WriteLn('Help: ', ExtractFileName(ExeName), ' -h (--help)'); WriteLn(' Show this help text.'+#13#10); WriteLn('Build info: ', ExtractFileName(ExeName), ' -b (--build)'); WriteLn(' Show the program build info.'+#13#10); WriteLn('API info: ', ExtractFileName(ExeName), ' -a (--api)'); WriteLn(' Show the Frontier Silicon API info.'+#13#10); WriteLn('Banner: ', ExtractFileName(ExeName), ' -n (--nobanner)'); WriteLn(' Hide the banner.'+#13#10); WriteLn(' ', ExtractFileName(ExeName), ' -s (--showbanner)'); WriteLn(' Just show the banner (overrides -n --nobanner).'+#13#10); WriteLn('License info: ', ExtractFileName(ExeName), ' -l (--license)'); WriteLn(' Show license info.'+#13#10); WriteLn('Device list: ', ExtractFileName(ExeName), ' -d (--devicelist)'); WriteLn(' UPnP network scan of supported active devices with icon URL if available.'); WriteLn(' This scan may take up around to 5 seconds.'+#13#10); WriteLn('Read command: ', ExtractFileName(ExeName), ' -u [IP] (--url=[IP]) -p [PIN] (--pin=[PIN]) -r [COMMAND] (--read=[COMMAND])'); WriteLn(' Read by sending a RAW fsapi GET command and the resulting XML output will be printed.'); WriteLn(' For example: '); WriteLn(' ', ExtractFileName(ExeName), ' --url=192.168.0.34 --pin=1234 --read=netRemote.sys.info.friendlyName'+#13#10); WriteLn('Write command: ', ExtractFileName(ExeName), ' -u [IP] (--url=[IP]) -p [PIN] (--pin=[PIN]) -w [COMMAND:VALUE] (--write=[COMMAND:VALUE])'); WriteLn(' Write a value by sending a RAW fsapi SET command and the resulting XML output will be printed.'); WriteLn(' For example: '); WriteLn(' ', ExtractFileName(ExeName), ' -u 192.168.0.34 -p 1234 -w "netRemote.sys.info.friendlyName:DigitRadio 360 CD"'); WriteLn(' ', ExtractFileName(ExeName), ' --url=192.168.0.34 --pin=1234 --write=netRemote.sys.audio.volume:10'+#13#10); WriteLn('FullRAW command: ', ExtractFileName(ExeName), ' -u [IP] (--url=[IP]) -p [PIN] (--pin=[PIN]) -f [COMMAND:VALUE] (--fullraw=[COMMAND])'); WriteLn(' Sends a RAW HTTP command and the resulting XML output will be printed.'); WriteLn(' For example: '); WriteLn(' ', ExtractFileName(ExeName), ' -u 192.168.0.34 -p 1234 -f /fsapi/GET/netRemote.sys.info.version'); WriteLn(' Normally the PIN will be automatically added to the RAW command but the PIN can'); WriteLn(' also be added manually.'); WriteLn(' For example: '); WriteLn(' ', ExtractFileName(ExeName), ' -u 192.168.0.34 -f /fsapi/GET/netRemote.sys.info.version?pin=1234'); WriteLn(' In most cases the session ID will also be automatically created and added to the RAW command.'); WriteLn(' In case the session ID should be manually added to a RAW command create a session ID first.'); WriteLn(' For example: '); WriteLn(' ', ExtractFileName(ExeName), ' -u 192.168.0.34 -f /fsapi/CREATE_SESSION'); WriteLn(' Now extract the session ID from the XML output and add it manually.'); WriteLn(' For example: '); WriteLn(' ', ExtractFileName(ExeName), ' -u 192.168.0.34 -f "/fsapi/GET/netRemote.sys.power?pin=1234&sid=1970732077"'); WriteLn(' In case the RAW commandline is not accepted by your terminal quote the RAW command'); WriteLn(' as shown above with ".'); WriteLn('Icon download: ', ExtractFileName(ExeName), ' -u [ICONURL] (--url=[ICONURL]) --icondownload=[LocalFilePath]'); WriteLn(' Download the device icon. In this case the URL must be the Icon URL and NOT only the device IP!'); WriteLn(' The Icon URL can be found by using -d (--devicelist) (see "Device list").'+#13#10); WriteLn(' For example: '); WriteLn(' ', ExtractFileName(ExeName), ' -u 192.168.0.13:8080/icon2.jpg --icondownload="C:/Icon Folder/Icon2.jpg"'); WriteLn('Cover download: ', ExtractFileName(ExeName), ' -u [URL] (--url=[URL]) --coverdownload=[LocalFolderPath]'); WriteLn(' Download an actual cover or logo graphic (see "GETGRAPHICURI").'); WriteLn(' In this case the URL must be only the device IP!'+#13#10); WriteLn(' For example: '); WriteLn(' ', ExtractFileName(ExeName), ' -u 192.168.0.13 -p 1234 --coverdownload="C:/Cover Folder/"'); end; procedure TApp.HelpHint; //show a hint for the help function begin WriteLn(STR_Info+'Try "', ExtractFileName(ExeName), ' -h" or "', ExtractFileName(ExeName), ' --help" for a detailed help.'); WriteLn(STR_Info+'Try "', ExtractFileName(ExeName), ' -l" or "', ExtractFileName(ExeName), ' --license" for the license.'); end; procedure TApp.WaitPrint; //show waiting hint begin Write(STR_Info+STR_WaitingMsg); end; procedure TApp.WaitClear; //clear waiting hint begin Write(StringOfChar(#8, Length(STR_Info)+Length(STR_WaitingMsg))+StringOfChar(' ', Length(STR_Info)+Length(STR_WaitingMsg))); end; var Application: TApp; begin Application:=TApp.Create(nil); Application.Run; Application.Free; end.
unit EcySetting; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, iComponent, iVCLComponent, iEditCustom, iAnalogOutput, LbSpeedButton, LbButton, iLed, iLedRectangle, EController; type TFrmEcySetting = class(TForm) GroupBox7: TGroupBox; Label36: TLabel; Output_FGain: TiAnalogOutput; Output_FOff: TiAnalogOutput; GroupBox1: TGroupBox; Label3: TLabel; Label4: TLabel; Label6: TLabel; Output_Kp: TiAnalogOutput; GroupBox2: TGroupBox; Label5: TLabel; Label7: TLabel; Output_MaxSpeed: TiAnalogOutput; Btn_Update: TLbSpeedButton; Btn_Close: TLbSpeedButton; LbButton1: TLbButton; CB_Lead: TComboBox; Label1: TLabel; Btn_Reset: TLbSpeedButton; LbSpeedButton1: TLbSpeedButton; Led_SelfCheck: TiLedRectangle; LbSpeedButton2: TLbSpeedButton; Label2: TLabel; Output_FMax: TiAnalogOutput; Label8: TLabel; Output_FMin: TiAnalogOutput; Label9: TLabel; Output_SMax: TiAnalogOutput; Label10: TLabel; Output_SMin: TiAnalogOutput; Output_Ki: TiAnalogOutput; Output_Kd: TiAnalogOutput; procedure Btn_UpdateClick(Sender: TObject); procedure Btn_CloseClick(Sender: TObject); procedure LbButton1Click(Sender: TObject); procedure Btn_ResetClick(Sender: TObject); procedure CB_LeadChange(Sender: TObject); procedure LbSpeedButton1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure LbSpeedButton2Click(Sender: TObject); private { Private declarations } EP:TECyPara; public { Public declarations } ECy: TECylinder; end; var FrmEcySetting: TFrmEcySetting; implementation {$R *.DFM} procedure TFrmEcySetting.Btn_UpdateClick(Sender: TObject); var EP:TECyPara; begin EP.ch:=ECy.CH; EP.control_kp:=Output_Kp.Value; EP.control_ki:=Output_Ki.Value; EP.control_kd:=Output_Kd.Value; EP.screw_lead:=StrToFloat(CB_Lead.Text); EP.screw_max:=Output_SMax.Value; EP.screw_min:=Output_SMin.Value; EP.force_gain:=Output_FGain.Value; EP.force_off:=Output_FOff.Value; EP.force_max:=Output_FMax.Value; EP.force_min:=Output_FMin.Value; ECy.SetEcyPara(EP); end; procedure TFrmEcySetting.Btn_CloseClick(Sender: TObject); begin Close; end; procedure TFrmEcySetting.LbButton1Click(Sender: TObject); begin Output_FOff.Value:=ECy.TD.actforce/EP.force_gain+EP.force_off; end; procedure TFrmEcySetting.Btn_ResetClick(Sender: TObject); begin ECy.ECtr.Reset; end; procedure TFrmEcySetting.CB_LeadChange(Sender: TObject); begin Output_MaxSpeed.Value:=StrToFloat(CB_Lead.Text)*50; end; procedure TFrmEcySetting.LbSpeedButton1Click(Sender: TObject); begin Led_SelfCheck.Active:=ECy.SelfCheck; end; procedure TFrmEcySetting.FormShow(Sender: TObject); var i:integer; begin ECy.GetEcyPara(EP); Output_Kp.Value:=EP.control_kp; Output_Ki.Value:=EP.control_ki; Output_Kd.Value:=EP.control_kd; if Abs(EP.screw_lead-2.5)<0.001 then CB_Lead.ItemIndex:=1 else CB_Lead.ItemIndex:=CB_Lead.items.IndexOf(IntToStr(Round(EP.screw_lead))); Output_FGain.Value:=EP.force_gain; Output_FOff.Value:=EP.force_off; Output_SMax.Value:=EP.screw_max; Output_SMin.Value:=EP.screw_min; Output_FMax.Value:=EP.force_max; Output_FMin.Value:=EP.force_min; end; procedure TFrmEcySetting.LbSpeedButton2Click(Sender: TObject); begin ECy.ShowSingleCyTest; end; end.
unit Main; interface uses System.Types, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ExtCtrls, FMX.ScrollBox, FMX.Memo, FMX.Objects, FMX.Layouts, FMX.Edit, System.ImageList, FMX.ImgList, FMX.Memo.Types, FMX.TreeView, LogWindow; type TForm1 = class(TForm) GroupBox1: TGroupBox; Memo1: TMemo; GroupBox2: TGroupBox; popupPolicies: TPopupBox; Memo2: TMemo; Layout1: TLayout; buttonValidateModel: TButton; labelValidateModel: TLabel; rectangleModel: TRectangle; buttonValidatePolicies: TButton; Layout2: TLayout; rectanglePolicies: TRectangle; labelValidatePolicies: TLabel; Label1: TLabel; editParams: TEdit; Button1: TButton; Layout3: TLayout; rectangleEnforced: TRectangle; labelEnforced: TLabel; labelVersion: TLabel; Layout4: TLayout; Rectangle1: TRectangle; LabelError: TLabel; ImageList1: TImageList; Image1: TImage; layoutWarning: TLayout; Rectangle2: TRectangle; lblWarning: TLabel; Image2: TImage; mainLayout: TLayout; Layout7: TLayout; Layout8: TLayout; Splitter1: TSplitter; Layout9: TLayout; Layout10: TLayout; Label3: TLabel; tvModels: TTreeView; TreeViewItem1: TTreeViewItem; Splitter2: TSplitter; Layout5: TLayout; Rectangle3: TRectangle; lbTime: TLabel; Rectangle4: TRectangle; btnDebug: TSpeedButton; Image3: TImage; procedure btnDebugClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure buttonValidateModelClick(Sender: TObject); procedure buttonValidatePoliciesClick(Sender: TObject); procedure editParamsChangeTracking(Sender: TObject); procedure FormCreate(Sender: TObject); procedure popupPoliciesChange(Sender: TObject); procedure tvModelsChange(Sender: TObject); private fFolder: string; fDefaultFolder: string; fAdditionalFolder: string; fLogForm: TFormLog; procedure addDefaultModels (const aParent: TTreeViewItem); procedure addAdditionalModels (const aParent: TTreeViewItem); procedure addFolder(const aParent: TTreeViewItem; const aPath: string; const aLabel: string = '%s'; const aTag: integer = 0); procedure resetLayout; public { Public declarations } end; var Form1: TForm1; implementation uses System.IOUtils, Casbin.Parser.Types, Casbin.Parser, Casbin.Types, Casbin, Casbin.Core.Utilities, Casbin.Model.Types, Casbin.Policy.Types, Casbin.Model, Casbin.Adapter.Types, Casbin.Policy, Casbin.Adapter.Memory.Policy, Casbin.Adapter.Policy.Types, Casbin.Adapter.Filesystem, Casbin.Adapter.Memory, Casbin.Adapter.Filesystem.Policy, System.UITypes, System.SysUtils, Quick.Chrono, Logger.Debug; {$R *.fmx} procedure TForm1.addAdditionalModels(const aParent: TTreeViewItem); var item: TTreeViewItem; begin if TDirectory.Exists(fAdditionalFolder) then begin item:=TTreeViewItem.Create(aParent); item.Text:='Additional'; item.TagString:='additional'; item.TextSettings.Font.Style:=[TFontStyle.fsBold]; item.Parent:=aParent; addFolder(item, fAdditionalFolder, 'Additional - %s', 1); end; end; procedure TForm1.addDefaultModels(const aParent: TTreeViewItem); var item: TTreeViewItem; begin if TDirectory.Exists(fDefaultFolder) then begin item:=TTreeViewItem.Create(aParent); item.Text:='Default'; item.TextSettings.Font.Style:=[TFontStyle.fsBold]; item.TagString:='default'; item.Parent:=aParent; addFolder(item, fDefaultFolder, 'Default - %s', 0); end; end; procedure TForm1.addFolder(const aParent: TTreeViewItem; const aPath: string; const aLabel: string = '%s'; const aTag: integer = 0); var res: integer; SRec: TSearchRec; name: string; item: TTreeViewItem; begin Res := FindFirst(TPath.Combine(aPath, '*.conf'), faAnyfile, SRec ); if Res = 0 then try while res = 0 do begin if (SRec.Attr and faDirectory <> faDirectory) then begin name:=TPath.GetFileNameWithoutExtension(SRec.Name); item:=TTreeViewItem.Create(aParent); item.Text:=name; item.TagString:=name; item.Parent:=aParent; if name.Contains('model') then name:=StringReplace(name, 'model', 'policy', [rfIgnoreCase]) else name:=name+'_policy'; if FileExists(TPath.Combine(aPath, name + '.csv')) then popupPolicies.Items.AddObject(format(aLabel, [name]), TObject(aTag)); end; Res := FindNext(SRec); end; finally FindClose(SRec) end; end; procedure TForm1.btnDebugClick(Sender: TObject); begin fLogForm.Visible:=not fLogForm.Visible; end; procedure TForm1.Button1Click(Sender: TObject); var casbin: ICasbin; model: IModel; modelAdapter: IAdapter; policy: IPolicyManager; policyAdapter: IPolicyAdapter; params: TStringDynArray; chrono: TChronometer; enfRes: boolean; begin if Trim(editParams.Text)='' then begin ShowMessage('The parameters are empty'); Exit; end; params:=TStringDynArray(editParams.Text.Split([','])); model:=nil; modelAdapter:=nil; policy:=nil; policyAdapter:=nil; modelAdapter:=TMemoryAdapter.Create; modelAdapter.Assertions.AddRange(Memo1.Lines.ToStringArray); model:=TModel.Create(modelAdapter); policyAdapter:=TPolicyMemoryAdapter.Create; policyAdapter.Assertions.AddRange(Memo2.Lines.ToStringArray); policy:=TPolicyManager.Create(policyAdapter); chrono:=TChronometer.Create(false); chrono.ReportFormatPrecission:=TPrecissionFormat.pfFloat; casbin:=TCasbin.Create(model, policy); casbin.LoggerPool.Loggers.Add(TLogDebug.Create(fLogForm)); casbin.LoggerPool.log('------------------- ENFORCER STARTED ------->'); try try chrono.Start; enfRes:= casbin.enforce(params); chrono.Stop; if enfRes then begin rectangleEnforced.Fill.Color:=TAlphaColorRec.Green; labelEnforced.Text:='ALLOW'; // No Errors Image1.Bitmap:=ImageList1.Bitmap(TSizeF.Create(Image1.Height,Image1.Height), 1); LabelError.Text:='No Errors'; end else begin rectangleEnforced.Fill.Color:=TAlphaColorRec.Red; labelEnforced.Text:='DENY'; end; labelEnforced.FontColor:=TAlphaColorRec.White; lbTime.Text:=chrono.ElapsedTime; except on E: Exception do begin Image1.Bitmap:=ImageList1.Bitmap(TSizeF.Create(Image1.Height,Image1.Height), 0); if E.Message.Contains('math') then LabelError.Text:='Select the correct model-policy files' else LabelError.Text:=E.Message; end; end; finally chrono.Free; casbin.LoggerPool.log('------------------- ENFORCER FINISHED ------->'); end; end; procedure TForm1.buttonValidateModelClick(Sender: TObject); var parser: IParser; begin parser:=TParser.Create(Memo1.Text, ptModel); parser.parse; if parser.Status=psError then begin labelValidateModel.Text:=parser.ErrorMessage; rectangleModel.Fill.Color:=TAlphaColorRec.Red; end else begin labelValidateModel.Text:='No Errors'; rectangleModel.Fill.Color:=TAlphaColorRec.Green; end; labelValidateModel.FontColor:=TAlphaColorRec.White; end; procedure TForm1.buttonValidatePoliciesClick(Sender: TObject); var parser: IParser; begin parser:=TParser.Create(Memo2.Text, ptPolicy); parser.parse; if parser.Status=psError then begin labelValidatePolicies.Text:=parser.ErrorMessage; rectanglePolicies.Fill.Color:=TAlphaColorRec.Red; end else begin labelValidatePolicies.Text:='No Errors'; rectanglePolicies.Fill.Color:=TAlphaColorRec.Green; end; labelValidatePolicies.FontColor:=TAlphaColorRec.White; end; procedure TForm1.editParamsChangeTracking(Sender: TObject); begin labelEnforced.Text:='Nothing Enforced Yet'; labelEnforced.FontColor:=TAlphaColorRec.Black; rectangleEnforced.Fill.Color:=TAlphaColorRec.Null; Image1.Bitmap:=ImageList1.Bitmap(TSizeF.Create(Image1.Height,Image1.Height), 1); LabelError.Text:='No Errors'; end; procedure TForm1.FormCreate(Sender: TObject); var SRec: TSearchRec; Res: Integer; nItem: TTreeViewItem; begin fDefaultFolder:='..\..\Examples\Default\'; fAdditionalFolder:='..\..\Examples\Additional\'; labelVersion.Text:='Casbin4D - ' + version; mainLayout.Enabled:=false; tvModels.BeginUpdate; try with tvModels do begin Clear; nItem:=TTreeViewItem.Create(tvModels); nItem.Text:='Models'; nItem.TextSettings.Font.Style:=[TFontStyle.fsBold]; nItem.TagString:='models'; nItem.Parent:=tvModels; addDefaultModels(nItem); addAdditionalModels(nItem); Selected:=nItem; ExpandAll; end; finally tvModels.EndUpdate; end; // No Errors Image1.Bitmap:=ImageList1.Bitmap(TSizeF.Create(Image1.Height,Image1.Height), 1); // Warnings Image2.Bitmap:=ImageList1.Bitmap(TSizeF.Create(Image2.Height,Image2.Height), 2); resetLayout; fLogForm:=TFormLog.Create(self); fLogForm.Visible:=false; end; procedure TForm1.popupPoliciesChange(Sender: TObject); var name: string; begin if popupPolicies.ItemIndex = -1 then Exit; Memo2.Lines.Clear; name:=popupPolicies.Text.Split(['-'])[1].Trim; if integer(popupPolicies.Items.Objects[popupPolicies.ItemIndex]) = 0 then name:=TPath.Combine(fDefaultFolder, name); if integer(popupPolicies.Items.Objects[popupPolicies.ItemIndex]) = 1 then name:=TPath.Combine(fAdditionalFolder, name); name:=name + '.csv'; Memo2.Lines.AddStrings(TArray<string>(TFile.ReadAllLines(name))); labelValidatePolicies.FontColor:=TAlphaColorRec.Black; rectanglePolicies.Fill.Color:=TAlphaColorRec.Null; end; procedure TForm1.resetLayout; begin Memo1.Lines.Clear; labelValidateModel.Text:='Not Validated Yet'; labelValidateModel.FontColor:=TAlphaColorRec.Black; rectangleModel.Fill.Color:=TAlphaColorRec.Null; Memo2.Lines.Clear; labelValidatePolicies.FontColor:=TAlphaColorRec.Black; rectanglePolicies.Fill.Color:=TAlphaColorRec.Null; LabelError.Text:='No Errors'; layoutWarning.Visible:=false; popupPolicies.ItemIndex:=-1; lbTime.Text:=''; end; procedure TForm1.tvModelsChange(Sender: TObject); var rootFolder: string; policyFile: string; line: string; begin mainLayout.Enabled:= (tvModels.Selected.TagString <> 'models') and (tvModels.Selected.TagString <> 'default') and (tvModels.Selected.TagString <> 'additional'); if not mainLayout.Enabled then Exit; resetLayout; if tvModels.Selected.ParentItem.TagString = 'default' then rootFolder:=fDefaultFolder; if tvModels.Selected.ParentItem.TagString = 'additional' then rootFolder:=fAdditionalFolder; Memo1.Lines.AddStrings(TArray<string>(TFile.ReadAllLines( TPath.Combine(rootFolder, tvModels.Selected.TagString + '.conf')))); policyFile:=tvModels.Selected.TagString; if policyFile.Contains('model') then policyFile:=StringReplace(policyFile, 'model', 'policy', [rfIgnoreCase]) else policyFile:=policyFile +'_policy'; policyFile:=policyFile + '.csv'; policyFile:=TPath.Combine(rootFolder, policyFile); if FileExists(policyFile) then Memo2.Lines.AddStrings(TArray<string>(TFile.ReadAllLines(policyFile))) else begin lblWarning.Text:='Policy file ' + policyFile + ' not found' + sLineBreak + 'You can select a policy file manually'; layoutWarning.Visible:=true; end; if (memo2.Lines.Count > 0) then begin for line in memo2.Lines do begin if (Trim(line) <> '') and (line.StartsWith('p,')) then editParams.Text:=line.Substring('p,'.Length + 1).Trim; end; end; end; end.
///<summary>Abstract syntax tree for the SQL query builder.</summary> ///<author>Primoz Gabrijelcic</author> ///<remarks><para> ///Copyright (c) 2016, Primoz Gabrijelcic ///All rights reserved. /// ///Redistribution and use in source and binary forms, with or without ///modification, are permitted provided that the following conditions are met: /// ///* Redistributions of source code must retain the above copyright notice, this /// list of conditions and the following disclaimer. /// ///* Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// ///* Neither the name of GpSQLBuilder nor the names of its /// contributors may be used to endorse or promote products derived from /// this software without specific prior written permission. /// ///THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ///AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ///IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ///DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ///FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ///DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ///SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ///CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ///OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ///OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// /// Author : Primoz Gabrijelcic /// Creation date : 2015-04-20 /// Last modification : 2016-09-08 /// Version : 1.05 /// History: /// 1.05: 2016-09-08 /// - Added support for Insert columns. /// 1.04: 2015-07-12 /// - [leledumbo] Added support for Insert statement. /// 1.03: 2015-06-17 /// - Added support for Update and Delete statements. /// 1.02: 2015-05-05 /// - IGpSQLColums was renamed to IGpSQLNames. /// - IGpSQLSelect.TableName: IGpSQLName was changed to .TableNames:IGpSQLNames to /// accomodate more than one table in the From part. /// 1.01: 2015-04-30 /// - Added sqDistinct TGpSQLSelectQualifierType, representing SELECT DISTINCT. /// 1.0: 2015-04-29 /// - Released. ///</para></remarks> unit GpSQLBuilder.AST; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} interface uses System.Generics.Collections; type IGpSQLCase = interface; IGpSQLName = interface ['{B219D388-7E5E-4F71-A1F1-9AE4DDE754BC}'] function GetAlias: string; function GetCase: IGpSQLCase; function GetName: string; procedure SetAlias(const value: string); procedure SetCase(const value: IGpSQLCase); procedure SetName(const value: string); // procedure Clear; function IsEmpty: boolean; property Name: string read GetName write SetName; property &Case: IGpSQLCase read GetCase write SetCase; property Alias: string read GetAlias write SetAlias; end; { IGpSQLName } IGpSQLNames = interface ['{DA9157F6-3526-4DA4-8CD3-115DFE7719B3}'] function GetColumns(idx: integer): IGpSQLName; // function Add: IGpSQLName; overload; procedure Add(const name: IGpSQLName); overload; procedure Clear; function Count: integer; function IsEmpty: boolean; property Columns[idx: integer]: IGpSQLName read GetColumns; default; end; { IGpSQLNames } IGpSQLNameValue = interface ['{64F2DDD0-3A26-4BBA-8AD2-3C791AC77747}'] function GetName: string; function GetValue: string; procedure SetName(const value: string); procedure SetValue(const value: string); // procedure Clear; function IsEmpty: boolean; property Name: string read GetName write SetName; property Value: string read GetValue write SetValue; end; { IGpSQLNameValue } IGpSQLNameValuePairs = interface ['{2859B885-1E9A-4452-AE36-F31799E7E10D}'] function GetItem(idx: integer): IGpSQLNameValue; // function Add: IGpSQLNameValue; overload; procedure Add(const nameValue: IGpSQLNameValue); overload; procedure Clear; function Count: integer; function IsEmpty: boolean; property Item[idx: integer]: IGpSQLNameValue read GetItem; default; end; { IGpSQLNameValuePairs } TGpSQLExpressionOperation = (opNone, opAnd, opOr); IGpSQLExpression = interface ['{011D9FD2-AE54-4720-98AB-085D6F6B421E}'] function GetLeft: IGpSQLExpression; function GetOperation: TGpSQLExpressionOperation; function GetRight: IGpSQLExpression; function GetTerm: string; procedure SetLeft(const value: IGpSQLExpression); procedure SetOperation(const value: TGpSQLExpressionOperation); procedure SetRight(const value: IGpSQLExpression); procedure SetTerm(const value: string); // procedure Assign(const node: IGpSQLExpression); procedure Clear; function IsEmpty: boolean; property Term: string read GetTerm write SetTerm; property Operation: TGpSQLExpressionOperation read GetOperation write SetOperation; property Left: IGpSQLExpression read GetLeft write SetLeft; property Right: IGpSQLExpression read GetRight write SetRight; end; { IGpSQLExpression } IGpSQLCaseWhenThen = interface ['{ADEF8C82-FDF5-4960-9F77-EC0A57AA082E}'] function GetThenExpression: IGpSQLExpression; function GetWhenExpression: IGpSQLExpression; procedure SetThenExpression(const value: IGpSQLExpression); procedure SetWhenExpression(const value: IGpSQLExpression); // property WhenExpression: IGpSQLExpression read GetWhenExpression write SetWhenExpression; property ThenExpression: IGpSQLExpression read GetThenExpression write SetThenExpression; end; { IGpSQLCaseWhenThen } IGpSQLCaseWhenList = interface ['{0D18F711-5002-421D-A1CA-8D1D36F4653E}'] function GetWhenThen(idx: integer): IGpSQLCaseWhenThen; procedure SetWhenThen(idx: integer; const value: IGpSQLCaseWhenThen); // function Add: IGpSQLCaseWhenThen; overload; function Add(const whenThen: IGpSQLCaseWhenThen): integer; overload; function Count: integer; property WhenThen[idx: integer]: IGpSQLCaseWhenThen read GetWhenThen write SetWhenThen; default; end; { IGpSQLCaseWhenList } IGpSQLCase = interface ['{F6F45A4A-1108-4BA6-92F5-7A7386E2388C}'] function GetCaseExpression: IGpSQLExpression; function GetElseExpression: IGpSQLExpression; function GetWhenList: IGpSQLCaseWhenList; procedure SetCaseExpression(const value: IGpSQLExpression); procedure SetElseExpression(const value: IGpSQLExpression); procedure SetWhenList(const value: IGpSQLCaseWhenList); // property CaseExpression: IGpSQLExpression read GetCaseExpression write SetCaseExpression; property WhenList: IGpSQLCaseWhenList read GetWhenList write SetWhenList; property ElseExpression: IGpSQLExpression read GetElseExpression write SetElseExpression; end; { IGpSQLCase } IGpSQLSection = interface ['{BE0A0FF9-AD70-40C5-A1C2-7FA2F7061153}'] function GetName: string; // procedure Clear; function IsEmpty: boolean; property Name: string read GetName; end; { IGpSQLSection } TGpSQLSelectQualifierType = (sqFirst, sqSkip, sqDistinct); IGpSQLSelectQualifier = interface ['{EC0EC192-81C6-493B-B4A7-F8DA7F6D0D4B}'] function GetQualifier: TGpSQLSelectQualifierType; function GetValue: integer; procedure SetQualifier(const value: TGpSQLSelectQualifierType); procedure SetValue(const value: integer); // property Qualifier: TGpSQLSelectQualifierType read GetQualifier write SetQualifier; property Value: integer read GetValue write SetValue; end; { IGpSQLSelectQualifier } IGpSQLSelectQualifiers = interface ['{522F34BC-C916-45B6-9DC2-E800FEC7661A}'] function GetQualifier(idx: integer): IGpSQLSelectQualifier; // function Add: IGpSQLSelectQualifier; overload; procedure Add(qualifier: IGpSQLSelectQualifier); overload; procedure Clear; function Count: integer; function IsEmpty: boolean; property Qualifier[idx: integer]: IGpSQLSelectQualifier read GetQualifier; default; end; { IGpSQLSelectQualifiers } IGpSQLSelect = interface(IGpSQLSection) ['{6B23B86E-97F3-4D8A-BED5-A678EAEF7842}'] function GetColumns: IGpSQLNames; function GetQualifiers: IGpSQLSelectQualifiers; function GetTableNames: IGpSQLNames; // property Columns: IGpSQLNames read GetColumns; property Qualifiers: IGpSQLSelectQualifiers read GetQualifiers; property TableNames: IGpSQLNames read GetTableNames; end; { IGpSQLSelect } IGpSQLDelete = interface(IGpSQLSection) ['{FFD88B81-CB86-4F4B-8CBC-12BB991D531B}'] function GetTableNames: IGpSQLNames; // property TableNames: IGpSQLNames read GetTableNames; end; { IGpSQLDelete } IGpSQLInsert = interface(IGpSQLSection) ['{FD8380C4-C20A-4F02-B3D9-95B6F2CCDF40}'] function GetColumns: IGpSQLNames; function GetTableName: string; function GetValues: IGpSQLNameValuePairs; procedure SetTableName(const value: string); // property Columns: IGpSQLNames read GetColumns; property TableName: string read GetTableName write SetTableName; property Values: IGpSQLNameValuePairs read GetValues; end; { IGpSQLInsert } IGpSQLUpdate = interface(IGpSQLSection) ['{61AA0D87-382C-4F83-AAA6-65B9416C09A8}'] function GetTableName: string; function GetValues: IGpSQLNameValuePairs; procedure SetTableName(const value: string); // property TableName: string read GetTableName write SetTableName; property Values: IGpSQLNameValuePairs read GetValues; end; { IGpSQLUpdate } TGpSQLJoinType = (jtInner, jtLeft, jtRight, jtFull); IGpSQLJoin = interface(IGpSQLSection) ['{CD8AD84D-2FCC-4EBD-A83A-A637CF9D188E}'] function GetCondition: IGpSQLExpression; function GetJoinedTable: IGpSQLName; function GetJoinType: TGpSQLJoinType; procedure SetCondition(const value: IGpSQLExpression); procedure SetJoinedTable(const value: IGpSQLName); procedure SetJoinType(const value: TGpSQLJoinType); // property JoinedTable: IGpSQLName read GetJoinedTable write SetJoinedTable; property JoinType: TGpSQLJoinType read GetJoinType write SetJoinType; property Condition: IGpSQLExpression read GetCondition write SetCondition; end; { IGpSQLJoin } IGpSQLJoins = interface ['{5C277003-FC57-4DE5-B041-371012A51D82}'] function GetJoins(idx: integer): IGpSQLJoin; procedure SetJoins(idx: integer; const value: IGpSQLJoin); // function Add: IGpSQLJoin; overload; procedure Add(const join: IGpSQLJoin); overload; procedure Clear; function Count: integer; function IsEmpty: boolean; property Joins[idx: integer]: IGpSQLJoin read GetJoins write SetJoins; default; end; { IGpSQLJoins } IGpSQLWhere = interface(IGpSQLSection) ['{77BD3E41-53DC-4FC7-B0ED-B339564791AA}'] function GetExpression: IGpSQLExpression; procedure SetExpression(const value: IGpSQLExpression); // property Expression: IGpSQLExpression read GetExpression write SetExpression; end; { IGpSQLWhere } IGpSQLGroupBy = interface(IGpSQLSection) ['{B8B50CF2-2E2A-4C3C-B9B6-D6B0BE92502C}'] function GetColumns: IGpSQLNames; // property Columns: IGpSQLNames read GetColumns; end; { IGpSQLGroupBy } IGpSQLHaving = interface(IGpSQLSection) ['{BF1459A7-C665-4983-A724-A7002F6D201F}'] function GetExpression: IGpSQLExpression; procedure SetExpression(const value: IGpSQLExpression); // property Expression: IGpSQLExpression read GetExpression write SetExpression; end; { IGpSQLHaving } TGpSQLOrderByDirection = (dirAscending, dirDescending); IGpSQLOrderByColumn = interface(IGpSQLName) ['{05ECC702-D102-4D7D-A150-49A7A8787A7C}'] function GetDirection: TGpSQLOrderByDirection; procedure SetDirection(const value: TGpSQLOrderByDirection); // property Direction: TGpSQLOrderByDirection read GetDirection write SetDirection; end; { IGpSQLOrderByColumn } IGpSQLOrderBy = interface(IGpSQLSection) ['{6BC985B7-219A-4359-9F21-60A985969368}'] function GetColumns: IGpSQLNames; // property Columns: IGpSQLNames read GetColumns; end; { IGpSQLOrderBy } IGpSQLAST = interface function GetDelete: IGpSQLDelete; function GetGroupBy: IGpSQLGroupBy; function GetHaving: IGpSQLHaving; function GetJoins: IGpSQLJoins; function GetOrderBy: IGpSQLOrderBy; function GetSelect: IGpSQLSelect; function GetInsert: IGpSQLInsert; function GetUpdate: IGpSQLUpdate; function GetWhere: IGpSQLWhere; // procedure Clear; function IsEmpty: boolean; property Select: IGpSQLSelect read GetSelect; property Delete: IGpSQLDelete read GetDelete; property Insert: IGpSQLInsert read GetInsert; property Update: IGpSQLUpdate read GetUpdate; property Joins: IGpSQLJoins read GetJoins; property Where: IGpSQLWhere read GetWhere; property GroupBy: IGpSQLGroupBy read GetGroupBy; property Having: IGpSQLHaving read GetHaving; property OrderBy: IGpSQLOrderBy read GetOrderBy; end; { IGpSQLAST } function CreateSQLAST: IGpSQLAST; function CreateSQLExpression: IGpSQLExpression; function CreateSQLCase: IGpSQLCase; implementation uses {$IFNDEF FPC}System.SysUtils{$ELSE}Sysutils{$ENDIF}; type TGpSQLName = class(TInterfacedObject, IGpSQLName) strict private FAlias: string; FCase : IGpSQLCase; FName : string; strict protected function GetAlias: string; function GetCase: IGpSQLCase; function GetName: string; procedure SetAlias(const value: string); procedure SetCase(const value: IGpSQLCase); procedure SetName(const value: string); public procedure Clear; function IsEmpty: boolean; property Name: string read GetName write SetName; property &Case: IGpSQLCase read GetCase write SetCase; property Alias: string read GetAlias write SetAlias; end; { TGpSQLName } TGpSQLNames = class(TInterfacedObject, IGpSQLNames) strict private FColumns: TList<IGpSQLName>; strict protected function GetColumns(idx: integer): IGpSQLName; public constructor Create; destructor Destroy; override; function Add: IGpSQLName; overload; virtual; procedure Add(const name: IGpSQLName); overload; virtual; procedure Clear; function Count: integer; function IsEmpty: boolean; property Columns[idx: integer]: IGpSQLName read GetColumns; default; end; { TGpSQLNames } TGpSQLNameValue = class(TInterfacedObject, IGpSQLNameValue) strict private FName : string; FValue: string; strict protected function GetName: string; function GetValue: string; procedure SetName(const value: string); procedure SetValue(const value: string); public procedure Clear; function IsEmpty: boolean; property Name: string read GetName write SetName; property Value: string read GetValue write SetValue; end; { TGpSQLNameValue } TGpSQLNameValuePairs = class(TInterfacedObject, IGpSQLNameValuePairs) strict private FList: TList<IGpSQLNameValue>; strict protected function GetItem(idx: integer): IGpSQLNameValue; public constructor Create; destructor Destroy; override; function Add: IGpSQLNameValue; overload; procedure Add(const nameValue: IGpSQLNameValue); overload; procedure Clear; function Count: integer; function IsEmpty: boolean; property Item[idx: integer]: IGpSQLNameValue read GetItem; default; end; { TGpSQLNameValuePairs } TGpSQLExpression = class(TInterfacedObject, IGpSQLExpression) strict private FLeft : IGpSQLExpression; FOperation: TGpSQLExpressionOperation; FRight : IGpSQLExpression; FTerm : string; strict protected function GetLeft: IGpSQLExpression; function GetOperation: TGpSQLExpressionOperation; function GetRight: IGpSQLExpression; function GetTerm: string; procedure SetLeft(const value: IGpSQLExpression); procedure SetOperation(const value: TGpSQLExpressionOperation); procedure SetRight(const value: IGpSQLExpression); procedure SetTerm(const value: string); public procedure Assign(const node: IGpSQLExpression); procedure Clear; function IsEmpty: boolean; property Term: string read GetTerm write SetTerm; property Operation: TGpSQLExpressionOperation read GetOperation write SetOperation; property Left: IGpSQLExpression read GetLeft write SetLeft; property Right: IGpSQLExpression read GetRight write SetRight; end; { TGpSQLExpression } TGpSQLCaseWhenThen = class(TInterfacedObject, IGpSQLCaseWhenThen) strict private FThenExpression: IGpSQLExpression; FWhenExpression: IGpSQLExpression; strict protected function GetThenExpression: IGpSQLExpression; function GetWhenExpression: IGpSQLExpression; procedure SetThenExpression(const value: IGpSQLExpression); procedure SetWhenExpression(const value: IGpSQLExpression); public constructor Create; property WhenExpression: IGpSQLExpression read GetWhenExpression write SetWhenExpression; property ThenExpression: IGpSQLExpression read GetThenExpression write SetThenExpression; end; { TGpSQLCaseWhenThen } TGpSQLCaseWhenList = class(TInterfacedObject, IGpSQLCaseWhenList) strict private FWhenThenList: TList<IGpSQLCaseWhenThen>; strict protected function GetWhenThen(idx: integer): IGpSQLCaseWhenThen; procedure SetWhenThen(idx: integer; const value: IGpSQLCaseWhenThen); public constructor Create; destructor Destroy; override; function Add: IGpSQLCaseWhenThen; overload; function Add(const whenThen: IGpSQLCaseWhenThen): integer; overload; function Count: integer; property WhenThen[idx: integer]: IGpSQLCaseWhenThen read GetWhenThen write SetWhenThen; default; end; { TGpSQLCaseWhenList } TGpSQLCase = class(TInterfacedObject, IGpSQLCase) strict private FCaseExpression: IGpSQLExpression; FElseExpression: IGpSQLExpression; FWhenList : IGpSQLCaseWhenList; strict protected function GetCaseExpression: IGpSQLExpression; function GetElseExpression: IGpSQLExpression; function GetWhenList: IGpSQLCaseWhenList; procedure SetCaseExpression(const value: IGpSQLExpression); procedure SetElseExpression(const value: IGpSQLExpression); procedure SetWhenList(const value: IGpSQLCaseWhenList); public constructor Create; property CaseExpression: IGpSQLExpression read GetCaseExpression write SetCaseExpression; property WhenList: IGpSQLCaseWhenList read GetWhenList write SetWhenList; property ElseExpression: IGpSQLExpression read GetElseExpression write SetElseExpression; end; { TGpSQLCase } TGpSQLSection = class(TInterfacedObject, IGpSQLSection) strict private FName: string; strict protected function GetName: string; public constructor Create(sectionName: string); procedure Clear; virtual; abstract; function IsEmpty: boolean; virtual; abstract; property Name: string read GetName; end; { TGpSQLSection } TGpSQLSelectQualifier = class(TInterfacedObject, IGpSQLSelectQualifier) strict private FQualifier: TGpSQLSelectQualifierType; FValue : integer; strict protected function GetQualifier: TGpSQLSelectQualifierType; function GetValue: integer; procedure SetQualifier(const value: TGpSQLSelectQualifierType); procedure SetValue(const value: integer); public property Qualifier: TGpSQLSelectQualifierType read GetQualifier write SetQualifier; property Value: integer read GetValue write SetValue; end; { TGpSQLSelectQualifier } TGpSQLSelectQualifiers = class(TInterfacedObject, IGpSQLSelectQualifiers) strict private FQualifiers: TList<IGpSQLSelectQualifier>; strict protected function GetQualifier(idx: integer): IGpSQLSelectQualifier; public constructor Create; destructor Destroy; override; function Add: IGpSQLSelectQualifier; overload; procedure Add(qualifier: IGpSQLSelectQualifier); overload; procedure Clear; function Count: integer; function IsEmpty: boolean; property Qualifier[idx: integer]: IGpSQLSelectQualifier read GetQualifier; default; end; { TGpSQLSelectQualifiers } TGpSQLSelect = class(TGpSQLSection, IGpSQLSelect) strict private FColumns : IGpSQLNames; FQualifiers: IGpSQLSelectQualifiers; FTableNames: IGpSQLNames; strict protected function GetColumns: IGpSQLNames; function GetQualifiers: IGpSQLSelectQualifiers; function GetTableNames: IGpSQLNames; public constructor Create; procedure Clear; override; function IsEmpty: boolean; override; property Columns: IGpSQLNames read GetColumns; property Qualifiers: IGpSQLSelectQualifiers read GetQualifiers; property TableNames: IGpSQLNames read GetTableNames; end; { IGpSQLSelect } TGpSQLDelete = class(TGpSQLSection, IGpSQLDelete) strict private FTableNames: IGpSQLNames; strict protected function GetTableNames: IGpSQLNames; public constructor Create; procedure Clear; override; function IsEmpty: boolean; override; property TableNames: IGpSQLNames read GetTableNames; end; { TGpSQLDelete } TGpSQLInsert = class(TGpSQLSection, IGpSQLInsert) strict private FColumns : IGpSQLNames; FTableName: string; FValues : IGpSQLNameValuePairs; strict protected function GetColumns: IGpSQLNames; function GetTableName: string; function GetValues: IGpSQLNameValuePairs; procedure SetTableName(const value: string); public constructor Create; procedure Clear; override; property Columns: IGpSQLNames read GetColumns; function IsEmpty: boolean; override; property TableName: string read GetTableName write SetTableName; property Values: IGpSQLNameValuePairs read GetValues; end; { TGpSQLInsert } TGpSQLUpdate = class(TGpSQLSection, IGpSQLUpdate) strict private FTableName: string; FValues: IGpSQLNameValuePairs; strict protected function GetTableName: string; function GetValues: IGpSQLNameValuePairs; procedure SetTableName(const value: string); public constructor Create; procedure Clear; override; function IsEmpty: boolean; override; property TableName: string read GetTableName write SetTableName; property Values: IGpSQLNameValuePairs read GetValues; end; { TGpSQLUpdate } TGpSQLJoin = class(TGpSQLSection, IGpSQLJoin) strict private FCondition : IGpSQLExpression; FJoinedTable: IGpSQLName; FJoinType : TGpSQLJoinType; strict protected function GetCondition: IGpSQLExpression; function GetJoinedTable: IGpSQLName; function GetJoinType: TGpSQLJoinType; procedure SetCondition(const value: IGpSQLExpression); procedure SetJoinedTable(const value: IGpSQLName); procedure SetJoinType(const value: TGpSQLJoinType); public constructor Create; procedure Clear; override; function IsEmpty: boolean; override; property Condition: IGpSQLExpression read GetCondition write SetCondition; property JoinedTable: IGpSQLName read GetJoinedTable write SetJoinedTable; property JoinType: TGpSQLJoinType read GetJoinType write SetJoinType; end; { TGpSQLJoin } TGpSQLJoins = class(TInterfacedObject, IGpSQLJoins) strict private FJoins: TList<IGpSQLJoin>; strict protected function GetJoins(idx: integer): IGpSQLJoin; procedure SetJoins(idx: integer; const value: IGpSQLJoin); public constructor Create; destructor Destroy; override; function Add: IGpSQLJoin; overload; procedure Add(const join: IGpSQLJoin); overload; procedure Clear; function Count: integer; function IsEmpty: boolean; property Joins[idx: integer]: IGpSQLJoin read GetJoins write SetJoins; default; end; { TGpSQLJoins } TGpSQLWhere = class(TGpSQLSection, IGpSQLWhere) strict private FExpression: IGpSQLExpression; strict protected function GetExpression: IGpSQLExpression; procedure SetExpression(const value: IGpSQLExpression); public constructor Create; procedure Clear; override; function IsEmpty: boolean; override; property Expression: IGpSQLExpression read GetExpression write SetExpression; end; { TGpSQLWhere } TGpSQLGroupBy = class(TGpSQLSection, IGpSQLGroupBy) strict private FColumns: IGpSQLNames; strict protected function GetColumns: IGpSQLNames; public constructor Create; procedure Clear; override; function IsEmpty: boolean; override; property Columns: IGpSQLNames read GetColumns; end; { IGpSQLGroupBy } TGpSQLHaving = class(TGpSQLSection, IGpSQLHaving) strict private FExpression: IGpSQLExpression; strict protected function GetExpression: IGpSQLExpression; procedure SetExpression(const value: IGpSQLExpression); public constructor Create; procedure Clear; override; function IsEmpty: boolean; override; property Expression: IGpSQLExpression read GetExpression write SetExpression; end; { TGpSQLHaving } TGpSQLOrderByColumn = class(TGpSQLName, IGpSQLOrderByColumn) strict private FDirection: TGpSQLOrderByDirection; strict protected function GetDirection: TGpSQLOrderByDirection; procedure SetDirection(const value: TGpSQLOrderByDirection); public property Direction: TGpSQLOrderByDirection read GetDirection write SetDirection; end; { TGpSQLOrderByColumn } TGpSQLOrderByColumns = class(TGpSQLNames) public function Add: IGpSQLName; override; end; { TGpSQLOrderByColumns } TGpSQLOrderBy = class(TGpSQLSection, IGpSQLOrderBy) strict private FColumns: IGpSQLNames; strict protected function GetColumns: IGpSQLNames; public constructor Create; procedure Clear; override; function IsEmpty: boolean; override; property Columns: IGpSQLNames read GetColumns; end; { IGpSQLOrderBy } TGpSQLAST = class(TInterfacedObject, IGpSQLAST) strict private FDelete : IGpSQLDelete; FGroupBy: IGpSQLGroupBy; FHaving : IGpSQLHaving; FJoins : IGpSQLJoins; FOrderBy: IGpSQLOrderBy; FSelect : IGpSQLSelect; FInsert : IGpSQLInsert; FUpdate : IGpSQLUpdate; FWhere : IGpSQLWhere; strict protected function GetDelete: IGpSQLDelete; function GetGroupBy: IGpSQLGroupBy; function GetHaving: IGpSQLHaving; function GetJoins: IGpSQLJoins; function GetOrderBy: IGpSQLOrderBy; function GetSelect: IGpSQLSelect; function GetInsert: IGpSQLInsert; function GetUpdate: IGpSQLUpdate; function GetWhere: IGpSQLWhere; public constructor Create; procedure Clear; function IsEmpty: boolean; property Select: IGpSQLSelect read GetSelect; property Delete: IGpSQLDelete read GetDelete; property Insert: IGpSQLInsert read GetInsert; property Update: IGpSQLUpdate read GetUpdate; property Joins: IGpSQLJoins read GetJoins; property Where: IGpSQLWhere read GetWhere; property GroupBy: IGpSQLGroupBy read GetGroupBy; property Having: IGpSQLHaving read GetHaving; property OrderBy: IGpSQLOrderBy read GetOrderBy; end; { TGpSQLAST } { exports } function CreateSQLAST: IGpSQLAST; begin Result := TGpSQLAST.Create; end; { CreateSQLAST } function CreateSQLExpression: IGpSQLExpression; begin Result := TGpSQLExpression.Create; end; { CreateSQLExpression } function CreateSQLCase: IGpSQLCase; begin Result := TGpSQLCase.Create; end; { CreateSQLCase } { TGpSQLName } procedure TGpSQLName.Clear; begin FName := ''; FAlias := ''; end; { TGpSQLName.Clear } function TGpSQLName.GetAlias: string; begin Result := FAlias; end; { TGpSQLName.GetAlias } function TGpSQLName.GetCase: IGpSQLCase; begin Result := FCase; end; { TGpSQLName.GetCase } function TGpSQLName.GetName: string; begin Result := FName; end; { TGpSQLName.GetName } function TGpSQLName.IsEmpty: boolean; begin Result := (FName = '') and (FAlias = ''); end; { TGpSQLName.IsEmpty } procedure TGpSQLName.SetAlias(const value: string); begin FAlias := value; end; { TGpSQLName.SetAlias } procedure TGpSQLName.SetCase(const value: IGpSQLCase); begin FCase := value; end; { TGpSQLName.SetCase } procedure TGpSQLName.SetName(const value: string); begin FName := value; end; { TGpSQLName.SetName } { TGpSQLNames } constructor TGpSQLNames.Create; begin inherited Create; FColumns := TList<IGpSQLName>.Create; end; { TGpSQLNames.Create } destructor TGpSQLNames.Destroy; begin FreeAndNil(FColumns); inherited; end; { TGpSQLNames.Destroy } function TGpSQLNames.Add: IGpSQLName; begin Result := TGpSQLName.Create; Add(Result); end; { TGpSQLNames.Add } procedure TGpSQLNames.Add(const name: IGpSQLName); begin FColumns.Add(name); end; { TGpSQLNames.Add } procedure TGpSQLNames.Clear; begin FColumns.Clear; end; { TGpSQLNames.Clear } function TGpSQLNames.Count: integer; begin Result := FColumns.Count; end; { TGpSQLNames.Count } function TGpSQLNames.GetColumns(idx: integer): IGpSQLName; begin Result := FColumns[idx]; end; { TGpSQLNames.GetColumns } function TGpSQLNames.IsEmpty: boolean; begin Result := (Count = 0); end; { TGpSQLNames.IsEmpty } { TGpSQLNameValue } procedure TGpSQLNameValue.Clear; begin FName := ''; FValue := ''; end; { TGpSQLNameValue.Clear } function TGpSQLNameValue.GetName: string; begin Result := FName; end; { TGpSQLNameValue.GetName } function TGpSQLNameValue.GetValue: string; begin Result := FValue; end; { TGpSQLNameValue.GetValue } function TGpSQLNameValue.IsEmpty: boolean; begin Result := (FName <> ''); end; { TGpSQLNameValue.IsEmpty } procedure TGpSQLNameValue.SetName(const value: string); begin FName := value; end; { TGpSQLNameValue.SetName } procedure TGpSQLNameValue.SetValue(const value: string); begin FValue := value; end; { TGpSQLNameValue.SetValue } { TGpSQLNameValuePairs } constructor TGpSQLNameValuePairs.Create; begin inherited Create; FList := TList<IGpSQLNameValue>.Create; end; { TGpSQLNameValuePairs.Create } destructor TGpSQLNameValuePairs.Destroy; begin FreeAndNil(FList); inherited; end; { TGpSQLNameValuePairs.Destroy } function TGpSQLNameValuePairs.Add: IGpSQLNameValue; begin Result := TGpSQLNameValue.Create; Add(Result); end; { TGpSQLNameValuePairs.Add } procedure TGpSQLNameValuePairs.Add(const nameValue: IGpSQLNameValue); begin FList.Add(nameValue); end; { TGpSQLNameValuePairs.Add } procedure TGpSQLNameValuePairs.Clear; begin FList.Clear; end; { TGpSQLNameValuePairs.Clear } function TGpSQLNameValuePairs.Count: integer; begin Result := FList.Count; end; { TGpSQLNameValuePairs.Count } function TGpSQLNameValuePairs.GetItem(idx: integer): IGpSQLNameValue; begin Result := FList[idx]; end; { TGpSQLNameValuePairs.GetItem } function TGpSQLNameValuePairs.IsEmpty: boolean; begin Result := (Count = 0); end; { TGpSQLNameValuePairs.IsEmpty } { TGpSQLExpression } procedure TGpSQLExpression.Assign(const node: IGpSQLExpression); begin FLeft := node.Left; FRight := node.Right; FTerm := node.Term; FOperation := node.Operation; end; { TGpSQLExpression.Assign } procedure TGpSQLExpression.Clear; begin FOperation := opNone; FTerm := ''; FLeft := nil; FRight := nil; end; { TGpSQLExpression.Clear } function TGpSQLExpression.GetLeft: IGpSQLExpression; begin Result := FLeft; end; { TGpSQLExpression.GetLeft } function TGpSQLExpression.GetOperation: TGpSQLExpressionOperation; begin Result := FOperation; end; { TGpSQLExpression.GetOperation } function TGpSQLExpression.GetRight: IGpSQLExpression; begin Result := FRight; end; { TGpSQLExpression.GetRight } function TGpSQLExpression.GetTerm: string; begin Result := FTerm; end; { TGpSQLExpression.GetTerm } function TGpSQLExpression.IsEmpty: boolean; begin Result := (FOperation = opNone) and (FTerm = ''); end; { TGpSQLExpression.IsEmpty } procedure TGpSQLExpression.SetLeft(const value: IGpSQLExpression); begin FLeft := value; end; { TGpSQLExpression.SetLeft } procedure TGpSQLExpression.SetOperation(const value: TGpSQLExpressionOperation); begin FOperation := value; end; { TGpSQLExpression.SetOperation } procedure TGpSQLExpression.SetRight(const value: IGpSQLExpression); begin FRight := value; end; { TGpSQLExpression.SetRight } procedure TGpSQLExpression.SetTerm(const value: string); begin FTerm := value; end; { TGpSQLExpression.SetTerm } { TGpSQLCaseWhenThen } constructor TGpSQLCaseWhenThen.Create; begin inherited Create; FWhenExpression := TGpSQLExpression.Create; FThenExpression := TGpSQLExpression.Create; end; { TGpSQLCaseWhenThen.Create } function TGpSQLCaseWhenThen.GetThenExpression: IGpSQLExpression; begin Result := FThenExpression; end; { TGpSQLCaseWhenThen.GetThenExpression } function TGpSQLCaseWhenThen.GetWhenExpression: IGpSQLExpression; begin Result := FWhenExpression; end; { TGpSQLCaseWhenThen.GetWhenExpression } procedure TGpSQLCaseWhenThen.SetThenExpression(const value: IGpSQLExpression); begin FThenExpression := value; end; { TGpSQLCaseWhenThen.SetThenExpression } procedure TGpSQLCaseWhenThen.SetWhenExpression(const value: IGpSQLExpression); begin FWhenExpression := value; end; { TGpSQLCaseWhenThen.SetWhenExpression } { TGpSQLCaseWhenList } constructor TGpSQLCaseWhenList.Create; begin inherited Create; FWhenThenList := TList<IGpSQLCaseWhenThen>.Create; end; { TGpSQLCaseWhenList.Create } destructor TGpSQLCaseWhenList.Destroy; begin FreeAndNil(FWhenThenList); inherited Destroy; end; { TGpSQLCaseWhenList.Destroy } function TGpSQLCaseWhenList.Add: IGpSQLCaseWhenThen; begin Result := TGpSQLCaseWhenThen.Create; Add(Result); end; { TGpSQLCaseWhenList.Add } function TGpSQLCaseWhenList.Add(const whenThen: IGpSQLCaseWhenThen): integer; begin Result := FWhenThenList.Add(whenThen); end; { TGpSQLCaseWhenList.Add } function TGpSQLCaseWhenList.Count: integer; begin Result := FWhenThenList.Count; end; { TGpSQLCaseWhenList.Count } function TGpSQLCaseWhenList.GetWhenThen(idx: integer): IGpSQLCaseWhenThen; begin Result := FWhenThenList[idx]; end; { TGpSQLCaseWhenList.GetWhenThen } procedure TGpSQLCaseWhenList.SetWhenThen(idx: integer; const value: IGpSQLCaseWhenThen); begin FWhenThenList[idx] := value; end; { TGpSQLCaseWhenList.SetWhenThen } { TGpSQLCase } constructor TGpSQLCase.Create; begin inherited Create; FCaseExpression := TGpSQLExpression.Create; FElseExpression := TGpSQLExpression.Create; FWhenList := TGpSQLCaseWhenList.Create; end; { TGpSQLCase.Create } function TGpSQLCase.GetCaseExpression: IGpSQLExpression; begin Result := FCaseExpression; end; { TGpSQLCase.GetCaseExpression } function TGpSQLCase.GetElseExpression: IGpSQLExpression; begin Result := FElseExpression; end; { TGpSQLCase.GetElseExpression } function TGpSQLCase.GetWhenList: IGpSQLCaseWhenList; begin Result := FWhenList; end; { TGpSQLCase.GetWhenList } procedure TGpSQLCase.SetCaseExpression(const value: IGpSQLExpression); begin FCaseExpression := value; end; { TGpSQLCase.SetCaseExpression } procedure TGpSQLCase.SetElseExpression(const value: IGpSQLExpression); begin FElseExpression := value; end; { TGpSQLCase.SetElseExpression } procedure TGpSQLCase.SetWhenList(const value: IGpSQLCaseWhenList); begin FWhenList := value; end; { TGpSQLCase.SetWhenList } { TGpSQLSection } constructor TGpSQLSection.Create(sectionName: string); begin inherited Create; FName := sectionName; end; { TGpSQLSection.Create } function TGpSQLSection.GetName: string; begin Result := FName; end; { TGpSQLSection.GetName } { TGpSQLSelectQualifier } function TGpSQLSelectQualifier.GetQualifier: TGpSQLSelectQualifierType; begin Result := FQualifier; end; { TGpSQLSelectQualifier.GetQualifier } function TGpSQLSelectQualifier.GetValue: integer; begin Result := FValue; end; { TGpSQLSelectQualifier.GetValue } procedure TGpSQLSelectQualifier.SetQualifier(const value: TGpSQLSelectQualifierType); begin FQualifier := value; end; { TGpSQLSelectQualifier.SetQualifier } procedure TGpSQLSelectQualifier.SetValue(const value: integer); begin FValue := value; end; { TGpSQLSelectQualifier.SetValue } { TGpSQLSelectQualifiers } constructor TGpSQLSelectQualifiers.Create; begin inherited Create; FQualifiers := TList<IGpSQLSelectQualifier>.Create; end; { TGpSQLSelectQualifiers.Create } destructor TGpSQLSelectQualifiers.Destroy; begin FreeAndNil(FQualifiers); inherited; end; { TGpSQLSelectQualifiers.Destroy } function TGpSQLSelectQualifiers.Add: IGpSQLSelectQualifier; begin Result := TGpSQLSelectQualifier.Create; Add(Result); end; { TGpSQLSelectQualifiers.Add } procedure TGpSQLSelectQualifiers.Add(qualifier: IGpSQLSelectQualifier); begin FQualifiers.Add(qualifier); end; { TGpSQLSelectQualifiers.Add } procedure TGpSQLSelectQualifiers.Clear; begin FQualifiers.Clear; end; { TGpSQLSelectQualifiers.Clear } function TGpSQLSelectQualifiers.Count: integer; begin Result := FQualifiers.Count; end; { TGpSQLSelectQualifiers.Count } function TGpSQLSelectQualifiers.GetQualifier(idx: integer): IGpSQLSelectQualifier; begin Result := FQualifiers[idx]; end; { TGpSQLSelectQualifiers.GetQualifier } function TGpSQLSelectQualifiers.IsEmpty: boolean; begin Result := (Count = 0); end; { TGpSQLSelectQualifiers.IsEmpty } { TGpSQLSelect } constructor TGpSQLSelect.Create; begin inherited Create('Select'); FColumns := TGpSQLNames.Create; FQualifiers := TGpSQLSelectQualifiers.Create; FTableNames := TGpSQLNames.Create; end; { TGpSQLSelect.Create } procedure TGpSQLSelect.Clear; begin Columns.Clear; TableNames.Clear; end; { TGpSQLSelect.Clear } function TGpSQLSelect.GetColumns: IGpSQLNames; begin Result := FColumns; end; { TGpSQLSelect.GetColumns } function TGpSQLSelect.GetQualifiers: IGpSQLSelectQualifiers; begin Result := FQualifiers; end; { TGpSQLSelect.GetQualifiers } function TGpSQLSelect.GetTableNames: IGpSQLNames; begin Result := FTableNames; end; { TGpSQLSelect.GetTableNames } function TGpSQLSelect.IsEmpty: boolean; begin Result := Columns.IsEmpty and TableNames.IsEmpty; end; { TGpSQLSelect.IsEmpty } { TGpSQLDelete } constructor TGpSQLDelete.Create; begin inherited Create('Delete'); FTableNames := TGpSQLNames.Create; end; { TGpSQLDelete.Create } procedure TGpSQLDelete.Clear; begin TableNames.Clear; end; { TGpSQLDelete.Clear } function TGpSQLDelete.GetTableNames: IGpSQLNames; begin Result := FTableNames; end; { TGpSQLDelete.GetTableNames } function TGpSQLDelete.IsEmpty: boolean; begin Result := TableNames.IsEmpty; end; { TGpSQLDelete.IsEmpty } { TGpSQLInsert } constructor TGpSQLInsert.Create; begin inherited Create('Insert'); FColumns := TGpSQLNames.Create; FValues := TGpSQLNameValuePairs.Create; end; { TGpSQLInsert.Create } procedure TGpSQLInsert.Clear; begin TableName := ''; end; { TGpSQLInsert.Clear } function TGpSQLInsert.GetColumns: IGpSQLNames; begin Result := FColumns; end; { TGpSQLInsert.GetColumns } function TGpSQLInsert.GetTableName: string; begin Result := FTableName; end; { TGpSQLInsert.GetTableName } function TGpSQLInsert.GetValues: IGpSQLNameValuePairs; begin Result := FValues; end; { TGpSQLInsert.GetValues } function TGpSQLInsert.IsEmpty: boolean; begin Result := (TableName = ''); end; { TGpSQLInsert.IsEmpty } procedure TGpSQLInsert.SetTableName(const value: string); begin FTableName := value; end; { TGpSQLInsert.SetTableName } { TGpSQLUpdate } constructor TGpSQLUpdate.Create; begin inherited Create('Update'); FValues := TGpSQLNameValuePairs.Create; end; { TGpSQLUpdate.Create } procedure TGpSQLUpdate.Clear; begin TableName := ''; end; { TGpSQLUpdate.Clear } function TGpSQLUpdate.GetTableName: string; begin Result := FTableName; end; { TGpSQLUpdate.GetTableName } function TGpSQLUpdate.GetValues: IGpSQLNameValuePairs; begin Result := FValues; end; { TGpSQLUpdate.GetValues } function TGpSQLUpdate.IsEmpty: boolean; begin Result := (TableName = ''); end; { TGpSQLUpdate.IsEmpty } procedure TGpSQLUpdate.SetTableName(const value: string); begin FTableName := value; end; { TGpSQLUpdate.SetTableName } { TGpSQLJoin } procedure TGpSQLJoin.Clear; begin Condition.Clear; JoinedTable.Clear; end; { TGpSQLJoin.Clear } constructor TGpSQLJoin.Create; begin inherited Create('Join'); FJoinedTable := TGpSQLName.Create; FCondition := TGpSQLExpression.Create; end; { TGpSQLJoin.Create } function TGpSQLJoin.GetCondition: IGpSQLExpression; begin Result := FCondition; end; { TGpSQLJoin.GetCondition } function TGpSQLJoin.GetJoinedTable: IGpSQLName; begin Result := FJoinedTable; end; { TGpSQLJoin.GetJoinedTable } function TGpSQLJoin.GetJoinType: TGpSQLJoinType; begin Result := FJoinType; end; { TGpSQLJoin.GetJoinType } function TGpSQLJoin.IsEmpty: boolean; begin Result := Condition.IsEmpty and JoinedTable.IsEmpty; end; { TGpSQLJoin.IsEmpty } procedure TGpSQLJoin.SetCondition(const value: IGpSQLExpression); begin FCondition := value; end; { TGpSQLJoin.SetCondition } procedure TGpSQLJoin.SetJoinedTable(const value: IGpSQLName); begin FJoinedTable := value; end; { TGpSQLJoin.SetJoinedTable } procedure TGpSQLJoin.SetJoinType(const value: TGpSQLJoinType); begin FJoinType := value; end; { TGpSQLJoin.SetJoinType } { TGpSQLJoins } procedure TGpSQLJoins.Clear; begin FJoins.Clear; end; { TGpSQLJoins.Clear } constructor TGpSQLJoins.Create; begin inherited Create; FJoins := TList<IGpSQLJoin>.Create; end; { TGpSQLJoins.Create } destructor TGpSQLJoins.Destroy; begin FreeAndNil(FJoins); inherited; end; { TGpSQLJoins.Destroy } function TGpSQLJoins.IsEmpty: boolean; begin Result := (FJoins.Count = 0); end; { TGpSQLJoins.IsEmpty } procedure TGpSQLJoins.Add(const join: IGpSQLJoin); begin FJoins.Add(join); end; { TGpSQLJoins.Add } function TGpSQLJoins.Add: IGpSQLJoin; begin Result := TGpSQLJoin.Create; Add(Result); end; { TGpSQLJoins.Add } function TGpSQLJoins.Count: integer; begin Result := FJoins.Count; end; { TGpSQLJoins.Count } function TGpSQLJoins.GetJoins(idx: integer): IGpSQLJoin; begin Result := FJoins[idx]; end; { TGpSQLJoins.GetJoins } procedure TGpSQLJoins.SetJoins(idx: integer; const value: IGpSQLJoin); begin FJoins[idx] := value; end; { TGpSQLJoins.SetJoins } { TGpSQLWhere } procedure TGpSQLWhere.Clear; begin Expression.Clear; end; { TGpSQLWhere.Clear } constructor TGpSQLWhere.Create; begin inherited Create('Where'); FExpression := TGpSQLExpression.Create; end; { TGpSQLWhere.Create } function TGpSQLWhere.GetExpression: IGpSQLExpression; begin Result := FExpression; end; { TGpSQLWhere.GetExpression } function TGpSQLWhere.IsEmpty: boolean; begin Result := Expression.IsEmpty; end; { TGpSQLWhere.IsEmpty } procedure TGpSQLWhere.SetExpression(const value: IGpSQLExpression); begin FExpression := value; end; { TGpSQLWhere.SetExpression } { TGpSQLGroupBy } procedure TGpSQLGroupBy.Clear; begin Columns.Clear; end; { TGpSQLGroupBy.Clear } constructor TGpSQLGroupBy.Create; begin inherited Create('GroupBy'); FColumns := TGpSQLNames .Create; end; { TGpSQLGroupBy.Create } function TGpSQLGroupBy.GetColumns: IGpSQLNames; begin Result := FColumns; end; { TGpSQLGroupBy.GetColumns } function TGpSQLGroupBy.IsEmpty: boolean; begin Result := Columns.Isempty; end; { TGpSQLGroupBy.IsEmpty } { TGpSQLHaving } procedure TGpSQLHaving.Clear; begin Expression.Clear; end; { TGpSQLHaving.Clear } constructor TGpSQLHaving.Create; begin inherited Create('Having'); FExpression := TGpSQLExpression.Create; end; { TGpSQLHaving.Create } function TGpSQLHaving.GetExpression: IGpSQLExpression; begin Result := FExpression; end; { TGpSQLHaving.GetExpression } function TGpSQLHaving.IsEmpty: boolean; begin Result := Expression.IsEmpty; end; { TGpSQLHaving.IsEmpty } { TGpSQLHaving } procedure TGpSQLHaving.SetExpression(const value: IGpSQLExpression); begin FExpression := value; end; { TGpSQLHaving.SetExpression } { TGpSQLOrderByColumn } function TGpSQLOrderByColumn.GetDirection: TGpSQLOrderByDirection; begin Result := FDirection; end; { TGpSQLOrderByColumn.GetDirection } procedure TGpSQLOrderByColumn.SetDirection(const value: TGpSQLOrderByDirection); begin FDirection := value; end; { TGpSQLOrderByColumn.SetDirection } { TGpSQLOrderByColumns } function TGpSQLOrderByColumns.Add: IGpSQLName; begin Result := TGpSQLOrderByColumn.Create; Add(Result); end; { TGpSQLOrderByColumns.Add } { TGpSQLOrderBy } constructor TGpSQLOrderBy.Create; begin inherited Create('OrderBy'); FColumns := TGpSQLOrderByColumns.Create; end; { TGpSQLOrderBy.Create } procedure TGpSQLOrderBy.Clear; begin Columns.Clear; end; { TGpSQLOrderBy.Clear } function TGpSQLOrderBy.GetColumns: IGpSQLNames; begin Result := FColumns; end; { TGpSQLOrderBy.GetColumns } function TGpSQLOrderBy.IsEmpty: boolean; begin Result := Columns.IsEmpty; end; { TGpSQLOrderBy.IsEmpty } { TGpSQLAST } procedure TGpSQLAST.Clear; begin Select.Clear; Joins.Clear; Where.Clear; GroupBy.Clear; Having.Clear; OrderBy.Clear; end; { TGpSQLAST.Clear } constructor TGpSQLAST.Create; begin inherited; FSelect := TGpSQLSelect.Create; FDelete := TGpSQLDelete.Create; FInsert := TGpSQLInsert.Create; FUpdate := TGpSQLUpdate.Create; FJoins := TGpSQLJoins.Create; FWhere := TGpSQLWhere.Create; FGroupBy := TGpSQLGroupBy.Create; FHaving := TGpSQLHaving.Create; FOrderBy := TGpSQLOrderBy.Create; end; { TGpSQLAST.Create } function TGpSQLAST.GetDelete: IGpSQLDelete; begin Result := FDelete; end; { TGpSQLAST.GetDelete } function TGpSQLAST.GetGroupBy: IGpSQLGroupBy; begin Result := FGroupBy; end; { TGpSQLAST.GetGroupBy } function TGpSQLAST.GetHaving: IGpSQLHaving; begin Result := FHaving; end; { TGpSQLAST.GetHaving } function TGpSQLAST.GetJoins: IGpSQLJoins; begin Result := FJoins; end; { TGpSQLAST.GetJoins } function TGpSQLAST.GetOrderBy: IGpSQLOrderBy; begin Result := FOrderBy; end; { TGpSQLAST.GetOrderBy } function TGpSQLAST.GetSelect: IGpSQLSelect; begin Result := FSelect; end; { TGpSQLAST.GetSelect } function TGpSQLAST.GetInsert: IGpSQLInsert; begin Result := FInsert; end; { TGpSQLAST.GetInsert } function TGpSQLAST.GetUpdate: IGpSQLUpdate; begin Result := FUpdate; end; { TGpSQLAST.GetUpdate } function TGpSQLAST.GetWhere: IGpSQLWhere; begin Result := FWhere; end; { TGpSQLAST.GetWhere } function TGpSQLAST.IsEmpty: boolean; begin Result := Select.IsEmpty and Joins.IsEmpty and Where.IsEmpty and GroupBy.IsEmpty and Having.IsEmpty and OrderBy.IsEmpty; end; { TGpSQLAST.IsEmpty } end.
unit DAO.InventarioProdutosVA; interface uses DAO.Base, Model.InventarioProdutosVA, Generics.Collections, System.Classes; type TInventarioProdutosVADAO = class(TDAO) public function Insert(aInventarios: TInventarioProdutosVA): Boolean; function Update(aInventarios: TInventarioProdutosVA): Boolean; function Delete(iID: Integer): Boolean; function FindByID(iID: Integer): TObjectList<TInventarioProdutosVA>; function FindByInventario(iProduto: Integer; dtData: TDate; iBanca: Integer): TObjectList<TInventarioProdutosVA>; function FindByData(dtData: TDate): TObjectList<TInventarioProdutosVA>; end; const TABLENAME = 'va_inventarioProdutos'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TInventarioProdutosVADAO.Insert(aInventarios: TInventarioProdutosVA): Boolean; var sSQL: String; begin Result := False; aInventarios.ID := GetKeyValue(TABLENAME,'ID_INVENTARIO'); sSQL := 'INSERT INTO ' + TABLENAME + ' (' + 'ID_INVENTARIO, ID_PRODUTO, DAT_INVENTARIO, QTD_PRODUTO, DES_LOG) ' + 'VALUE (' + ':pID_INVENTARIO, :pID_PRODUTO, :pDAT_INVENTARIO, :pQTD_PRODUTO, :pDES_LOG); '; Connection.ExecSQL(sSQL, [aInventarios.ID, aInventarios.Produto, aInventarios.Data, aInventarios.Qtde, aInventarios.Log], [ftInteger, ftInteger, ftInteger, ftDate, ftFloat, ftString]); Result := True; end; function TInventarioProdutosVADAO.Update(aInventarios: TInventarioProdutosVA): Boolean; var sSQL: String; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' SET ' + 'ID_PRODUTO = :pID_PRODUTO, DAT_INVENTARIO = :pDAT_INVENTARIO, ' + 'QTD_PRODUTO = :pQTD_PRODUTO, DES_LOG = :pDES_LOG ' + 'WHERE ID_INVENTARIO = :pID_INVENTARIO;'; Connection.ExecSQL(sSQL, [aInventarios.Produto, aInventarios.Data, aInventarios.Qtde, aInventarios.Log, aInventarios.ID], [ftInteger, ftInteger, ftDate, ftFloat, ftString, ftInteger]); Result := True; end; function TInventarioProdutosVADAO.Delete(iID: Integer): Boolean; var sSQL: String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE ID_INVENTARIO = :pID_INVENTARIO;'; Connection.ExecSQL(sSQL,[iID],[ftInteger]); Result := True; end; function TInventarioProdutosVADAO.FindByID(iID: Integer): TObjectList<TInventarioProdutosVA>; var FDQuery: TFDQuery; inventarios: TObjectList<TInventarioProdutosVA>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE ID_INVENTARIO = :pID_INVENTARIO'); FDQuery.ParamByName('pID_INVENTARIO').AsInteger := iID; FDQuery.Open(); inventarios := TObjectList<TInventarioProdutosVA>.Create(); while not FDQuery.Eof do begin inventarios.Add(TInventarioProdutosVA.Create(FDQuery.FieldByName('ID_INVENTARIO').AsInteger, FDQuery.FieldByName('ID_PRODUTO').AsInteger, FDQuery.FieldByName('DAT_INVENTARIO').AsDateTime, FDQuery.FieldByName('QTD_PRODUTO').AsFloat, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := inventarios; end; function TInventarioProdutosVADAO.FindByInventario(iProduto: Integer; dtData: TDate; iBanca: Integer): TObjectList<TInventarioProdutosVA>; var FDQuery: TFDQuery; inventarios: TObjectList<TInventarioProdutosVA>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE ID_PRODUTO = :pID_PRODUTO AND DAT_INVENTARIO = :pDAT_INVENTARIO AND COD_BANCA = :pCOD_BANCA'); FDQuery.ParamByName('pID_PRODUTO').AsInteger := iProduto; FDQuery.ParamByName('pDAT_INVENTARIO').AsDate := dtData; FDQuery.ParamByName('pCOD_BANCA').AsInteger := iBanca; FDQuery.Open(); inventarios := TObjectList<TInventarioProdutosVA>.Create(); while not FDQuery.Eof do begin inventarios.Add(TInventarioProdutosVA.Create(FDQuery.FieldByName('ID_INVENTARIO').AsInteger, FDQuery.FieldByName('ID_PRODUTO').AsInteger, FDQuery.FieldByName('DAT_INVENTARIO').AsDateTime, FDQuery.FieldByName('QTD_PRODUTO').AsFloat, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := inventarios; end; function TInventarioProdutosVADAO.FindByData(dtData: TDate): TObjectList<TInventarioProdutosVA>; var FDQuery: TFDQuery; inventarios: TObjectList<TInventarioProdutosVA>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE DAT_INVENTARIO = :pDAT_INVENTARIO'); FDQuery.ParamByName('pDAT_INVENTARIO').AsDate := dtData; FDQuery.Open(); inventarios := TObjectList<TInventarioProdutosVA>.Create(); while not FDQuery.Eof do begin inventarios.Add(TInventarioProdutosVA.Create(FDQuery.FieldByName('ID_INVENTARIO').AsInteger, FDQuery.FieldByName('ID_PRODUTO').AsInteger, FDQuery.FieldByName('DAT_INVENTARIO').AsDateTime, FDQuery.FieldByName('QTD_PRODUTO').AsFloat, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := inventarios; end; end.
unit untfieldarraylist; {$mode objfpc}{$H+} interface uses Classes, SysUtils, untField; type { TArrayList } { TFieldArrayList } TFieldArrayList = class Items: array of Field; nLength:word; constructor Create; destructor Destroy; override; procedure Add(Value: Field); function Count: integer; function GetItems(Index: integer): Field; end; implementation constructor TFieldArrayList.Create; begin SetLength(Items, 0); end; destructor TFieldArrayList.Destroy; begin SetLength(Items, 0); inherited Destroy; end; procedure TFieldArrayList.Add(Value: Field); begin SetLength(Items, Length(Items) + 1); Items[Length(Items) - 1] := Value; end; function TFieldArrayList.Count: integer; begin Result := Length(Items); end; function TFieldArrayList.GetItems(Index: integer): Field; begin Result := Items[Index]; end; end.
unit UFrmProgressBar; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls; type TFrmProgressBar = class(TForm) TimerProgress: TTimer; // JvGradProgressBar: TJvGradientProgressBar; LblCaption: TLabel; procedure TimerProgressTimer(Sender: TObject); procedure Start; procedure Stop; private { Private declarations } public { Public declarations } end; var FrmProgressBar: TFrmProgressBar; implementation {$R *.dfm} procedure TFrmProgressBar.Start; begin TimerProgress.Enabled := true; Show; end; procedure TFrmProgressBar.Stop; begin TimerProgress.Enabled := false; close; end; procedure TFrmProgressBar.TimerProgressTimer(Sender: TObject); begin { if JvGradProgressBar.Position = 100 then begin JvGradProgressBar.Position := 0; if JvGradProgressBar.Inverted = false then begin JvGradProgressBar.Inverted := true; JvGradProgressBar.BarColorFrom := clLime; JvGradProgressBar.BarColorTo := clGreen; end else begin JvGradProgressBar.Inverted := false; JvGradProgressBar.BarColorFrom := clGreen; JvGradProgressBar.BarColorTo := clLime; end; end; JvGradProgressBar.Position := JvGradProgressBar.Position + 2; } end; end.
unit EncParam; {$MINENUMSIZE 4} interface uses Windows, CodecDefine; type // 视频参数 VideoParam = record dwFourCC : DWORD; // 视频编码器 FourCC : '1VMW'/'2VMW'/'3VMW' /'DIVX'/'462H' nWidth : Integer; // 分辨率宽度 nHeight : Integer; // 分辨率高度 dFrameRate : double; // 帧率 0表示自动选择 nBitrate : Integer; // 码率 bps (恒定码率、可变最小码率) bIsVBR : BOOL; // 是否使用变码率 nMaxBitrate : Integer; // 最大码率 nResizeStyle : IMAGE_RESIZE_METHOD; // 图像缩放方式 nInterpolation : IMAGE_INTERPOLATION; // 图像插值算法 dwCompression : DWORD; // 图像格式 nBitsDepth : Integer; // 图像位深度 //=============== MPEG 编码器参数 ===========================// // 使用Mpeg编码请参考 mpeg_param.pas // dwFormat : DWORD; // 编码格式 // dwNorm : DWORD; // 电视制式 // dwAspect : DWORD; // 比例 // bFieldEnc : BOOL; // 是否使用交错模式 // //=============== MPEG 编码器参数 ===========================// end; // 音频参数 AudioParam = record dwFourCC : DWORD; // 音频编码器 FourCC : '1AMW'/'2AMW'/'3AMW' /' 3PM' nSampleRate : Integer; // 采样率 Hz nChannels : Integer; // 声道数量 nBitrate : Integer; // 码率 bps (恒定码率、可变最小码率) bIsVBR : BOOL; // 是否使用变码率 nMaxBitrate : Integer; // 最大码率 nBitsPerSample : Integer; // Number of bits per sample of mono data end; // 编码参数 EncodeParam = record video : VideoParam; // 视频参数 audio : AudioParam; // 音频参数 bVideoDisable : BOOL; // 禁用视频 bAudioDisable : BOOL; // 禁用音频 // case Integer of // 0: (format : EncoderFormat); // 文件格式 // 1: (dwFourCC: DWORD); //视频编码器 dwFourCC: DWORD; // 文件格式FourCC:' 4PM' end; EncoderInfo = record dwFourCC : DWORD; szEncName : array [0..63] of widechar; szDescription : array [0..127] of widechar; end; type PENCODERINFO = ^EncoderInfo; PPENCODERINFO = ^PENCODERINFO; FileFormatInfo = record dwFourCC : DWORD; szExtName : array [0..9] of widechar; szFormatName : array [0..63] of widechar; szDescription : array [0..127] of widechar; nAudioEncs : Integer; nVideoEncs : Integer; ppAudioEncInfos : PPENCODERINFO; ppVideoEncInfos : PPENCODERINFO; end; type PFILEFORMATINFO = ^FileFormatInfo; type PENCODEPARAM = ^EncodeParam; // 编码时的预览使用回调函数 //typedef BOOL (__stdcall * ENCODE_CALLBACK)(void* pUserObj, UINT uMsg, WPARAM wParam, LPARAM lParam); // uMsg - 0 进度消息 wParam - 进度(0-100) lParam - ProgressInfo* // 1 转换完成 wParam - 0 正常完成 1 用户终止 2 外部回掉终止 3 遭遇错误 // 100 第二次进度开始 // 101 进度消息 wParam - 进度(0-100) lParam - 0 // 110 第二次进度结束 在第二次进度期间 不能调用WEPause和WEStop函数 // 返回FALSE 则停止转换 type ENCODE_CALLBACK = function(pUserObj: Pointer; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): BOOL; stdcall; implementation end.
unit uSaveUnitForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox, FMX.TabControl; type TSaveUnitForm = class(TForm) Panel1: TPanel; btnClose: TButton; btnSave: TButton; sd: TSaveDialog; Label1: TLabel; StyleBook1: TStyleBook; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; MemoDelphiDTO: TMemo; MemoJsonDTO: TMemo; procedure btnCloseClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure Memo1KeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; procedure GetJSONDTO(Buffer : TStrings); var SaveUnitForm: TSaveUnitForm; implementation {$R *.fmx} uses uMainForm, System.IoUtils; procedure GetJSONDTO(Buffer : TStrings); var ResourceStream: TResourceStream; begin ResourceStream := TResourceStream.Create(HInstance, 'JsonDTO', 'PAS'); try ResourceStream.Position := 0; Buffer.LoadFromStream(ResourceStream); finally ResourceStream.Free; end; end; procedure TSaveUnitForm.btnCloseClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TSaveUnitForm.btnSaveClick(Sender: TObject); var Buffer: TStringList; begin if not sd.Execute then exit; MemoDelphiDTO.Lines.SaveToFile(sd.FileName); Buffer := TStringList.Create; try GetJSONDTO(Buffer); Buffer.SaveToFile(TPath.GetDirectoryName(sd.FileName) + TPath.DirectorySeparatorChar + 'Pkg.Json.DTO.pas'); finally Buffer.Free; end; end; procedure TSaveUnitForm.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = 27 then ModalResult := mrCancel; end; procedure TSaveUnitForm.FormShow(Sender: TObject); begin SaveUnitForm.width := MainForm.width - 50; SaveUnitForm.height := MainForm.height - 50; SaveUnitForm.left := MainForm.left + 25; SaveUnitForm.top := MainForm.top + 25; end; procedure TSaveUnitForm.Memo1KeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = 27 then ModalResult := mrCancel; end; end.
{*******************************************************} { } { NTS Aero UI Library } { Created by GooD-NTS ( good.nts@gmail.com ) } { http://ntscorp.ru/ Copyright(c) 2011 } { License: Mozilla Public License 1.1 } { } {*******************************************************} unit UI.Aero.Footer; interface {$I '../../Common/CompilerVersion.Inc'} uses {$IFDEF HAS_UNITSCOPE} System.SysUtils, System.Classes, Winapi.Windows, Winapi.Messages, Winapi.UxTheme, Winapi.GDIPOBJ, Vcl.Graphics, Vcl.Controls, {$ELSE} SysUtils, Windows, Messages, Classes, Controls, Graphics, UxTheme, Winapi.GDIPOBJ, {$ENDIF} UI.Aero.Globals, UI.Aero.Core, UI.Aero.ThemeElement; type TAeroFooter = class(TAeroThemeElement) Private function UseWhiteColor: Boolean; Protected procedure ClassicRender(const ACanvas: TCanvas); OverRide; procedure ThemedRender(const PaintDC: hDC; const Surface: TGPGraphics; var RConfig: TRenderConfig); OverRide; Public Constructor Create(AOwner: TComponent); OverRide; Published property PartID Default 4; property StateID Default 1; property Height Default 41; property Align Default alBottom; property DesigningRect Default False; end; implementation uses {$IFDEF HAS_UNITSCOPE} Vcl.Forms; {$ELSE} Forms; {$ENDIF} { TAeroFooter } constructor TAeroFooter.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle:= ControlStyle+[csAcceptsControls]; ThemeClassName:= 'AeroWizard'; PartID:= 4; StateID:= 1; Height:= 41; Align:= alBottom; DesigningRect:= False; end; function TAeroFooter.UseWhiteColor: Boolean; begin Result:= False; if Parent is TForm then Result:= (TForm(Parent).Color = clBtnFace); end; procedure TAeroFooter.ClassicRender(const ACanvas: TCanvas); begin if UseWhiteColor then ACanvas.Brush.Color:= clWhite else ACanvas.Brush.Color:= clBtnFace; ACanvas.FillRect(ClientRect); ACanvas.Pen.Color:= clBtnShadow; ACanvas.MoveTo(0,0); ACanvas.LineTo(Width,0); inherited ClassicRender(ACanvas); end; procedure TAeroFooter.ThemedRender(const PaintDC: hDC; const Surface: TGPGraphics; var RConfig: TRenderConfig); var clRect: TRect; PaintSurface: TCanvas; begin clRect:= GetClientRect; if ThemeData <> 0 then DrawThemeBackground(ThemeData,PaintDC,PartID,StateID,clRect,@clRect) else begin PaintSurface:= TCanvas.Create; PaintSurface.Handle:= PaintDC; ClassicRender(PaintSurface); PaintSurface.Handle:= 0; PaintSurface.Free; end; end; end.
unit GenSourceObject; interface uses Classes, Types, Generics.Collections, GenesisConsts, SiAuto, SmartInspect; type TGenSourceObject = class(TObject) private FElements: TObjectList<TGenSourceObject>; FIdentifier: string; FParent: TGenSourceObject; FEnabled: Boolean; FAccessLevel: TAccessLevel; public constructor Create(); destructor Destroy(); override; function GetLiteCSource(): string; virtual; function GetElement(AIdentifier: string; AType: TClass): TGenSourceObject; procedure AddElement(AOject: TGenSourceObject); procedure AddElementAtTop(AObject: TGenSourceObject); property Identifier: string read FIdentifier write FIdentifier; property Parent: TGenSourceObject read FParent write FParent; property Elements: TObjectList<TGenSourceObject> read FElements; property Enabled: Boolean read FEnabled write FEnabled; property AccessLevel: TAccessLevel read FAccessLevel write FAccessLevel; end; TGenIdentifier = class(TGenSourceObject) public function GetLiteCSource(): string; override; end; TGenType = class(TGenIdentifier) private FPostChars: string; published function GetLiteCSource(): string; override; property PostChars: string read FPostChars write FPostChars; end; TGenInclude = class(TGenSourceObject) public function GetLiteCSource(): string; override; end; TGenSourceSnippet = class(TGenSourceObject) private FSource: string; public function GetLiteCSource(): string; override; property Source: string read FSource write FSource; end; TGenVarDeclaration = class(TGenSourceObject) private FGenType: TGenType; FNoDelimiter: Boolean; public constructor Create(); reintroduce; destructor Destroy(); override; function GetLiteCSource(): string; override; property GenType: TGenType read FGenType; property NoDelimiter: Boolean read FNoDelimiter write FNoDelimiter; end; TGenMethodDummyDeclaration = class(TGenVarDeclaration) private FIsAbstract: Boolean; FDoOverride: Boolean; FIsOverriding: Boolean; FIsVirtual: Boolean; FNeedsPrefix: Boolean; FNeedsThis: Boolean; FOverridingParentIdentifier: string; public function GetLiteCSource(): string; override; procedure AddVarDec(AIdentifier, AType, APostChars: string); property IsOverriding: Boolean read FIsOverriding write FIsOverriding; property DoOverride: Boolean read FDoOverride write FDoOverride; property IsVirtual: Boolean read FIsVirtual write FIsVirtual; property IsAbstract: Boolean read FIsAbstract write FIsAbstract; property NeedsThis: Boolean read FNeedsThis write FNeedsThis; property NeedsPrefix: Boolean read FNeedsPrefix write FNeedsPrefix; property OverridingParentIdentifier: string read FOverridingParentIdentifier write FOverridingParentIdentifier; end; TGenMethodDeclaration = class(TGenMethodDummyDeclaration) private FSource: string; FLiteCLineStart: Integer; FGenesisLineStart: Integer; FLiteCLineEnd: Integer; FGenesisLineEnd: Integer; public function GetLiteCSource(): string; override; property Source: string read FSource write FSource; property GenesisLineStart: Integer read FGenesisLineStart write FGenesisLineStart; property GenesisLineEnd: Integer read FGenesisLineEnd write FGenesisLineEnd; property LiteCLineStart: Integer read FLiteCLineStart write FLiteCLineStart; property LiteCLineEnd: Integer read FLiteCLineEnd write FLiteCLineEnd; end; TGenStructDeclaration = class(TGenSourceObject) public function GetLiteCSource(): string; override; end; TGenEnumDeclaration = class(TGenSourceObject) public function GetLiteCSource(): string; override; end; implementation uses SysUtils, GenesisClass; { TGenSourceObject } procedure TGenSourceObject.AddElement(AOject: TGenSourceObject); begin FElements.Add(AOject); end; procedure TGenSourceObject.AddElementAtTop(AObject: TGenSourceObject); begin FElements.Insert(0, AObject); end; constructor TGenSourceObject.Create; begin FElements := TObjectList<TGenSourceObject>.Create(); FEnabled := True; FAccessLevel := alPublic; end; destructor TGenSourceObject.Destroy; begin FElements.Free; inherited; end; function TGenSourceObject.GetElement(AIdentifier: string; AType: TClass): TGenSourceObject; var LElement: TGenSourceObject; begin Result := nil; for LElement in FElements do begin if SameStr(LElement.Identifier, AIdentifier) and ((LElement.ClassType = AType) or (LElement.InheritsFrom(AType))) then begin Result := LElement; Break; end; end; end; function TGenSourceObject.GetLiteCSource: string; var LElement: TGenSourceObject; begin for LElement in FElements do begin Result := Result + LElement.GetLiteCSource(); end; end; { TGenType } function TGenType.GetLiteCSource: string; begin Result := Identifier + FPostChars; end; { TGenIdentifier } function TGenIdentifier.GetLiteCSource: string; begin Result := FIdentifier; end; { TGenSourceSnippet } function TGenSourceSnippet.GetLiteCSource: string; begin Result := FSource; end; { TGenVarDeclaration } constructor TGenVarDeclaration.Create; begin inherited; FGenType := TGenType.Create(); end; destructor TGenVarDeclaration.Destroy; begin FGenType.Free; inherited; end; function TGenVarDeclaration.GetLiteCSource: string; begin Result := FGenType.GetLiteCSource() + ' ' + Identifier; if not NoDelimiter then begin Result := Result + ';' + sLineBreak; end; end; { TGenMethodDummyDeclaration } procedure TGenMethodDummyDeclaration.AddVarDec(AIdentifier, AType, APostChars: string); var LVarDec: TGenVarDeclaration; begin LVarDec := TGenVarDeclaration.Create(); LVarDec.Identifier := AIdentifier; LVarDec.GenType.Identifier := AType; LVarDec.GenType.PostChars := APostChars; AddElement(LVarDec); end; function TGenMethodDummyDeclaration.GetLiteCSource: string; var LElement: TGenSourceObject; LIsNotFirst: Boolean; i: Integer; LParentIdentifier: string; begin Result := GenType.GetLiteCSource() + ' '; if DoOverride and (not IsVirtual) then begin Result := Result +'zzOverriden'; end; if (NeedsPrefix) then begin Result := Result + GenesisPrefix; end; if (Assigned(Parent)) and NeedsPrefix then begin Result := Result + Parent.Identifier; end; Result := Result + Identifier + '('; // if NeedsThis and (Assigned(Parent)) and (Parent is TGenesisClass) then // begin // Result := Result + Parent.Identifier + '* this'; // end; LIsNotFirst := False; for i := 0 to Elements.Count - 1 do begin LElement := Elements.Items[i]; if (LElement is TGenVarDeclaration) and (LElement.Enabled) then begin if LIsNotFirst then begin Result := Result + ', '; end; if (not LIsNotFirst) and (OverridingParentIdentifier <> '') then begin Result := Result +OverridingParentIdentifier; //simply place void here if overriden and ignore original this type end else begin TGenVarDeclaration(LElement).NoDelimiter := True; Result := Result + LElement.GetLiteCSource(); end; LIsNotFirst := True; // if i < Elements.Count - 1 then // begin // Result := Result + ', '; // end; end; end; Result := Result + ')'; if not NoDelimiter then begin Result := Result + ';' + sLineBreak; end; end; { TGenMethodDeclaration } function TGenMethodDeclaration.GetLiteCSource: string; begin NoDelimiter := True; Result := inherited; if Source <> '' then begin Result := Result + sLineBreak + '{' + sLineBreak; Result := Result + Source + '}'; end else begin Result := Result + ';' + sLineBreak; end; end; { TGenInclude } function TGenInclude.GetLiteCSource: string; begin Result := '#include<' + Identifier + '>;' + sLineBreak; end; { TGenStructDeclaration } function TGenStructDeclaration.GetLiteCSource: string; begin Result := 'typedef struct ' + Identifier + sLineBreak; Result := Result + '{' + sLineBreak; Result := Result + inherited; Result := Result + '}'+Identifier+';' + sLineBreak; end; { TGenEnumDeclaration } function TGenEnumDeclaration.GetLiteCSource: string; var LElement: TGenSourceObject; LNum: Integer; begin LNum := 0; Result := '#define ' + Identifier + ' int' + sLineBreak; for LElement in Elements do begin Result := Result + '#define ' + LElement.Identifier + ' ' + IntToStr(LNum) + sLineBreak; Inc(LNum); end; end; end.
unit StaffManagement; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Vcl.Buttons, Vcl.Touch.Keyboard, Vcl.Menus; {Staff Record} Type TStaff = Record Firstname: String[20]; Surname: String[25]; Username: String[15]; Password: String[15]; Email: String[30]; AccessLevel: String[10]; //Management or Staff used SecurityQuestion: String[40]; SecurityAnswer: String[25]; End; Var StaffFile: File of TStaff; NewStaffDetails: TStaff; StaffList: Array [1..25] of TStaff; //Allows 25 Users n, Ptr: Integer; {Direction Type} Type TRecMove = (FirstRecord, LastRecord, NextRecord, PreviousRecord); type TFRMStaffManagement = class(TForm) GroupBox2: TGroupBox; LBLUsername: TLabel; LBLPassword: TLabel; LBLEmail: TLabel; LBLConfirmPassword: TLabel; LBLAccess: TLabel; LBLQuestion: TLabel; LBLAnswer: TLabel; CBAccess: TComboBox; CBQuestion: TComboBox; EDTUsername: TEdit; EDTPassword: TEdit; EDTConfirmPassword: TEdit; EDTAnswer: TEdit; EDTEmail: TEdit; EDTFirstname: TEdit; EDTSurname: TEdit; LBLSurname: TLabel; LBLFirstname: TLabel; BTNNewStaff: TBitBtn; BTNDelete: TBitBtn; BTNUpdate: TButton; BTNInsert: TBitBtn; LBLStrength: TLabel; BTNFirst: TButton; BTNPrev: TButton; BTNNext: TButton; BTNLast: TButton; BTNFind: TButton; EDTUsernameSearch: TEdit; BTNConfirm: TButton; MainMenu: TMainMenu; FileItem: TMenuItem; LogOut: TMenuItem; procedure FormCreate(Sender: TObject); procedure BTNFirstClick(Sender: TObject); procedure BTNLastClick(Sender: TObject); procedure BTNNextClick(Sender: TObject); procedure BTNPrevClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnDeleteClick(Sender: TObject); procedure BTNUpdateClick(Sender: TObject); procedure BTNFindClick(Sender: TObject); procedure btnFindNextClick(Sender: TObject); procedure BTNNewStaffClick(Sender: TObject); procedure BTNInsertClick(Sender: TObject); procedure BTNConfirmClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure EDTPasswordChange(Sender: TObject); procedure EDTFirstnameChange(Sender: TObject); procedure EDTSurnameChange(Sender: TObject); procedure EDTEmailChange(Sender: TObject); procedure LogOutClick(Sender: TObject); private procedure SetRecordValues; procedure EnableButtons(EnableIt : Boolean); procedure MoveToRec(Direction : TRecMove); procedure LocateRecord(Value : String; FirstSearch : Boolean); procedure CreateNewRecord; procedure InsertRecord; procedure AddRecord (Message, ErrorMessage: String); procedure DeleteRecord; Procedure SetFieldsReadOnly(ReadOnly: Boolean); Procedure CheckFields; public NewRecord : Boolean; Procedure Encryption (EnteredPasswordValue: String); Procedure Decryption; procedure ReadRecords; end; var FRMStaffManagement: TFRMStaffManagement; EncryptedPassword, DecryptedPassword: String; UserConfirm, NewUser, UpdateUser, FieldsComplete:Boolean; EDTList: Array [1..7] Of TEdit; LabelList: Array [1..7] Of TLabel; const MaxRecord = 25; Implementation {$R *.DFM} Uses AddNewCustomer; Procedure TFRMStaffManagement.Decryption; Var CharPtr: Integer; Begin Randseed:= 12; DecryptedPassword := ''; For CharPtr := 1 To Length(NewStaffDetails.Password) Do Begin DecryptedPassword := DecryptedPassword + chr(ord(NewStaffDetails.Password[CharPtr]) - Random(10) -1); End; End; {=============Basic Form Methods================} procedure TFRMStaffManagement.FormCreate(Sender: TObject); Var I: Integer; Begin SetFieldsReadOnly(True); AssignFile(StaffFile, 'Staff.dat'); If FileExists('Staff.dat') then Begin Reset(StaffFile); IF (FileSize(StaffFile) > 0) Then Begin Seek(StaffFile, 0); ReadRecords; NewRecord := False; End; End Else Begin Rewrite(StaffFile); NewRecord := True; End; BTNNewStaff.Enabled := True; BTNInsert.Enabled := False; BTNFirst.Enabled := True; BTNPrev.Enabled := True; BTNNext.Enabled := True; BTNLast.Enabled := True; EDTList[1] := EDTFirstname; EDTList[2] := EDTSurname; EDTList[3] := EDTUsername; EDTList[4] := EDTPassword; EDTList[5] := EDTConfirmPassword; EDTList[6] := EDTEmail; EDTList[7] := EDTAnswer; LabelList[1] := LBLFirstname; LabelList[2] := LBLSurname; LabelList[3] := LBLUsername; LabelList[4] := LBLPassword; LabelList[5] := LBLConfirmPassword; LabelList[6] := LBLEmail; LabelList[7] := LBLAnswer; For I := 0 to ComponentCount - 1 Do IF (Components[I] is TLabel) Then TLabel(Components[I]).Font.Color := clBlack; LBLStrength.Visible := False; End; procedure TFRMStaffManagement.FormClose(Sender: TObject; var Action: TCloseAction); Begin End; {=============General Purpose Routines===============} Procedure TFRMStaffManagement.SetFieldsReadOnly(ReadOnly: Boolean); Var I: Integer; Begin For I := 0 to ComponentCount - 1 Do IF (Components[I] is TEdit) Then TEdit(Components[I]).ReadOnly := (ReadOnly); CBAccess.Enabled := (NOT ReadOnly); CBQuestion.Enabled := (NOT ReadOnly); EDTUsernameSearch.ReadOnly := False; BTNConfirm.Enabled := (NOT ReadOnly); BTNUpdate.Enabled := (ReadOnly); End; //Encryption routine for passwords which extracts each letter of the //entered password, finds its ANSI value, adds a random number, then adds 1 //and then coverts this value back into a character //It then concatenates all values into EncryptedPassword string. Procedure TFRMStaffManagement.Encryption(EnteredPasswordValue: string); Var EnteredPassword: String; CharPtr: Integer; Begin Randseed:= 12; EnteredPassword := EnteredPasswordValue; EncryptedPassword := ''; For CharPtr:=1 To Length(EnteredPassword) Do Begin EncryptedPassword := EncryptedPassword + chr(ord(EnteredPassword[CharPtr]) + Random(10) + 1); End; End; Procedure TFRMStaffManagement.CheckFields; Var Index: Integer; Begin FieldsComplete := True; For Index := 1 to 7 Do Begin IF EDTList[Index].Text = '' Then Begin LabelList[Index].Font.Color := clRed; FieldsComplete := False; End Else LabelList[Index].Font.Color := clBlack; End; End; Procedure TFRMStaffManagement.SetRecordValues; Var Index: Integer; Begin Encryption(EDTPassword.Text); IF EDTPassword.Text <> EDTConfirmPassword.Text Then UserConfirm := False Else IF FieldsComplete <> True Then ShowMessage ('Please Complete All Fields') Else Begin With NewStaffDetails Do Begin Firstname := EDTFirstname.Text; Surname := EDTSurname.Text; Username := EDTUsername.Text; Password := EncryptedPassword; Email := EDTEmail.Text; AccessLevel := CBAccess.Text; SecurityQuestion := CBQuestion.Text; SecurityAnswer := EDTAnswer.Text; End; UserConfirm := True; End End; //Procedure which reads the current record in firl into EDT fields Procedure TFRMStaffManagement.ReadRecords; Begin SetFieldsReadOnly(True); Read(StaffFile, NewStaffDetails); Decryption; With NewStaffDetails Do Begin EDTFirstname.Text := Firstname; EDTSurname.Text := Surname; EDTUsername.Text := Username; EDTEmail.Text := Email; CBAccess.Text := AccessLevel; CBQuestion.Text := SecurityQuestion; EDTAnswer.Text := SecurityAnswer; End; //Value for EDTPassword calculated using Decryption procedure EDTPassword.Text := DecryptedPassword; EDTConfirmPassword.Text := '-'; LBLConfirmPassword.Enabled := False; Seek(StaffFile, FilePos(StaffFile) - 1); End; //Validation Function which passes the parameter 'Action' to check that //specified edit box contains either only text or integers. Function ValidEntry(Text, Action: String):Boolean; Var Char:Integer; Begin Result := True; IF Action = 'TextField' Then Begin For Char := 1 To Length(Text) Do Begin IF (Text[Char] < '0' ) Or (Text[Char] > '9') Then Result := True Else Begin Result := False; Exit; End; End End ELSE IF Action = 'IntegerField' Then Begin For Char := 1 To Length(Text) Do Begin IF ((Text[Char] >= '0' )) And ((Text[Char] <= '9')) Then Result := True Else Begin Result := False; Exit; End; End; End; End; //Function which checks the email entered by the user is of a valid format Function ValidateEmail(Email:String): Boolean; Var N, Counter:integer; Valid:boolean; TempEmail, TempStore:string; EmailSection:array[0..5] of string; Begin N := AnsiPos('@',Email); Valid := true; IF N <> 0 Then Begin //If '@' is found Then... //Copy text before @ into array EmailSection[0]:= copy(Email,0,n-1); //Copy text after @ into array EmailSection[1]:= copy(Email,n+1,length(Email)); For counter := 1 To Length(EmailSection[0]) Do //Check text before @ IF Not (EmailSection[0][Counter] In ['a'..'z','A'..'Z','0'..'9','_','-','.']) Then Valid := False; IF (Valid) //If text before @ is valid we now check the text after @ Then Begin //Place all text after @ into variable 'TempEmail' TempEmail := EmailSection[1]; Result := False; Repeat Begin //Count how many .'s are present N := AnsiPos('.',TempEmail); IF N = 0 //If no . present after @ Email is invalid Then Exit Else Begin Result := True; TempStore := Copy(TempEmail, 0, n-1); TempEmail := copy(TempEmail, n+1, Length(TempEmail)); For Counter := 1 to Length(TempStore) Do Begin IF Not (TempStore[counter] In ['a'..'z','A'..'Z','0'..'9','_','-','.']) Then Begin //Check first section of text before '.' Result := False; Exit; End; End; End; //End repeat when N = 0 as no more .'s present End Until N = 0; End Else Result := False; //End checking second part of email End Else Result:=False; // If any checks fail Email is set to invalid End; Procedure TFRMStaffManagement.EDTEmailChange(Sender: TObject); Begin IF ValidateEmail(EDTEmail.Text) = True Then Begin LBLEmail.Font.Color := clBlack; FieldsComplete := False; End Else LBLEmail.Font.Color := clRed; End; Procedure TFRMStaffManagement.EDTFirstnameChange(Sender: TObject); Begin IF ValidEntry(EDTFirstname.Text, 'TextField') = True Then Begin LBLFirstname.Font.Color := clBlack; FieldsComplete := False; End Else LBLFirstname.Font.Color := clRed; End; Procedure TFRMStaffManagement.EDTPasswordChange(Sender: TObject); Var PasswordLength, CharPtr, Counter, PasswordInt: Integer; PasswordChar: Char; AnsiPassword, AnsiPasswordChar: String; Begin Counter := 0; PasswordLength := Length(EDTPassword.Text); {IF(Passwordlength > 0) and (Passwordlength <= 4) Then ShowMessage ('Password must be between 5-18 characters long.');} For CharPtr := 1 To PasswordLength Do Begin PasswordChar := EDTPassword.Text[CharPtr]; AnsiPasswordChar := IntToStr(Ord(PasswordChar)); AnsiPassword := AnsiPassword + IntToStr(Ord(PasswordChar)); PasswordInt := (StrToInt(AnsiPasswordChar)); //Check if value is Integer using ANSI integer values between 48-57 IF (PasswordInt >= 48) And (PasswordInt <= 57) Then Counter := Counter +1; End; IF Counter = 0 Then Begin LBLStrength.Font.Color := clRed; LBLStrength.Caption := ('*Weak'); End; IF Counter = 1 Then Begin LBLStrength.Font.Color := clYellow; LBLStrength.Caption := ('*Moderate'); End; IF Counter >= 2 Then Begin LBLStrength.Font.Color := clGreen; LBLStrength.Caption := ('*Strong'); End; End; Procedure TFRMStaffManagement.EDTSurnameChange(Sender: TObject); Begin IF ValidEntry(EDTSurname.Text, 'TextField') = True Then Begin LBLSurname.Font.Color := clBlack; FieldsComplete := False; End Else LBLSurname.Font.Color := clRed; End; Procedure TFRMStaffManagement.EnableButtons(EnableIt : Boolean); Begin BTNNewStaff.Enabled := EnableIt; BTNFirst.Enabled := EnableIt; BTNPrev.Enabled := EnableIt; BTNNext.Enabled := EnableIt; BTNLast.Enabled := EnableIt; BTNUpdate.Enabled := EnableIt; //Only enable insert button when 'New' is pressed BTNInsert.Enabled := NOT EnableIt; End; //Procedure which simple clears all fields. Procedure TFRMStaffManagement.CreateNewRecord; Var I: Integer; Begin IF NewRecord Then LockWindowUpdate(Handle); //Clear TEdit values For i := 0 to ComponentCount - 1 Do If (Components[I] is TEdit) Then TEdit(Components[I]).Clear; LBLConfirmPassword.Enabled := True; LockWindowUpdate(0); NewRecord := True; EnableButtons(False); End; //Procedure which finds current position of file pointer //caluculates total number of records to write, writes all records up to current //position to temp array, enters new user to temp array, writes rest of records //in file to temp array then rewrites file with temp array. Procedure TFRMStaffManagement.InsertRecord; Var CurPos, NumRecs, I : Integer; RecordBuffer : Array[0..MaxRecord] of TStaff; Begin CheckFields; //Read field values into temporary record structure SetRecordValues; IF UserConfirm = True Then Begin //Get current file position CurPos := FilePos(StaffFile); //Calcute total number of records to write NumRecs := FileSize(StaffFile); //Write all the records from the file up to the current position to the //temp array of records IF FilePos(StaffFile) > 0 Then Begin I := 0; Seek(StaffFile, 0); While FilePos(StaffFile) < CurPos Do Begin Read(StaffFile, RecordBuffer[I]); Inc(I); End; End; //Write the newly inserted record into the array RecordBuffer[CurPos] := NewStaffDetails; //Write all the remaining records from the file into the buffer array //Array pointed is incremented by one so the newly inserted record is //not overwritten I := curPos + 1; While NOT EOF(StaffFile) Do Begin Read(StaffFile, RecordBuffer[I]); Inc(I); End; //Write entire buffer array back to file I := 0; Seek(StaffFile, 0); While (I <= NumRecs) Do Begin Write(StaffFile, RecordBuffer[I]); Inc(I); End; //Go back to starting position and read records into fields' Seek(StaffFile, CurPos); SetRecordValues; BTNUpdate.Caption := '&Update'; EnableButtons(True); SetFieldsReadOnly(True); ShowMessage ('Staff member inserted'); BTNDelete.Caption := 'Delete Staff'; FormCreate(Self); End Else ShowMessage ('Selected Staff Not insterted'); End; //Procedure which uses the boolean variable 'New Record' to either add a new //user t0 the staffe file or update the details held about the selected user. procedure TFRMStaffManagement.AddRecord(Message, ErrorMessage: String); Var CurPos : Integer; Begin CurPos := FilePos(StaffFile); //Copy TEdit values into temporary record SetRecordValues; IF UserConfirm = True Then Begin //If New record then seek to end of file so others are overwritten IF NewRecord Then Begin Seek(StaffFile, FileSize(StaffFile)); CurPos := FileSize(StaffFile) + 1; End; Write(StaffFile, NewStaffDetails); //Write increments position by 1, so return to position again and fix onto it IF (FileSize(StaffFile) > 0) Then Begin Seek(StaffFile, CurPos); NewRecord := False; End; EnableButtons(True); BTNUpdate.Caption := 'Update'; ShowMessage (Message); SetFieldsReadOnly(True); BTNDelete.Caption := 'Delete Staff'; FormCreate(Self); End Else ShowMessage (ErrorMessage); End; //Reads all the records after the selected record to delete into //RecordBuffer Array. Truncates the file from the current position of the file //Reads the RecordBuffer Array back into the file, writing them to the end Procedure TFRMStaffManagement.DeleteRecord; Var CurPos,NumRecs,I : Integer; RecordBuffer : Array[0..MaxRecord] of TStaff; Begin IF MessageDlg('Are you sure you want to delete this record?', mtConfirmation, [mbYes, mbNo], 0) = mrNo Then Begin FormCreate(Self); ShowMessage ('No staff deleted'); Exit; End; //If user wishes to cancel deletion during entry of new record //just re-read current position in records file and exit If NewRecord Then Begin ReadRecords; NewRecord := False; EnableButtons(True); BTNDelete.Caption := 'Delete Staff'; Exit; End; //Get current file position CurPos := FilePos(StaffFile); //Get number of records to copy NumRecs := FileSize(StaffFile) - curPos - 1; //If not on the last record.. If (FilePos(StaffFile) < (FileSize(StaffFile) - 1)) Then Begin //..Begin by going to the record after the one selected for deletion Seek(StaffFile, FilePos(StaffFile) + 1); I := 0; //Copy remaining records into temporary buffer array {RecordBuffer{ While NOT EOF(StaffFile) Do Begin Read(StaffFile, RecordBuffer[I]); Inc(I); End; //Go back to record selected for deletion and truncate the file at that position Seek(StaffFile, CurPos); Truncate(StaffFile); //Once file is truncate, write all records in buffer back to new end of file For I := 0 to NumRecs - 1 Do Write(StaffFile, RecordBuffer[I]); End Else //..If last record just turncate the record that's at the end Begin Truncate(StaffFile); //End of file so decrement position by 1 as we can't return to this position Dec(curPos); End; //Show staff deleted message ShowMessage('Selected staff deleted'); //Always return to original positon Seek(StaffFile, curPos); //Read current record into fields ReadRecords; End; Procedure TFRMStaffManagement.BTNConfirmClick(Sender: TObject); Var SearchPos, CurPos: Integer; UserFound: Boolean; Begin CheckFields; IF FieldsComplete = False Then ShowMessage ('Please complete all fields before making changes') Else Begin IF (FieldsComplete = True) AND (NewUser = True) AND (UpdateUser = False) Then AddRecord('New User Successfully Added', 'Incorrect Password, New User Not Added'); IF (FieldsComplete = True) AND (NewUser = False) AND (UpdateUser = True) Then Begin NewRecord := False; AddRecord('User Successfully Updated', 'Incorrect Password, User Not Updated'); End; End; End; Procedure TFRMStaffManagement.btnDeleteClick(Sender: TObject); Begin IF BTNDelete.Caption = 'Cancel' Then Begin FormCreate(Self); BTNDelete.Caption := 'Delete Staff'; Exit; End Else Begin DeleteRecord; End; End; {-------------Data Navigation Routines and Methods-------------} //Procedure to locate a record either from the begining of file of from pointer procedure TFRMStaffManagement.MoveToRec(Direction : TRecMove); var Pos : Integer; Begin //Enable appropriate buttons EnableButtons(True); //Get current file position Pos := FilePos(StaffFile); //If file empty then exit IF (FileSize(StaffFile) = 0) Then Exit; //Get which way to move the pointer Case Direction Of FirstRecord: Pos := 0; LastRecord: Pos := FileSize(StaffFile) - 1; NextRecord: IF (FilePos(StaffFile) < (FileSize(StaffFile) - 1)) Then Pos := FilePos(StaffFile) + 1 Else Exit; PreviousRecord: IF (FilePos(StaffFile) > 0) Then Pos := FilePos(StaffFile) - 1 Else Exit; End; Seek(StaffFile, pos); ReadRecords; NewRecord := False; End; //End locate procedure //Searched for staff account with entered username procedure TFRMStaffManagement.LocateRecord(Value :String; FirstSearch :Boolean); Var CurPos, SearchPos: Integer; Found: Boolean; Begin CurPos := FilePos(StaffFile); IF (FirstSearch = True) Then SearchPos := 0 Else SearchPos := CurPos + 1; Found := False; While (SearchPos <= (FileSize(StaffFile) - 1)) AND (NOT Found) Do Begin //Move to search position Seek(StaffFile, SearchPos); Read(StaffFile, NewStaffDetails); IF (NewStaffDetails.Username = Value) Then Begin Found := True; MessageBeep(MB_OK); Seek(StaffFile, SearchPos); ReadRecords; End; INC(SearchPos) End; IF NOT Found Then ShowMessage ('Staff Username Not found in system file'); End; Procedure TFRMStaffManagement.LogOutClick(Sender: TObject); Begin FormCreate(Self); FRMStaffManagement.Visible := False; End; //End search procedure //Create a new blank record Procedure TFRMStaffManagement.BTNUpdateClick(Sender: TObject); Begin NewUser := False; UpdateUser := True; SetFieldsReadOnly(False); ShowMessage ('Make necessary changes'); LBLConfirmPassword.Enabled := True; LBLStrength.Visible := True; BTNDelete.Caption := 'Cancel' End; Procedure TFRMStaffManagement.Button1Click(Sender: TObject); Begin End; //Moves file pointer to first record and reads it in Procedure TFRMStaffManagement.BTNFirstClick(Sender: TObject); Begin MoveToRec(FirstRecord); End; //Calls proceudre to insert new staff Procedure TFRMStaffManagement.BTNInsertClick(Sender: TObject); Begin InsertRecord; End; //Moves file pointer to last record and reads it in Procedure TFRMStaffManagement.BTNLastClick(Sender: TObject); Begin MoveToRec(LastRecord); End; //Calls procedure to create new staff record Procedure TFRMStaffManagement.BTNNewStaffClick(Sender: TObject); Begin NewUser := True; UpdateUser := False; SetFieldsReadOnly(False); CreateNewRecord; BTNDelete.Caption := 'Cancel'; LBLStrength.Visible := True; End; //Moves file pointer to next record and reads it in Procedure TFRMStaffManagement.BTNNextClick(Sender: TObject); Begin MoveToRec(NextRecord); End; //Moves file pointer to previous record and reads it in Procedure TFRMStaffManagement.BTNPrevClick(Sender: TObject); Begin MoveToRec(PreviousRecord); End; Procedure TFRMStaffManagement.BTNFindClick(Sender: TObject); Begin IF (EDTUsernameSearch.Text <> '') Then Begin If NewRecord Then BTNUpdateClick(Self); LocateRecord(EDTUsernameSearch.Text, True); End; End; Procedure TFRMStaffManagement.btnFindNextClick(Sender: TObject); Begin LocateRecord(EDTUsernameSearch.Text, False); End; End. //End Program
unit MonkeyMixer.Wizard; interface uses Classes, VCL.Dialogs, ToolsAPI, SysUtils, StrUtils, UITypes; type TMonkeyMixerMenu = class(TNotifierObject, IOTANotifier, IOTAProjectMenuItemCreatorNotifier) protected procedure AddMenu(const Project: IOTAProject; const IdentList: TStrings; const ProjectManagerMenuList: IInterfaceList; IsMultiSelect: Boolean); end; TMonkeyMixerTogglerMenuItem = class(TInterfacedObject, IOTANotifier, IOTALocalMenu, IOTAProjectManagerMenu) private FCaption: String; FChecked: Boolean; FEnabled: Boolean; FFrameworkType: String; FProject: IOTAProject150; FHelpContext: Integer; FName: String; FParent: String; FPosition: Integer; FVerb: String; protected // IOTANotifier Methods procedure AfterSave; // Not used! procedure BeforeSave; // Not used! procedure Destroyed; procedure Modified; // Not used! // IOTALocalMenu Methods function GetCaption: string; function GetChecked: Boolean; function GetEnabled: Boolean; function GetHelpContext: Integer; function GetName: string; function GetParent: string; function GetPosition: Integer; function GetVerb: string; procedure SetCaption(const Value: string); procedure SetChecked(Value: Boolean); procedure SetEnabled(Value: Boolean); procedure SetHelpContext(Value: Integer); procedure SetName(const Value: string); procedure SetParent(const Value: string); procedure SetPosition(Value: Integer); procedure SetVerb(const Value: string); // IOTAProjectManagerMenu Methods function GetIsMultiSelectable: Boolean; procedure SetIsMultiSelectable(Value: Boolean); procedure Execute(const MenuContextList: IInterfaceList); overload; function PreExecute(const MenuContextList: IInterfaceList): Boolean; function PostExecute(const MenuContextList: IInterfaceList): Boolean; public constructor Create; end; {$IFNDEF DLLEXPERT} procedure Register; {$ELSE} function InitWizard(Const BorlandIDEServices: IBorlandIDEServices; RegisterProc: TWizardRegisterProc; var Terminate: TWizardTerminateProc): Boolean; stdcall; exports InitWizard name WizardEntryPoint; {$ENDIF} implementation uses UsesFixerParser; var FWizardIndex: Integer = -1; function InitializeWizard(BorlandIDEServices: IBorlandIDEServices): TMonkeyMixerMenu; begin Result := TMonkeyMixerMenu.Create; end; {$IFNDEF DLLEXPERT} procedure Register; begin if BorlandIDEServices <> nil then FWizardIndex := (BorlandIDEServices as IOTAProjectManager).AddMenuItemCreatorNotifier(InitializeWizard(BorlandIDEServices)); end; {$ELSE} function InitWizard(Const BorlandIDEServices: IBorlandIDEServices; RegisterProc: TWizardRegisterProc; var Terminate: TWizardTerminateProc): Boolean; stdcall; begin if BorlandIDEServices <> nil then FWizardIndex := (BorlandIDEServices as IOTAProjectManager).AddMenuItemCreatorNotifier(InitializeWizard(BorlandIDEServices)); Result := (BorlandIDEServices <> nil) end; {$ENDIF} { TMonkeyMixerTogglerMenuItem } procedure TMonkeyMixerTogglerMenuItem.AfterSave; begin // Not used! end; procedure TMonkeyMixerTogglerMenuItem.BeforeSave; begin // Not used! end; constructor TMonkeyMixerTogglerMenuItem.Create; begin inherited; end; procedure TMonkeyMixerTogglerMenuItem.Destroyed; begin // Do Nothing! end; procedure TMonkeyMixerTogglerMenuItem.Execute(const MenuContextList: IInterfaceList); const CN_FORMS = 'FORMS'; CN_VCLFORMS = 'VCL.FORMS'; CN_FMXFORMS = 'FMX.FORMS'; var LMenuContext: IOTAProjectMenuContext; LProject: IOTAProject; LDproj: TStringList; LUsesFixer: TUsesFixer; begin LMenuContext := MenuContextList.Items[0] as IOTAProjectMenuContext; LProject := (LMenuContext.Project as IOTAProject); if FileExists(LProject.FileName) then begin LDproj := TStringList.Create; try LDproj.LoadFromFile(LProject.FileName); LDproj.Text := ReplaceText(LDproj.Text, Format('<FrameworkType>%s</FrameworkType>', [LProject.FrameworkType]), Format('<FrameworkType>%s</FrameworkType>', [FFrameworkType])); LDproj.SaveToFile(LProject.FileName); // XE3 FIX if LProject.FrameworkType = sFrameworkTypeVCL then begin LUsesFixer := TUsesFixer.Create; try LDproj.LoadFromFile(ChangeFileExt(LProject.FileName, '.dpr')); LUsesFixer.ProcessSource(LDproj.Text); LUsesFixer.DeleteUnit('Forms'); LUsesFixer.AddUnitToUses('Vcl.Forms'); LUsesFixer.AddUnitToUses('FMX.Forms'); LDproj.Text := LUsesFixer.Source; LDproj.SaveToFile(ChangeFileExt(LProject.FileName, '.dpr')); finally LUsesFixer.Free; end; end; // XE3 FIX ENDS LProject.Refresh(True); finally LDproj.Free; end; end else if MessageDlg(Format('Project "%s" must be saved first, do you wish to save it now, then have MonkeyMixer work its magic?', [ExtractFileName(LProject.FileName)]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then if LProject.Save(True, True) then Execute(MenuContextList); end; function TMonkeyMixerTogglerMenuItem.GetCaption: string; begin Result := FCaption; end; function TMonkeyMixerTogglerMenuItem.GetChecked: Boolean; begin Result := FChecked; end; function TMonkeyMixerTogglerMenuItem.GetEnabled: Boolean; begin Result := FEnabled; end; function TMonkeyMixerTogglerMenuItem.GetHelpContext: Integer; begin Result := FHelpContext; end; function TMonkeyMixerTogglerMenuItem.GetIsMultiSelectable: Boolean; begin Result := False; end; function TMonkeyMixerTogglerMenuItem.GetName: string; begin Result := FName; end; function TMonkeyMixerTogglerMenuItem.GetParent: string; begin Result := FParent; end; function TMonkeyMixerTogglerMenuItem.GetPosition: Integer; begin Result := FPosition; end; function TMonkeyMixerTogglerMenuItem.GetVerb: string; begin Result := FVerb; end; procedure TMonkeyMixerTogglerMenuItem.Modified; begin // Not used for IOTAWizard! end; function TMonkeyMixerTogglerMenuItem.PostExecute(const MenuContextList: IInterfaceList): Boolean; begin Result := True; end; function TMonkeyMixerTogglerMenuItem.PreExecute(const MenuContextList: IInterfaceList): Boolean; begin Result := True; end; procedure TMonkeyMixerTogglerMenuItem.SetCaption(const Value: string); begin FCaption := Value; end; procedure TMonkeyMixerTogglerMenuItem.SetChecked(Value: Boolean); begin FChecked := Value; end; procedure TMonkeyMixerTogglerMenuItem.SetEnabled(Value: Boolean); begin FEnabled := Value; end; procedure TMonkeyMixerTogglerMenuItem.SetHelpContext(Value: Integer); begin FHelpContext := Value; end; procedure TMonkeyMixerTogglerMenuItem.SetIsMultiSelectable(Value: Boolean); begin // Not used! end; procedure TMonkeyMixerTogglerMenuItem.SetName(const Value: string); begin FName := Value; end; procedure TMonkeyMixerTogglerMenuItem.SetParent(const Value: string); begin FParent := Value; end; procedure TMonkeyMixerTogglerMenuItem.SetPosition(Value: Integer); begin FPosition := Value; end; procedure TMonkeyMixerTogglerMenuItem.SetVerb(const Value: string); begin FVerb := Value; end; { TMonkeyMixerMenu } procedure TMonkeyMixerMenu.AddMenu(const Project: IOTAProject; const IdentList: TStrings; const ProjectManagerMenuList: IInterfaceList; IsMultiSelect: Boolean); var LMenuItem: TMonkeyMixerTogglerMenuItem; begin if (not IsMultiSelect) and (IdentList.IndexOf(sProjectContainer) <> -1) and Assigned(ProjectManagerMenuList) and ((Project.FrameworkType = sFrameworkTypeVCL) or (Project.FrameworkType = sFrameworkTypeFMX)) and (Project.Personality = sDelphiPersonality) then {TODO: Fix MonkeyMixer to work with C++ Builder projects! } begin LMenuItem := TMonkeyMixerTogglerMenuItem.Create; // Toggeler if Project.FrameworkType = sFrameworkTypeVCL then begin LMenuItem.FCaption := 'Switch Project to FireMonkey'; LMenuItem.FFrameworkType := sFrameworkTypeFMX; end else if Project.FrameworkType = sFrameworkTypeFMX then begin LMenuItem.FCaption := 'Switch Project to VCL'; LMenuItem.FFrameworkType := sFrameworkTypeVCL; end; LMenuItem.FProject := (Project as IOTAProject150); LMenuItem.FEnabled := True; LMenuItem.FPosition := pmmpAdd; ProjectManagerMenuList.Add(LMenuItem); end; end; initialization // Bleh finalization if FWizardIndex > -1 then begin (BorlandIDEServices as IOTAProjectManager).RemoveMenuItemCreatorNotifier(FWizardIndex); FWizardIndex := -1; end; end.
unit Server.Models.Cadastros.Campanhas; interface uses System.Classes, DB, System.SysUtils, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, dbcbr.mapping.register, Server.Models.Base.TabelaBase; type [Entity] [Table('campanhas','')] [PrimaryKey('CODIGO', AutoInc, NoSort, False, 'Chave primária')] TCampanhas = class(TTabelaBase) private FNome: String; function Getid: Integer; procedure Setid(const Value: Integer); public constructor create; destructor destroy; override; { Public declarations } [Restrictions([NotNull, Unique])] [Column('CODIGO', ftInteger)] [Dictionary('CODIGO','','','','',taCenter)] property id: Integer read Getid write Setid; [Column('NOME', ftString)] property Nome: string read Fnome write FNome; end; implementation { TCampanhas } constructor TCampanhas.create; begin // end; destructor TCampanhas.destroy; begin // inherited; end; function TCampanhas.Getid: Integer; begin Result := fid; end; procedure TCampanhas.Setid(const Value: Integer); begin fid := Value; end; initialization TRegisterClass.RegisterEntity(TCampanhas); end.
unit TimeFunc; interface uses sysutils; type TMoonPhase=(Newmoon,FirstQuarter,Fullmoon,LastQuarter); TSeason=(Winter,Spring,Summer,Autumn); TEclipse=(none, partial, noncentral, circular, circulartotal, total, halfshadow); E_NoRiseSet=class(Exception); E_OutOfAlgorithRange=class(Exception); function julian_date(date:TDateTime):extended; function sun_distance(date:TDateTime): extended; function moon_distance(date:TDateTime): extended; function age_of_moon(date:TDateTime): extended; function last_phase(date:TDateTime; phase:TMoonPhase):TDateTime; function next_phase(date:TDateTime; phase:TMoonPhase):TDateTime; function current_phase(date:TDateTime):extended; function lunation(date:TDateTime):integer; function sun_diameter(date:TDateTime):extended; function moon_diameter(date:TDateTime):extended; function star_time(date:TDateTime):extended; function StartSeason(year: integer; season:TSeason):TDateTime; function Sun_Rise(date:TDateTime; latitude, longitude:extended):TDateTime; function Sun_Set(date:TDateTime; latitude, longitude:extended):TDateTime; function Sun_Transit(date:TDateTime; latitude, longitude:extended):TDateTime; function Moon_Rise(date:TDateTime; latitude, longitude:extended):TDateTime; function Moon_Set(date:TDateTime; latitude, longitude:extended):TDateTime; function Moon_Transit(date:TDateTime; latitude, longitude:extended):TDateTime; function nextperigee(date:TDateTime):TDateTime; function nextapogee(date:TDateTime):TDateTime; function NextEclipse(var date:TDateTime; sun:boolean):TEclipse; implementation uses MyMath; const AU=149597869; (* astronomical unit in km *) mean_lunation=29.530589; (* Mean length of a month *) earth_radius=6378.15; (* Radius of the earth *) type t_coord = record longitude, latitude, radius: extended; rektaszension, declination: extended; parallax: extended; end; T_RiseSet=(_rise,_set,_transit); function put_in_360(x:extended):extended; begin result:=x-round(x/360)*360; while result<0 do result:=result+360; end; { Angular functions with degrees } (*@/// function sin_d(x:extended):extended; *) function sin_d(x:extended):extended; begin sin_d:=sin(put_in_360(x)*pi/180); end; (*@\\\000000030A*) (*@/// function cos_d(x:extended):extended; *) function cos_d(x:extended):extended; begin cos_d:=cos(put_in_360(x)*pi/180); end; (*@\\\0000000301*) (*@/// function tan_d(x:extended):extended; *) function tan_d(x:extended):extended; begin tan_d:=tan(put_in_360(x)*pi/180); end; (*@\\\000000030D*) (*@/// function arctan2_d(a,b:extended):extended; *) function arctan2_d(a,b:extended):extended; begin result:=arctan2(a,b)*180/pi; end; (*@\\\000000030B*) (*@/// function arcsin_d(x:extended):extended; *) function arcsin_d(x:extended):extended; begin result:=arcsin(x)*180/pi; end; (*@\\\0000000301*) (*@/// function arccos_d(x:extended):extended; *) function arccos_d(x:extended):extended; begin result:=arccos(x)*180/pi; end; (*@\\\0000000301*) (*@/// function arctan_d(x:extended):extended; *) function arctan_d(x:extended):extended; begin result:=arctan(x)*180/pi end; (*@\\\0000000310*) { Julian date } (*@/// function julian_date(date:TDateTime):extended; *) function julian_date(date:TDateTime):extended; begin if date>encodedate(1582,10,14) then julian_date:=2451544.5-encodedate(2000,1,1)+date else julian_date:=0; { not yet implemented !!! } end; (*@\\\0000000601*) (*@/// function delphi_date(juldat:extended):TDateTime; *) function delphi_date(juldat:extended):TDateTime; begin if juldat>=julian_date(encodedate(1582,10,15)) then begin delphi_date:= juldat-2451544.5+encodedate(2000,1,1); end else delphi_date:=0; { not yet implemented !!! } end; (*@\\\0000000701*) (*@/// function star_time(date:TDateTime):extended; // degrees *) function star_time(date:TDateTime):extended; var jd, t: extended; begin jd:=julian_date(date); t:=(jd-2451545.0)/36525; result:=put_in_360(280.46061837+360.98564736629*(jd-2451545.0)+ t*t*(0.000387933-t/38710000)); end; (*@\\\0000000901*) { Coordinate functions } (*@/// procedure calc_geocentric(var coord:t_coord; date:TDateTime); *) { Based upon Chapter 12 and 21 of Meeus } procedure calc_geocentric(var coord:t_coord; date:TDateTime); (*$ifndef correction_low *) const (*@/// arg_mul:array[0..30,0..4] of shortint = (..); *) arg_mul:array[0..30,0..4] of shortint = ( ( 0, 0, 0, 0, 1), (-2, 0, 0, 2, 2), ( 0, 0, 0, 2, 2), ( 0, 0, 0, 0, 2), ( 0, 1, 0, 0, 0), ( 0, 0, 1, 0, 0), (-2, 1, 0, 2, 2), ( 0, 0, 0, 2, 1), ( 0, 0, 1, 2, 2), (-2,-1, 0, 2, 2), (-2, 0, 1, 0, 0), (-2, 0, 0, 2, 1), ( 0, 0,-1, 2, 2), ( 2, 0, 0, 0, 0), ( 0, 0, 1, 0, 1), ( 2, 0,-1, 2, 2), ( 0, 0,-1, 0, 1), ( 0, 0, 1, 2, 1), (-2, 0, 2, 0, 0), ( 0, 0,-2, 2, 1), ( 2, 0, 0, 2, 2), ( 0, 0, 2, 2, 2), ( 0, 0, 2, 0, 0), (-2, 0, 1, 2, 2), ( 0, 0, 0, 2, 0), (-2, 0, 0, 2, 0), ( 0, 0,-1, 2, 1), ( 0, 2, 0, 0, 0), ( 2, 0,-1, 0, 1), (-2, 2, 0, 2, 2), ( 0, 1, 0, 0, 1) ); (*@\\\0000000109*) (*@/// arg_phi:array[0..30,0..1] of longint = (); *) arg_phi:array[0..30,0..1] of longint = ( (-171996,-1742), ( -13187, -16), ( -2274, -2), ( 2062, 2), ( 1426, -34), ( 712, 1), ( -517, 12), ( -386, -4), ( -301, 0), ( 217, -5), ( -158, 0), ( 129, 1), ( 123, 0), ( 63, 0), ( 63, 1), ( -59, 0), ( -58, -1), ( -51, 0), ( 48, 0), ( 46, 0), ( -38, 0), ( -31, 0), ( 29, 0), ( 29, 0), ( 26, 0), ( -22, 0), ( 21, 0), ( 17, -1), ( 16, 0), ( -16, 1), ( -15, 0) ); (*@\\\*) (*@/// arg_eps:array[0..30,0..1] of longint = (); *) arg_eps:array[0..30,0..1] of longint = ( ( 92025, 89), ( 5736, -31), ( 977, -5), ( -895, 5), ( 54, -1), ( -7, 0), ( 224, -6), ( 200, 0), ( 129, -1), ( -95, 3), ( 0, 0), ( -70, 0), ( -53, 0), ( 0, 0), ( -33, 0), ( 26, 0), ( 32, 0), ( 27, 0), ( 0, 0), ( -24, 0), ( 16, 0), ( 13, 0), ( 0, 0), ( -12, 0), ( 0, 0), ( 0, 0), ( -10, 0), ( 0, 0), ( -8, 0), ( 7, 0), ( 9, 0) ); (*@\\\*) (*$endif *) var t,omega: extended; (*$ifdef correction_low *) l,ls: extended; (*$else *) d,m,ms,f,s: extended; i: integer; (*$endif *) epsilon,epsilon_0,delta_epsilon: extended; delta_phi: extended; alpha,delta: extended; begin t:=(julian_date(date)-2451545.0)/36525; (* longitude of rising knot *) omega:=put_in_360(125.04452+(-1934.136261+(0.0020708+1/450000*t)*t)*t); (*$ifdef correction_low *) (*@/// delta_phi and delta_epsilon - low accuracy *) (* mean longitude of sun (l) and moon (ls) *) l:=280.4665+36000.7698*t; ls:=218.3165+481267.8813*t; (* correction due to nutation *) delta_epsilon:=9.20*cos_d(omega)+0.57*cos_d(2*l)+0.10*cos_d(2*ls)-0.09*cos_d(2*omega); (* longitude correction due to nutation *) delta_phi:=(-17.20*sin_d(omega)-1.32*sin_d(2*l)-0.23*sin_d(2*ls)+0.21*sin_d(2*omega))/3600; (*@\\\0000000401*) (*$else *) (*@/// delta_phi and delta_epsilon - higher accuracy *) (* mean elongation of moon to sun *) d:=put_in_360(297.85036+(445267.111480+(-0.0019142+t/189474)*t)*t); (* mean anomaly of the sun *) m:=put_in_360(357.52772+(35999.050340+(-0.0001603-t/300000)*t)*t); (* mean anomly of the moon *) ms:=put_in_360(134.96298+(477198.867398+(0.0086972+t/56250)*t)*t); (* argument of the latitude of the moon *) f:=put_in_360(93.27191+(483202.017538+(-0.0036825+t/327270)*t)*t); delta_phi:=0; delta_epsilon:=0; for i:=0 to 30 do begin s:= arg_mul[i,0]*d +arg_mul[i,1]*m +arg_mul[i,2]*ms +arg_mul[i,3]*f +arg_mul[i,4]*omega; delta_phi:=delta_phi+(arg_phi[i,0]+arg_phi[i,1]*t*0.1)*sin_d(s); delta_epsilon:=delta_epsilon+(arg_eps[i,0]+arg_eps[i,1]*t*0.1)*cos_d(s); end; delta_phi:=delta_phi*0.0001/3600; delta_epsilon:=delta_epsilon*0.0001/3600; (*@\\\0000001B01*) (*$endif *) (* angle of ecliptic *) epsilon_0:=84381.448+(-46.8150+(-0.00059+0.001813*t)*t)*t; epsilon:=(epsilon_0+delta_epsilon)/3600; coord.longitude:=put_in_360(coord.longitude+delta_phi); (* geocentric coordinates *) { alpha:=arctan2_d(cos_d(epsilon)*sin_d(o),cos_d(o)); } { delta:=arcsin_d(sin_d(epsilon)*sin_d(o)); } alpha:=arctan2_d( sin_d(coord.longitude)*cos_d(epsilon) -tan_d(coord.latitude)*sin_d(epsilon) ,cos_d(coord.longitude)); delta:=arcsin_d( sin_d(coord.latitude)*cos_d(epsilon) +cos_d(coord.latitude)*sin_d(epsilon)*sin_d(coord.longitude)); coord.rektaszension:=alpha; coord.declination:=delta; end; (*@\\\0000000501*) (*@/// function sun_coordinate(date:TDateTime):t_coord; *) { Based upon Chapter 24 of Meeus } function sun_coordinate(date:TDateTime):t_coord; var t,e,m,c,nu: extended; l0,o,omega,lambda: extended; begin t:=(julian_date(date)-2451545.0)/36525; (* geometrical mean longitude of the sun *) l0:=280.46645+(36000.76983+0.0003032*t)*t; (* excentricity of the erath orbit *) e:=0.016708617+(-0.000042037-0.0000001236*t)*t; (* mean anomaly of the sun *) m:=357.52910+(35999.05030-(0.0001559+0.00000048*t)*t)*t; (* mean point of sun *) c:= (1.914600+(-0.004817-0.000014*t)*t)*sin_d(m) +(0.019993-0.000101*t)*sin_d(2*m) +0.000290*sin_d(3*m); (* true longitude of the sun *) o:=put_in_360(l0+c); (* true anomaly of the sun *) nu:=m+c; (* distance of the sun in km *) result.radius:=(1.000001018*(1-e*e))/(1+e*cos_d(nu))*AU; (* apparent longitude of the sun *) omega:=125.04452+(-1934.136261+(0.0020708+1/450000*t)*t)*t; lambda:=put_in_360(o-0.00569-0.00478*sin_d(omega) -20.4898/3600/(result.radius/AU)); result.longitude:=lambda; result.latitude:=0; calc_geocentric(result,date); end; (*@\\\0000002715*) (*@/// function moon_coordinate(date:TDateTime):t_coord; *) { Based upon Chapter 45 of Meeus } function moon_coordinate(date:TDateTime):t_coord; const (*@/// arg_lr:array[0..59,0..3] of shortint = (..); *) arg_lr:array[0..59,0..3] of shortint = ( ( 0, 0, 1, 0), ( 2, 0,-1, 0), ( 2, 0, 0, 0), ( 0, 0, 2, 0), ( 0, 1, 0, 0), ( 0, 0, 0, 2), ( 2, 0,-2, 0), ( 2,-1,-1, 0), ( 2, 0, 1, 0), ( 2,-1, 0, 0), ( 0, 1,-1, 0), ( 1, 0, 0, 0), ( 0, 1, 1, 0), ( 2, 0, 0,-2), ( 0, 0, 1, 2), ( 0, 0, 1,-2), ( 4, 0,-1, 0), ( 0, 0, 3, 0), ( 4, 0,-2, 0), ( 2, 1,-1, 0), ( 2, 1, 0, 0), ( 1, 0,-1, 0), ( 1, 1, 0, 0), ( 2,-1, 1, 0), ( 2, 0, 2, 0), ( 4, 0, 0, 0), ( 2, 0,-3, 0), ( 0, 1,-2, 0), ( 2, 0,-1, 2), ( 2,-1,-2, 0), ( 1, 0, 1, 0), ( 2,-2, 0, 0), ( 0, 1, 2, 0), ( 0, 2, 0, 0), ( 2,-2,-1, 0), ( 2, 0, 1,-2), ( 2, 0, 0, 2), ( 4,-1,-1, 0), ( 0, 0, 2, 2), ( 3, 0,-1, 0), ( 2, 1, 1, 0), ( 4,-1,-2, 0), ( 0, 2,-1, 0), ( 2, 2,-1, 0), ( 2, 1,-2, 0), ( 2,-1, 0,-2), ( 4, 0, 1, 0), ( 0, 0, 4, 0), ( 4,-1, 0, 0), ( 1, 0,-2, 0), ( 2, 1, 0,-2), ( 0, 0, 2,-2), ( 1, 1, 1, 0), ( 3, 0,-2, 0), ( 4, 0,-3, 0), ( 2,-1, 2, 0), ( 0, 2, 1, 0), ( 1, 1,-1, 0), ( 2, 0, 3, 0), ( 2, 0,-1,-2) ); (*@\\\0000000701*) (*@/// arg_b:array[0..59,0..3] of shortint = (); *) arg_b:array[0..59,0..3] of shortint = ( ( 0, 0, 0, 1), ( 0, 0, 1, 1), ( 0, 0, 1,-1), ( 2, 0, 0,-1), ( 2, 0,-1, 1), ( 2, 0,-1,-1), ( 2, 0, 0, 1), ( 0, 0, 2, 1), ( 2, 0, 1,-1), ( 0, 0, 2,-1), (* !!! Error in German Meeus *) ( 2,-1, 0,-1), ( 2, 0,-2,-1), ( 2, 0, 1, 1), ( 2, 1, 0,-1), ( 2,-1,-1, 1), ( 2,-1, 0, 1), ( 2,-1,-1,-1), ( 0, 1,-1,-1), ( 4, 0,-1,-1), ( 0, 1, 0, 1), ( 0, 0, 0, 3), ( 0, 1,-1, 1), ( 1, 0, 0, 1), ( 0, 1, 1, 1), ( 0, 1, 1,-1), ( 0, 1, 0,-1), ( 1, 0, 0,-1), ( 0, 0, 3, 1), ( 4, 0, 0,-1), ( 4, 0,-1, 1), ( 0, 0, 1,-3), ( 4, 0,-2, 1), ( 2, 0, 0,-3), ( 2, 0, 2,-1), ( 2,-1, 1,-1), ( 2, 0,-2, 1), ( 0, 0, 3,-1), ( 2, 0, 2, 1), ( 2, 0,-3,-1), ( 2, 1,-1, 1), ( 2, 1, 0, 1), ( 4, 0, 0, 1), ( 2,-1, 1, 1), ( 2,-2, 0,-1), ( 0, 0, 1, 3), ( 2, 1, 1,-1), ( 1, 1, 0,-1), ( 1, 1, 0, 1), ( 0, 1,-2,-1), ( 2, 1,-1,-1), ( 1, 0, 1, 1), ( 2,-1,-2,-1), ( 0, 1, 2, 1), ( 4, 0,-2,-1), ( 4,-1,-1,-1), ( 1, 0, 1,-1), ( 4, 0, 1,-1), ( 1, 0,-1,-1), ( 4,-1, 0,-1), ( 2,-2, 0, 1) ); (*@\\\0000001224*) (*@/// sigma_r: array[0..59] of longint = (..); *) sigma_r: array[0..59] of longint = ( -20905355, -3699111, -2955968, -569925, 48888, -3149, 246158, -152138, -170733, -204586, -129620, 108743, 104755, 10321, 0, 79661, -34782, -23210, -21636, 24208, 30824, -8379, -16675, -12831, -10445, -11650, 14403, -7003, 0, 10056, 6322, -9884, 5751, 0, -4950, 4130, 0, -3958, 0, 3258, 2616, -1897, -2117, 2354, 0, 0, -1423, -1117, -1571, -1739, 0, -4421, 0, 0, 0, 0, 1165, 0, 0, 8752 ); (*@\\\*) (*@/// sigma_l: array[0..59] of longint = (..); *) sigma_l: array[0..59] of longint = ( 6288774, 1274027, 658314, 213618, -185116, -114332, 58793, 57066, 53322, 45758, -40923, -34720, -30383, 15327, -12528, 10980, 10675, 10034, 8548, -7888, -6766, -5163, 4987, 4036, 3994, 3861, 3665, -2689, -2602, 2390, -2348, 2236, -2120, -2069, 2048, -1773, -1595, 1215, -1110, -892, -810, 759, -713, -700, 691, 596, 549, 537, 520, -487, -399, -381, 351, -340, 330, 327, -323, 299, 294, 0 ); (*@\\\*) (*@/// sigma_b: array[0..59] of longint = (..); *) sigma_b: array[0..59] of longint = ( 5128122, 280602, 277693, 173237, 55413, 46271, 32573, 17198, 9266, 8822, 8216, 4324, 4200, -3359, 2463, 2211, 2065, -1870, 1828, -1794, -1749, -1565, -1491, -1475, -1410, -1344, -1335, 1107, 1021, 833, 777, 671, 607, 596, 491, -451, 439, 422, 421, -366, -351, 331, 315, 302, -283, -229, 223, 223, -220, -220, -185, 181, -177, 176, 166, -164, 132, -119, 115, 107 ); (*@\\\*) var t,d,m,ms,f,e,ls : extended; sr,sl,sb,temp: extended; a1,a2,a3: extended; lambda,beta,delta: extended; i: integer; begin t:=(julian_date(date)-2451545)/36525; (* mean elongation of the moon *) d:=297.8502042+(445267.1115168+(-0.0016300+(1/545868-1/113065000*t)*t)*t)*t; (* mean anomaly of the sun *) m:=357.5291092+(35999.0502909+(-0.0001536+1/24490000*t)*t)*t; (* mean anomaly of the moon *) ms:=134.9634114+(477198.8676313+(0.0089970+(1/69699-1/1471200*t)*t)*t)*t; (* argument of the longitude of the moon *) f:=93.2720993+(483202.0175273+(-0.0034029+(-1/3526000+1/863310000*t)*t)*t)*t; (* correction term due to excentricity of the earth orbit *) e:=1.0+(-0.002516-0.0000074*t)*t; (* mean longitude of the moon *) ls:=218.3164591+(481267.88134236+(-0.0013268+(1/538841-1/65194000*t)*t)*t)*t; (* arguments of correction terms *) a1:=119.75+131.849*t; a2:=53.09+479264.290*t; a3:=313.45+481266.484*t; (*@/// sr := ä r_i cos(d,m,ms,f); !!! gives different value than in Meeus *) sr:=0; for i:=0 to 59 do begin temp:=sigma_r[i]*cos_d( arg_lr[i,0]*d +arg_lr[i,1]*m +arg_lr[i,2]*ms +arg_lr[i,3]*f); if abs(arg_lr[i,1])=1 then temp:=temp*e; if abs(arg_lr[i,1])=2 then temp:=temp*e; sr:=sr+temp; end; (*@\\\0000000301*) (*@/// sl := ä l_i sin(d,m,ms,f); *) sl:=0; for i:=0 to 59 do begin temp:=sigma_l[i]*sin_d( arg_lr[i,0]*d +arg_lr[i,1]*m +arg_lr[i,2]*ms +arg_lr[i,3]*f); if abs(arg_lr[i,1])=1 then temp:=temp*e; if abs(arg_lr[i,1])=2 then temp:=temp*e; sl:=sl+temp; end; (* correction terms *) sl:=sl +3958*sin_d(a1) +1962*sin_d(ls-f) +318*sin_d(a2); (*@\\\0000000B01*) (*@/// sb := ä b_i sin(d,m,ms,f); *) sb:=0; for i:=0 to 59 do begin temp:=sigma_b[i]*sin_d( arg_b[i,0]*d +arg_b[i,1]*m +arg_b[i,2]*ms +arg_b[i,3]*f); if abs(arg_b[i,1])=1 then temp:=temp*e; if abs(arg_b[i,1])=2 then temp:=temp*e; sb:=sb+temp; end; (* correction terms *) sb:=sb -2235*sin_d(ls) +382*sin_d(a3) +175*sin_d(a1-f) +175*sin_d(a1+f) +127*sin_d(ls-ms) -115*sin_d(ls+ms); (*@\\\0000001216*) lambda:=ls+sl/1000000; beta:=sb/1000000; delta:=385000.56+sr/1000; result.radius:=delta; result.longitude:=lambda; result.latitude:=beta; calc_geocentric(result,date); end; (*@\\\0000003601*) (*@/// procedure correct_position(var position:t_coord; date:TDateTime; ...); *) { Based upon chapter 39 of Meeus } procedure correct_position(var position:t_coord; date:TDateTime; latitude,longitude,height:extended); var u,h,delta_alpha: extended; rho_sin, rho_cos: extended; const b_a=0.99664719; begin u:=arctan_d(b_a*b_a*tan_d(longitude)); rho_sin:=b_a*sin_d(u)+height/6378140*sin_d(longitude); rho_cos:=cos_d(u)+height/6378140*cos_d(longitude); position.parallax:=arcsin_d(sin_d(8.794/3600)/(moon_distance(date)/AU)); h:=star_time(date)-longitude-position.rektaszension; delta_alpha:=arctan_d( (-rho_cos*sin_d(position.parallax)*sin_d(h))/ (cos_d(position.declination)- rho_cos*sin_d(position.parallax)*cos_d(h))); position.rektaszension:=position.rektaszension+delta_alpha; position.declination:=arctan_d( (( sin_d(position.declination) -rho_sin*sin_d(position.parallax))*cos_d(delta_alpha))/ ( cos_d(position.declination) -rho_cos*sin_d(position.parallax)*cos_d(h))); end; (*@\\\0000001501*) { Moon phases and age of the moon } (*@/// procedure calc_phase_data(date:TDateTime; phase:TMoonPhase; var jde,kk,m,ms,f,o,e: extended); *) { Based upon Chapter 47 of Meeus } { Both used for moon phases and moon and sun eclipses } procedure calc_phase_data(date:TDateTime; phase:TMoonPhase; var jde,kk,m,ms,f,o,e: extended); var t: extended; k: longint; ts: extended; begin k:=round((date-encodedate(2000,1,1))/36525.0*1236.85); ts:=(date-encodedate(2000,1,1))/36525.0; kk:=int(k)+ord(phase)/4.0; t:=kk/1236.85; jde:=2451550.09765+29.530588853*kk +t*t*(0.0001337-t*(0.000000150-0.00000000073*t)); m:=2.5534+29.10535669*kk-t*t*(0.0000218+0.00000011*t); ms:=201.5643+385.81693528*kk+t*t*(0.1017438+t*(0.00001239-t*0.000000058)); f:= 160.7108+390.67050274*kk-t*t*(0.0016341+t*(0.00000227-t*0.000000011)); o:=124.7746-1.56375580*kk+t*t*(0.0020691+t*0.00000215); e:=1-ts*(0.002516+ts*0.0000074); end; (*@\\\0000000447*) (*@/// function nextphase(date:TDateTime; phase:TMoonPhase):TDateTime; *) { Based upon Chapter 47 of Meeus } function nextphase(date:TDateTime; phase:TMoonPhase):TDateTime; var t: extended; kk: extended; jde: extended; m,ms,f,o,e: extended; korr,w,akorr: extended; a:array[1..14] of extended; begin calc_phase_data(date,phase,jde,kk,m,ms,f,o,e); { k:=round((date-encodedate(2000,1,1))/36525.0*1236.85); } { ts:=(date-encodedate(2000,1,1))/36525.0; } { kk:=int(k)+ord(phase)/4.0; } t:=kk/1236.85; { m:=2.5534+29.10535669*kk-t*t*(0.0000218+0.00000011*t); } { ms:=201.5643+385.81693528*kk+t*t*(0.1017438+t*(0.00001239-t*0.000000058)); } { f:= 160.7108+390.67050274*kk-t*t*(0.0016341+t*(0.00000227-t*0.000000011)); } { o:=124.7746-1.56375580*kk+t*t*(0.0020691+t*0.00000215); } { e:=1-ts*(0.002516+ts*0.0000074); } case phase of (*@/// Newmoon: *) Newmoon: begin korr:= -0.40720*sin_d(ms) +0.17241*e*sin_d(m) +0.01608*sin_d(2*ms) +0.01039*sin_d(2*f) +0.00739*e*sin_d(ms-m) -0.00514*e*sin_d(ms+m) +0.00208*e*e*sin_d(2*m) -0.00111*sin_d(ms-2*f) -0.00057*sin_d(ms+2*f) +0.00056*e*sin_d(2*ms+m) -0.00042*sin_d(3*ms) +0.00042*e*sin_d(m+2*f) +0.00038*e*sin_d(m-2*f) -0.00024*e*sin_d(2*ms-m) -0.00017*sin_d(o) -0.00007*sin_d(ms+2*m) +0.00004*sin_d(2*ms-2*f) +0.00004*sin_d(3*m) +0.00003*sin_d(ms+m-2*f) +0.00003*sin_d(2*ms+2*f) -0.00003*sin_d(ms+m+2*f) +0.00003*sin_d(ms-m+2*f) -0.00002*sin_d(ms-m-2*f) -0.00002*sin_d(3*ms+m) +0.00002*sin_d(4*ms); end; (*@\\\0000001701*) (*@/// FirstQuarter,LastQuarter: *) FirstQuarter,LastQuarter: begin korr:= -0.62801*sin_d(ms) +0.17172*e*sin_d(m) -0.01183*e*sin_d(ms+m) +0.00862*sin_d(2*ms) +0.00804*sin_d(2*f) +0.00454*e*sin_d(ms-m) +0.00204*e*e*sin_d(2*m) -0.00180*sin_d(ms-2*f) -0.00070*sin_d(ms+2*f) -0.00040*sin_d(3*ms) -0.00034*e*sin_d(2*ms-m) +0.00032*e*sin_d(m+2*f) +0.00032*e*sin_d(m-2*f) -0.00028*e*e*sin_d(ms+2*m) +0.00027*e*sin_d(2*ms+m) -0.00017*sin_d(o) -0.00005*sin_d(ms-m-2*f) +0.00004*sin_d(2*ms+2*f) -0.00004*sin_d(ms+m+2*f) +0.00004*sin_d(ms-2*m) +0.00003*sin_d(ms+m-2*f) +0.00003*sin_d(3*m) +0.00002*sin_d(2*ms-2*f) +0.00002*sin_d(ms-m+2*f) -0.00002*sin_d(3*ms+m); w:=0.00306-0.00038*e*cos_d(m) +0.00026*cos_d(ms) -0.00002*cos_d(ms-m) +0.00002*cos_d(ms+m) +0.00002*cos_d(2*f); if phase = FirstQuarter then begin korr:=korr+w; end else begin korr:=korr-w; end; end; (*@\\\*) (*@/// Fullmoon: *) Fullmoon: begin korr:= -0.40614*sin_d(ms) +0.17302*e*sin_d(m) +0.01614*sin_d(2*ms) +0.01043*sin_d(2*f) +0.00734*e*sin_d(ms-m) -0.00515*e*sin_d(ms+m) +0.00209*e*e*sin_d(2*m) -0.00111*sin_d(ms-2*f) -0.00057*sin_d(ms+2*f) +0.00056*e*sin_d(2*ms+m) -0.00042*sin_d(3*ms) +0.00042*e*sin_d(m+2*f) +0.00038*e*sin_d(m-2*f) -0.00024*e*sin_d(2*ms-m) -0.00017*sin_d(o) -0.00007*sin_d(ms+2*m) +0.00004*sin_d(2*ms-2*f) +0.00004*sin_d(3*m) +0.00003*sin_d(ms+m-2*f) +0.00003*sin_d(2*ms+2*f) -0.00003*sin_d(ms+m+2*f) +0.00003*sin_d(ms-m+2*f) -0.00002*sin_d(ms-m-2*f) -0.00002*sin_d(3*ms+m) +0.00002*sin_d(4*ms); end; (*@\\\*) (*@/// else *) else korr:=0; (* Delphi 2 shut up! *) (*@\\\*) end; (*@/// Additional Corrections due to planets *) a[1]:=299.77+0.107408*kk-0.009173*t*t; a[2]:=251.88+0.016321*kk; a[3]:=251.83+26.651886*kk; a[4]:=349.42+36.412478*kk; a[5]:= 84.66+18.206239*kk; a[6]:=141.74+53.303771*kk; a[7]:=207.14+2.453732*kk; a[8]:=154.84+7.306860*kk; a[9]:= 34.52+27.261239*kk; a[10]:=207.19+0.121824*kk; a[11]:=291.34+1.844379*kk; a[12]:=161.72+24.198154*kk; a[13]:=239.56+25.513099*kk; a[14]:=331.55+3.592518*kk; akorr:= +0.000325*sin_d(a[1]) +0.000165*sin_d(a[2]) +0.000164*sin_d(a[3]) +0.000126*sin_d(a[4]) +0.000110*sin_d(a[5]) +0.000062*sin_d(a[6]) +0.000060*sin_d(a[7]) +0.000056*sin_d(a[8]) +0.000047*sin_d(a[9]) +0.000042*sin_d(a[10]) +0.000040*sin_d(a[11]) +0.000037*sin_d(a[12]) +0.000035*sin_d(a[13]) +0.000023*sin_d(a[14]); korr:=korr+akorr; (*@\\\*) nextphase:=delphi_date(jde+korr); end; (*@\\\0000001D0E*) (*@/// function last_phase(date:TDateTime; phase:TMoonPhase):TDateTime; *) function last_phase(date:TDateTime; phase:TMoonPhase):TDateTime; var temp_date: TDateTime; begin temp_date:=date+28; result:=temp_date; while result>date do begin result:=nextphase(temp_date,phase); temp_date:=temp_date-28; end; end; (*@\\\0000000303*) (*@/// function next_phase(date:TDateTime; phase:TMoonPhase):TDateTime; *) function next_phase(date:TDateTime; phase:TMoonPhase):TDateTime; var temp_date: TDateTime; begin temp_date:=date-28; result:=temp_date; while result<date do begin result:=nextphase(temp_date,phase); temp_date:=temp_date+28; end; end; (*@\\\0000000201*) (*@/// function moon_phase_angle(date: TDateTime):extended; *) { Based upon Chapter 46 of Meeus } function moon_phase_angle(date: TDateTime):extended; var sun_coord,moon_coord: t_coord; phi,i: extended; begin sun_coord:=sun_coordinate(date); moon_coord:=moon_coordinate(date); phi:=arccos(cos_d(moon_coord.latitude) *cos_d(moon_coord.longitude-sun_coord.longitude)); i:=arctan(sun_coord.radius*sin(phi)/ (moon_coord.radius-sun_coord.radius*cos(phi))); if i<0 then result:=i/pi*180+180 else result:=i/pi*180; if put_in_360(moon_coord.longitude-sun_coord.longitude)>180 then result:=-result; end; (*@\\\*) (*@/// function age_of_moon(date: TDateTime):extended; *) function age_of_moon(date: TDateTime):extended; var sun_coord,moon_coord: t_coord; begin sun_coord:=sun_coordinate(date); moon_coord:=moon_coordinate(date); result:=put_in_360(moon_coord.longitude-sun_coord.longitude)/360*mean_lunation; end; (*@\\\*) (*@/// function current_phase(date:TDateTime):extended; *) function current_phase(date:TDateTime):extended; begin result:=(1+cos_d(moon_phase_angle(date)))/2; end; (*@\\\0000000301*) (*@/// function lunation(date:TDateTime):integer; *) function lunation(date:TDateTime):integer; begin result:=round((last_phase(date,NewMoon)-delphi_date(2423436))/mean_lunation)+1; end; (*@\\\0000000301*) { The distances } (*@/// function sun_distance(date: TDateTime): extended; // AU *) function sun_distance(date: TDateTime): extended; begin result:=sun_coordinate(date).radius/au; end; (*@\\\0000000301*) (*@/// function moon_distance(date: TDateTime): extended; // km *) function moon_distance(date: TDateTime): extended; begin result:=moon_coordinate(date).radius; end; (*@\\\0000000301*) { The angular diameter (which is 0.5 of the subtent in moontool) } (*@/// function sun_diameter(date:TDateTime):extended; // angular seconds *) function sun_diameter(date:TDateTime):extended; begin result:=959.63/(sun_coordinate(date).radius/au)*2; end; (*@\\\0000000335*) (*@/// function moon_diameter(date:TDateTime):extended; // angular seconds *) function moon_diameter(date:TDateTime):extended; begin result:=358473400/moon_coordinate(date).radius*2; end; (*@\\\0000000334*) { Perigee and Apogee } (*@/// function nextXXXgee(date:TDateTime; apo: boolean):TDateTime; *) function nextXXXgee(date:TDateTime; apo: boolean):TDateTime; const (*@/// arg_apo:array[0..31,0..2] of shortint = (..); *) arg_apo:array[0..31,0..2] of shortint = ( { D F M } ( 2, 0, 0), ( 4, 0, 0), ( 0, 0, 1), ( 2, 0,-1), ( 0, 2, 0), ( 1, 0, 0), ( 6, 0, 0), ( 4, 0,-1), ( 2, 2, 0), ( 1, 0, 1), ( 8, 0, 0), ( 6, 0,-1), ( 2,-2, 0), ( 2, 0,-2), ( 3, 0, 0), ( 4, 2, 0), ( 8, 0,-1), ( 4, 0,-2), (10, 0, 0), ( 3, 0, 1), ( 0, 0, 2), ( 2, 0, 1), ( 2, 0, 2), ( 6, 2, 0), ( 6, 0,-2), (10, 0,-1), ( 5, 0, 0), ( 4,-2, 0), ( 0, 2, 1), (12, 0, 0), ( 2, 2,-1), ( 1, 0,-1) ); (*@\\\0000002201*) (*@/// arg_per:array[0..59,0..2] of shortint = (..); *) arg_per:array[0..59,0..2] of shortint = ( { D F M } ( 2, 0, 0), ( 4, 0, 0), ( 6, 0, 0), ( 8, 0, 0), ( 2, 0,-1), ( 0, 0, 1), (10, 0, 0), ( 4, 0,-1), ( 6, 0,-1), (12, 0, 0), ( 1, 0, 0), ( 8, 0,-1), (14, 0, 0), ( 0, 2, 0), ( 3, 0, 0), (10, 0,-1), (16, 0, 0), (12, 0,-1), ( 5, 0, 0), ( 2, 2, 0), (18, 0, 0), (14, 0,-1), ( 7, 0, 0), ( 2, 1, 0), (20, 0, 0), ( 1, 0, 1), (16, 0,-1), ( 4, 0, 1), ( 2, 0,-2), ( 4, 0,-2), ( 6, 0,-2), (22, 0, 0), (18, 0,-1), ( 6, 0, 1), (11, 0, 0), ( 8, 0, 1), ( 4,-2, 0), ( 6, 2, 0), ( 3, 0, 1), ( 5, 0, 1), (13, 0, 0), (20, 0,-1), ( 3, 0, 2), ( 4, 2,-2), ( 1, 0, 2), (22, 0,-1), ( 0, 4, 0), ( 6,-2, 0), ( 2,-2, 1), ( 0, 0, 2), ( 0, 2,-1), ( 2, 4, 0), ( 0, 2,-2), ( 2,-2, 2), (24, 0, 0), ( 4,-4, 0), ( 9, 0, 0), ( 4, 2, 0), ( 2, 0, 2), ( 1, 0,-1) ); (*@\\\*) (*@/// koe_apo:array[0..31,0..1] of longint = (..); *) koe_apo:array[0..31,0..1] of longint = ( { 1 T } ( 4392, 0), ( 684, 0), ( 456,-11), ( 426,-11), ( 212, 0), ( -189, 0), ( 144, 0), ( 113, 0), ( 47, 0), ( 36, 0), ( 35, 0), ( 34, 0), ( -34, 0), ( 22, 0), ( -17, 0), ( 13, 0), ( 11, 0), ( 10, 0), ( 9, 0), ( 7, 0), ( 6, 0), ( 5, 0), ( 5, 0), ( 4, 0), ( 4, 0), ( 4, 0), ( -4, 0), ( -4, 0), ( 3, 0), ( 3, 0), ( 3, 0), ( -3, 0) ); (*@\\\0000001501*) (*@/// koe_per:array[0..59,0..1] of longint = (..); *) koe_per:array[0..59,0..1] of longint = ( { 1 T } (-16769, 0), ( 4589, 0), ( -1856, 0), ( 883, 0), ( -773, 19), ( 502,-13), ( -460, 0), ( 422,-11), ( -256, 0), ( 253, 0), ( 237, 0), ( 162, 0), ( -145, 0), ( 129, 0), ( -112, 0), ( -104, 0), ( 86, 0), ( 69, 0), ( 66, 0), ( -53, 0), ( -52, 0), ( -46, 0), ( -41, 0), ( 40, 0), ( 32, 0), ( -32, 0), ( 31, 0), ( -29, 0), ( -27, 0), ( 24, 0), ( -21, 0), ( -21, 0), ( -21, 0), ( 19, 0), ( -18, 0), ( -14, 0), ( -14, 0), ( -14, 0), ( 14, 0), ( -14, 0), ( 13, 0), ( 13, 0), ( 11, 0), ( -11, 0), ( -10, 0), ( -9, 0), ( -8, 0), ( 8, 0), ( 8, 0), ( 7, 0), ( 7, 0), ( 7, 0), ( -6, 0), ( -6, 0), ( 6, 0), ( 5, 0), ( 27, 0), ( 27, 0), ( 5, 0), ( -4, 0) ); (*@\\\0000000410*) var k, jde, t: extended; d,m,f,v: extended; i: integer; begin k:=round(((date-encodedate(1999,1,1))/365.25-0.97)*13.2555); if apo then k:=k+0.5; t:=k/1325.55; jde:=2451534.6698+27.55454988*k+(-0.0006886+ (-0.000001098+0.0000000052*t)*t)*t*t; d:=171.9179+335.9106046*k+(-0.0100250+(-0.00001156+0.000000055*t)*t)*t*t; m:=347.3477+27.1577721*k+(-0.0008323-0.0000010*t)*t*t; f:=316.6109+364.5287911*k+(-0.0125131-0.0000148*t)*t*t; v:=0; if apo then for i:=0 to 31 do v:=v+sin_d(arg_apo[i,0]*d+arg_apo[i,1]*f+arg_apo[i,2]*m)* (koe_apo[i,0]*0.0001+koe_apo[i,1]*0.00001*t) else for i:=0 to 59 do v:=v+sin_d(arg_per[i,0]*d+arg_per[i,1]*f+arg_per[i,2]*m)* (koe_per[i,0]*0.0001+koe_per[i,1]*0.00001*t); result:=delphi_date(jde+v); end; (*@\\\0000001836*) (*@/// function nextperigee(date:TDateTime):TDateTime; *) function nextperigee(date:TDateTime):TDateTime; var temp_date: TDateTime; begin temp_date:=date-28; result:=temp_date; while result<date do begin result:=nextXXXgee(temp_date,false); temp_date:=temp_date+28; end; end; (*@\\\*) (*@/// function nextapogee(date:TDateTime):TDateTime; *) function nextapogee(date:TDateTime):TDateTime; var temp_date: TDateTime; begin temp_date:=date-28; result:=temp_date; while result<date do begin result:=nextXXXgee(temp_date,true); temp_date:=temp_date+28; end; end; (*@\\\0000000801*) { The seasons } (*@/// function StartSeason(year: integer; season:TSeason):TDateTime; // maximum error 51 seconds *) { Based upon chapter 26 of Meeus } function StartSeason(year: integer; season:TSeason):TDateTime; var y: extended; jde0: extended; t, w, dl, s: extended; i: integer; const (*@/// a: array[0..23] of integer = (..); *) a: array[0..23] of integer = ( 485, 203, 199, 182, 156, 136, 77, 74, 70, 58, 52, 50, 45, 44, 29, 18, 17, 16, 14, 12, 12, 12, 9, 8 ); (*@\\\000000010F*) (*@/// bc:array[0..23,1..2] of extended = (..); *) bc:array[0..23,1..2] of extended = ( ( 324.96, 1934.136 ), ( 337.23, 32964.467 ), ( 342.08, 20.186 ), ( 27.85, 445267.112 ), ( 73.14, 45036.886 ), ( 171.52, 22518.443 ), ( 222.54, 65928.934 ), ( 296.72, 3034.906 ), ( 243.58, 9037.513 ), ( 119.81, 33718.147 ), ( 297.17, 150.678 ), ( 21.02, 2281.226 ), ( 247.54, 29929.562 ), ( 325.15, 31555.956 ), ( 60.93, 4443.417 ), ( 155.12, 67555.328 ), ( 288.79, 4562.452 ), ( 198.04, 62894.029 ), ( 199.76, 31436.921 ), ( 95.39, 14577.848 ), ( 287.11, 31931.756 ), ( 320.81, 34777.259 ), ( 227.73, 1222.114 ), ( 15.45, 16859.074 ) ); (*@\\\0000001901*) begin case year of (*@/// -1000..+999: *) -1000..+999: begin y:=year/1000; case season of spring: jde0:=1721139.29189+(365242.13740+( 0.06134+( 0.00111-0.00071*y)*y)*y)*y; summer: jde0:=1721223.25401+(365241.72562+(-0.05323+( 0.00907+0.00025*y)*y)*y)*y; autumn: jde0:=1721325.70455+(365242.49558+(-0.11677+(-0.00297+0.00074*y)*y)*y)*y; winter: jde0:=1721414.39987+(365242.88257+(-0.00769+(-0.00933-0.00006*y)*y)*y)*y; else jde0:=0; (* this can't happen *) end; end; (*@\\\0000000801*) (*@/// +1000..+3000: *) +1000..+3000: begin y:=(year-2000)/1000; case season of spring: jde0:=2451623.80984+(365242.37404+( 0.05169+(-0.00411-0.00057*y)*y)*y)*y; summer: jde0:=2451716.56767+(365241.62603+( 0.00325+( 0.00888-0.00030*y)*y)*y)*y; autumn: jde0:=2451810.21715+(365242.01767+(-0.11575+( 0.00337+0.00078*y)*y)*y)*y; winter: jde0:=2451900.05952+(365242.74049+(-0.06223+(-0.00823+0.00032*y)*y)*y)*y; else jde0:=0; (* this can't happen *) end; end; (*@\\\0000000901*) else raise E_OutOfAlgorithRange.Create('Out of range of the algorithm'); end; t:=(jde0-2451545.0)/36525; w:=35999.373*t-2.47; dl:=1+0.0334*cos_d(w)+0.0007*cos_d(2*w); (*@/// s := ä a cos(b+c*t) *) s:=0; for i:=0 to 23 do s:=s+a[i]*cos_d(bc[i,1]+bc[i,2]*t); (*@\\\0000000301*) result:=delphi_date(jde0+(0.00001*s)/dl); end; (*@\\\0000001001*) { Rising and setting of moon and sun } (*@/// function Calc_Set_Rise(date:TDateTime; latitude, longitude:extended; *) { Based upon chapter 14 of Meeus } function Calc_Set_Rise(date:TDateTime; latitude, longitude:extended; sun: boolean; kind: T_RiseSet):TDateTime; var h: Extended; pos1, pos2, pos3: t_coord; h0, theta0, cos_h0, cap_h0: extended; m0,m1,m2: extended; (*@/// function interpolation(y1,y2,y3,n: extended):extended; *) function interpolation(y1,y2,y3,n: extended):extended; var a,b,c: extended; begin a:=y2-y1; b:=y3-y2; if a>100 then a:=a-360; if a<-100 then a:=a+360; if b>100 then b:=b-360; if b<-100 then b:=b+360; c:=b-a; result:=y2+0.5*n*(a+b+n*c); end; (*@\\\0000000A09*) (*@/// function correction(m:extended; kind:integer):extended; *) function correction(m:extended; kind:integer):extended; var alpha,delta,h, height: extended; begin alpha:=interpolation(pos1.rektaszension, pos2.rektaszension, pos3.rektaszension, m); delta:=interpolation(pos1.declination, pos2.declination, pos3.declination, m); h:=put_in_360((theta0+360.985647*m)-longitude-alpha); if h>180 then h:=h-360; height:=arcsin_d(sin_d(latitude)*sin_d(delta) +cos_d(latitude)*cos_d(delta)*cos_d(h)); case kind of 0: result:=-h/360; 1,2: result:=(height-h0)/(360*cos_d(delta)*cos_d(latitude)*sin_d(h)); else result:=0; (* this cannot happen *) end; end; (*@\\\0000001501*) begin if sun then h0:=-0.8333 else begin pos1:=moon_coordinate(date); correct_position(pos1,date,latitude,longitude,0); h0:=0.7275*pos1.parallax-34/60; end; h:=int(date); theta0:=star_time(h); if sun then begin pos1:=sun_coordinate(h-1); pos2:=sun_coordinate(h); pos3:=sun_coordinate(h+1); end else begin pos1:=moon_coordinate(h-1); correct_position(pos1,h-1,latitude,longitude,0); pos2:=moon_coordinate(h); correct_position(pos2,h,latitude,longitude,0); pos3:=moon_coordinate(h+1); correct_position(pos3,h+1,latitude,longitude,0); end; cos_h0:=(sin_d(h0)-sin_d(latitude)*sin_d(pos2.declination))/ (cos_d(latitude)*cos_d(pos2.declination)); if (cos_h0<-1) or (cos_h0>1) then raise E_NoRiseSet.Create('No rises or sets calculable'); cap_h0:=arccos_d(cos_h0); m0:=(pos2.rektaszension+longitude-theta0)/360; m1:=m0-cap_h0/360; m2:=m0+cap_h0/360; m0:=frac(m0); if m0<0 then m0:=m0+1; m1:=frac(m1); if m1<0 then m1:=m1+1; m2:=frac(m2); if m2<0 then m2:=m2+1; m0:=m0+correction(m0,0); m1:=m1+correction(m1,1); m2:=m2+correction(m2,2); case kind of _rise: result:=h+m1; _set: result:=h+m2; _transit: result:=h+m0; else result:=0; (* this can't happen *) end; end; (*@\\\0000000701*) (*@/// function Sun_Rise(date:TDateTime; latitude, longitude:extended):TDateTime; *) function Sun_Rise(date:TDateTime; latitude, longitude:extended):TDateTime; begin result:=Calc_Set_Rise(date,latitude,longitude,true,_rise); end; (*@\\\000000033B*) (*@/// function Sun_Set(date:TDateTime; latitude, longitude:extended):TDateTime; *) function Sun_Set(date:TDateTime; latitude, longitude:extended):TDateTime; begin result:=Calc_Set_Rise(date,latitude,longitude,true,_set); end; (*@\\\000000033A*) (*@/// function Sun_Transit(date:TDateTime; latitude, longitude:extended):TDateTime; *) function Sun_Transit(date:TDateTime; latitude, longitude:extended):TDateTime; begin result:=Calc_Set_Rise(date,latitude,longitude,true,_transit); end; (*@\\\0000000301*) (*@/// function Moon_Rise(date:TDateTime; latitude, longitude:extended):TDateTime; *) function Moon_Rise(date:TDateTime; latitude, longitude:extended):TDateTime; begin result:=Calc_Set_Rise(date,latitude,longitude,false,_rise); end; (*@\\\000000033C*) (*@/// function Moon_Set(date:TDateTime; latitude, longitude:extended):TDateTime; *) function Moon_Set(date:TDateTime; latitude, longitude:extended):TDateTime; begin result:=Calc_Set_Rise(date,latitude,longitude,false,_set); end; (*@\\\000000033B*) (*@/// function Moon_Transit(date:TDateTime; latitude, longitude:extended):TDateTime; *) function Moon_Transit(date:TDateTime; latitude, longitude:extended):TDateTime; begin result:=Calc_Set_Rise(date,latitude,longitude,false,_transit); end; (*@\\\000000033F*) { Checking for eclipses } (*@/// function Eclipse(var date:TDateTime; sun:boolean):TEclipse; *) function Eclipse(var date:TDateTime; sun:boolean):TEclipse; var jde,kk,m,ms,f,o,e: extended; t,f1,a1: extended; p,q,w,gamma,u: extended; begin if sun then calc_phase_data(date,NewMoon,jde,kk,m,ms,f,o,e) else calc_phase_data(date,FullMoon,jde,kk,m,ms,f,o,e); t:=kk/1236.85; if abs(sin_d(f))>0.36 then result:=none (*@/// else *) else begin f1:=f-0.02665*sin_d(o); a1:=299.77+0.107408*kk-0.009173*t*t; if sun then jde:=jde - 0.4075 * sin_d(ms) + 0.1721 * e * sin_d(m) else jde:=jde - 0.4065 * sin_d(ms) + 0.1727 * e * sin_d(m); jde:=jde + 0.0161 * sin_d(2*ms) - 0.0097 * sin_d(2*f1) + 0.0073 * e * sin_d(ms-m) - 0.0050 * e * sin_d(ms+m) - 0.0023 * sin_d(ms-2*f1) + 0.0021 * e * sin_d(2*m) + 0.0012 * sin_d(ms+2*f1) + 0.0006 * e * sin_d(2*ms+m) - 0.0004 * sin_d(3*ms) - 0.0003 * e * sin_d(m+2*f1) + 0.0003 * sin_d(a1) - 0.0002 * e * sin_d(m-2*f1) - 0.0002 * e * sin_d(2*ms-m) - 0.0002 * sin_d(o); p:= + 0.2070 * e * sin_d(m) + 0.0024 * e * sin_d(2*m) - 0.0392 * sin_d(ms) + 0.0116 * sin_d(2*ms) - 0.0073 * e * sin_d(ms+m) + 0.0067 * e * sin_d(ms-m) + 0.0118 * sin_d(2*f1); q:= + 5.2207 - 0.0048 * e * cos_d(m) + 0.0020 * e * cos_d(2*m) - 0.3299 * cos_d(ms) - 0.0060 * e * cos_d(ms+m) + 0.0041 * e * cos_d(ms-m); w:=abs(cos_d(f1)); gamma:=(p*cos_d(f1)+q*sin_d(f1))*(1-0.0048*w); u:= + 0.0059 + 0.0046 * e * cos_d(m) - 0.0182 * cos_d(ms) + 0.0004 * cos_d(2*ms) - 0.0005 * cos_d(m+ms); (*@/// if sun then *) if sun then begin if abs(gamma)<0.9972 then begin if u<0 then result:=total else if u>0.0047 then result:=circular else if u<0.00464*sqrt(1-gamma*gamma) then result:=circulartotal else result:=circular; end else if abs(gamma)>1.5433+u then result:=none else if abs(gamma)<0.9972+abs(u) then result:=noncentral else result:=partial; end (*@\\\*) (*@/// else *) else begin if (1.0128 - u - abs(gamma)) / 0.5450 > 0 then result:=total else if (1.5573 + u - abs(gamma)) / 0.5450 > 0 then result:=halfshadow else result:=none; end; (*@\\\0000000801*) end; (*@\\\*) date:=delphi_date(jde); end; (*@\\\0000000E01*) (*@/// function NextEclipse(var date:TDateTime; sun:boolean):TEclipse; *) function NextEclipse(var date:TDateTime; sun:boolean):TEclipse; var temp_date: TDateTime; begin result:=none; (* just to make Delphi 2/3 shut up, not needed really *) temp_date:=date-28*2; while temp_date<date do begin temp_date:=temp_date+28; result:=Eclipse(temp_date,sun); end; date:=temp_date; end; (*@\\\003C000501000501000503000509000B01*) end.
unit Globals; //sourceforge.net/projects/dclx interface uses Classes, SysUtils, Windows, Messages, Guide, RulersWnd; var isControl: boolean; running: boolean; mainWnd: TRulersWnd; sizeHCursor, sizeVCursor: HCURSOR; displayMode: integer; procedure Init; procedure Run; procedure AddGuide(g: TGuide); procedure RemoveGuide(g: TGuide); procedure RemoveAllGuides(); procedure BringToFrontAll(); procedure DumpGuides(list: TStringList); function GetDistance(g: TGuide): integer; procedure NotifyAll(); implementation uses AlphaWnd; type KBDLLHOOKSTRUCT = record vkCode: DWORD; scanCode: DWORD; flags: DWORD; time: DWORD; dwExtraInfo: LongWord; end; LPKBDLLHOOKSTRUCT = ^KBDLLHOOKSTRUCT; TGuideArray = array of TGuide; PGuideArray = ^TGuideArray; const WH_KEYBOARD_LL = 13; var HOOK: HHOOK; vGuides, hGuides: TGuideArray; procedure AddGuide(g: TGuide); var i: integer; l: PGuideArray; begin if g.Vertical then l:=@vGuides else l:=@hGuides; i:=Length(l^); SetLength(l^, i + 1); l^[i]:=g; g.Show(); end; procedure doRemoveGuide(g: TGuide; allGuides: PGuideArray); var i, c: integer; begin for i:=0 to Length(allGuides^) - 1 do begin if allGuides^[i] = g then begin c := Length(allGuides^) - 1; allGuides^[i] := allGuides^[c]; SetLength(allGuides^, c); g.Hide; g.Free(); end; end; end; procedure RemoveGuide(g: TGuide); begin if g.Vertical then doRemoveGuide(g, @vGuides) else doRemoveGuide(g, @hGuides); end; procedure RemoveAllGuides(); var i: integer; begin for i:=0 to Length(vGuides) - 1 do begin vGuides[i].Hide; vGuides[i].Free(); end; SetLength(vGuides, 0); for i:=0 to Length(hGuides) - 1 do begin hGuides[i].Hide; hGuides[i].Free(); end; SetLength(hGuides, 0); end; procedure DumpGuides(list: TStringList); var i: integer; begin for i := 0 to Length(hGuides) - 1 do list.Add('H' + IntToStr(i) + '=' + IntToStr(hGuides[i].Top)); for i := 0 to Length(vGuides) - 1 do list.Add('V' + IntToStr(i) + '=' + IntToStr(vGuides[i].Left)); end; function GetDistance(g: TGuide): integer; var i: integer; l: PGuideArray; begin Result:=-2; if g.Vertical then begin l:=@vGuides; for i:=0 to Length(l^) - 1 do if (l^[i].Left < g.Left) and (l^[i].Left > Result) then Result:=l^[i].Left; end else begin l:=@hGuides; for i:=0 to Length(l^) - 1 do if (l^[i].Top < g.Top) and (l^[i].Top > Result) then Result:=l^[i].Top; end; end; procedure BringToFrontAll(); var i: integer; begin for i:=0 to Length(vGuides) - 1 do SetForegroundWindow(vGuides[i].Handle); for i:=0 to Length(hGuides) - 1 do SetForegroundWindow(hGuides[i].Handle); SetForegroundWindow(mainWnd.Handle); {SetWindowPos(mainWnd.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE); } end; procedure NotifyAll(); var i: integer; begin for i:=0 to Length(vGuides) - 1 do vGuides[i].Notify(); for i:=0 to Length(hGuides) - 1 do hGuides[i].Notify(); end; // Keyboard Hook function LowLevelKeyboardProc(nCode: integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; var pkb: LPKBDLLHOOKSTRUCT; i: integer; begin try pkb:=LPKBDLLHOOKSTRUCT(lParam); if pkb.vkCode = 162 then if isControl <> (wParam = WM_KEYDOWN) then begin isControl:= wParam = WM_KEYDOWN; //WM_SYSKEYDOWN NotifyAll(); //MessageBox(0, PChar(BoolToStr(isControl, true)), nil, 0); end; Result:=CallNextHookEx(HOOK, nCode, wParam, lParam); except Result:=CallNextHookEx(HOOK, nCode, wParam, lParam); MessageBeep(MB_ICONSTOP); end; end; function ProcessMessage: boolean; var AMessage: TMsg; begin Result:=False; if PeekMessage(AMessage, 0, 0, 0, PM_REMOVE) then begin if AMessage.Message <> WM_QUIT then begin TranslateMessage(AMessage); DispatchMessage(AMessage); end else running:=False; Result:=True; end; end; procedure Init; begin sizeHCursor:=LoadCursor(HInstance, 'SIZEH'); sizeVCursor:=LoadCursor(HInstance, 'SIZEV'); isControl:=false; HOOK:=SetWindowsHookEx(WH_KEYBOARD_LL, @LowLevelKeyboardProc, hinstance, 0); running:=true; mainWnd:=TRulersWnd.Create(); mainWnd.Show(); end; procedure Run; begin while running do if not ProcessMessage then WaitMessage; if HOOK <> 0 then UnhookWindowsHookEx(HOOK); mainWnd.Free(); end; end.
unit URelatorioDesenho; interface uses Windows, SysUtils, Messages, Classes, Graphics, Controls, QuickRpt, QRPrntr, QRCtrls, DBClient, QRPDFFilt, DB; type TTipoShape = (tsLinha, tsRetangulo); TDesenho = class(TObject) private fComponenteParent: TWinControl; fRelatorioParent: TWinControl; procedure RedimensionarParent(Componente: TWinControl); procedure VerificaParent; procedure VerificaField(ANomeField: String; ADataSet: TDataSet); public property ComponenteParent: TWinControl read fComponenteParent write fComponenteParent; property RelatorioParent: TWinControl read fRelatorioParent write fRelatorioParent; procedure AdicionarCampoDBLabel(NomeField: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); procedure AdicionarCampoLabel(Texto: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); procedure AdicionarIncrementoAlturaBand(IncrementoAltura: Integer); procedure AdicionarShape(TipoShape: TTipoShape; Linha, Coluna, Comprimento, Altura: Integer); procedure ConfigurarCampoLabel(var Componente: TQRCustomLabel; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); constructor Create(ARelatorioParent, AComponenteParent: TWinControl); destructor Destroy; override; end; implementation uses StrUtils; { TDesenho } constructor TDesenho.Create(ARelatorioParent, AComponenteParent: TWinControl); begin fRelatorioParent := ARelatorioParent; fComponenteParent := AComponenteParent; end; destructor TDesenho.Destroy; begin fComponenteParent := nil; fRelatorioParent := nil; inherited; end; procedure TDesenho.ConfigurarCampoLabel(var Componente: TQRCustomLabel; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); begin VerificaParent(); Componente.Parent := ComponenteParent; Componente.Left := Coluna; Componente.Top := Linha; Componente.Font.Size := TamanhoFonte; Componente.Width := TamanhoMaxTexto; Componente.AutoSize := False; if (TamanhoMaxTexto = 0) then Componente.AutoSize := True; RedimensionarParent(Componente); end; procedure TDesenho.AdicionarCampoLabel(Texto: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); var Componente: TQRCustomLabel; begin VerificaParent(); Componente := TQRLabel.Create(RelatorioParent); TQRLabel(Componente).Transparent := True; TQRLabel(Componente).Caption := Texto; ConfigurarCampoLabel(Componente, Linha, Coluna, TamanhoMaxTexto, TamanhoFonte); end; procedure TDesenho.AdicionarCampoDBLabel(NomeField: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); var Componente: TQRCustomLabel; begin VerificaParent(); Componente := TQRDBText.Create(RelatorioParent); TQRDBText(Componente).Transparent := True; if (ComponenteParent.ClassType = TQRSubDetail) then TQRDBText(Componente).DataSet := TQRSubDetail(ComponenteParent).DataSet else if (ComponenteParent.ClassType = TQRBand) or (ComponenteParent.ClassType = TQRChildBand) then TQRDBText(Componente).DataSet := TQuickRep(RelatorioParent).DataSet else raise Exception.CreateFmt('Não identificado Parent para adicionar campo DBLabel %S', [NomeField]); TQRDBText(Componente).DataField := NomeField; VerificaField(TQRDBText(Componente).DataField, TQRDBText(Componente).DataSet); ConfigurarCampoLabel(Componente, Linha, Coluna, TamanhoMaxTexto, TamanhoFonte); end; procedure TDesenho.AdicionarShape(TipoShape: TTipoShape; Linha, Coluna, Comprimento, Altura: Integer); var Componente: TQRShape; begin VerificaParent(); Componente := TQRShape.Create(RelatorioParent); case TipoShape of tsLinha: Componente.Shape := qrsHorLine; tsRetangulo: Componente.Shape := qrsRectangle; end; Componente.Pen.Style := psDot; { linha tracejada } Componente.Parent := ComponenteParent; Componente.Left := Coluna; Componente.Top := Linha; Componente.Width := Comprimento; Componente.Height := Altura; if (Comprimento = 0) then Componente.Width := ComponenteParent.Width - Coluna; if (Altura <= 0) then raise Exception.Create('Obrigatório Informar Altura'); RedimensionarParent(Componente); end; procedure TDesenho.RedimensionarParent(Componente: TWinControl); { Result := TWinControl(FindComponent(NomeComponente)); } var TamanhoOcupadoComponente: Integer; begin VerificaParent(); TamanhoOcupadoComponente := Componente.Top + Componente.Height; if (ComponenteParent.Height < TamanhoOcupadoComponente) then ComponenteParent.Height := TamanhoOcupadoComponente; end; procedure TDesenho.AdicionarIncrementoAlturaBand(IncrementoAltura: Integer); begin VerificaParent(); TQRCustomBand(ComponenteParent).Height := TQRCustomBand(ComponenteParent).Height + IncrementoAltura; end; procedure TDesenho.VerificaParent(); begin if (RelatorioParent = nil) then raise Exception.Create('Relatório Parent não informado'); if (ComponenteParent = nil) then raise Exception.Create('Componente Parent não informado'); end; procedure TDesenho.VerificaField(ANomeField: String; ADataSet: TDataSet); begin if (ADataSet.FindField(ANomeField) = nil) then raise Exception.CreateFmt('Campo %S não existe no DataSet %S', [ANomeField, ADataSet.Name]); end; end.
unit CommonProgressForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls; type TfrmProgress = class(TForm) prg: TProgressBar; private function GetMax: integer; function GetMin: integer; procedure SetMax(const Value: integer); procedure SetMin(const Value: integer); { Private declarations } public { Public declarations } property Min: integer read GetMin write SetMin; property Max: integer read GetMax write SetMax; procedure StepIt; end; var frmProgress: TfrmProgress; implementation {$R *.dfm} { TfrmProgress } function TfrmProgress.GetMax: integer; begin Result := prg.Max; end; function TfrmProgress.GetMin: integer; begin Result := prg.Max; end; procedure TfrmProgress.SetMax(const Value: integer); begin prg.Max := Value; end; procedure TfrmProgress.SetMin(const Value: integer); begin prg.Min := Value; end; procedure TfrmProgress.StepIt; begin prg.StepIt; end; end.
unit lmerrlog; interface uses lmglobal; const LOGFLAGS_FORWARD = 0; LOGFLAGS_BACKWARD = $1; LOGFLAGS_SEEK = $2; // // Generic (could be used by more than one service) // error log messages from 0 to 25 // // Do not change the comments following the manifest constants without // understanding how mapmsg works. // ERRLOG_BASE = 3100; (* NELOG errors start here *) NELOG_Internal_Error = ERRLOG_BASE + 0; (* * The operation failed because a network software error occurred. *) NELOG_Resource_Shortage = ERRLOG_BASE + 1; (* * The system ran out of a resource controlled by the %1 option. *) NELOG_Unable_To_Lock_Segment = ERRLOG_BASE + 2; (* * The service failed to obtain a long-term lock on the * segment for network control blocks (NCBs). The error code is the data. *) NELOG_Unable_To_Unlock_Segment = ERRLOG_BASE + 3; (* * The service failed to release the long-term lock on the * segment for network control blocks (NCBs). The error code is the data. *) NELOG_Uninstall_Service = ERRLOG_BASE + 4; (* * There was an error stopping service %1. * The error code from NetServiceControl is the data. *) NELOG_Init_Exec_Fail = ERRLOG_BASE + 5; (* * Initialization failed because of a system execution failure on * path %1. The system error code is the data. *) NELOG_Ncb_Error = ERRLOG_BASE + 6; (* * An unexpected network control block (NCB) was received. The NCB is the data. *) NELOG_Net_Not_Started = ERRLOG_BASE + 7; (* * The network is not started. *) NELOG_Ioctl_Error = ERRLOG_BASE + 8; (* * A DosDevIoctl or DosFsCtl to NETWKSTA.SYS failed. * The data shown is in this format: * DWORD approx CS:IP of call to ioctl or fsctl * WORD error code * WORD ioctl or fsctl number *) NELOG_System_Semaphore = ERRLOG_BASE + 9; (* * Unable to create or open system semaphore %1. * The error code is the data. *) NELOG_Init_OpenCreate_Err = ERRLOG_BASE + 10; (* * Initialization failed because of an open/create error on the * file %1. The system error code is the data. *) NELOG_NetBios = ERRLOG_BASE + 11; (* * An unexpected NetBIOS error occurred. * The error code is the data. *) NELOG_SMB_Illegal = ERRLOG_BASE + 12; (* * An illegal server message block (SMB) was received. * The SMB is the data. *) NELOG_Service_Fail = ERRLOG_BASE + 13; (* * Initialization failed because the requested service %1 * could not be started. *) NELOG_Entries_Lost = ERRLOG_BASE + 14; (* * Some entries in the error log were lost because of a buffer * overflow. *) // // Server specific error log messages from 20 to 40 // NELOG_Init_Seg_Overflow = ERRLOG_BASE + 20; (* * Initialization parameters controlling resource usage other * than net buffers are sized so that too much memory is needed. *) NELOG_Srv_No_Mem_Grow = ERRLOG_BASE + 21; (* * The server cannot increase the size of a memory segment. *) NELOG_Access_File_Bad = ERRLOG_BASE + 22; (* * Initialization failed because account file %1 is either incorrect * or not present. *) NELOG_Srvnet_Not_Started = ERRLOG_BASE + 23; (* * Initialization failed because network %1 was not started. *) NELOG_Init_Chardev_Err = ERRLOG_BASE + 24; (* * The server failed to start. Either all three chdev * parameters must be zero or all three must be nonzero. *) NELOG_Remote_API = ERRLOG_BASE + 25; (* A remote API request was halted due to the following * invalid description string: %1. *) NELOG_Ncb_TooManyErr = ERRLOG_BASE + 26; (* The network %1 ran out of network control blocks (NCBs). You may need to increase NCBs * for this network. The following information includes the * number of NCBs submitted by the server when this error occurred: *) NELOG_Mailslot_err = ERRLOG_BASE + 27; (* The server cannot create the %1 mailslot needed to send * the ReleaseMemory alert message. The error received is: *) NELOG_ReleaseMem_Alert = ERRLOG_BASE + 28; (* The server failed to register for the ReleaseMemory alert, * with recipient %1. The error code from * NetAlertStart is the data. *) NELOG_AT_cannot_write = ERRLOG_BASE + 29; (* The server cannot update the AT schedule file. The file * is corrupted. *) NELOG_Cant_Make_Msg_File = ERRLOG_BASE + 30; (* The server encountered an error when calling * NetIMakeLMFileName. The error code is the data. *) NELOG_Exec_Netservr_NoMem = ERRLOG_BASE + 31; (* Initialization failed because of a system execution failure on * path %1. There is not enough memory to start the process. * The system error code is the data. *) NELOG_Server_Lock_Failure = ERRLOG_BASE + 32; (* Longterm lock of the server buffers failed. * Check swap disk's free space and restart the system to start the server. *) // // Message service and POPUP specific error log messages from 40 to 55 // NELOG_Msg_Shutdown = ERRLOG_BASE + 40; (* * The service has stopped due to repeated consecutive * occurrences of a network control block (NCB) error. The last bad NCB follows * in raw data. *) NELOG_Msg_Sem_Shutdown = ERRLOG_BASE + 41; (* * The Message server has stopped due to a lock on the * Message server shared data segment. *) NELOG_Msg_Log_Err = ERRLOG_BASE + 50; (* * A file system error occurred while opening or writing to the * system message log file %1. Message logging has been * switched off due to the error. The error code is the data. *) NELOG_VIO_POPUP_ERR = ERRLOG_BASE + 51; (* * Unable to display message POPUP due to system VIO call error. * The error code is the data. *) NELOG_Msg_Unexpected_SMB_Type = ERRLOG_BASE + 52; (* * An illegal server message block (SMB) was received. The SMB is the data. *) // // Workstation specific error log messages from 60 to 75 // NELOG_Wksta_Infoseg = ERRLOG_BASE + 60; (* * The workstation information segment is bigger than 64K. * The size follows, in DWORD format: *) NELOG_Wksta_Compname = ERRLOG_BASE + 61; (* * The workstation was unable to get the name-number of the computer. *) NELOG_Wksta_BiosThreadFailure = ERRLOG_BASE + 62; (* * The workstation could not initialize the Async NetBIOS Thread. * The error code is the data. *) NELOG_Wksta_IniSeg = ERRLOG_BASE + 63; (* * The workstation could not open the initial shared segment. * The error code is the data. *) NELOG_Wksta_HostTab_Full = ERRLOG_BASE + 64; (* * The workstation host table is full. *) NELOG_Wksta_Bad_Mailslot_SMB = ERRLOG_BASE + 65; (* * A bad mailslot server message block (SMB) was received. The SMB is the data. *) NELOG_Wksta_UASInit = ERRLOG_BASE + 66; (* * The workstation encountered an error while trying to start the user accounts database. * The error code is the data. *) NELOG_Wksta_SSIRelogon = ERRLOG_BASE + 67; (* * The workstation encountered an error while responding to an SSI revalidation request. * The function code and the error codes are the data. *) // // Alerter service specific error log messages from 70 to 79 // NELOG_Build_Name = ERRLOG_BASE + 70; (* * The Alerter service had a problem creating the list of * alert recipients. The error code is %1. *) NELOG_Name_Expansion = ERRLOG_BASE + 71; (* * There was an error expanding %1 as a group name. Try * splitting the group into two or more smaller groups. *) NELOG_Message_Send = ERRLOG_BASE + 72; (* * There was an error sending %2 the alert message - * ( * %3 ) * The error code is %1. *) NELOG_Mail_Slt_Err = ERRLOG_BASE + 73; (* * There was an error in creating or reading the alerter mailslot. * The error code is %1. *) NELOG_AT_cannot_read = ERRLOG_BASE + 74; (* * The server could not read the AT schedule file. *) NELOG_AT_sched_err = ERRLOG_BASE + 75; (* * The server found an invalid AT schedule record. *) NELOG_AT_schedule_file_created = ERRLOG_BASE + 76; (* * The server could not find an AT schedule file so it created one. *) NELOG_Srvnet_NB_Open = ERRLOG_BASE + 77; (* * The server could not access the %1 network with NetBiosOpen. *) NELOG_AT_Exec_Err = ERRLOG_BASE + 78; (* * The AT command processor could not run %1. *) // // Cache Lazy Write and HPFS386 specific error log messages from 80 to 89 // NELOG_Lazy_Write_Err = ERRLOG_BASE + 80; (* * WARNING: Because of a lazy-write error, drive %1 now * contains some corrupted data. The cache is stopped. *) NELOG_HotFix = ERRLOG_BASE + 81; (* * A defective sector on drive %1 has been replaced (hotfixed). * No data was lost. You should run CHKDSK soon to restore full * performance and replenish the volume's spare sector pool. * * The hotfix occurred while processing a remote request. *) NELOG_HardErr_From_Server = ERRLOG_BASE + 82; (* * A disk error occurred on the HPFS volume in drive %1. * The error occurred while processing a remote request. *) NELOG_LocalSecFail1 = ERRLOG_BASE + 83; (* * The user accounts database (NET.ACC) is corrupted. The local security * system is replacing the corrupted NET.ACC with the backup * made at %1. * Any updates made to the database after this time are lost. * *) NELOG_LocalSecFail2 = ERRLOG_BASE + 84; (* * The user accounts database (NET.ACC) is missing. The local * security system is restoring the backup database * made at %1. * Any updates made to the database made after this time are lost. * *) NELOG_LocalSecFail3 = ERRLOG_BASE + 85; (* * Local security could not be started because the user accounts database * (NET.ACC) was missing or corrupted, and no usable backup * database was present. * * THE SYSTEM IS NOT SECURE. *) NELOG_LocalSecGeneralFail = ERRLOG_BASE + 86; (* * Local security could not be started because an error * occurred during initialization. The error code returned is %1. * * THE SYSTEM IS NOT SECURE. * *) // // NETWKSTA.SYS specific error log messages from 90 to 99 // NELOG_NetWkSta_Internal_Error = ERRLOG_BASE + 90; (* * A NetWksta internal error has occurred: * %1 *) NELOG_NetWkSta_No_Resource = ERRLOG_BASE + 91; (* * The redirector is out of a resource: %1. *) NELOG_NetWkSta_SMB_Err = ERRLOG_BASE + 92; (* * A server message block (SMB) error occurred on the connection to %1. * The SMB header is the data. *) NELOG_NetWkSta_VC_Err = ERRLOG_BASE + 93; (* * A virtual circuit error occurred on the session to %1. * The network control block (NCB) command and return code is the data. *) NELOG_NetWkSta_Stuck_VC_Err = ERRLOG_BASE + 94; (* * Hanging up a stuck session to %1. *) NELOG_NetWkSta_NCB_Err = ERRLOG_BASE + 95; (* * A network control block (NCB) error occurred (%1). * The NCB is the data. *) NELOG_NetWkSta_Write_Behind_Err = ERRLOG_BASE + 96; (* * A write operation to %1 failed. * Data may have been lost. *) NELOG_NetWkSta_Reset_Err = ERRLOG_BASE + 97; (* * Reset of driver %1 failed to complete the network control block (NCB). * The NCB is the data. *) NELOG_NetWkSta_Too_Many = ERRLOG_BASE + 98; (* * The amount of resource %1 requested was more * than the maximum. The maximum amount was allocated. *) // // Spooler specific error log messages from 100 to 103 // NELOG_Srv_Thread_Failure = ERRLOG_BASE + 104; (* * The server could not create a thread. * The THREADS parameter in the CONFIG.SYS file should be increased. *) NELOG_Srv_Close_Failure = ERRLOG_BASE + 105; (* * The server could not close %1. * The file is probably corrupted. *) NELOG_ReplUserCurDir = ERRLOG_BASE + 106; (* *The replicator cannot update directory %1. It has tree integrity * and is the current directory for some process. *) NELOG_ReplCannotMasterDir = ERRLOG_BASE + 107; (* *The server cannot export directory %1 to client %2. * It is exported from another server. *) NELOG_ReplUpdateError = ERRLOG_BASE + 108; (* *The replication server could not update directory %2 from the source * on %3 due to error %1. *) NELOG_ReplLostMaster = ERRLOG_BASE + 109; (* *Master %1 did not send an update notice for directory %2 at the expected * time. *) NELOG_NetlogonAuthDCFail = ERRLOG_BASE + 110; (* *Failed to authenticate with %2, a Windows NT domain controller for domain %1. *) NELOG_ReplLogonFailed = ERRLOG_BASE + 111; (* *The replicator attempted to log on at %2 as %1 and failed. *) NELOG_ReplNetErr = ERRLOG_BASE + 112; (* * Network error %1 occurred. *) NELOG_ReplMaxFiles = ERRLOG_BASE + 113; (* * Replicator limit for files in a directory has been exceeded. *) NELOG_ReplMaxTreeDepth = ERRLOG_BASE + 114; (* * Replicator limit for tree depth has been exceeded. *) NELOG_ReplBadMsg = ERRLOG_BASE + 115; (* * Unrecognized message received in mailslot. *) NELOG_ReplSysErr = ERRLOG_BASE + 116; (* * System error %1 occurred. *) NELOG_ReplUserLoged = ERRLOG_BASE + 117; (* * Cannot log on. User is currently logged on and argument TRYUSER * is set to NO. *) NELOG_ReplBadImport = ERRLOG_BASE + 118; (* * IMPORT path %1 cannot be found. *) NELOG_ReplBadExport = ERRLOG_BASE + 119; (* * EXPORT path %1 cannot be found. *) NELOG_ReplSignalFileErr = ERRLOG_BASE + 120; (* * Replicator failed to update signal file in directory %2 due to * %1 system error. *) NELOG_DiskFT = ERRLOG_BASE+121; (* * Disk Fault Tolerance Error * * %1 *) NELOG_ReplAccessDenied = ERRLOG_BASE + 122; (* * Replicator could not access %2 * on %3 due to system error %1. *) NELOG_NetlogonFailedPrimary = ERRLOG_BASE + 123; (* *The primary domain controller for domain %1 has apparently failed. *) NELOG_NetlogonPasswdSetFailed = ERRLOG_BASE + 124; (* * Changing machine account password for account %1 failed with * the following error: %n%2 *) NELOG_NetlogonTrackingError = ERRLOG_BASE + 125; (* *An error occurred while updating the logon or logoff information for %1. *) NELOG_NetlogonSyncError = ERRLOG_BASE + 126; (* *An error occurred while synchronizing with primary domain controller %1 *) // // UPS service specific error log messages from 130 to 135 // NELOG_UPS_PowerOut = ERRLOG_BASE + 130; (* * A power failure was detected at the server. *) NELOG_UPS_Shutdown = ERRLOG_BASE + 131; (* * The UPS service performed server shut down. *) NELOG_UPS_CmdFileError = ERRLOG_BASE + 132; (* * The UPS service did not complete execution of the * user specified shut down command file. *) NELOG_UPS_CannotOpenDriver = ERRLOG_BASE+133; (* * The UPS driver could not be opened. The error code is * the data. *) NELOG_UPS_PowerBack = ERRLOG_BASE + 134; (* * Power has been restored. *) NELOG_UPS_CmdFileConfig = ERRLOG_BASE + 135; (* * There is a problem with a configuration of user specified * shut down command file. *) NELOG_UPS_CmdFileExec = ERRLOG_BASE + 136; (* * The UPS service failed to execute a user specified shutdown * command file %1. The error code is the data. *) // // Remoteboot server specific error log messages are from 150 to 157 // NELOG_Missing_Parameter = ERRLOG_BASE + 150; (* * Initialization failed because of an invalid or missing * parameter in the configuration file %1. *) NELOG_Invalid_Config_Line = ERRLOG_BASE + 151; (* * Initialization failed because of an invalid line in the * configuration file %1. The invalid line is the data. *) NELOG_Invalid_Config_File = ERRLOG_BASE + 152; (* * Initialization failed because of an error in the configuration * file %1. *) NELOG_File_Changed = ERRLOG_BASE + 153; (* * The file %1 has been changed after initialization. * The boot-block loading was temporarily terminated. *) NELOG_Files_Dont_Fit = ERRLOG_BASE + 154; (* * The files do not fit to the boot-block configuration * file %1. Change the BASE and ORG definitions or the order * of the files. *) NELOG_Wrong_DLL_Version = ERRLOG_BASE + 155; (* * Initialization failed because the dynamic-link * library %1 returned an incorrect version number. *) NELOG_Error_in_DLL = ERRLOG_BASE + 156; (* * There was an unrecoverable error in the dynamic- * link library of the service. *) NELOG_System_Error = ERRLOG_BASE + 157; (* * The system returned an unexpected error code. * The error code is the data. *) NELOG_FT_ErrLog_Too_Large = ERRLOG_BASE + 158; (* * The fault-tolerance error log file, LANROOT\LOGS\FT.LOG, * is more than 64K. *) NELOG_FT_Update_In_Progress = ERRLOG_BASE + 159; (* * The fault-tolerance error-log file, LANROOT\LOGS\FT.LOG, had the * update in progress bit set upon opening, which means that the * system crashed while working on the error log. *) // // another error log range defined for NT Lanman. // ERRLOG2_BASE = 5700; (* New NT NELOG errors start here *) NELOG_NetlogonSSIInitError = ERRLOG2_BASE + 0; (* * The Netlogon service could not initialize the replication data * structures successfully. The service was terminated. The following * error occurred: %n%1 *) NELOG_NetlogonFailedToUpdateTrustList = ERRLOG2_BASE + 1; (* * The Netlogon service failed to update the domain trust list. The * following error occurred: %n%1 *) NELOG_NetlogonFailedToAddRpcInterface = ERRLOG2_BASE + 2; (* * The Netlogon service could not add the RPC interface. The * service was terminated. The following error occurred: %n%1 *) NELOG_NetlogonFailedToReadMailslot = ERRLOG2_BASE + 3; (* * The Netlogon service could not read a mailslot message from %1 due * to the following error: %n%2 *) NELOG_NetlogonFailedToRegisterSC = ERRLOG2_BASE + 4; (* * The Netlogon service failed to register the service with the * service controller. The service was terminated. The following * error occurred: %n%1 *) NELOG_NetlogonChangeLogCorrupt = ERRLOG2_BASE + 5; (* * The change log cache maintained by the Netlogon service for * database changes is corrupted. The Netlogon service is resetting * the change log. *) NELOG_NetlogonFailedToCreateShare = ERRLOG2_BASE + 6; (* * The Netlogon service could not create server share %1. The following * error occurred: %n%2 *) NELOG_NetlogonDownLevelLogonFailed = ERRLOG2_BASE + 7; (* * The down-level logon request for the user %1 from %2 failed. *) NELOG_NetlogonDownLevelLogoffFailed = ERRLOG2_BASE + 8; (* * The down-level logoff request for the user %1 from %2 failed. *) NELOG_NetlogonNTLogonFailed = ERRLOG2_BASE + 9; (* * The Windows NT %1 logon request for the user %2\%3 from %4 (via %5; * failed. *) NELOG_NetlogonNTLogoffFailed = ERRLOG2_BASE + 10; (* * The Windows NT %1 logoff request for the user %2\%3 from %4 * failed. *) NELOG_NetlogonPartialSyncCallSuccess = ERRLOG2_BASE + 11; (* * The partial synchronization request from the server %1 completed * successfully. %2 changes(s; has(have; been returned to the * caller. *) NELOG_NetlogonPartialSyncCallFailed = ERRLOG2_BASE + 12; (* * The partial synchronization request from the server %1 failed with * the following error: %n%2 *) NELOG_NetlogonFullSyncCallSuccess = ERRLOG2_BASE + 13; (* * The full synchronization request from the server %1 completed * successfully. %2 object(s; has(have; been returned to * the caller. *) NELOG_NetlogonFullSyncCallFailed = ERRLOG2_BASE + 14; (* * The full synchronization request from the server %1 failed with * the following error: %n%2 *) NELOG_NetlogonPartialSyncSuccess = ERRLOG2_BASE + 15; (* * The partial synchronization replication of the %1 database from the * primary domain controller %2 completed successfully. %3 change(s; is(are; * applied to the database. *) NELOG_NetlogonPartialSyncFailed = ERRLOG2_BASE + 16; (* * The partial synchronization replication of the %1 database from the * primary domain controller %2 failed with the following error: %n%3 *) NELOG_NetlogonFullSyncSuccess = ERRLOG2_BASE + 17; (* * The full synchronization replication of the %1 database from the * primary domain controller %2 completed successfully. *) NELOG_NetlogonFullSyncFailed = ERRLOG2_BASE + 18; (* * The full synchronization replication of the %1 database from the * primary domain controller %2 failed with the following error: %n%3 *) NELOG_NetlogonAuthNoDomainController = ERRLOG2_BASE + 19; (* * No Windows NT Domain Controller is available for domain %1 for * the following reason: %n%2 *) NELOG_NetlogonAuthNoTrustLsaSecret = ERRLOG2_BASE + 20; (* * The session setup to the Windows NT Domain Controller %1 for the domain %2 * failed because the computer %3 does not have a local security database account. *) NELOG_NetlogonAuthNoTrustSamAccount = ERRLOG2_BASE + 21; (* * The session setup to the Windows NT Domain Controller %1 for the domain %2 * failed because the Windows NT Domain Controller does not have an account * for the computer %3. *) NELOG_NetlogonServerAuthFailed = ERRLOG2_BASE + 22; (* * The session setup from the computer %1 failed to authenticate. * The name of the account referenced in the security database is * %2. The following error occurred: %n%3 *) NELOG_NetlogonServerAuthNoTrustSamAccount = ERRLOG2_BASE + 23; (* * The session setup from the computer %1 failed because there is * no trust account in the security database for this computer. The name of * the account referenced in the security database is %2. *) // // General log messages for NT services. // NELOG_FailedToRegisterSC = ERRLOG2_BASE + 24; (* * Could not register control handler with service controller %1. *) NELOG_FailedToSetServiceStatus = ERRLOG2_BASE + 25; (* * Could not set service status with service controller %1. *) NELOG_FailedToGetComputerName = ERRLOG2_BASE + 26; (* * Could not find the computer name %1. *) NELOG_DriverNotLoaded = ERRLOG2_BASE + 27; (* * Could not load %1 device driver. *) NELOG_NoTranportLoaded = ERRLOG2_BASE + 28; (* * Could not load any transport. *) // // More Netlogon service events // NELOG_NetlogonFailedDomainDelta = ERRLOG2_BASE + 29; (* * Replication of the %1 Domain Object "%2" from primary domain controller * %3 failed with the following error: %n%4 *) NELOG_NetlogonFailedGlobalGroupDelta = ERRLOG2_BASE + 30; (* * Replication of the %1 Global Group "%2" from primary domain controller * %3 failed with the following error: %n%4 *) NELOG_NetlogonFailedLocalGroupDelta = ERRLOG2_BASE + 31; (* * Replication of the %1 Local Group "%2" from primary domain controller * %3 failed with the following error: %n%4 *) NELOG_NetlogonFailedUserDelta = ERRLOG2_BASE + 32; (* * Replication of the %1 User "%2" from primary domain controller * %3 failed with the following error: %n%4 *) NELOG_NetlogonFailedPolicyDelta = ERRLOG2_BASE + 33; (* * Replication of the %1 Policy Object "%2" from primary domain controller * %3 failed with the following error: %n%4 *) NELOG_NetlogonFailedTrustedDomainDelta = ERRLOG2_BASE + 34; (* * Replication of the %1 Trusted Domain Object "%2" from primary domain controller * %3 failed with the following error: %n%4 *) NELOG_NetlogonFailedAccountDelta = ERRLOG2_BASE + 35; (* * Replication of the %1 Account Object "%2" from primary domain controller * %3 failed with the following error: %n%4 *) NELOG_NetlogonFailedSecretDelta = ERRLOG2_BASE + 36; (* * Replication of the %1 Secret "%2" from primary domain controller * %3 failed with the following error: %n%4 *) NELOG_NetlogonSystemError = ERRLOG2_BASE + 37; (* * The system returned the following unexpected error code: %n%1 *) NELOG_NetlogonDuplicateMachineAccounts = ERRLOG2_BASE + 38; (* * Netlogon has detected two machine accounts for server "%1". * The server can be either a Windows NT Server that is a member of the * domain or the server can be a LAN Manager server with an account in the * SERVERS global group. It cannot be both. *) NELOG_NetlogonTooManyGlobalGroups = ERRLOG2_BASE + 39; (* * This domain has more global groups than can be replicated to a LanMan * BDC. Either delete some of your global groups or remove the LanMan * BDCs from the domain. *) NELOG_NetlogonBrowserDriver = ERRLOG2_BASE + 40; (* * The Browser driver returned the following error to Netlogon: %n%1 *) NELOG_NetlogonAddNameFailure = ERRLOG2_BASE + 41; (* * Netlogon could not register the %1<1B> name for the following reason: %n%2 *) // // More Remoteboot service events. // NELOG_RplMessages = ERRLOG2_BASE + 42; (* * Service failed to retrieve messages needed to boot remote boot clients. *) NELOG_RplXnsBoot = ERRLOG2_BASE + 43; (* * Service experienced a severe error and can no longer provide remote boot * for 3Com 3Start remote boot clients. *) NELOG_RplSystem = ERRLOG2_BASE + 44; (* * Service experienced a severe system error and will shut itself down. *) NELOG_RplWkstaTimeout = ERRLOG2_BASE + 45; (* * Client with computer name %1 failed to acknowledge receipt of the * boot data. Remote boot of this client was not completed. *) NELOG_RplWkstaFileOpen = ERRLOG2_BASE + 46; (* * Client with computer name %1 was not booted due to an error in opening * file %2. *) NELOG_RplWkstaFileRead = ERRLOG2_BASE + 47; (* * Client with computer name %1 was not booted due to an error in reading * file %2. *) NELOG_RplWkstaMemory = ERRLOG2_BASE + 48; (* * Client with computer name %1 was not booted due to insufficent memory * at the remote boot server. *) NELOG_RplWkstaFileChecksum = ERRLOG2_BASE + 49; (* * Client with computer name %1 will be booted without using checksums * because checksum for file %2 could not be calculated. *) NELOG_RplWkstaFileLineCount = ERRLOG2_BASE + 50; (* * Client with computer name %1 was not booted due to too many lines in * file %2. *) NELOG_RplWkstaBbcFile = ERRLOG2_BASE + 51; (* * Client with computer name %1 was not booted because the boot block * configuration file %2 for this client does not contain boot block * line and/or loader line. *) NELOG_RplWkstaFileSize = ERRLOG2_BASE + 52; (* * Client with computer name %1 was not booted due to a bad size of * file %2. *) NELOG_RplWkstaInternal = ERRLOG2_BASE + 53; (* * Client with computer name %1 was not booted due to remote boot * service internal error. *) NELOG_RplWkstaWrongVersion = ERRLOG2_BASE + 54; (* * Client with computer name %1 was not booted because file %2 has an * invalid boot header. *) NELOG_RplWkstaNetwork = ERRLOG2_BASE + 55; (* * Client with computer name %1 was not booted due to network error. *) NELOG_RplAdapterResource = ERRLOG2_BASE + 56; (* * Client with adapter id %1 was not booted due to lack of resources. *) NELOG_RplFileCopy = ERRLOG2_BASE + 57; (* * Service experienced error copying file or directory %1. *) NELOG_RplFileDelete = ERRLOG2_BASE + 58; (* * Service experienced error deleting file or directory %1. *) NELOG_RplFilePerms = ERRLOG2_BASE + 59; (* * Service experienced error setting permissions on file or directory %1. *) NELOG_RplCheckConfigs = ERRLOG2_BASE + 60; (* * Service experienced error evaluating RPL configurations. *) NELOG_RplCreateProfiles = ERRLOG2_BASE + 61; (* * Service experienced error creating RPL profiles for all configurations. *) NELOG_RplRegistry = ERRLOG2_BASE + 62; (* * Service experienced error accessing registry. *) NELOG_RplReplaceRPLDISK = ERRLOG2_BASE + 63; (* * Service experienced error replacing possibly outdated RPLDISK.SYS. *) NELOG_RplCheckSecurity = ERRLOG2_BASE + 64; (* * Service experienced error adding security accounts or setting * file permissions. These accounts are the RPLUSER local group * and the user accounts for the individual RPL workstations. *) NELOG_RplBackupDatabase = ERRLOG2_BASE + 65; (* * Service failed to back up its database. *) NELOG_RplInitDatabase = ERRLOG2_BASE + 66; (* * Service failed to initialize from its database. The database may be * missing or corrupted. Service will attempt restoring the database * from the backup. *) NELOG_RplRestoreDatabaseFailure = ERRLOG2_BASE + 67; (* * Service failed to restore its database from the backup. Service * will not start. *) NELOG_RplRestoreDatabaseSuccess = ERRLOG2_BASE + 68; (* * Service sucessfully restored its database from the backup. *) NELOG_RplInitRestoredDatabase = ERRLOG2_BASE + 69; (* * Service failed to initialize from its restored database. Service * will not start. *) // // More Netlogon and RPL service events // NELOG_NetlogonSessionTypeWrong = ERRLOG2_BASE + 70; (* * The session setup to the Windows NT Domain Controller %1 from computer * %2 using account %4 failed. %2 is declared to be a BDC in domain %3. * However, %2 tried to connect as either a DC in a trusted domain, * a member workstation in domain %3, or as a server in domain %3. * Use the Server Manager to remove the BDC account for %2. *) NELOG_RplUpgradeDBTo40 = ERRLOG2_BASE + 71; (* * The remoteboot database was in NT 3.5 / NT 3.51 format and NT is * attempting to convert it to NT 4.0 format. The JETCONV converter * will write to the Application event log when it is finished. *) type ERROR_LOG = record el_len : Integer; el_reserved : Integer; el_time : Integer; el_error : Integer; el_name : PWideChar; // pointer to service name el_text : PWideChar; // pointer to string array el_data : Pointer; // pointer to BYTE array el_data_size : Integer; // byte count of el_data area el_nstrings : Integer; // number of strings in el_text. end; PERROR_LOG = ^ERROR_LOG; HLOG = record time : Integer; last_flags : Integer; offset : Integer; rec_offset : Integer; end; PHLOG = ^HLOG; function NetErrorLogClear ( server : PWideChar; backupfile : PWideChar; reserved : pointer) : NetAPIStatus; stdcall; function NetErrorLogRead ( server, reserved1 : PWideChar; errloghandle : PHLOG; offset : Integer; var reserved2 : Integer; reserved3 : Integer; offsetflag : Integer; var buffer : Pointer; prefMaxLen : Integer; var bytesRead, totalBytes : Integer) : NetAPIStatus; stdcall; function NetErrorLogWrite ( reserved : Pointer; code : Integer; component : PWideChar; buffer : Pointer; numbytes : Integer; msgbuf : Pointer; strcount : Integer; reserved2 : Pointer) : NetAPIStatus; stdcall; implementation function NetErrorLogClear; external 'NETAPI32.DLL'; function NetErrorLogRead; external 'NETAPI32.DLL'; function NetErrorLogWrite; external 'NETAPI32.DLL'; end.
unit CyclomaticComplexityCalculatorVisitor; interface uses Classes, SysUtils, StrUtils, PascalParser, ParseTreeNode, ParseTreeNodeType, SourceToken, Tokens, SourceTreeWalker; type TMethod = class (TObject) private FParent: TMethod; FHeadingNode: TParseTreeNode; FBlockNode: TParseTreeNode; FEndNode: TParseTreeNode; FIfCount: Integer; FElseCount: Integer; FAndCount: Integer; FOrCount: Integer; FForCount: Integer; FWhileCount: Integer; FCaseCount: Integer; FExceptCount: Integer; FRepeatCount: Integer; function GetNameNode: TParseTreeNode; function GetName: String; function GetCyclomaticComplexity: Integer; public property Name: String read GetName; property CyclomaticComplexity: Integer read GetCyclomaticComplexity; end; TMethodList = class (TList) private function GetItem(Index: Integer): TMethod; public procedure Clear; override; property Items[Index: Integer]: TMethod read GetItem; default; end; TCyclomaticComplexityCalculatorVisitor = class (TInterfacedObject, INodeVisitor) private FMethods: TMethodList; FCurrentMethod: TMethod; function CreateNewMethodFromNode(Node: TParseTreeNode): TMethod; procedure ProcessSourceToken(Token: TSourceToken); protected property Methods: TMethodList read FMethods; public constructor Create(AMethods: TMethodList); procedure Visit(Node: TParseTreeNode); end; implementation { TMethod } { Private declarations } function TMethod.GetNameNode: TParseTreeNode; var I: Integer; begin Result := nil; for I := 0 to FHeadingNode.ChildNodeCount - 1 do begin Result := FHeadingNode.ChildNodes[I]; if Result.NodeType <> nUnknown then Break; end; end; function TMethod.GetName: String; var I: Integer; Node: TParseTreeNode; begin Result := ''; if Assigned(FParent) then Result := Result + FParent.Name + ':'; Node := GetNameNode; for I := 0 to Node.ChildNodeCount - 1 do Result := Result + Node.ChildNodes[I].Describe; end; function TMethod.GetCyclomaticComplexity: Integer; begin Result := 1 + FIfCount + FAndCount + FOrCount + FElseCount + FForCount + FWhileCount + FRepeatCount + FCaseCount + FExceptCount; end; { TMethodList } { Private declarations } function TMethodList.GetItem(Index: Integer): TMethod; begin Result := TObject(Get(Index)) as TMethod; end; { Public declarations } procedure TMethodList.Clear; var I: Integer; begin for I := 0 to Count - 1 do Items[I].Free; inherited Clear; end; { TCyclomaticComplexityCalculatorVisitor } { Private declarations } function TCyclomaticComplexityCalculatorVisitor.CreateNewMethodFromNode(Node: TParseTreeNode): TMethod; begin if Node.ChildNodeCount < 4 then Result := FCurrentMethod else begin Result := TMethod.Create; Result.FHeadingNode := Node.ChildNodes[0]; Result.FBlockNode := Node.ChildNodes[2]; Result.FEndNode := Node.ChildNodes[3]; Methods.Add(Result); Result.FParent := FCurrentMethod; end; end; procedure TCyclomaticComplexityCalculatorVisitor.ProcessSourceToken(Token: TSourceToken); begin case Token.TokenType of ttIf: Inc(FCurrentMethod.FIfCount); ttAnd: Inc(FCurrentMethod.FAndCount); ttOr: Inc(FCurrentMethod.FOrCount); ttElse: if Token.NextLeafNode <> nil then if TSourceToken(Token.NextLeafNode).TokenType <> ttIf then Inc(FCurrentMethod.FElseCount); ttFor: Inc(FCurrentMethod.FForCount); ttWhile: Inc(FCurrentMethod.FWhileCount); ttRepeat: Inc(FCurrentMethod.FRepeatCount); end; end; { Public declarations } constructor TCyclomaticComplexityCalculatorVisitor.Create(AMethods: TMethodList); begin inherited Create; FMethods := AMethods; end; procedure TCyclomaticComplexityCalculatorVisitor.Visit(Node: TParseTreeNode); begin if Node.NodeType in ProcedureNodes then FCurrentMethod := CreateNewMethodFromNode(Node) else if Assigned(FCurrentMethod) then begin if FCurrentMethod.FEndNode = Node then FCurrentMethod := FCurrentMethod.FParent else if Node.NodeType in [nCaseStatement, nCaseLabel] then Inc(FCurrentMethod.FCaseCount) else if Node.NodeType in [nExceptBlock] then Inc(FCurrentMethod.FExceptCount) else if Node is TSourceToken then ProcessSourceToken(Node as TSourceToken) end; end; end.
unit TarantoolTypes; {$mode delphi} interface uses Classes, SysUtils, Generics.Collections, msgpack; type TTIterator=( tiEQ,tiREQ,tiALL, tiLT,tiLE, tiGE,tiGT, tiBitsetAllSet, tiBitsetAnySet, tiBitsetAllNotSet, tiOverlaps,tiNeighbor); TTType=( ttUnsigned, ttString, ttVarbinary, ttInteger, ttNumber, ttDouble, ttBoolean, ttDecimal, ttArray, ttMap, ttScalar ); TTIndexType=( titHASH, titTREE, titBITSET, RTREE ); TTSpaceFormatRecord=record Name:String; &Type:TTType; IsNullable:Boolean; constructor Create(ARecord:IMsgPackObject); end; TTSpaceFormat=TList<TTSpaceFormatRecord>; TTIndexFormatRecord=record FieldNum:Integer; &Type:TTType; IsNullable:Boolean; constructor Create(ARecord:IMsgPackObject); end; TTIndexFormat=TList<TTIndexFormatRecord>; function StringToTTType(s:String):TTType; function StringToTTIterator(s:String):TTIterator; implementation function StringToTTType(s:String):TTType; begin Result:=TTType.ttScalar; if s='unsigned' then Result:=TTType.ttUnsigned; if s='string' then Result:=TTType.ttString; if s='varbinary' then Result:=TTType.ttVarbinary; if s='integer' then Result:=TTType.ttInteger; if s='number' then Result:=TTType.ttNumber; if s='double' then Result:=TTType.ttDouble; if s='boolean' then Result:=TTType.ttBoolean; if s='decimal' then Result:=TTType.ttDecimal; if s='array' then Result:=TTType.ttArray; if s='map' then Result:=TTType.ttMap; if s='scalar' then Result:=TTType.ttScalar; end; function StringToTTIterator(s:String):TTIterator; begin if s='EQ' then Result:=TTIterator.tiEQ; if s='REQ' then Result:=TTIterator.tiREQ; if s='ALL' then Result:=TTIterator.tiALL; if s='LT' then Result:=TTIterator.tiLT; if s='LE' then Result:=TTIterator.tiLE; if s='GE' then Result:=TTIterator.tiGE; if s='GT' then Result:=TTIterator.tiGT; if s='BitsetAllSet' then Result:=TTIterator.tiBitsetAllSet; if s='BitsetAnySet' then Result:=TTIterator.tiBitsetAnySet; if s='BitsetAllNotSet' then Result:=TTIterator.tiBitsetAllNotSet; if s='Overlaps' then Result:=TTIterator.tiOverlaps; if s='Neighbor' then Result:=TTIterator.tiNeighbor; end; constructor TTSpaceFormatRecord.Create(ARecord:IMsgPackObject); const NameS:UnicodeString='name'; TypeS:UnicodeString='type'; IsNullableS:UnicodeString='is_nullable'; var MPO:TMsgPackObject; begin MPO:=TMsgPackObject.Create(NameS); Name:=ARecord.AsMap.GetEx(MPO).AsString; MPO.Free; MPO:=TMsgPackObject.Create(TypeS); &Type:=StringToTTType(ARecord.AsMap.GetEx(MPO).AsString); MPO.Free; MPO:=TMsgPackObject.Create(IsNullableS); if Assigned(ARecord.AsMap.GetEx(MPO)) then IsNullable:=ARecord.AsMap.GetEx(MPO).AsBoolean; MPO.Free; end; constructor TTIndexFormatRecord.Create(ARecord:IMsgPackObject); const FieldS:UnicodeString='field'; TypeS:UnicodeString='type'; IsNullableS:UnicodeString='is_nullable'; var MPO:TMsgPackObject; begin if ARecord.ObjectType=mptArray then begin FieldNum:=ARecord.AsArray.Get(0).AsInteger; &Type:=StringToTTType(ARecord.AsArray.Get(1).AsString); IsNullable:=False; end else begin MPO:=TMsgPackObject.Create(FieldS); FieldNum:=ARecord.AsMap.GetEx(MPO).AsInteger; MPO.Free; MPO:=TMsgPackObject.Create(TypeS); &Type:=StringToTTType(ARecord.AsMap.GetEx(MPO).AsString); MPO.Free; MPO:=TMsgPackObject.Create(IsNullableS); IsNullable:=ARecord.AsMap.GetEx(MPO).AsBoolean; MPO.Free; end; end; end.
{ Subroutine STRING_CMLINE_TOKEN_INT (I,STAT) * * Read the next token from the command line and convert it to the integer I. * STAT is the completion status code. } module string_cmline_token_int; define string_cmline_token_int; %include 'string2.ins.pas'; procedure string_cmline_token_int ( {read next command line token as machine int} out i: univ sys_int_machine_t; {returned integer value} out stat: sys_err_t); {completion status code} var token: string_var132_t; {token read from command line} begin token.max := sizeof(token.str); {init var string} string_cmline_token (token, stat); {get next token from command line} if sys_error(stat) then return; string_t_int (token, i, stat); {convert string to integer} end;
{******************************************************************************* 作者: dmzn@163.com 2020-12-20 描述: 通讯协议定义 *******************************************************************************} unit UProtocol; interface uses Windows, Classes, SysUtils, IdGlobal, ULibFun; const cFrame_Begin = Char($FF) + Char($FF) + Char($FF); //帧头 cFrame_End = Char($FE); //帧尾 {*功能码*} cFrame_CMD_UpData = $01; //数据上传 cFrame_CMD_QueryData = $02; //数据查询 {*扩展码*} cFrame_Ext_RunData = $01; //运行状态数据 cFrame_Ext_RunParam = $01; //运行参数数据 type TValFloat = array[0..3] of Char; //浮点值 THexFloat = record //IEEE754浮点值转换 case Byte of 0: (AsHex: TValFloat); 1: (AsFloat: Single); end; PFrameData = ^TFrameData; TFrameData = packed record FHeader : array[0..2] of Char; //帧头 FStation : Word; //设备ID FCommand : Byte; //功能码 FExtCMD : Byte; //扩展码 FDataLen : Byte; //数据长度 FData : array[0..255] of Char; //数据 FEnd : Char; //帧尾 end; PRunData = ^TRunData; TRunData = packed record I00 : Byte; //断电 I01 : Byte; //开到位 I02 : Byte; //关到位 VD300 : TValFloat; //瞬时流量 VD304 : TValFloat; //温度 VD308 : TValFloat; //压力 VD312 : TValFloat; //累计流量 VD316 : TValFloat; //压差 VD320 : TValFloat; //热量 VD324 : TValFloat; //累计热量 VD328 : TValFloat; //温度高限设定 VD332 : TValFloat; //温度低限设定 VD336 : TValFloat; //压力高限设定 VD340 : TValFloat; //压力低限设定 VD348 : TValFloat; //单价 VD352 : TValFloat; //余额 VD356 : TValFloat; //余额低设定 V3650 : Byte; //阀门自动 V3651 : Byte; //温度高报警 V3652 : Byte; //温度低报警 V3653 : Byte; //压力高报警 V3654 : Byte; //压力低报警 V3655 : Byte; //总报警 V3656 : Byte; //余额低报警 V3657 : Byte; //开阀无流量报警 V20000 : Byte; //手动开阀 V20001 : Byte; //手动关阀 V20002 : Byte; //阀门中停 end; PRunParams = ^TRunParams; TRunParams = packed record VD328 : TValFloat; //温度高限设定 VD332 : TValFloat; //温度低限设定 VD336 : TValFloat; //压力高限设定 VD340 : TValFloat; //压力低限设定 VD348 : TValFloat; //单价 VD352 : TValFloat; //余额 VD356 : TValFloat; //余额低设定 V3650 : Byte; //阀门自动 V20000 : Byte; //手动开阀 V20001 : Byte; //手动关阀 V20002 : Byte; //阀门中停 end; const cSize_Frame_All = SizeOf(TFrameData); cSize_Frame_RunData = SizeOf(TRunData); cSize_Frame_RunParams = SizeOf(TRunParams); cSize_Record_ValFloat = SizeOf(TValFloat); const sTable_RunData = 'D_RunData'; sTable_RunParams = 'D_RunParams'; function SwapWordHL(const nVal: Word): Word; //双字节 procedure PutValFloat(const nVal: Single; var nFloat: TValFloat); function GetValFloat(const nFloat: TValFloat): Single; //转换浮点数 procedure InitFrameData(var nData: TFrameData); procedure InitRunData(var nData: TRunData); procedure InitRunParams(var nData: TRunParams); //初始化数据 function FrameValidLen(const nData: PFrameData): Integer; function BuildRunData(const nFrame: PFrameData; const nRun: PRunData): TIdBytes; function BuildRunParams(const nFrame: PFrameData; const nParams: PRunParams): TIdBytes; //构建发送缓冲 implementation //Date: 2020-12-23 //Desc: 交换Word值的高低字节 function SwapWordHL(const nVal: Word): Word; var nL,nH: Byte; begin nL := Lo(nVal); nH := Hi(nVal); Result := MakeWord(nH, nL); end; //Date: 2020-12-23 //Parm: 4字节浮点数 //Desc: 交换nFloat的高低字节 procedure SwapFloatHL(var nFloat: TValFloat); var nCH: Char; nL,nH: Integer; begin nL := Low(nFloat); nH := High(nFloat); while nL < nH do begin nCH := nFloat[nL]; nFloat[nL] := nFloat[nH]; nFloat[nH] := nCH; Inc(nL); Dec(nH); end; end; //Date: 2020-12-20 //Parm: 浮点值;浮点结构 //Desc: 将nVal存入nFloat中 procedure PutValFloat(const nVal: Single; var nFloat: TValFloat); var nHF: THexFloat; begin nHF.AsFloat := nVal; nFloat := nHF.AsHex; SwapFloatHL(nFloat); end; //Date: 2020-12-20 //Parm: 浮点结构 //Desc: 计算nFloat的值 function GetValFloat(const nFloat: TValFloat): Single; var nHF: THexFloat; begin nHF.AsHex := nFloat; SwapFloatHL(nHF.AsHex); Result := nHF.AsFloat; end; //Date: 2020-12-20 //Parm: 帧数据 //Desc: 初始化nData procedure InitFrameData(var nData: TFrameData); begin FillChar(nData, cSize_Frame_All, #0); with nData do begin FHeader := cFrame_Begin; FEnd := cFrame_End; end; end; procedure InitRunData(var nData: TRunData); var nInit: TRunData; begin FillChar(nInit, cSize_Frame_RunData, #0); nData := nInit; end; procedure InitRunParams(var nData: TRunParams); var nInit: TRunParams; begin FillChar(nInit, cSize_Frame_RunParams, #0); nData := nInit; end; //Date: 2020-12-20 //Parm: 帧数据 //Desc: 计算nData的有效数据大小 function FrameValidLen(const nData: PFrameData): Integer; begin Result := 5 + 3 + nData.FDataLen + 1; end; //Date: 2020-12-20 //Parm: 帧数据;运行数据 //Desc: 将nFrame + nRun打包为发送缓冲 function BuildRunData(const nFrame: PFrameData; const nRun: PRunData): TIdBytes; begin Move(nRun^, nFrame.FData[0], cSize_Frame_RunData); //合并进数据区 nFrame.FData[cSize_Frame_RunData] := cFrame_End; //补帧尾 nFrame.FDataLen := cSize_Frame_RunData; Result := RawToBytes(nFrame^, FrameValidLen(nFrame)); end; //Date: 2020-12-20 //Parm: 帧数据;运行参数 //Desc: 将nFrame + nParams打包为发送缓冲 function BuildRunParams(const nFrame: PFrameData; const nParams: PRunParams): TIdBytes; begin Move(nParams^, nFrame.FData[0], cSize_Frame_RunParams); //合并进数据区 nFrame.FData[cSize_Frame_RunParams] := cFrame_End; //补帧尾 nFrame.FDataLen := cSize_Frame_RunParams; Result := RawToBytes(nFrame^, FrameValidLen(nFrame)); end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Image.PNG.ExternalLibrary; {$ifdef fpc} {$mode objfpc} {$else} {$i PasVulkan.inc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} interface {$if defined(fpc) and defined(Android)} { Automatically converted by H2Pas 0.99.15 from png.h } { The following command line parameters were used: png.h } {$PACKRECORDS C} uses ctypes, zlib; Const {$ifdef windows} LibPng = 'libpng12'; // Library name { matching lib version for libpng12.dll, needed for initialization } PNG_LIBPNG_VER_STRING='1.2.12'; {$else windows} LibPng = 'png'; // Library name {$if defined(Android)} {$linklib png} {$linklib m} {$ifend} { matching lib version for libpng, needed for initialization } PNG_LIBPNG_VER_STRING='1.2.12'; {$endif windows} PNG_COLOR_MASK_PALETTE=1; PNG_COLOR_MASK_COLOR=2; PNG_COLOR_MASK_ALPHA=4; PNG_COLOR_TYPE_GRAY=0; PNG_COLOR_TYPE_PALETTE=PNG_COLOR_MASK_COLOR or PNG_COLOR_MASK_PALETTE; PNG_COLOR_TYPE_RGB=PNG_COLOR_MASK_COLOR; PNG_COLOR_TYPE_RGB_ALPHA=PNG_COLOR_MASK_COLOR or PNG_COLOR_MASK_ALPHA; PNG_COLOR_TYPE_GRAY_ALPHA=PNG_COLOR_MASK_ALPHA; PNG_COLOR_TYPE_RGBA=PNG_COLOR_TYPE_RGB_ALPHA; PNG_COLOR_TYPE_GA=PNG_COLOR_TYPE_GRAY_ALPHA; PNG_INFO_tRNS=$10; PNG_FILLER_AFTER=1; type time_t = longint; int = longint; z_stream = TZStream; voidp = pointer; png_uint_32 = dword; png_int_32 = longint; png_uint_16 = word; png_int_16 = smallint; png_byte = byte; ppng_uint_32 = ^png_uint_32; ppng_int_32 = ^png_int_32; ppng_uint_16 = ^png_uint_16; ppng_int_16 = ^png_int_16; ppng_byte = ^png_byte; pppng_uint_32 = ^ppng_uint_32; pppng_int_32 = ^ppng_int_32; pppng_uint_16 = ^ppng_uint_16; pppng_int_16 = ^ppng_int_16; pppng_byte = ^ppng_byte; png_size_t = csize_t; png_fixed_point = png_int_32; ppng_fixed_point = ^png_fixed_point; pppng_fixed_point = ^ppng_fixed_point; png_voidp = pointer; png_bytep = Ppng_byte; ppng_bytep = ^png_bytep; png_uint_32p = Ppng_uint_32; png_int_32p = Ppng_int_32; png_uint_16p = Ppng_uint_16; ppng_uint_16p = ^png_uint_16p; png_int_16p = Ppng_int_16; (* Const before type ignored *) png_const_charp = Pchar; png_charp = Pchar; ppng_charp = ^png_charp; png_fixed_point_p = Ppng_fixed_point; TFile = Pointer; png_FILE_p = ^FILE; png_doublep = Pdouble; png_bytepp = PPpng_byte; png_uint_32pp = PPpng_uint_32; png_int_32pp = PPpng_int_32; png_uint_16pp = PPpng_uint_16; png_int_16pp = PPpng_int_16; (* Const before type ignored *) png_const_charpp = PPchar; png_charpp = PPchar; ppng_charpp = ^png_charpp; png_fixed_point_pp = PPpng_fixed_point; png_doublepp = PPdouble; png_charppp = PPPchar; Pcharf = Pchar; PPcharf = ^Pcharf; png_zcharp = Pcharf; png_zcharpp = PPcharf; png_zstreamp = Pzstream; var {$ifndef darwin} png_libpng_ver : array[0..11] of char; cvar; external; png_pass_start : array[0..6] of longint; cvar; external; png_pass_inc : array[0..6] of longint; cvar; external; png_pass_ystart : array[0..6] of longint; cvar; external; png_pass_yinc : array[0..6] of longint; cvar; external; png_pass_mask : array[0..6] of longint; cvar; external; png_pass_dsp_mask : array[0..6] of longint; cvar; external; {$else darwin} png_libpng_ver : array[0..11] of char; external LibPng name 'png_libpng_ver'; png_pass_start : array[0..6] of longint; external LibPng name 'png_pass_start'; png_pass_inc : array[0..6] of longint; external LibPng name 'png_pass_inc'; png_pass_ystart : array[0..6] of longint; external LibPng name 'png_pass_ystart'; png_pass_yinc : array[0..6] of longint; external LibPng name 'png_pass_yinc'; png_pass_mask : array[0..6] of longint; external LibPng name 'png_pass_mask'; png_pass_dsp_mask : array[0..6] of longint; external LibPng name 'png_pass_dsp_mask'; {$endif darwin} Type png_color = record red : png_byte; green : png_byte; blue : png_byte; end; ppng_color = ^png_color; pppng_color = ^ppng_color; png_color_struct = png_color; png_colorp = Ppng_color; ppng_colorp = ^png_colorp; png_colorpp = PPpng_color; png_color_16 = record index : png_byte; red : png_uint_16; green : png_uint_16; blue : png_uint_16; gray : png_uint_16; end; ppng_color_16 = ^png_color_16 ; pppng_color_16 = ^ppng_color_16 ; png_color_16_struct = png_color_16; png_color_16p = Ppng_color_16; ppng_color_16p = ^png_color_16p; png_color_16pp = PPpng_color_16; png_color_8 = record red : png_byte; green : png_byte; blue : png_byte; gray : png_byte; alpha : png_byte; end; ppng_color_8 = ^png_color_8; pppng_color_8 = ^ppng_color_8; png_color_8_struct = png_color_8; png_color_8p = Ppng_color_8; ppng_color_8p = ^png_color_8p; png_color_8pp = PPpng_color_8; png_sPLT_entry = record red : png_uint_16; green : png_uint_16; blue : png_uint_16; alpha : png_uint_16; frequency : png_uint_16; end; ppng_sPLT_entry = ^png_sPLT_entry; pppng_sPLT_entry = ^ppng_sPLT_entry; png_sPLT_entry_struct = png_sPLT_entry; png_sPLT_entryp = Ppng_sPLT_entry; png_sPLT_entrypp = PPpng_sPLT_entry; png_sPLT_t = record name : png_charp; depth : png_byte; entries : png_sPLT_entryp; nentries : png_int_32; end; ppng_sPLT_t = ^png_sPLT_t; pppng_sPLT_t = ^ppng_sPLT_t; png_sPLT_struct = png_sPLT_t; png_sPLT_tp = Ppng_sPLT_t; png_sPLT_tpp = PPpng_sPLT_t; png_text = record compression : longint; key : png_charp; text : png_charp; text_length : png_size_t; end; ppng_text = ^png_text; pppng_text = ^ppng_text; png_text_struct = png_text; png_textp = Ppng_text; ppng_textp = ^png_textp; png_textpp = PPpng_text; png_time = record year : png_uint_16; month : png_byte; day : png_byte; hour : png_byte; minute : png_byte; second : png_byte; end; ppng_time = ^png_time; pppng_time = ^ppng_time; png_time_struct = png_time; png_timep = Ppng_time; PPNG_TIMEP = ^PNG_TIMEP; png_timepp = PPpng_time; png_unknown_chunk = record name : array[0..4] of png_byte; data : Ppng_byte; size : png_size_t; location : png_byte; end; ppng_unknown_chunk = ^png_unknown_chunk; pppng_unknown_chunk = ^ppng_unknown_chunk; png_unknown_chunk_t = png_unknown_chunk; png_unknown_chunkp = Ppng_unknown_chunk; png_unknown_chunkpp = PPpng_unknown_chunk; png_info = record width : png_uint_32; height : png_uint_32; valid : png_uint_32; rowbytes : png_uint_32; palette : png_colorp; num_palette : png_uint_16; num_trans : png_uint_16; bit_depth : png_byte; color_type : png_byte; compression_type : png_byte; filter_type : png_byte; interlace_type : png_byte; channels : png_byte; pixel_depth : png_byte; spare_byte : png_byte; signature : array[0..7] of png_byte; gamma : double; srgb_intent : png_byte; num_text : longint; max_text : longint; text : png_textp; mod_time : png_time; sig_bit : png_color_8; trans : png_bytep; trans_values : png_color_16; background : png_color_16; x_offset : png_int_32; y_offset : png_int_32; offset_unit_type : png_byte; x_pixels_per_unit : png_uint_32; y_pixels_per_unit : png_uint_32; phys_unit_type : png_byte; hist : png_uint_16p; x_white : double; y_white : double; x_red : double; y_red : double; x_green : double; y_green : double; x_blue : double; y_blue : double; pcal_purpose : png_charp; pcal_X0 : png_int_32; pcal_X1 : png_int_32; pcal_units : png_charp; pcal_params : png_charpp; pcal_type : png_byte; pcal_nparams : png_byte; free_me : png_uint_32; unknown_chunks : png_unknown_chunkp; unknown_chunks_num : png_size_t; iccp_name : png_charp; iccp_profile : png_charp; iccp_proflen : png_uint_32; iccp_compression : png_byte; splt_palettes : png_sPLT_tp; splt_palettes_num : png_uint_32; scal_unit : png_byte; scal_pixel_width : double; scal_pixel_height : double; scal_s_width : png_charp; scal_s_height : png_charp; row_pointers : png_bytepp; int_gamma : png_fixed_point; int_x_white : png_fixed_point; int_y_white : png_fixed_point; int_x_red : png_fixed_point; int_y_red : png_fixed_point; int_x_green : png_fixed_point; int_y_green : png_fixed_point; int_x_blue : png_fixed_point; int_y_blue : png_fixed_point; end; ppng_info = ^png_info; pppng_info = ^ppng_info; png_info_struct = png_info; png_infop = Ppng_info; png_infopp = PPpng_info; png_row_info = record width : png_uint_32; rowbytes : png_uint_32; color_type : png_byte; bit_depth : png_byte; channels : png_byte; pixel_depth : png_byte; end; ppng_row_info = ^png_row_info; pppng_row_info = ^ppng_row_info; png_row_info_struct = png_row_info; png_row_infop = Ppng_row_info; png_row_infopp = PPpng_row_info; // png_struct_def = png_struct; png_structp = ^png_struct; png_error_ptr = Procedure(Arg1 : png_structp; Arg2 : png_const_charp);cdecl; png_rw_ptr = Procedure(Arg1 : png_structp; Arg2 : png_bytep; Arg3 : png_size_t);cdecl; png_flush_ptr = procedure (Arg1 : png_structp) ;cdecl; png_read_status_ptr = procedure (Arg1 : png_structp; Arg2 : png_uint_32; Arg3: int);cdecl; png_write_status_ptr = Procedure (Arg1 : png_structp; Arg2:png_uint_32;Arg3 : int) ;cdecl; png_progressive_info_ptr = Procedure (Arg1 : png_structp; Arg2 : png_infop) ;cdecl; png_progressive_end_ptr = Procedure (Arg1 : png_structp; Arg2 : png_infop) ;cdecl; png_progressive_row_ptr = Procedure (Arg1 : png_structp; Arg2 : png_bytep; Arg3 : png_uint_32; Arg4 : int) ;cdecl; png_user_transform_ptr = Procedure (Arg1 : png_structp; Arg2 : png_row_infop; Arg3 : png_bytep) ;cdecl; png_user_chunk_ptr = Function (Arg1 : png_structp; Arg2 : png_unknown_chunkp): longint;cdecl; png_unknown_chunk_ptr = Procedure (Arg1 : png_structp);cdecl; png_malloc_ptr = Function (Arg1 : png_structp; Arg2 : png_size_t) : png_voidp ;cdecl; png_free_ptr = Procedure (Arg1 : png_structp; Arg2 : png_voidp) ; cdecl; png_struct_def = record jmpbuf : jmp_buf; error_fn : png_error_ptr; warning_fn : png_error_ptr; error_ptr : png_voidp; write_data_fn : png_rw_ptr; read_data_fn : png_rw_ptr; io_ptr : png_voidp; read_user_transform_fn : png_user_transform_ptr; write_user_transform_fn : png_user_transform_ptr; user_transform_ptr : png_voidp; user_transform_depth : png_byte; user_transform_channels : png_byte; mode : png_uint_32; flags : png_uint_32; transformations : png_uint_32; zstream : z_stream; zbuf : png_bytep; zbuf_size : png_size_t; zlib_level : longint; zlib_method : longint; zlib_window_bits : longint; zlib_mem_level : longint; zlib_strategy : longint; width : png_uint_32; height : png_uint_32; num_rows : png_uint_32; usr_width : png_uint_32; rowbytes : png_uint_32; irowbytes : png_uint_32; iwidth : png_uint_32; row_number : png_uint_32; prev_row : png_bytep; row_buf : png_bytep; sub_row : png_bytep; up_row : png_bytep; avg_row : png_bytep; paeth_row : png_bytep; row_info : png_row_info; idat_size : png_uint_32; crc : png_uint_32; palette : png_colorp; num_palette : png_uint_16; num_trans : png_uint_16; chunk_name : array[0..4] of png_byte; compression : png_byte; filter : png_byte; interlaced : png_byte; pass : png_byte; do_filter : png_byte; color_type : png_byte; bit_depth : png_byte; usr_bit_depth : png_byte; pixel_depth : png_byte; channels : png_byte; usr_channels : png_byte; sig_bytes : png_byte; filler : png_uint_16; background_gamma_type : png_byte; background_gamma : double; background : png_color_16; background_1 : png_color_16; output_flush_fn : png_flush_ptr; flush_dist : png_uint_32; flush_rows : png_uint_32; gamma_shift : longint; gamma : double; screen_gamma : double; gamma_table : png_bytep; gamma_from_1 : png_bytep; gamma_to_1 : png_bytep; gamma_16_table : png_uint_16pp; gamma_16_from_1 : png_uint_16pp; gamma_16_to_1 : png_uint_16pp; sig_bit : png_color_8; shift : png_color_8; trans : png_bytep; trans_values : png_color_16; read_row_fn : png_read_status_ptr; write_row_fn : png_write_status_ptr; info_fn : png_progressive_info_ptr; row_fn : png_progressive_row_ptr; end_fn : png_progressive_end_ptr; save_buffer_ptr : png_bytep; save_buffer : png_bytep; current_buffer_ptr : png_bytep; current_buffer : png_bytep; push_length : png_uint_32; skip_length : png_uint_32; save_buffer_size : png_size_t; save_buffer_max : png_size_t; buffer_size : png_size_t; current_buffer_size : png_size_t; process_mode : longint; cur_palette : longint; current_text_size : png_size_t; current_text_left : png_size_t; current_text : png_charp; current_text_ptr : png_charp; palette_lookup : png_bytep; dither_index : png_bytep; hist : png_uint_16p; heuristic_method : png_byte; num_prev_filters : png_byte; prev_filters : png_bytep; filter_weights : png_uint_16p; inv_filter_weights : png_uint_16p; filter_costs : png_uint_16p; inv_filter_costs : png_uint_16p; time_buffer : png_charp; free_me : png_uint_32; user_chunk_ptr : png_voidp; read_user_chunk_fn : png_user_chunk_ptr; num_chunk_list : longint; chunk_list : png_bytep; rgb_to_gray_status : png_byte; rgb_to_gray_red_coeff : png_uint_16; rgb_to_gray_green_coeff : png_uint_16; rgb_to_gray_blue_coeff : png_uint_16; empty_plte_permitted : png_byte; int_gamma : png_fixed_point; end; ppng_struct_def = ^png_struct_def; pppng_struct_def = ^ppng_struct_def; png_struct = png_struct_def; ppng_struct = ^png_struct; pppng_struct = ^ppng_struct; version_1_0_8 = png_structp; png_structpp = PPpng_struct; function png_access_version_number:png_uint_32;cdecl; external LibPng; procedure png_set_sig_bytes(png_ptr:png_structp; num_bytes:longint);cdecl; external LibPng; function png_sig_cmp(sig:png_bytep; start:png_size_t; num_to_check:png_size_t):longint;cdecl; external LibPng; function png_check_sig(sig:png_bytep; num:longint):longint;cdecl; external LibPng; function png_create_read_struct(user_png_ver:png_const_charp; error_ptr:png_voidp; error_fn:png_error_ptr; warn_fn:png_error_ptr):png_structp;cdecl; external LibPng; function png_create_write_struct(user_png_ver:png_const_charp; error_ptr:png_voidp; error_fn:png_error_ptr; warn_fn:png_error_ptr):png_structp;cdecl; external LibPng; function png_get_compression_buffer_size(png_ptr:png_structp):png_uint_32;cdecl; external LibPng; procedure png_set_compression_buffer_size(png_ptr:png_structp; size:png_uint_32);cdecl; external LibPng; function png_reset_zstream(png_ptr:png_structp):longint;cdecl; external LibPng; procedure png_write_chunk(png_ptr:png_structp; chunk_name:png_bytep; data:png_bytep; length:png_size_t);cdecl; external LibPng; procedure png_write_chunk_start(png_ptr:png_structp; chunk_name:png_bytep; length:png_uint_32);cdecl; external LibPng; procedure png_write_chunk_data(png_ptr:png_structp; data:png_bytep; length:png_size_t);cdecl; external LibPng; procedure png_write_chunk_end(png_ptr:png_structp);cdecl; external LibPng; function png_create_info_struct(png_ptr:png_structp):png_infop;cdecl; external LibPng; procedure png_info_init(info_ptr:png_infop);cdecl; external LibPng; procedure png_write_info_before_PLTE(png_ptr:png_structp; info_ptr:png_infop);cdecl; external LibPng; procedure png_write_info(png_ptr:png_structp; info_ptr:png_infop);cdecl; external LibPng; procedure png_read_info(png_ptr:png_structp; info_ptr:png_infop);cdecl; external LibPng; function png_convert_to_rfc1123(png_ptr:png_structp; ptime:png_timep):png_charp;cdecl; external LibPng; procedure png_convert_from_struct_tm(ptime:png_timep; ttime:Pointer);cdecl; external LibPng; procedure png_convert_from_time_t(ptime:png_timep; ttime:time_t);cdecl; external LibPng; procedure png_set_expand(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_gray_1_2_4_to_8(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_palette_to_rgb(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_tRNS_to_alpha(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_bgr(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_gray_to_rgb(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_rgb_to_gray(png_ptr:png_structp; error_action:longint; red:double; green:double);cdecl; external LibPng; procedure png_set_rgb_to_gray_fixed(png_ptr:png_structp; error_action:longint; red:png_fixed_point; green:png_fixed_point);cdecl; external LibPng; function png_get_rgb_to_gray_status(png_ptr:png_structp):png_byte;cdecl; external LibPng; procedure png_build_grayscale_palette(bit_depth:longint; palette:png_colorp);cdecl; external LibPng; procedure png_set_strip_alpha(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_swap_alpha(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_invert_alpha(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_filler(png_ptr:png_structp; filler:png_uint_32; flags:longint);cdecl; external LibPng; procedure png_set_swap(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_packing(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_packswap(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_shift(png_ptr:png_structp; true_bits:png_color_8p);cdecl; external LibPng; function png_set_interlace_handling(png_ptr:png_structp):longint;cdecl; external LibPng; procedure png_set_invert_mono(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_background(png_ptr:png_structp; background_color:png_color_16p; background_gamma_code:longint; need_expand:longint; background_gamma:double);cdecl; external LibPng; procedure png_set_strip_16(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_dither(png_ptr:png_structp; palette:png_colorp; num_palette:longint; maximum_colors:longint; histogram:png_uint_16p; full_dither:longint);cdecl; external LibPng; procedure png_set_gamma(png_ptr:png_structp; screen_gamma:double; default_file_gamma:double);cdecl; external LibPng; procedure png_permit_empty_plte(png_ptr:png_structp; empty_plte_permitted:longint);cdecl; external LibPng; procedure png_set_flush(png_ptr:png_structp; nrows:longint);cdecl; external LibPng; procedure png_write_flush(png_ptr:png_structp);cdecl; external LibPng; procedure png_start_read_image(png_ptr:png_structp);cdecl; external LibPng; procedure png_read_update_info(png_ptr:png_structp; info_ptr:png_infop);cdecl; external LibPng; procedure png_read_rows(png_ptr:png_structp; row:png_bytepp; display_row:png_bytepp; num_rows:png_uint_32);cdecl; external LibPng; procedure png_read_row(png_ptr:png_structp; row:png_bytep; display_row:png_bytep);cdecl; external LibPng; procedure png_read_image(png_ptr:png_structp; image:png_bytepp);cdecl; external LibPng; procedure png_write_row(png_ptr:png_structp; row:png_bytep);cdecl; external LibPng; procedure png_write_rows(png_ptr:png_structp; row:png_bytepp; num_rows:png_uint_32);cdecl; external LibPng; procedure png_write_image(png_ptr:png_structp; image:png_bytepp);cdecl; external LibPng; procedure png_write_end(png_ptr:png_structp; info_ptr:png_infop);cdecl; external LibPng; procedure png_read_end(png_ptr:png_structp; info_ptr:png_infop);cdecl; external LibPng; procedure png_destroy_info_struct(png_ptr:png_structp; info_ptr_ptr:png_infopp);cdecl; external LibPng; procedure png_destroy_read_struct(png_ptr_ptr:png_structpp; info_ptr_ptr:png_infopp; end_info_ptr_ptr:png_infopp);cdecl; external LibPng; procedure png_read_destroy(png_ptr:png_structp; info_ptr:png_infop; end_info_ptr:png_infop);cdecl; external LibPng; procedure png_destroy_write_struct(png_ptr_ptr:png_structpp; info_ptr_ptr:png_infopp);cdecl; external LibPng; procedure png_write_destroy_info(info_ptr:png_infop);cdecl; external LibPng; procedure png_write_destroy(png_ptr:png_structp);cdecl; external LibPng; procedure png_set_crc_action(png_ptr:png_structp; crit_action:longint; ancil_action:longint);cdecl; external LibPng; procedure png_set_filter(png_ptr:png_structp; method:longint; filters:longint);cdecl; external LibPng; procedure png_set_filter_heuristics(png_ptr:png_structp; heuristic_method:longint; num_weights:longint; filter_weights:png_doublep; filter_costs:png_doublep);cdecl; external LibPng; procedure png_set_compression_level(png_ptr:png_structp; level:longint);cdecl; external LibPng; procedure png_set_compression_mem_level(png_ptr:png_structp; mem_level:longint);cdecl; external LibPng; procedure png_set_compression_strategy(png_ptr:png_structp; strategy:longint);cdecl; external LibPng; procedure png_set_compression_window_bits(png_ptr:png_structp; window_bits:longint);cdecl; external LibPng; procedure png_set_compression_method(png_ptr:png_structp; method:longint);cdecl; external LibPng; procedure png_init_io(png_ptr:png_structp; fp:png_FILE_p);cdecl; external LibPng; procedure png_set_error_fn(png_ptr:png_structp; error_ptr:png_voidp; error_fn:png_error_ptr; warning_fn:png_error_ptr);cdecl; external LibPng; function png_get_error_ptr(png_ptr:png_structp):png_voidp;cdecl; external LibPng; procedure png_set_write_fn(png_ptr:png_structp; io_ptr:png_voidp; write_data_fn:png_rw_ptr; output_flush_fn:png_flush_ptr);cdecl; external LibPng; procedure png_set_read_fn(png_ptr:png_structp; io_ptr:png_voidp; read_data_fn:png_rw_ptr);cdecl; external LibPng; function png_get_io_ptr(png_ptr:png_structp):png_voidp;cdecl; external LibPng; procedure png_set_read_status_fn(png_ptr:png_structp; read_row_fn:png_read_status_ptr);cdecl; external LibPng; procedure png_set_write_status_fn(png_ptr:png_structp; write_row_fn:png_write_status_ptr);cdecl; external LibPng; procedure png_set_read_user_transform_fn(png_ptr:png_structp; read_user_transform_fn:png_user_transform_ptr);cdecl; external LibPng; procedure png_set_write_user_transform_fn(png_ptr:png_structp; write_user_transform_fn:png_user_transform_ptr);cdecl; external LibPng; procedure png_set_user_transform_info(png_ptr:png_structp; user_transform_ptr:png_voidp; user_transform_depth:longint; user_transform_channels:longint);cdecl; external LibPng; function png_get_user_transform_ptr(png_ptr:png_structp):png_voidp;cdecl; external LibPng; procedure png_set_read_user_chunk_fn(png_ptr:png_structp; user_chunk_ptr:png_voidp; read_user_chunk_fn:png_user_chunk_ptr);cdecl; external LibPng; function png_get_user_chunk_ptr(png_ptr:png_structp):png_voidp;cdecl; external LibPng; procedure png_set_progressive_read_fn(png_ptr:png_structp; progressive_ptr:png_voidp; info_fn:png_progressive_info_ptr; row_fn:png_progressive_row_ptr; end_fn:png_progressive_end_ptr);cdecl; external LibPng; function png_get_progressive_ptr(png_ptr:png_structp):png_voidp;cdecl; external LibPng; procedure png_process_data(png_ptr:png_structp; info_ptr:png_infop; buffer:png_bytep; buffer_size:png_size_t);cdecl; external LibPng; procedure png_progressive_combine_row(png_ptr:png_structp; old_row:png_bytep; new_row:png_bytep);cdecl; external LibPng; function png_malloc(png_ptr:png_structp; size:png_uint_32):png_voidp;cdecl; external LibPng; procedure png_free(png_ptr:png_structp; ptr:png_voidp);cdecl; external LibPng; procedure png_free_data(png_ptr:png_structp; info_ptr:png_infop; free_me:png_uint_32; num:longint);cdecl; external LibPng; procedure png_data_freer(png_ptr:png_structp; info_ptr:png_infop; freer:longint; mask:png_uint_32);cdecl; external LibPng; function png_memcpy_check(png_ptr:png_structp; s1:png_voidp; s2:png_voidp; size:png_uint_32):png_voidp;cdecl; external LibPng; function png_memset_check(png_ptr:png_structp; s1:png_voidp; value:longint; size:png_uint_32):png_voidp;cdecl; external LibPng; procedure png_error(png_ptr:png_structp; error:png_const_charp);cdecl; external LibPng; procedure png_chunk_error(png_ptr:png_structp; error:png_const_charp);cdecl; external LibPng; procedure png_warning(png_ptr:png_structp; message:png_const_charp);cdecl; external LibPng; procedure png_chunk_warning(png_ptr:png_structp; message:png_const_charp);cdecl; external LibPng; function png_get_valid(png_ptr:png_structp; info_ptr:png_infop; flag:png_uint_32):png_uint_32;cdecl; external LibPng; function png_get_rowbytes(png_ptr:png_structp; info_ptr:png_infop):png_uint_32;cdecl; external LibPng; function png_get_rows(png_ptr:png_structp; info_ptr:png_infop):png_bytepp;cdecl; external LibPng; procedure png_set_rows(png_ptr:png_structp; info_ptr:png_infop; row_pointers:png_bytepp);cdecl; external LibPng; function png_get_channels(png_ptr:png_structp; info_ptr:png_infop):png_byte;cdecl; external LibPng; function png_get_image_width(png_ptr:png_structp; info_ptr:png_infop):png_uint_32;cdecl; external LibPng; function png_get_image_height(png_ptr:png_structp; info_ptr:png_infop):png_uint_32;cdecl; external LibPng; function png_get_bit_depth(png_ptr:png_structp; info_ptr:png_infop):png_byte;cdecl; external LibPng; function png_get_color_type(png_ptr:png_structp; info_ptr:png_infop):png_byte;cdecl; external LibPng; function png_get_filter_type(png_ptr:png_structp; info_ptr:png_infop):png_byte;cdecl; external LibPng; function png_get_interlace_type(png_ptr:png_structp; info_ptr:png_infop):png_byte;cdecl; external LibPng; function png_get_compression_type(png_ptr:png_structp; info_ptr:png_infop):png_byte;cdecl; external LibPng; function png_get_pixels_per_meter(png_ptr:png_structp; info_ptr:png_infop):png_uint_32;cdecl; external LibPng; function png_get_x_pixels_per_meter(png_ptr:png_structp; info_ptr:png_infop):png_uint_32;cdecl; external LibPng; function png_get_y_pixels_per_meter(png_ptr:png_structp; info_ptr:png_infop):png_uint_32;cdecl; external LibPng; function png_get_pixel_aspect_ratio(png_ptr:png_structp; info_ptr:png_infop):double;cdecl; external LibPng; function png_get_x_offset_pixels(png_ptr:png_structp; info_ptr:png_infop):png_int_32;cdecl; external LibPng; function png_get_y_offset_pixels(png_ptr:png_structp; info_ptr:png_infop):png_int_32;cdecl; external LibPng; function png_get_x_offset_microns(png_ptr:png_structp; info_ptr:png_infop):png_int_32;cdecl; external LibPng; function png_get_y_offset_microns(png_ptr:png_structp; info_ptr:png_infop):png_int_32;cdecl; external LibPng; function png_get_signature(png_ptr:png_structp; info_ptr:png_infop):png_bytep;cdecl; external LibPng; function png_get_bKGD(png_ptr:png_structp; info_ptr:png_infop; background:Ppng_color_16p):png_uint_32;cdecl; external LibPng; procedure png_set_bKGD(png_ptr:png_structp; info_ptr:png_infop; background:png_color_16p);cdecl; external LibPng; function png_get_cHRM(png_ptr:png_structp; info_ptr:png_infop; white_x:Pdouble; white_y:Pdouble; red_x:Pdouble; red_y:Pdouble; green_x:Pdouble; green_y:Pdouble; blue_x:Pdouble; blue_y:Pdouble):png_uint_32;cdecl; external LibPng; function png_get_cHRM_fixed(png_ptr:png_structp; info_ptr:png_infop; int_white_x:Ppng_fixed_point; int_white_y:Ppng_fixed_point; int_red_x:Ppng_fixed_point; int_red_y:Ppng_fixed_point; int_green_x:Ppng_fixed_point; int_green_y:Ppng_fixed_point; int_blue_x:Ppng_fixed_point; int_blue_y:Ppng_fixed_point):png_uint_32;cdecl; external LibPng; procedure png_set_cHRM(png_ptr:png_structp; info_ptr:png_infop; white_x:double; white_y:double; red_x:double; red_y:double; green_x:double; green_y:double; blue_x:double; blue_y:double);cdecl; external LibPng; procedure png_set_cHRM_fixed(png_ptr:png_structp; info_ptr:png_infop; int_white_x:png_fixed_point; int_white_y:png_fixed_point; int_red_x:png_fixed_point; int_red_y:png_fixed_point; int_green_x:png_fixed_point; int_green_y:png_fixed_point; int_blue_x:png_fixed_point; int_blue_y:png_fixed_point);cdecl; external LibPng; function png_get_gAMA(png_ptr:png_structp; info_ptr:png_infop; file_gamma:Pdouble):png_uint_32;cdecl; external LibPng; function png_get_gAMA_fixed(png_ptr:png_structp; info_ptr:png_infop; int_file_gamma:Ppng_fixed_point):png_uint_32;cdecl; external LibPng; procedure png_set_gAMA(png_ptr:png_structp; info_ptr:png_infop; file_gamma:double);cdecl; external LibPng; procedure png_set_gAMA_fixed(png_ptr:png_structp; info_ptr:png_infop; int_file_gamma:png_fixed_point);cdecl; external LibPng; function png_get_hIST(png_ptr:png_structp; info_ptr:png_infop; hist:Ppng_uint_16p):png_uint_32;cdecl; external LibPng; procedure png_set_hIST(png_ptr:png_structp; info_ptr:png_infop; hist:png_uint_16p);cdecl; external LibPng; function png_get_IHDR(png_ptr:png_structp; info_ptr:png_infop; width:Ppng_uint_32; height:Ppng_uint_32; bit_depth:Plongint; color_type:Plongint; interlace_type:Plongint; compression_type:Plongint; filter_type:Plongint):png_uint_32;cdecl; external LibPng; procedure png_set_IHDR(png_ptr:png_structp; info_ptr:png_infop; width:png_uint_32; height:png_uint_32; bit_depth:longint; color_type:longint; interlace_type:longint; compression_type:longint; filter_type:longint);cdecl; external LibPng; function png_get_oFFs(png_ptr:png_structp; info_ptr:png_infop; offset_x:Ppng_int_32; offset_y:Ppng_int_32; unit_type:Plongint):png_uint_32;cdecl; external LibPng; procedure png_set_oFFs(png_ptr:png_structp; info_ptr:png_infop; offset_x:png_int_32; offset_y:png_int_32; unit_type:longint);cdecl; external LibPng; function png_get_pCAL(png_ptr:png_structp; info_ptr:png_infop; purpose:Ppng_charp; X0:Ppng_int_32; X1:Ppng_int_32; atype:Plongint; nparams:Plongint; units:Ppng_charp; params:Ppng_charpp):png_uint_32;cdecl; external LibPng; procedure png_set_pCAL(png_ptr:png_structp; info_ptr:png_infop; purpose:png_charp; X0:png_int_32; X1:png_int_32; atype:longint; nparams:longint; units:png_charp; params:png_charpp);cdecl; external LibPng; function png_get_pHYs(png_ptr:png_structp; info_ptr:png_infop; res_x:Ppng_uint_32; res_y:Ppng_uint_32; unit_type:Plongint):png_uint_32;cdecl; external LibPng; procedure png_set_pHYs(png_ptr:png_structp; info_ptr:png_infop; res_x:png_uint_32; res_y:png_uint_32; unit_type:longint);cdecl; external LibPng; function png_get_PLTE(png_ptr:png_structp; info_ptr:png_infop; palette:Ppng_colorp; num_palette:Plongint):png_uint_32;cdecl; external LibPng; procedure png_set_PLTE(png_ptr:png_structp; info_ptr:png_infop; palette:png_colorp; num_palette:longint);cdecl; external LibPng; function png_get_sBIT(png_ptr:png_structp; info_ptr:png_infop; sig_bit:Ppng_color_8p):png_uint_32;cdecl; external LibPng; procedure png_set_sBIT(png_ptr:png_structp; info_ptr:png_infop; sig_bit:png_color_8p);cdecl; external LibPng; function png_get_sRGB(png_ptr:png_structp; info_ptr:png_infop; intent:Plongint):png_uint_32;cdecl; external LibPng; procedure png_set_sRGB(png_ptr:png_structp; info_ptr:png_infop; intent:longint);cdecl; external LibPng; procedure png_set_sRGB_gAMA_and_cHRM(png_ptr:png_structp; info_ptr:png_infop; intent:longint);cdecl; external LibPng; function png_get_iCCP(png_ptr:png_structp; info_ptr:png_infop; name:png_charpp; compression_type:Plongint; profile:png_charpp; proflen:Ppng_uint_32):png_uint_32;cdecl; external LibPng; procedure png_set_iCCP(png_ptr:png_structp; info_ptr:png_infop; name:png_charp; compression_type:longint; profile:png_charp; proflen:png_uint_32);cdecl; external LibPng; function png_get_sPLT(png_ptr:png_structp; info_ptr:png_infop; entries:png_sPLT_tpp):png_uint_32;cdecl; external LibPng; procedure png_set_sPLT(png_ptr:png_structp; info_ptr:png_infop; entries:png_sPLT_tp; nentries:longint);cdecl; external LibPng; function png_get_text(png_ptr:png_structp; info_ptr:png_infop; text_ptr:Ppng_textp; num_text:Plongint):png_uint_32;cdecl; external LibPng; procedure png_set_text(png_ptr:png_structp; info_ptr:png_infop; text_ptr:png_textp; num_text:longint);cdecl; external LibPng; function png_get_tIME(png_ptr:png_structp; info_ptr:png_infop; mod_time:Ppng_timep):png_uint_32;cdecl; external LibPng; procedure png_set_tIME(png_ptr:png_structp; info_ptr:png_infop; mod_time:png_timep);cdecl; external LibPng; function png_get_tRNS(png_ptr:png_structp; info_ptr:png_infop; trans:Ppng_bytep; num_trans:Plongint; trans_values:Ppng_color_16p):png_uint_32;cdecl; external LibPng; procedure png_set_tRNS(png_ptr:png_structp; info_ptr:png_infop; trans:png_bytep; num_trans:longint; trans_values:png_color_16p);cdecl; external LibPng; function png_get_sCAL(png_ptr:png_structp; info_ptr:png_infop; aunit:Plongint; width:Pdouble; height:Pdouble):png_uint_32;cdecl; external LibPng; procedure png_set_sCAL(png_ptr:png_structp; info_ptr:png_infop; aunit:longint; width:double; height:double);cdecl; external LibPng; procedure png_set_sCAL_s(png_ptr:png_structp; info_ptr:png_infop; aunit:longint; swidth:png_charp; sheight:png_charp);cdecl; external LibPng; procedure png_set_keep_unknown_chunks(png_ptr:png_structp; keep:longint; chunk_list:png_bytep; num_chunks:longint);cdecl; external LibPng; procedure png_set_unknown_chunks(png_ptr:png_structp; info_ptr:png_infop; unknowns:png_unknown_chunkp; num_unknowns:longint);cdecl; external LibPng; procedure png_set_unknown_chunk_location(png_ptr:png_structp; info_ptr:png_infop; chunk:longint; location:longint);cdecl; external LibPng; function png_get_unknown_chunks(png_ptr:png_structp; info_ptr:png_infop; entries:png_unknown_chunkpp):png_uint_32;cdecl; external LibPng; procedure png_set_invalid(png_ptr:png_structp; info_ptr:png_infop; mask:longint);cdecl; external LibPng; procedure png_read_png(png_ptr:png_structp; info_ptr:png_infop; transforms:longint; params:voidp);cdecl; external LibPng; procedure png_write_png(png_ptr:png_structp; info_ptr:png_infop; transforms:longint; params:voidp);cdecl; external LibPng; function png_get_header_ver(png_ptr:png_structp):png_charp;cdecl; external LibPng; function png_get_header_version(png_ptr:png_structp):png_charp;cdecl; external LibPng; function png_get_libpng_ver(png_ptr:png_structp):png_charp;cdecl; external LibPng; {$ifend} implementation end.
unit Form.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Actions, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ActnList, Vcl.DBActns, Vcl.StdCtrls, Plus.TWork, Work.CommandOne, Work.Async.NotShippedOrders; type TForm1 = class(TForm) GroupBox1: TGroupBox; Button1: TButton; Button2: TButton; lblResults: TLabel; procedure FormCreate(Sender: TObject); private actCommandOne: TWorkAction; actNotShipped: TWorkAction; procedure EventWork2Started(Sender: TObject; Work:TWork); procedure EventWork2Done(Sender: TObject; Work:TWork); procedure Event_OnActionExecute(Sender: TObject); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.EventWork2Done(Sender: TObject; Work:TWork); var WorkResult: string; begin WorkResult := (Work as TNotShippedOrdersWork).NotShippedOrders.ToString; lblResults.Caption := 'Not Shipped orders: ' + sLineBreak + WorkResult; end; procedure TForm1.EventWork2Started(Sender: TObject; Work:TWork); begin lblResults.Caption := '...'; end; procedure TForm1.Event_OnActionExecute(Sender: TObject); begin actCommandOne.Caption := 'Shortcut'; end; procedure TForm1.FormCreate(Sender: TObject); begin // -------------------------------------------------------------------- // -------------------------------------------------------------------- actCommandOne := TWorkAction.Create(Self); actCommandOne.Caption := 'Command One: Click to preapre'; // TODO: Provide proper code, this is not working: // actCommandOne.ShortCut := Vcl.Menus.TextToShortCut('Ctrl+1'); // actCommandOne.ShortCut := System.Classes.scCtrl + System.UITypes.vk1; actCommandOne.OnExecute := Event_OnActionExecute; Button1.Action := actCommandOne; // actCommandOne.CreateAndAddWork(TCommandOneWork); // -------------------------------------------------------------------- // -------------------------------------------------------------------- actNotShipped := TWorkAction.Create(Self); actNotShipped.Caption := 'Get not shipped orders (SQLite_Demo)'; Button2.Action := actNotShipped; actNotShipped.CreateAndAddWork(TNotShippedOrdersWork); actNotShipped.OnWorkStarted := EventWork2Started; actNotShipped.OnWorkDone := EventWork2Done; end; end.
(* * Copyright (c) 2008, Susnea Andrei * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''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 <copyright holder> 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. *) unit Tests.Map; interface uses SysUtils, TestFramework, HelperLib.TypeSupport, HelperLib.Collections.Dictionary, HelperLib.Collections.KeyValuePair, HelperLib.Collections.Map, HelperLib.Collections.Exceptions; type TExceptionClosure = reference to procedure; TClassOfException = class of Exception; TTestMap = class(TTestCase) private procedure CheckException(ExType : TClassOfException; Proc : TExceptionClosure; const Msg : String); published procedure TestCreationAndDestroy(); procedure TestInsertAddRemoveClearCount(); procedure TestContainsFindItems(); procedure TestCopyTo(); procedure TestEnumerator(); procedure TestExceptions(); procedure TestBigCounts(); end; implementation { TTestQueue } procedure TTestMap.CheckException(ExType: TClassOfException; Proc: TExceptionClosure; const Msg: String); var bWasEx : Boolean; begin bWasEx := False; try { Cannot self-link } Proc(); except on E : Exception do begin if E is ExType then bWasEx := True; end; end; Check(bWasEx, Msg); end; procedure TTestMap.TestBigCounts; const NrCount = 1000; var Map : HMap<Integer, Integer>; I, X : Integer; KV : HKeyValuePair<Integer, Integer>; CIn, SumV, SumK : Int64; begin Map := HMap<Integer, Integer>.Create(); Randomize; CIn := 0; SumV := 0; SumK := 0; for I := 0 to NrCount - 1 do begin X := Random(MaxInt); if not Map.Contains(X) then begin Map.Insert(X, I); Inc(CIn); SumV := SumV + I; SumK := SumK + X; end; end; Check(Map.Count = CIn, 'Expected count to be ' + IntToStr(CIn)); for I := 0 to Map.Count - 1 do begin KV := Map[I]; SumV := SumV - KV.Value; SumK := SumK - KV.Key; end; Check(SumK = 0, 'Expectency to cover all keys failed!'); Check(SumV = 0, 'Expectency to cover all values failed!'); Map.Free; end; procedure TTestMap.TestContainsFindItems; var Map : HMap <String, Integer>; begin Map := HMap<String, Integer>.Create(); { Add some stuff } Map.Insert('Key 1', 1); Map.Insert('Key 2', 2); Map.Insert('Key 3', 3); Map.Insert('Key 4', 4); Map.Insert('Key 5', 5); { First checks } Check(Map.Contains('Key 1'), 'Map expected to contain "Key 1"'); Check(Map.Contains('Key 2'), 'Map expected to contain "Key 2"'); Check(Map.Contains('Key 3'), 'Map expected to contain "Key 3"'); Check(Map.Contains('Key 4'), 'Map expected to contain "Key 4"'); Check(Map.Contains('Key 5'), 'Map expected to contain "Key 5"'); Check(not Map.Contains('Key 6'), 'Map expected not to contain "Key 6"'); { Indexer } Check(Map[0].Key = 'Key 1', 'Map[0] expected to be "Key 1"'); Check(Map[1].Key = 'Key 2', 'Map[1] expected to be "Key 2"'); Check(Map[2].Key = 'Key 3', 'Map[2] expected to be "Key 3"'); Check(Map[3].Key = 'Key 4', 'Map[3] expected to be "Key 4"'); Check(Map[4].Key = 'Key 5', 'Map[4] expected to be "Key 5"'); { Find checks } Check(Map.Find('Key 1') = 1, 'Map expected to find "Key 1" = 1'); Check(Map.Find('Key 2') = 2, 'Map expected to find "Key 2" = 2'); Check(Map.Find('Key 3') = 3, 'Map expected to find "Key 3" = 3'); Check(Map.Find('Key 4') = 4, 'Map expected to find "Key 4" = 4'); Check(Map.Find('Key 5') = 5, 'Map expected to find "Key 5" = 5'); Map.Free; end; procedure TTestMap.TestCopyTo; var Map : HMap <Integer, String>; IL : array of HKeyValuePair<Integer, String>; begin Map := HMap<Integer, String>.Create(); Map.Insert(4, '4'); Map.Insert(1, '1'); Map.Insert(89, '89'); Map.Insert(7, '7'); Map.Insert(123, '123'); { Check the copy } SetLength(IL, 5); Map.CopyTo(IL); Check((IL[0].Key = 4) and (IL[0].Value = '4'), 'Element 0 in the new array is wrong!'); Check((IL[1].Key = 1) and (IL[1].Value = '1'), 'Element 1 in the new array is wrong!'); Check((IL[2].Key = 89) and (IL[2].Value = '89'), 'Element 2 in the new array is wrong!'); Check((IL[3].Key = 7) and (IL[3].Value = '7'), 'Element 3 in the new array is wrong!'); Check((IL[4].Key = 123) and (IL[4].Value = '123'), 'Element 4 in the new array is wrong!'); { Check the copy with index } SetLength(IL, 6); Map.CopyTo(IL, 1); Check((IL[1].Key = 4) and (IL[1].Value = '4'), 'Element 1 in the new array is wrong!'); Check((IL[2].Key = 1) and (IL[2].Value = '1'), 'Element 2 in the new array is wrong!'); Check((IL[3].Key = 89) and (IL[3].Value = '89'), 'Element 3 in the new array is wrong!'); Check((IL[4].Key = 7) and (IL[4].Value = '7'), 'Element 4 in the new array is wrong!'); Check((IL[5].Key = 123) and (IL[5].Value = '123'), 'Element 5 in the new array is wrong!'); { Exception } SetLength(IL, 4); CheckException(EArgumentOutOfRangeException, procedure() begin Map.CopyTo(IL); end, 'EArgumentOutOfRangeException not thrown in CopyTo (too small size).' ); SetLength(IL, 5); CheckException(EArgumentOutOfRangeException, procedure() begin Map.CopyTo(IL, 1); end, 'EArgumentOutOfRangeException not thrown in CopyTo (too small size +1).' ); Map.Free(); end; procedure TTestMap.TestCreationAndDestroy; var Map : HMap <Integer, Boolean>; Dict : HDictionary<Integer, Boolean>; begin Map := HMap<Integer, Boolean>.Create(); Map.Insert(1, False); Map.Insert(5, True); Map.Insert(3, True); Map.Insert(2, False); { Check map values } Check((Map.Count = 4) and (Map.Count = Map.GetCount()), 'Count of elements expected to be 4'); Map.Insert(6, True); Check((Map.Count = 5) and (Map.Count = Map.GetCount()), 'Count of elements expected to be 5'); Map.Free; { Copy constructor } Dict := HDictionary<Integer, Boolean>.Create(); Dict.Add(1, False); Dict.Add(2, False); Dict.Add(3, True); Dict.Add(4, True); Map := HMap<Integer, Boolean>.Create(Dict); { Check map values } Check((Map.Count = 4) and (Map.Count = Map.GetCount()), 'Count of elements expected to be 4'); { First checks } Check(Map.Contains(1), 'Map expected to contain 1'); Check(Map.Contains(2), 'Map expected to contain 2'); Check(Map.Contains(3), 'Map expected to contain 3'); Check(Map.Contains(4), 'Map expected to contain 4'); Check(not Map.Contains(6), 'Map expected not to contain 6'); Map.Free; Dict.Free; end; procedure TTestMap.TestEnumerator; var Map : HMap<Integer, Integer>; X : Integer; I : HKeyValuePair<Integer, Integer>; begin Map := HMap<Integer, Integer>.Create(); Map.Insert(10, 11); Map.Insert(20, 21); Map.Insert(30, 31); X := 0; for I in Map do begin if X = 0 then Check((I.Key = 10) and (I.Value = 11), 'Enumerator failed at 0!') else if X = 1 then Check((I.Key = 20) and (I.Value = 21), 'Enumerator failed at 1!') else if X = 2 then Check((I.Key = 30) and (I.Value = 31), 'Enumerator failed at 2!') else Fail('Enumerator failed!'); Inc(X); end; { Test exceptions } CheckException(ECollectionChanged, procedure() var I : HKeyValuePair<Integer, Integer>; begin for I in Map do begin Map.Remove(I.Key); end; end, 'ECollectionChanged not thrown in Enumerator!' ); Check(Map.Count = 2, 'Enumerator failed too late'); Map.Free(); end; procedure TTestMap.TestExceptions; var Map : HMap<String, Integer>; NullArg : ITypeSupport<String>; begin NullArg := nil; CheckException(EArgumentException, procedure() begin Map := HMap<String, Integer>.Create(NullArg); Map.Free(); end, 'EArgumentException not thrown in constructor (nil comparer).' ); CheckException(EArgumentException, procedure() begin Map := HMap<String, Integer>.Create(NullArg, nil); Map.Free(); end, 'EArgumentException not thrown in constructor (nil comparer).' ); CheckException(EArgumentException, procedure() begin Map := HMap<String, Integer>.Create(HTypeSupport<String>.Default, nil); Map.Free(); end, 'EArgumentException not thrown in constructor (nil enum).' ); Map := HMap<String, Integer>.Create(); CheckException(EDuplicateKeyException, procedure() begin Map.Insert('A', 2); Map.Insert('A', 7); end, 'EDuplicateKeyException not thrown in Insert.' ); CheckException(EKeyNotFoundException, procedure() begin Map.Remove('H'); end, 'EKeyNotFoundException not thrown in Remove.' ); CheckException(EKeyNotFoundException, procedure() begin Map.Find('H'); end, 'EKeyNotFoundException not thrown in Find.' ); CheckException(EArgumentOutOfRangeException, procedure() begin Map.Insert('first', 1); Map.Insert('second', 2); if Map[10].Key = 'string' then Exit; end, 'EArgumentOutOfRangeException not thrown (Items[X]).' ); Map.Free; end; procedure TTestMap.TestInsertAddRemoveClearCount; var Map : HMap <Integer, Boolean>; begin Map := HMap<Integer, Boolean>.Create(); Map.Insert(3, False); Map.Insert(4, True); Map.Insert(2, True); Check((Map.Count = 3) and (Map.Count = Map.GetCount()), 'Map count expected to be 3'); Map.Remove(3); Check((Map.Count = 2) and (Map.Count = Map.GetCount()), 'Map count expected to be 2'); Map.Remove(2); Map.Remove(4); Check((Map.Count = 0) and (Map.Count = Map.GetCount()), 'Map count expected to be 0'); Map.Insert(10, True); Map.Insert(15, True); Map.Insert(3, True); Map.Insert(7, True); Map.Insert(2, True); Check((Map.Count = 5) and (Map.Count = Map.GetCount()), 'Map count expected to be 5'); Map.Clear(); Check((Map.Count = 0) and (Map.Count = Map.GetCount()), 'Map count expected to be 0'); //now a little more complicated test { 4 / \ 2 7 / \ / \ 1 3 5 8 \ 6 } //left branch Map.Insert(4, True); Map.Insert(2, True); Map.Insert(1, True); Map.Insert(3, True); //right branch Map.Insert(7, True); Map.Insert(5, True); Map.Insert(6, True); Map.Insert(8, True); //removing the root Map.Remove(4); Check((Map.Count = 7) and (Map.Count = Map.GetCount()), 'Map count expected to be 7'); Map.Free; end; initialization TestFramework.RegisterTest(TTestMap.Suite); end.
{NIM/Nama : Agung Pratama Nama file : B03-16515046-151028-01.pas Tanggal : 28 Oktober 2015 Deskripsi : Membuat Kalkulator dengan pilihan menu. 1: tambah, 2: kurang, 3: kali, 4:bagi, 5:pangkat, 6:pola} Program KalkulatorTuanFin; uses crt; {Kamus} var n,i: integer; hasil: real; x,y,z: integer; lagi:string; {Deklarasi dan Realisasi Prosedur} procedure Main_Menu(var m:integer); {Menerima m dan melakukan aksi sesuai input} {I.S. : m terdefinisi} {F.S. : melanjutkan ke fungsi sesuai masukan yang diinginkan} {Algoritma} begin writeln('Pilihan Menu Kalkulator: '); writeln('1. Tambah'); writeln('2. Kurang'); writeln('3. Kali'); writeln('4. Bagi'); writeln('5. Pangkat'); writeln('6. Gambar Pola'); write('Input Pilihan: '); readln(m); end; {Deklarasi dan Realisasi Fungsi} function tambah(a,b: integer):integer; {Menambahkan nilai a dan b} {Algoritma} begin tambah:=a+b; end; function kurang(a,b: integer):integer; {Mengurangkan nilai a dan b} {Algoritma} begin kurang:=a-b; end; function kali(a,b:integer): integer; {Mengalikan nilai a dan b} {Algoritma} begin kali:=a*b; end; function bagi(a,b: integer): real; {membagi a dan b} {Algoritma} begin bagi:=a/b; end; function pangkat(a,b:integer): integer; {mempangkatkan a sebanyak b} {kamus lokal} var hslpngkt:integer; {Algoritma} begin hslpngkt:=1; for i:=1 to b do begin hslpngkt:=hslpngkt*a; end; pangkat:=hslpngkt; end; {Deklarasi dan Realisasi Prosedur} procedure gambar_pola(n:integer); {Menggambar Pola sesuai n} {I.S. : n terdefinisi} {F.S. : pola} {kamus lokal} var j: integer; {Algoritma} begin for i:=1 to n-1 do begin for j:=1 to (n-i) do begin write(' '); end; for j:=1 to i do begin write(j); end; for j:=i downto 2 do begin write(j-1); end; writeln; end; for i:=1 to n do begin write(i); end; for i:=n downto 2 do begin write(i-1); end; writeln; for i:=n-1 downto 1 do begin for j:=1 to (n-i) do begin write(' '); end; for j:=1 to i do begin write(j); end; for j:=i downto 2 do begin write(j-1); end; writeln; end; end; {Algoritma Program Utama} begin clrscr; lagi:='y'; while (lagi='y') do begin Main_Menu(n); if (n=1) or (n=2) or (n=3) or (n=4) or (n=5) then begin write('Masukkan nilai a: '); readln(x); write('Masukkan nilai b: '); readln(y); write('Hasil: '); end else if (n=6) then begin write('Masukkan nilai n: '); readln(z); end; if (n=1) then begin writeln(tambah(x,y)); end else if (n=2) then begin writeln(kurang(x,y)); end else if (n=3) then begin writeln(kali(x,y)); end else if (n=4) then begin writeln(bagi(x,y):4:2); end else if (n=5) then begin writeln(pangkat(x,y)); end else if (n=6) then begin gambar_pola(z); end; write('Apakah anda ingin menggunakan fitur lainnya? (y/n): '); readln(lagi); end; end.
unit DevMaxResource; // EMS Resource Module interface uses System.SysUtils, System.Classes, System.JSON, EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes; type [ResourceName('devmax')] TDevMaxManifestResource1 = class(TDataModule) published [ResourceSuffix('manifest/views')] procedure GetManifestViews(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [ResourceSuffix('manifest/views/{item}')] procedure GetManifestViewsItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); end; implementation {%CLASSGROUP 'System.Classes.TPersistent'} uses DataAccessObject; {$R *.dfm} procedure TDevMaxManifestResource1.GetManifestViews(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); begin // Sample code AResponse.Body.SetValue(TJSONString.Create('DevMax/Manifest'), True) end; procedure TDevMaxManifestResource1.GetManifestViewsItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var ViewId: string; JSONValue: TJSONValue; begin ViewId := ARequest.Params.Values['item']; JSONValue := TDataAccessObject.Instance.GetViewInfo(ViewId) as TJSONValue; if JSONValue = nil then AResponse.RaiseNotFound(); AResponse.Headers.SetValue('Content-Type', 'charset=utf-8'); AResponse.Body.SetValue(JSONValue, True); end; procedure Register; begin RegisterResource(TypeInfo(TDevMaxManifestResource1)); end; initialization Register; end.
{} {This is a comment} {This is a multi-line comment }
unit DW.Android.Helpers; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // Android Androidapi.JNI.JavaTypes, Androidapi.JNI.Net, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Os, Androidapi.JNI.App, // DW DW.Androidapi.JNI.App, DW.Androidapi.JNI.Os; type TAndroidHelperEx = record private class var FKeyguardManager: JKeyguardManager; class var FNotificationManager: JNotificationManager; class var FPowerManager: JPowerManager; class var FWakeLock: JPowerManager_WakeLock; public const ICE_CREAM_SANDWICH = 14; ICE_CREAM_SANDWICH_MR1 = 15; JELLY_BEAN = 16; JELLY_BEAN_MR1 = 17; JELLY_BEAN_MR2 = 18; KITKAT = 19; KITKAT_MR1 = 20; LOLLIPOP = 21; LOLLIPOP_MR1 = 22; MARSHMALLOW = 23; NOUGAT = 24; NOUGAT_MR1 = 25; OREO = 26; OREO_MR1 = 27; PIE = 28; Q = 29; /// <summary> /// Checks if both build and target are greater or equal to the tested value /// </summary> class function CheckBuildAndTarget(const AValue: Integer): Boolean; static; /// <summary> /// Enables/disables the Wake Lock. Needs Wake Lock checked in the Permissions section of the Project Options /// </summary> class procedure EnableWakeLock(const AEnable: Boolean); static; /// <summary> /// Returns the equivalent of "AndroidClass.class" /// </summary> class function GetClass(const APackageClassName: string): Jlang_Class; static; /// <summary> /// Returns the application default icon ID /// </summary> class function GetDefaultIconID: Integer; static; /// <summary> /// Returns a URI to the notification sound /// </summary> class function GetDefaultNotificationSound: Jnet_Uri; static; /// <summary> /// Returns target Sdk version /// </summary> class function GetTargetSdkVersion: Integer; static; /// <summary> /// Returns the time from now, plus the ASecondsFromNow /// </summary> class function GetTimeFromNowInMillis(const ASecondsFromNow: Int64): Int64; static; /// <summary> /// Returns installed Sdk version /// </summary> class function GetBuildSdkVersion: Integer; static; /// <summary> /// Returns information about a running service, if the service is running /// </summary> class function GetRunningServiceInfo(const AServiceName: string): JActivityManager_RunningServiceInfo; static; /// <summary> /// Returns whether the activity is running foreground /// </summary> /// <remarks> /// Useful from within a service to determine whether or not the service needs to run in foreground mode /// </remarks> class function IsActivityForeground: Boolean; static; /// <summary> /// Returns whether or not battery optimizations are being ignored /// </summary> class function IsIgnoringBatteryOptimizations: Boolean; static; /// <summary> /// Returns whether a service is running foreground /// </summary> class function IsServiceForeground(const AServiceName: string): Boolean; static; /// <summary> /// Returns whether or not a service is running /// </summary> class function IsServiceRunning(const AServiceName: string): Boolean; static; /// <summary> /// Returns the keyguard manager /// </summary> class function KeyguardManager: JKeyguardManager; static; /// <summary> /// Returns the notification manager /// </summary> class function NotificationManager: JNotificationManager; static; /// <summary> /// Returns the power manager /// </summary> class function PowerManager: JPowerManager; static; /// <summary> /// Restarts the app if it is not ignoring battery optimizations. /// </summary> /// <remarks> /// Needs this in the manifest: <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/> /// </remarks> class procedure RestartIfNotIgnoringBatteryOptimizations; static; /// <summary> /// Call this to start an activity from an alarm /// </summary> /// <remarks> /// Used in conjunction with dw-multireceiver.jar /// </remarks> class procedure SetStartAlarm(const AAlarm: TDateTime; const AStartFromLock: Boolean); static; /// <summary> /// Converts file to uri, using FileProvider if target API >= 24 /// </summary> /// <remarks> /// Use this only when accessing files with an "external" URI /// </remarks> class function UriFromFile(const AFile: JFile): Jnet_Uri; static; /// <summary> /// Converts filename to uri, using FileProvider if target API >= 24 /// </summary> /// <remarks> /// Use this only when accessing files with an "external" URI /// </remarks> class function UriFromFileName(const AFileName: string): Jnet_Uri; static; end; implementation uses // RTL System.SysUtils, System.DateUtils, // Android Androidapi.Helpers, Androidapi.JNI.Media, Androidapi.JNI.Provider, Androidapi.JNIBridge, // DW DW.Androidapi.JNI.SupportV4; const cReceiverClassName = 'DWMultiBroadcastReceiver'; cReceiverName = 'com.delphiworlds.kastri.' + cReceiverClassName; cActionStartAlarm = cReceiverName + '.ACTION_START_ALARM'; cExtraStartUnlock = cReceiverClassName + '.EXTRA_START_UNLOCK'; { TAndroidHelperEx } class function TAndroidHelperEx.CheckBuildAndTarget(const AValue: Integer): Boolean; begin Result := (GetBuildSdkVersion >= AValue) and (GetTargetSdkVersion >= AValue); end; class procedure TAndroidHelperEx.EnableWakeLock(const AEnable: Boolean); var LTag: string; begin if AEnable then begin if FWakeLock = nil then begin LTag := JStringToString(TAndroidHelper.Context.getPackageName) + '.wakelock'; FWakeLock := PowerManager.newWakeLock(TJPowerManager.JavaClass.PARTIAL_WAKE_LOCK, StringToJString(LTag)); end; if not FWakeLock.isHeld then FWakeLock.acquire; end else begin if (FWakeLock <> nil) and FWakeLock.isHeld then FWakeLock.release; FWakeLock := nil; end; end; class function TAndroidHelperEx.GetBuildSdkVersion: Integer; begin Result := TJBuild_VERSION.JavaClass.SDK_INT; end; class function TAndroidHelperEx.GetTimeFromNowInMillis(const ASecondsFromNow: Int64): Int64; begin Result := TJSystem.JavaClass.currentTimeMillis + (ASecondsFromNow * 1000); end; class function TAndroidHelperEx.GetClass(const APackageClassName: string): Jlang_Class; begin Result := TJLang_Class.JavaClass.forName(StringToJString(APackageClassName), True, TAndroidHelper.Context.getClassLoader); end; class function TAndroidHelperEx.GetDefaultIconID: Integer; begin Result := TAndroidHelper.Context.getApplicationInfo.icon; end; class function TAndroidHelperEx.GetDefaultNotificationSound: Jnet_Uri; begin Result := TJRingtoneManager.JavaClass.getDefaultUri(TJRingtoneManager.JavaClass.TYPE_NOTIFICATION); end; class function TAndroidHelperEx.UriFromFile(const AFile: JFile): Jnet_Uri; var LAuthority: JString; begin if CheckBuildAndTarget(NOUGAT) then begin LAuthority := StringToJString(JStringToString(TAndroidHelper.Context.getApplicationContext.getPackageName) + '.fileprovider'); Result := TJFileProvider.JavaClass.getUriForFile(TAndroidHelper.Context, LAuthority, AFile); end else Result := TJnet_uri.JavaClass.fromFile(AFile); end; class function TAndroidHelperEx.UriFromFileName(const AFileName: string): Jnet_Uri; begin Result := UriFromFile(TJFile.JavaClass.init(StringToJString(AFileName))); end; class function TAndroidHelperEx.GetTargetSdkVersion: Integer; var LApplicationInfo: JApplicationInfo; begin LApplicationInfo := TAndroidHelper.Context.getPackageManager.getApplicationInfo(TAndroidHelper.Context.getPackageName, 0); Result := LApplicationInfo.targetSdkVersion; end; class function TAndroidHelperEx.IsIgnoringBatteryOptimizations: Boolean; begin Result := PowerManager.isIgnoringBatteryOptimizations(TAndroidHelper.Context.getPackageName); end; class function TAndroidHelperEx.GetRunningServiceInfo(const AServiceName: string): JActivityManager_RunningServiceInfo; var LService: JObject; LRunningServices: JList; LServiceInfo: JActivityManager_RunningServiceInfo; I: Integer; begin Result := nil; LService := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.ACTIVITY_SERVICE); LRunningServices := TJActivityManager.Wrap(TAndroidHelper.JObjectToID(LService)).getRunningServices(MaxInt); for I := 0 to LRunningServices.size - 1 do begin LServiceInfo := TJActivityManager_RunningServiceInfo.Wrap(TAndroidHelper.JObjectToID(LRunningServices.get(I))); if AServiceName.Equals(JStringToString(LServiceInfo.service.getClassName)) then Exit(LServiceInfo); end; end; class function TAndroidHelperEx.IsActivityForeground: Boolean; var LService: JObject; LRunningApps: JList; LAppInfo: JActivityManager_RunningAppProcessInfo; I: Integer; begin Result := False; LService := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.ACTIVITY_SERVICE); LRunningApps := TJActivityManager.Wrap(TAndroidHelper.JObjectToID(LService)).getRunningAppProcesses; for I := 0 to LRunningApps.size - 1 do begin LAppInfo := TJActivityManager_RunningAppProcessInfo.Wrap(TAndroidHelper.JObjectToID(LRunningApps.get(I))); if LAppInfo.importance = 100 then begin if LAppInfo.importanceReasonComponent <> nil then begin if LAppInfo.importanceReasonComponent.getPackageName.equals(TAndroidHelper.Context.getPackageName) then Exit(True); end else if LRunningApps.size = 1 then Exit(True); end; end; end; class function TAndroidHelperEx.IsServiceForeground(const AServiceName: string): Boolean; var LServiceInfo: JActivityManager_RunningServiceInfo; begin LServiceInfo := GetRunningServiceInfo(AServiceName); Result := (LServiceInfo <> nil) and LServiceInfo.foreground; end; class function TAndroidHelperEx.IsServiceRunning(const AServiceName: string): Boolean; begin Result := GetRunningServiceInfo(AServiceName) <> nil; end; class function TAndroidHelperEx.KeyguardManager: JKeyguardManager; var LService: JObject; begin if FKeyguardManager = nil then begin LService := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.KEYGUARD_SERVICE); if LService <> nil then FKeyguardManager := TJKeyguardManager.Wrap(TAndroidHelper.JObjectToID(LService)); end; Result := FKeyguardManager; end; class function TAndroidHelperEx.NotificationManager: JNotificationManager; var LService: JObject; begin if FNotificationManager = nil then begin LService := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.NOTIFICATION_SERVICE); FNotificationManager := TJNotificationManager.Wrap(TAndroidHelper.JObjectToID(LService)); end; Result := FNotificationManager; end; class function TAndroidHelperEx.PowerManager: JPowerManager; var LService: JObject; begin if FPowerManager = nil then begin LService := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.POWER_SERVICE); if LService <> nil then FPowerManager := TJPowerManager.Wrap(TAndroidHelper.JObjectToID(LService)); end; Result := FPowerManager; end; class procedure TAndroidHelperEx.RestartIfNotIgnoringBatteryOptimizations; var LIntent: JIntent; begin if not IsIgnoringBatteryOptimizations then begin LIntent := TJIntent.Create; LIntent.setAction(TJSettings.javaClass.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); LIntent.setData(TJnet_Uri.JavaClass.parse(StringToJString('package:' + JStringtoString(TAndroidHelper.Context.getPackageName())))); // Restart app with action request TAndroidHelper.Context.startActivity(LIntent); end; end; function GetTimeFromNowInMillis(const ASecondsFromNow: Integer): Int64; var LCalendar: JCalendar; begin LCalendar := TJCalendar.JavaClass.getInstance; if ASecondsFromNow > 0 then LCalendar.add(TJCalendar.JavaClass.SECOND, ASecondsFromNow); Result := LCalendar.getTimeInMillis; end; class procedure TAndroidHelperEx.SetStartAlarm(const AAlarm: TDateTime; const AStartFromLock: Boolean); var LActionIntent: JIntent; LAlarmIntent: JPendingIntent; LStartAt: Int64; begin LActionIntent := TJIntent.JavaClass.init(StringToJString(cActionStartAlarm)); LActionIntent.setClassName(TAndroidHelper.Context.getPackageName, StringToJString(cReceiverName)); LActionIntent.putExtra(StringToJString(cExtraStartUnlock), AStartFromLock); LAlarmIntent := TJPendingIntent.JavaClass.getBroadcast(TAndroidHelper.Context, 0, LActionIntent, TJPendingIntent.JavaClass.FLAG_CANCEL_CURRENT); LStartAt := GetTimeFromNowInMillis(SecondsBetween(Now, AAlarm)); // Allow for alarms while in "doze" mode if TOSVersion.Check(6) then TAndroidHelper.AlarmManager.setExactAndAllowWhileIdle(TJAlarmManager.JavaClass.RTC_WAKEUP, LStartAt, LAlarmIntent) else TAndroidHelper.AlarmManager.&set(TJAlarmManager.JavaClass.RTC_WAKEUP, LStartAt, LAlarmIntent); end; end.
unit Litbutt; { This component is a pushbutton with a twist... it has a light panel imbedded into it which toggles between on and off every time the button is pressed. It has a slew of properties to control the appearance and behavior of the light panel. It also adds several new events... OnIsLit and OnIsUnlit fire whenever the light changes to the appropriate state (the light can be controlled seperately from the click event) and the button also fires events corresponding to which side of the button was depressed. A neat trick is to set the light position to centered, make it large enough to nearly fill the button, and then attach events to the various click events. This gives you a universal control to do all sorts of nifty things with such as controlling an audio playback device. Copyright (c) November, 1995 Gary D. Foster. This code is released under the provisions of the Gnu Public license and is freely redistributable. Author: Gary D. Foster Class Name: TIndicatorButton Descends From: TButton Exported properties/methods: Protected --------- procedure MouseDown -- overridden procedure MouseUp -- overridden procedure MouseMove -- overridden procedure SetColorLit(Value: TColor); virtual; -- Sets the "lit" color of the imbedded light. procedure SetColorUnlit(Value: TColor); virtual; -- Sets the "unlit" color of the imbedded light. procedure SetIsLit(Value: Boolean); virtual; -- Toggles the light status. procedure SetLightWidth(Value: Integer); virtual -- Sets the width of the imbedded light panel. It calculates the maximum width based on the OffsetX value and trims the value to the maximum if you try to exceed it. procedure SetLightHeight(Value: Integer); virtual; -- Same as above, except affects the Height. procedure SetOffsetX(Value: Integer); virtual; -- used to set the OffsetX property. procedure SetOffsetY(Value: Integer); virtual; -- used to set the OffsetY property. procedure SetCorner(Value: TCorner); virtual; -- positions the light panel in one of five places... allowable values are in the TCorner type. procedure SetFixed(Value: Boolean); virtual; -- used to set the 'LightRidesPanel' property which is kind of hard to explain... if this value is set to false, when you depress the button it pushes down around the imbedded light, so it looks like the light is fixed into place. Setting this value to true makes it appear that the light is attached to the button instead. procedure Click -- overridden procedure SetCaption(NewCaption: String); virtual; function GetCaption: String; virtual; -- these two caption methods are used to circumvent a PITA bug that occurred whenever the caption changed. Normally, a refresh had to be forced after a caption change because the light panel would disappear. However, if you override the caption PROPERTY and call a refresh after it's changed you no longer have that problem. MUCH thanks to Jon Shemitz, <jon@armory.com> for the thump in the head that it took to realize this. Public ------ constructor Create -- overridden; Published --------- property Caption: String; -- Republished to allow us to intercept the the caption changing and force a refresh. property ColorLit: TColor -- controls the 'lit' color of the light panel. property ColorUnlit: TColor -- controls the 'unlit' color of the light. property IsLit: Boolean -- Turns the light on and off. Also toggled in the click procedure. property LightWidth: Integer -- the width of the embedded light. Max value is (Button.Width - (2*OffsetX)) and is enforced in the SetWidth procedure. property LightHeight: Integer -- the height of the embedded light. Max is (Button.Height - (2*OffsetY)) and is enforced in the SetHeight procedure. property LightOffsetX: Integer -- the amount of pixels to offset the light along the X axis. Indents the light from either the left or the right side, depending on the corner position so you don't need to recalculate if you change the light position. Ignored if LightPosition = lpCenter. property LightOffsetY: Integer -- same as the X Offset, only different. property LightPosition: TCorner -- determines the sides that the light is offset from. Type TCorner = (lpTopLeft, lpTopRight, lpBottomRight, lpBottomLeft, lpCenter); property LightRidesPanel: Boolean -- determines the runtime behavior and appearance of the light. This is the action controlled by the SetFixed procedure. property OnLit: TNotifyEvent -- triggered when the light turns on. property OnUnlit: TNotifyEvent -- triggered when the light turns off. property OnClickTop: TNotifyEvent -- an EXTRA click procedure. property OnClickBottom: TNotifyEvent -- another EXTRA click procedure. property OnClickRight: TNotifyEvent -- yet another EXTRA click procedure. property OnClickLeft: TNotifyEvent -- the last EXTRA click procedure. The extra OnClick procedures are triggered depending on which side of the button the user clicks on and are fired after the standard OnClick event finishes. } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TCorner = (lpTopLeft, lpTopRight, lpBottomRight, lpBottomLeft, lpCenter); TIndicatorButton = class(TButton) private FColorLit: TColor; FColorUnlit: TColor; FIsLit: Boolean; FLightHeight: Integer; FLightWidth: Integer; FOffsetX: Integer; FOffsetY: Integer; FCorner: TCorner; FOnLit: TNotifyEvent; FOnUnlit: TNotifyEvent; FFixed: Boolean; FOnTopClick: TNotifyEvent; FOnBottomClick: TNotifyEvent; FOnRightClick: TNotifyEvent; FOnLeftClick: TNotifyEvent; FMouseX: Integer; FMouseY: Integer; MBDown: Boolean; protected Light: TPanel; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure SetColorLit(Value: TColor); virtual; procedure SetColorUnlit(Value: TColor); virtual; procedure SetIsLit(Value: Boolean); virtual; procedure SetLightWidth(Value: Integer); virtual; procedure SetLightHeight(Value: Integer); virtual; procedure SetOffsetX(Value: Integer); virtual; procedure SetOffsetY(Value: Integer); virtual; procedure SetCorner(Value: TCorner); virtual; procedure SetFixed(Value: Boolean); virtual; procedure SetCaption(NewCaption: String); virtual; function GetCaption: String; virtual; public constructor Create(AOwner: TComponent); override; procedure Click; override; published property ColorLit: TColor read FColorLit write SetColorLit default clLime; property ColorUnlit: TColor read FColorUnlit write SetColorUnlit default clBtnFace; property IsLit: Boolean read FIsLit write SetIsLit default true; property LightWidth: Integer read FLightWidth write SetLightWidth; property LightHeight: Integer read FLightHeight write SetLightHeight; property LightOffsetX: Integer read FOffsetX write SetOffsetX; property LightOffsetY: Integer read FOffsetY write SetOffsetY; property LightPosition: TCorner read FCorner write SetCorner default lpTopLeft; property LightRidesPanel: Boolean read FFixed write SetFixed default false; property OnLit: TNotifyEvent read FOnLit write FOnLit; property OnUnlit: TNotifyEvent read FOnUnlit write FOnUnlit; property OnClickTop: TNotifyEvent read FOnTopClick write FOnTopClick; property OnClickBottom: TNotifyEvent read FOnBottomClick write FOnBottomClick; property OnClickRight: TNotifyEvent read FOnRightClick write FOnRightClick; property OnClickLeft: TNotifyEvent read FOnLeftClick write FOnLeftClick; property Caption: String read GetCaption write SetCaption; end; implementation procedure TIndicatorButton.SetCaption(NewCaption: String); begin inherited Caption := NewCaption; refresh; end; function TIndicatorButton.GetCaption: String; begin result := inherited Caption; end; procedure TIndicatorButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin MBDown := True; FMouseX := X; FMouseY := Y; if not FFixed then Light.BevelOuter := BvRaised; Light.Refresh; inherited MouseDown(Button, Shift, X, Y); end; procedure TIndicatorButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin MBDown := False; Light.BevelOuter := BvLowered; Light.Refresh; inherited MouseUp(Button, Shift, X, Y); end; procedure TIndicatorButton.MouseMove(Shift: TShiftState; X, Y: Integer); begin If MBDown then begin FMouseX := X; FMouseY := Y; end; If MBDown and ((X < 0) or (Y < 0) or (X > Width) or (Y > Height)) then Light.BevelOuter := bvLowered; If MBDown and (X >= 0) and (X <= Width) and (Y >= 0) and (Y <= Height) and not FFixed then Light.BevelOuter := bvRaised; Light.Refresh; inherited MouseMove(Shift, X, Y); end; procedure TIndicatorButton.SetOffsetX(Value: Integer); var Max: Integer; begin FOffsetX := Value; Max := Width - Light.Width; if Value > Max then Value := Max; case FCorner of lpTopLeft: Light.Left := Value; lpBottomLeft: Light.Left := Value; lpTopRight: Light.Left := Width - (Light.Width + Value); lpBottomRight: Light.Left := Width - (Light.Width + Value); lpCenter: Light.Left := (Width div 2) - (Light.Width div 2); end; end; procedure TIndicatorButton.SetOffsetY(Value: Integer); var Max: Integer; begin FOffsetY := Value; Max := Height - Light.Height; If Value > Max then Value := Max; case FCorner of lpTopLeft: Light.Top := Value; lpBottomLeft: Light.Top := Height - (Light.Height + Value); lpTopRight: Light.Top := Value; lpBottomRight: Light.Top := Height - (Light.Height + Value); lpCenter: Light.Top := (Height div 2) - (Light.Height div 2); end; end; procedure TIndicatorButton.SetCorner(Value: TCorner); begin if Value = FCorner then exit; FCorner := Value; SetOffsetX(FOffsetX); SetOffsetY(FOffsetY); end; procedure TIndicatorButton.SetLightHeight(Value: Integer); var Max: Integer; begin If FLightHeight = Value then exit; Max := Height - (2 * LightOffsetY); if Value > Max then Value := Max; FLightHeight := Value; Light.Height := Value; SetOffsetY(FOffsetY); end; procedure TIndicatorButton.SetLightWidth(Value: Integer); var Max: Integer; begin If FLightWidth = Value then exit; Max := Width - (2 * LightOffsetX); if Value > Max then Value := Max; FLightWidth := Value; Light.Width := Value; SetOffsetX(FOffsetX); end; procedure TIndicatorButton.SetFixed(Value: Boolean); begin if FFixed = value then exit; FFixed := Value; if MBDown then if FFixed then Light.BevelOuter := bvLowered else Light.BevelOuter := bvRaised; end; constructor TIndicatorButton.Create(AOwner: TComponent); begin inherited Create(AOwner); SetFixed(False); Light := TPanel.Create(Self); Light.Parent := Self; SetCorner(lpTopLeft); SetOffsetX(8); SetOffsetY(8); SetLightHeight(Height div 3); SetLightWidth(Width div 4); Light.BevelOuter := bvLowered; Light.BevelWidth := 1; SetColorLit(clLime); SetColorUnlit(clBtnFace); SetIsLit(True); end; procedure TIndicatorButton.SetColorLit(Value: TColor); begin If FColorLit = Value then exit; FColorLit := Value; if FIsLit then Light.Color := Value; end; procedure TIndicatorButton.SetColorUnlit(Value: TColor); begin If FColorUnlit = Value then exit; FColorUnlit := Value; If not FIsLit then Light.Color := Value; end; procedure TIndicatorButton.Click; var Pos: Integer; begin Pos := 0; { initialize the click position } Light.BevelOuter := bvLowered; SetIsLit(Not FIsLit); inherited Click; { Now figure out where they were when they clicked } { Top: } if (FMouseX >= 0) and (FMouseX <= Width) and (FMouseY >= 0) and (FMouseY < Light.Top) then Pos := 1; { Bottom: } If (FMouseX >= 0) and (FMouseX <= Width) and (FMouseY > Light.Height) and (FMouseY <= Height) then Pos := 2; { Left Side: } If (FMouseX >= 0) and (FMouseX < FOffsetX) and (FMouseY >= 0) and (FMouseY <= Height) then Pos := 3; { Right Side: } If (FMouseX > (Width - FOffsetX)) and (FMouseX <= Width) and (FMouseY >= 0) and (FMouseY <= Height) then Pos := 4; case Pos of 1: If assigned(FOnTopClick) then FOnTopClick(Self); 2: If assigned(FOnBottomClick) then FOnBottomClick(Self); 3: If assigned(FOnLeftClick) then FOnLeftClick(Self); 4: If assigned(FOnRightClick) then FOnRightClick(Self); end; end; procedure TIndicatorButton.SetIsLit(Value: Boolean); begin If FIsLit = Value then exit; FIsLit := Value; If FIsLit then Light.Color := ColorLit else Light.Color := ColorUnlit; if not (csDesigning in ComponentState) then case FIsLit of True: if Assigned(FOnLit) then FOnLit(Self); False: if Assigned(FOnUnlit) then FOnUnlit(Self); end; end; end.
unit VSETexMan; interface uses Windows, AvL, avlUtils, avlMath, OpenGL, oglExtensions, VSEOpenGLExt, VSEImageCodec, VSECore{$IFDEF VSE_LOG}, VSELog{$ENDIF}{$IFDEF VSE_CONSOLE}, VSEConsole{$ENDIF}; type TOnLostTex=function(Sender: TObject; const Name: string): Cardinal of object; TRTTMethod=(rttCopy, rttFBO); //Render-to-Texture method - CopyTexture (slow), FrameBuffer Object TTextureFilter=(tfNone, tfBilinear, tfTrilinear, tfAnisotropic, tfCustomAnisotropy); //Use tfCustomAnisotropy+AnisoLevel to set custom anisotropy level TTexture=record //internally used ID: Cardinal; Name: string; end; TRTTInfo=record //internally used Method: TRTTMethod; FBO, RBODepth, Color, Depth: Cardinal; RTWidth, RTHeight: Integer; Exist: Boolean; end; TTexMan=class(TModule) private FCount, FMaxChannel: Integer; FTextures: array of TTexture; FRTTs: array of TRTTInfo; FOnLostTex: TOnLostTex; FRTTMethod: TRTTMethod; procedure SetRTTMethod(Value: TRTTMethod); {$IFDEF VSE_CONSOLE}function TexFilterHandler(Sender: TObject; Args: array of const): Boolean;{$ENDIF} public constructor Create; override; //internally used destructor Destroy; override; //internally used class function Name: string; override; //internally used function AddTexture(const Name: string; Stream: TStream; Clamp, MipMap: Boolean; FreeStream: Boolean = false): Cardinal; overload; //Add texture from stream function AddTexture(const Name: string; const Image: TImage; Clamp, MipMap: Boolean): Cardinal; overload; //Add texture from TImageData function AddTexture(Name: string; Data: Pointer; Width, Height: Integer; Comps, Format: GLenum; Clamp, MipMap: Boolean): Cardinal; overload; //Add texture from memory function GetTex(const Name: string; IgnoreLostTex: Boolean = false): Cardinal; //Get texture ID by texture name procedure SetFilter(ID: Cardinal; Filter: TTextureFilter); overload; //Set texture filter procedure SetFilter(const Prefix: string; Filter: TTextureFilter); overload; //Set filter for textures with name starting with Prefix procedure Bind(ID: Cardinal; Channel: Integer = 0); //Set current texture in specified texture channel procedure Unbind(Channel: Integer = 0); //Remove texture from specified texture channel {Render-To-Texture (RTT)} function InitRTT(Width, Height: Integer): Cardinal; //Init Render-To-Texture target with specified dimencions; returns RTT target ID procedure FreeRTT(RTT: Cardinal); //Remove RTT target function RTTBegin(RTT: Cardinal; TexColor: Cardinal; TexDepth: Cardinal = 0): Boolean; //Start render to RTT target; TexColor, TexDepth - target textures; returns true if successfully started procedure RTTEnd(RTT: Cardinal); //End render to RTT target {properties} property OnLostTex: TOnLostTex read FOnLostTex write FOnLostTex; //Invoked if texture not found; return TexID or 0 property RTTMethod: TRTTMethod read FRTTMethod write SetRTTMethod; //Method, used for RTT; default: autodetect end; var TexMan: TTexMan; //Global variable for accessing to Texture Manager implementation const TexCapDelta=16; constructor TTexMan.Create; begin inherited Create; TexMan:=Self; FCount:=0; SetLength(FTextures, TexCapDelta); FMaxChannel:=Max(glMaxTextureUnits, glMaxTextureImageUnits)-1; if GL_EXT_framebuffer_object then FRTTMethod:=rttFBO else FRTTMethod:=rttCopy; {$IFDEF VSE_CONSOLE}Console['texfilter flt=enone:bilin:trilin:aniso ?prefix=s']:=TexFilterHandler;{$ENDIF} end; destructor TTexMan.Destroy; var i: Integer; begin TexMan:=nil; {$IFDEF VSE_LOG}LogF(llInfo, 'TexMan: Freeing %d textures', [FCount]);{$ENDIF} for i:=0 to High(FRTTs) do FreeRTT(i); Finalize(FRTTs); for i:=0 to FCount-1 do glDeleteTextures(1, @FTextures[i].ID); Finalize(FTextures); inherited Destroy; end; class function TTexMan.Name: string; begin Result:='TexMan'; end; function TTexMan.AddTexture(const Name: string; Stream: TStream; Clamp, MipMap: Boolean; FreeStream: Boolean = false): Cardinal; var Image: TImage; begin Image:=TImage.Create; try Image.Load(Stream); Result:=AddTexture(Name, Image, Clamp, MipMap); finally Image.Free; if FreeStream then Stream.Free; end; end; function TTexMan.AddTexture(const Name: string; const Image: TImage; Clamp, MipMap: Boolean): Cardinal; const Comp: array[TPixelFormat] of GLenum = (GL_LUMINANCE8, GL_RGB8, GL_RGBA8, GL_RGBA8); Format: array[TPixelFormat] of GLenum = (GL_LUMINANCE, GL_BGR, GL_RGBA, GL_BGRA); begin Image.Pack; Result:=AddTexture(Name, Image.Pixels, Image.Width, Image.Height, Comp[Image.PixelFormat], Format[Image.PixelFormat], Clamp, MipMap); end; function TTexMan.AddTexture(Name: string; Data: Pointer; Width, Height: Integer; Comps, Format: GLenum; Clamp, MipMap: Boolean): Cardinal; begin //{$IFDEF VSE_LOG}Log(llInfo, 'TexMan: adding texture '+Name);{$ENDIF} Name:=Name; Result:=GetTex(Name, true); if Result=0 then begin if FCount=High(FTextures) then SetLength(FTextures, Length(FTextures)+TexCapDelta); FTextures[FCount].Name:=Name; glGenTextures(1, @Result); FTextures[FCount].ID:=Result; Inc(FCount); end; glBindTexture(GL_TEXTURE_2D, Result); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); if Clamp then begin glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); end else begin glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); end; glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if MipMap then begin glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, Comps, Width, Height, Format, GL_UNSIGNED_BYTE, Data) end else begin glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexImage2D(GL_TEXTURE_2D, 0, Comps, Width, Height, 0, Format, GL_UNSIGNED_BYTE, Data); end; end; function TTexMan.GetTex(const Name: string; IgnoreLostTex: Boolean = false): Cardinal; var i: Integer; begin Result:=0; for i:=0 to FCount-1 do if SameText(FTextures[i].Name, Name) then begin Result:=FTextures[i].ID; Exit; end; if not IgnoreLostTex then begin if Assigned(FOnLostTex) then Result:=FOnLostTex(Self, Name); {$IFDEF VSE_LOG}if Result=0 then Log(llError, 'TexMan: can''t find texture '+Name);{$ENDIF} end; end; procedure TTexMan.SetFilter(ID: Cardinal; Filter: TTextureFilter); const MagFilters: array[Boolean] of Cardinal = (GL_NEAREST, GL_LINEAR); MinFilters: array[Boolean, tfNone..tfAnisotropic] of Cardinal = ( (GL_NEAREST, GL_LINEAR, GL_LINEAR, GL_LINEAR), (GL_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR) ); var MaxLevel: Cardinal; begin Bind(ID); glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, @MaxLevel); glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, MagFilters[Filter>tfNone]); glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, MinFilters[MaxLevel>0, TTextureFilter(Min(Integer(Filter), Integer(tfAnisotropic)))]); case Filter of tfNone..tfTrilinear: glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); tfAnisotropic: glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, glMaxAnisotropy); else glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, Integer(Filter) - Integer(tfCustomAnisotropy)); end; Unbind; end; procedure TTexMan.SetFilter(const Prefix: string; Filter: TTextureFilter); var i: Integer; begin for i:=0 to FCount-1 do with FTextures[i] do if ((Length(Prefix)=0) and (Copy(Name, 1, 2)<>'__')) or ((Length(Prefix)>0) and SameText(Copy(Name, 1, Length(Prefix)), Prefix)) then SetFilter(ID, Filter); end; procedure TTexMan.Bind(ID: Cardinal; Channel: Integer); begin if not (Channel in [0..FMaxChannel]) then begin {$IFDEF VSE_LOG}LogF(llError, 'TexMan: can''t bind texture %d to channel %d', [ID, Channel]);{$ENDIF} Exit; end; if GL_ARB_multitexture then glActiveTextureARB(GL_TEXTURE0_ARB+Channel) else if Channel <> 0 then begin {$IFDEF VSE_LOG}LogF(llError, 'TexMan: can''t bind texture %d to channel %d: multitexturing not supported', [ID, Channel]);{$ENDIF} Exit; end; glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, ID); end; procedure TTexMan.Unbind(Channel: Integer); begin if not (Channel in [0..FMaxChannel]) then begin {$IFDEF VSE_LOG}LogF(llError, 'TexMan: can''t unbind texture from channel %d', [Channel]);{$ENDIF} Exit; end; if GL_ARB_multitexture then glActiveTextureARB(GL_TEXTURE0_ARB+Channel); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); if GL_ARB_multitexture then glActiveTextureARB(GL_TEXTURE0_ARB); end; function TTexMan.InitRTT(Width, Height: Integer): Cardinal; var i: Cardinal; begin Result:=$FFFFFFFF; if Length(FRTTs)>0 then for i:=0 to High(FRTTs) do if not FRTTs[i].Exist then begin Result:=i; Break; end; if Result=$FFFFFFFF then begin Result:=Length(FRTTs); SetLength(FRTTs, Result+1); end; ZeroMemory(@FRTTs[Result], SizeOf(TRTTInfo)); with FRTTs[Result] do begin Method:=FRTTMethod; RTWidth:=Width; RTHeight:=Height; Exist:=true; if Method=rttFBO then begin glGenFramebuffersEXT(1, @FBO); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FBO); glGenRenderbuffersEXT(1, @RBODepth); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, RBODepth); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24_ARB, Width, Height); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, RBODepth); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); end; end; end; procedure TTexMan.FreeRTT(RTT: Cardinal); begin if (RTT>High(FRTTs)) or not FRTTs[RTT].Exist then Exit; with FRTTs[RTT] do begin if Method=rttFBO then begin if FBO<>0 then glDeleteRenderbuffersEXT(1, @FBO); if RBODepth<>0 then glDeleteRenderbuffersEXT(1, @RBODepth); end; Exist:=false; end; end; function TTexMan.RTTBegin(RTT: Cardinal; TexColor, TexDepth: Cardinal): Boolean; begin Result:=false; if (RTT>High(FRTTs)) or (TexColor=0) then Exit; with FRTTs[RTT] do begin glViewport(0, 0, RTWidth, RTHeight); Color:=TexColor; Depth:=TexDepth; Bind(TexColor); glTexParameter(GL_TEXTURE, GL_GENERATE_MIPMAP, Integer(GL_TRUE)); Unbind; if Method=rttFBO then begin glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FBO); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, TexColor, 0); if TexDepth<>0 then begin glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, TexDepth, 0); end else begin glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, RBODepth); end; if glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT)<>GL_FRAMEBUFFER_COMPLETE_EXT then begin glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); Exit; end; end; Result:=true; end; end; procedure TTexMan.RTTEnd(RTT: Cardinal); var FMT: Cardinal; begin if RTT>High(FRTTs) then Exit; with FRTTs[RTT] do begin case Method of rttCopy: begin Bind(Color); glGetTexLevelParameter(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPONENTS, PGLInt(@Fmt)); glCopyTexImage2D(GL_TEXTURE_2D, 0, Fmt, 0, 0, RTWidth, RTHeight, 0); if Depth<>0 then begin Bind(Depth); glGetTexLevelParameter(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPONENTS, PGLInt(@Fmt)); glCopyTexImage2D(GL_TEXTURE_2D, 0, Fmt, 0, 0, RTWidth, RTHeight, 0); end; Unbind; end; rttFBO: begin glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0); if Depth<>0 then glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); end; end; end; glViewport(0, 0, Core.ResolutionX, Core.ResolutionY); end; procedure TTexMan.SetRTTMethod(Value: TRTTMethod); begin if not GL_EXT_framebuffer_object and (Value = rttFBO) then Value := rttCopy; FRTTMethod := Value; end; {$IFDEF VSE_CONSOLE} function TTexMan.TexFilterHandler(Sender: TObject; Args: array of const): Boolean; var Prefix: string; begin Result:=true; if Length(Args)=3 then Prefix:=string(Args[2].VAnsiString) else Prefix:=''; SetFilter(Prefix, TTextureFilter(Args[1].VInteger)); end; {$ENDIF} initialization RegisterModule(TTexMan); end.
unit Core.Interfaces; interface uses Spring.Collections , Spring.DesignPatterns , Core.BaseInterfaces , SysUtils ; type EGameException = class(Exception); EGameInvalidValueException = class(EGameException); EValueNotFoundException = class(EGameException); IScoreFrame = interface; TFrameStatus = (fsNormal, fsSpare, fsStrike); TRollInfo = record RollNo: Integer; Pins: Integer; constructor Create(const ARollNo, APins: Integer); end; TFrameInfo = record FrameNo: Integer; Rolls: IList<TRollInfo>; RollTotal: Integer; ExtraPinTotal: Integer; FrameTotal: Integer; Status: TFrameStatus; constructor Create(const AFrameNo, AFrameTotal: Integer; const AStatus: TFrameStatus); end; IBall = interface ['{D8AB5FAD-DAC8-4650-84BA-F6CE1E47EC19}'] procedure Roll(const ARollInfo: TRollInfo); end; IBallFactory = interface ['{DCE2E62B-ECA1-403C-BE95-76ED3BDB9AC6}'] function CreateBall(const AFrame: IScoreFrame): IBall; end; IScoreFrameProcessor = interface(IGameDataProcessor<Integer, IScoreFrame>) ['{0D005AFF-F592-4B73-A8A7-AF7C4B4A9F7A}'] end; IScoreFrame = interface(IGameObservable) ['{1313AA67-A5D9-4B75-9092-533C1B6431A6}'] function GetFrameNo: Integer; function GetStatus: TFrameStatus; function GetFrameTotal: Integer; function GetRollTotal: Integer; function GetRolls: IList<TRollInfo>; function GetFrameInfo: TFrameInfo; function GetPrevFrameInfo: TFrameInfo; procedure AddRollInfo(const ARollInfo: TRollInfo); procedure UpdateFrameTotal(const ATotal: Integer); procedure AddToFrameTotal(const APins: Integer); property FrameTotal: Integer read GetFrameTotal; property RollTotal: Integer read GetRollTotal; property FrameNo: Integer read GetFrameNo; property Rolls: IList<TRollInfo> read GetRolls; property Status: TFrameStatus read GetStatus; property FrameInfo: TFrameInfo read GetFrameInfo; end; IScoreFrameFactory = interface ['{5EAC514E-F37D-4FDE-AD95-F279B6A1C570}'] function CreateFrame(const AFrameNo: Integer; APrevFrame: IScoreFrame): IScoreFrame; end; IScoreCard = interface ['{BA7DD8C0-EAF6-4467-9AE7-EA6BB6378525}'] function GetPlayerName: String; procedure SetPlayerName(const AValue: String); function GetFrameInfoByFrameNo(const AFrameNo: Integer): TFrameInfo; function GetTotalScore: Integer; procedure ResetScoreCard(const APlayerName: String); procedure RollBall(const APinCount: Integer); procedure RegisterObserver(AObserver: IGameObserver); procedure UnregisterObserver(AObserver: IGameObserver); property PlayerName: String read GetPlayerName write SetPlayerName; end; IBowlingGame = interface ['{3AC22901-7FD8-42CF-AC2D-D8C115C37A7F}'] procedure StartGame(const APlayerName: String); procedure RollBall(const APins: Integer); function GetScoreByFrame(const AFrameNo: Integer): TFrameInfo; function GetTotalScore: Integer; procedure RegisterObserver(AObserver: IGameObserver); procedure UnregisterObserver(AObserver: IGameObserver); end; implementation { TRollInfo } constructor TRollInfo.Create(const ARollNo, APins: Integer); begin RollNo := ARollNo; Pins := APins; end; { TFrameInfo } constructor TFrameInfo.Create(const AFrameNo, AFrameTotal: Integer; const AStatus: TFrameStatus); begin FrameNo := AFrameNo; FrameTotal := AFrameTotal; Status := AStatus; ExtraPinTotal := 0; end; end.
{******************************************************************************* Title: T2Ti ERP 3.0 Description: Model relacionado à tabela [PRODUTO_FICHA_TECNICA] The MIT License Copyright: Copyright (C) 2021 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit ProdutoFichaTecnica; interface uses MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TProdutoFichaTecnica = class(TModelBase) private FId: Integer; FIdProduto: Integer; FDescricao: string; FIdProdutoFilho: Integer; FQuantidade: Extended; FValorCusto: Extended; FPercentualCusto: Extended; public // procedure ValidarInsercao; override; // procedure ValidarAlteracao; override; // procedure ValidarExclusao; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('ID_PRODUTO')] [MVCNameAsAttribute('idProduto')] property IdProduto: Integer read FIdProduto write FIdProduto; [MVCColumnAttribute('DESCRICAO')] [MVCNameAsAttribute('descricao')] property Descricao: string read FDescricao write FDescricao; [MVCColumnAttribute('ID_PRODUTO_FILHO')] [MVCNameAsAttribute('idProdutoFilho')] property IdProdutoFilho: Integer read FIdProdutoFilho write FIdProdutoFilho; [MVCColumnAttribute('QUANTIDADE')] [MVCNameAsAttribute('quantidade')] property Quantidade: Extended read FQuantidade write FQuantidade; [MVCColumnAttribute('VALOR_CUSTO')] [MVCNameAsAttribute('valorCusto')] property ValorCusto: Extended read FValorCusto write FValorCusto; [MVCColumnAttribute('PERCENTUAL_CUSTO')] [MVCNameAsAttribute('percentualCusto')] property PercentualCusto: Extended read FPercentualCusto write FPercentualCusto; end; implementation { TProdutoFichaTecnica } end.
unit Aurelius.Schema.ElevateDB; {$I Aurelius.Inc} interface uses Aurelius.Drivers.Interfaces, Aurelius.Schema.AbstractImporter, Aurelius.Sql.Metadata; type TElevateDBSchemaImporter = class(TAbstractSchemaImporter) strict protected procedure GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); override; end; TElevateDBSchemaRetriever = class(TSchemaRetriever) strict private procedure GetTables; procedure GetColumns; procedure GetPrimaryKeys; procedure GetUniqueKeys; procedure GetForeignKeys; procedure GetFieldDefinition(Column: TColumnMetadata; ADataType: string; ALength, APrecision, AScale: integer); public constructor Create(AConnection: IDBConnection; ADatabase: TDatabaseMetadata); override; procedure RetrieveDatabase; override; end; implementation uses SysUtils, Aurelius.Schema.Register; { TElevateDBSchemaImporter } procedure TElevateDBSchemaImporter.GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); var Retriever: TSchemaRetriever; begin Retriever := TElevateDBSchemaRetriever.Create(Connection, Database); try Retriever.RetrieveDatabase; finally Retriever.Free; end; end; { TElevateDBSchemaRetriever } constructor TElevateDBSchemaRetriever.Create(AConnection: IDBConnection; ADatabase: TDatabaseMetadata); begin inherited Create(AConnection, ADatabase); end; procedure TElevateDBSchemaRetriever.GetColumns; begin RetrieveColumns( 'SELECT TableName as TABLE_NAME, Name as COLUMN_NAME, "Type", "Length", '+ 'Precision, Scale, Nullable, Generated, Identity '+ 'FROM Information.TableColumns '+ 'ORDER BY TableName, OrdinalPos', procedure (Column: TColumnMetadata; ResultSet: IDBResultSet) begin Column.NotNull := not AsBoolean(ResultSet.GetFieldValue('Nullable')); GetFieldDefinition(Column, AsString(ResultSet.GetFieldValue('Type')), AsInteger(ResultSet.GetFieldValue('Length')), AsInteger(ResultSet.GetFieldValue('Precision')), AsInteger(ResultSet.GetFieldValue('Scale')) ); Column.AutoGenerated := AsBoolean(ResultSet.GetFieldValue('Generated')) and AsBoolean(ResultSet.GetFieldValue('Identity')); end ); end; procedure TElevateDBSchemaRetriever.GetFieldDefinition(Column: TColumnMetadata; ADataType: string; ALength, APrecision, AScale: integer); begin Column.DataType := ADataType; ADataType := LowerCase(ADataType); if (ADataType = 'byte') or (ADataType = 'char') or (ADataType = 'varbyte') or (ADataType = 'varchar') then Column.Length := ALength else if (ADataType = 'decimal') or (ADataType = 'numeric') then begin Column.DataType := 'NUMERIC'; Column.Precision := APrecision; Column.Scale := AScale; end; end; procedure TElevateDBSchemaRetriever.GetForeignKeys; begin RetrieveForeignKeys( 'SELECT C.TableName as FK_TABLE_NAME, C.Name as CONSTRAINT_NAME, C.TargetTable as PK_TABLE_NAME, '+ 'CC.ColumnName AS FK_COLUMN_NAME, CP.ColumnName AS PK_COLUMN_NAME '+ 'FROM Information.Constraints C, Information.ConstraintColumns CC, Information.ConstraintColumns CP '+ 'WHERE C.Type = ''Foreign Key'' '+ 'AND C.TableName = CC.TableName AND C.Name = CC.ConstraintName '+ 'AND C.TargetTable = CP.TableName AND C.TargetTableConstraint = CP.ConstraintName '+ 'AND CC.OrdinalPos = CP.OrdinalPos '+ 'ORDER BY C.TableName, C.Name, CC.OrdinalPos, CP.OrdinalPos' ); end; procedure TElevateDBSchemaRetriever.GetPrimaryKeys; begin RetrievePrimaryKeys( 'SELECT I.TableName as TABLE_NAME, C.ColumnName as COLUMN_NAME '+ 'FROM Information.Indexes I, Information.IndexColumns C '+ 'WHERE I.TableName = C.TableName '+ 'AND I.Name = C.IndexName '+ 'AND I.Type = ''Primary Key'' '+ 'ORDER BY I.TableName, I.Name, C.OrdinalPos' ); end; procedure TElevateDBSchemaRetriever.GetTables; begin RetrieveTables( 'SELECT Name as TABLE_NAME FROM Information.Tables ORDER BY Name' ); end; procedure TElevateDBSchemaRetriever.GetUniqueKeys; begin RetrieveUniqueKeys( 'SELECT C.TableName as TABLE_NAME, C.Name as CONSTRAINT_NAME, CC.ColumnName as COLUMN_NAME '+ 'FROM Information.Constraints C, Information.ConstraintColumns CC '+ 'WHERE C.TableName = CC.TableName AND C.Name = CC.ConstraintName '+ 'AND (C.Type = ''Unique'') '+ 'ORDER BY C.TableName, C.Name, CC.OrdinalPos' ); end; procedure TElevateDBSchemaRetriever.RetrieveDatabase; begin Database.Clear; GetTables; GetColumns; GetPrimaryKeys; GetUniqueKeys; GetForeignKeys; end; initialization TSchemaImporterRegister.GetInstance.RegisterImporter('ElevateDB', TElevateDBSchemaImporter.Create); end.
unit ImportASCIIUnit; // ---------------------------------- // ASCII file import setup dialog box // ---------------------------------- // 21.11.03 // 19.02.04 ... Data exchanged using ImportFile public object // Channel name/units can now be set // 02.06.07 ... Title lines at beginning of file can now be ignored interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ValidatedEdit, ADCDataFile, Grids, ExtCtrls ; type TImportASCIIFrm = class(TForm) bCancel: TButton; bOK: TButton; GroupBox3: TGroupBox; ChannelTable: TStringGrid; meText: TMemo; GroupBox6: TGroupBox; edNumTitleLines: TValidatedEdit; Label2: TLabel; GroupBox5: TGroupBox; rbTab: TRadioButton; rbComma: TRadioButton; rbSpace: TRadioButton; GroupBox1: TGroupBox; Label1: TLabel; cbTimeUnits: TComboBox; GroupBox2: TGroupBox; edRecordSize: TValidatedEdit; GroupBox4: TGroupBox; rbSampleTimesAvailable: TRadioButton; rbNoSampleTimes: TRadioButton; ckFixedRecordSize: TCheckBox; SamplingIntervalPanel: TPanel; Label3: TLabel; edScanInterval: TValidatedEdit; procedure FormShow(Sender: TObject); procedure bOKClick(Sender: TObject); procedure rbSampleTimesAvailableClick(Sender: TObject); procedure cbTimeUnitsChange(Sender: TObject); procedure rbNoSampleTimesClick(Sender: TObject); procedure ckFixedRecordSizeClick(Sender: TObject); private { Private declarations } procedure UpdateTimeUnits ; public { Public declarations } ImportFile : TADCDataFile ; FileName : String ; end; var ImportASCIIFrm: TImportASCIIFrm; implementation {$R *.dfm} uses MDIForm; const ChNum = 0 ; ChName = 1 ; ChUnits = 2 ; const MSecScale = 1000.0 ; SecScale = 1.0 ; MinScale = 1.0/60.0 ; procedure TImportASCIIFrm.FormShow(Sender: TObject); // --------------------------------------- // Initialise controls when form displayed // --------------------------------------- var ch : Integer ; Row : Integer ; F: TextFile; s : String ; begin Top := Main.Top + 60 ; Left := Main.Left + 20 ; cbTimeUnits.Clear ; cbTimeUnits.Items.Add('msecs') ; cbTimeUnits.Items.Add('secs') ; cbTimeUnits.Items.Add('mins') ; if ImportFile.ASCIITimeUnits = 'ms' then begin cbTimeUnits.ItemIndex := 0 ; end else if ImportFile.ASCIITimeUnits = 's' then begin cbTimeUnits.ItemIndex := 1 ; end else begin cbTimeUnits.ItemIndex := 2 ; end ; UpdateTimeUnits ; // Column separating character if ImportFile.ASCIISeparator = ',' then rbComma.Checked := True else if ImportFile.ASCIISeparator = ' ' then rbSpace.Checked := True else rbTab.Checked := True ; rbSampleTimesAvailable.Checked := True ; rbNoSampleTimes.Checked := not rbSampleTimesAvailable.Checked ; ckFixedRecordSize.Checked := rbNoSampleTimes.Checked ; SamplingIntervalPanel.Visible := not rbSampleTimesAvailable.Checked ; edRecordSize.Visible := ckFixedRecordSize.Checked ; edScanInterval.Value := ImportFile.ScanInterval ; { Set channel calibration table } ChannelTable.cells[ChNum,0] := 'Ch.' ; ChannelTable.colwidths[ChNum] := ChannelTable.DefaultColWidth div 2 ; ChannelTable.cells[ChName,0] := 'Name' ; ChannelTable.colwidths[ChName] := ChannelTable.DefaultColWidth ; ChannelTable.cells[ChUnits,0] := 'Units' ; ChannelTable.colwidths[ChUnits] := ChannelTable.DefaultColWidth ; ChannelTable.RowCount := WCPMaxChannels; ChannelTable.options := [goEditing,goHorzLine,goVertLine] ; { Add details for new channels to table } for Row := 1 to ChannelTable.RowCount-1 do begin ch := Row-1 ; ChannelTable.cells[ChNum,Row] := format('%d',[ch]) ; ChannelTable.cells[ChName,Row] := ImportFile.ChannelName[ch] ; ChannelTable.cells[ChUnits,Row] := ImportFile.ChannelUnits[ch] ; end ; // Display first 10 lines of file AssignFile( F, FileName ) ; Reset(F); meText.Clear ; While (not EOF(F)) and (meText.Lines.Count < 10) do begin Readln(F, s); meText.Lines.Add( s ) ; end ; CloseFile(F) ; end; procedure TImportASCIIFrm.bOKClick(Sender: TObject); // ------------------ // Exit and hide form // ------------------ var ch : Integer ; Row : Integer ; begin ImportFile.ASCIITimeDataInCol0 := rbSampleTimesAvailable.Checked ; ImportFile.ASCIITitleLines := Round(edNumTitleLines.Value) ; // Fixed record size if selected by user or if no time data available ImportFile.ASCIIFixedRecordSize := ckFixedRecordSize.Checked ; // Get record size if ImportFile.ASCIIFixedRecordSize then ImportFile.NumScansPerRecord := Round(edRecordSize.Value) ; // Get sampling interval if not ImportFile.ASCIITimeDataInCol0 then ImportFile.ScanInterval := edScanInterval.Value ; // Column separator if rbComma.Checked then ImportFile.ASCIISeparator := ',' else if rbSpace.Checked then ImportFile.ASCIISeparator := ' ' else ImportFile.ASCIISeparator := #9 ; { Add details for new channels to table } for Row := 1 to ChannelTable.RowCount-1 do begin ch := Row-1 ; ImportFile.ChannelName[ch] := ChannelTable.cells[ChName,Row] ; ImportFile.ChannelUnits[ch] := ChannelTable.cells[ChUnits,Row] ; end ; end; procedure TImportASCIIFrm.rbSampleTimesAvailableClick(Sender: TObject); // ---------------------------------------------- // Sample time available in first column of table // ---------------------------------------------- begin ckFixedRecordSize.Checked := False ; edRecordSize.Visible := False ; SamplingIntervalPanel.Visible := False ; end; procedure TImportASCIIFrm.cbTimeUnitsChange(Sender: TObject); begin UpdateTimeUnits ; end ; procedure TImportASCIIFrm.UpdateTimeUnits ; begin if cbTimeUnits.ItemIndex = 0 then begin ImportFile.ASCIITimeUnits := 'ms' ; edScanInterval.Units := 'ms' ; end else if cbTimeUnits.ItemIndex = 1 then begin ImportFile.ASCIITimeUnits := 's' ; edScanInterval.Units := 's' ; end else begin ImportFile.ASCIITimeUnits := 'm' ; edScanInterval.Units := 'm' ; end ; end ; procedure TImportASCIIFrm.rbNoSampleTimesClick(Sender: TObject); // -------------------------------------- // User-defined time data option selected // -------------------------------------- begin ckFixedRecordSize.Checked := True ; edRecordSize.Visible := True ; SamplingIntervalPanel.Visible := True ; end; procedure TImportASCIIFrm.ckFixedRecordSizeClick(Sender: TObject); // -------------------------------- // Fixed record size option changed // -------------------------------- begin edRecordSize.Visible := ckFixedRecordSize.Checked ; SamplingIntervalPanel.Visible := rbNoSampleTimes.Checked ; end ; end.
unit DAL; interface uses System.JSON, MVCFramework.SystemJSONUtils, System.Generics.Collections, MVCFramework.Serializer.Commons; type [MVCNameCase(ncLowerCase)] TPerson = class private FFirstName: string; FLastName: string; FAge: Integer; FItems: string; FGUID: string; procedure SetFirstName(const Value: string); procedure SetLastName(const Value: string); procedure SetAge(const Value: Integer); procedure SetGUID(const Value: string); procedure SetItems(const Value: string); public [MVCNameAs('first_name')] property FirstName: string read FFirstName write SetFirstName; [MVCNameAs('last_name')] property LastName: string read FLastName write SetLastName; property Age: Integer read FAge write SetAge; property Items: string read FItems write SetItems; property GUID: string read FGUID write SetGUID; end; TPeople = class(TObjectList<TPerson>) end; IPeopleDAL = interface ['{3E534A3E-EAEB-44ED-B74E-EFBBAAAE11B4}'] function GetPeople: TPeople; procedure AddPerson(FirstName, LastName: string; Age: Integer; Items: TArray<string>); procedure DeleteByGUID(GUID: string); function GetPersonByGUID(GUID: string): TPerson; end; TPeopleDAL = class(TInterfacedObject, IPeopleDAL) private const DATAFILE: string = 'people.data'; public function GetPeople: TPeople; procedure AddPerson(FirstName, LastName: string; Age: Integer; Items: TArray<string>); procedure DeleteByGUID(GUID: string); function GetPersonByGUID(GUID: string): TPerson; end; TServicesFactory = class sealed class function GetPeopleDAL: IPeopleDAL; end; implementation uses System.SyncObjs, System.IOUtils, MVCFramework.Serializer.Defaults, System.SysUtils; var // Hey! The storage is a simple json file, so some synchronization is needed _CS: TCriticalSection = nil; { TSimpleDAL } procedure TPeopleDAL.AddPerson(FirstName, LastName: string; Age: Integer; Items: TArray<string>); var lPeople: TPeople; lPerson: TPerson; begin _CS.Enter; try lPeople := GetPeople; try lPerson := TPerson.Create; lPeople.Add(lPerson); lPerson.FirstName := FirstName; lPerson.LastName := LastName; lPerson.Age := Age; lPerson.Items := string.Join(',', Items); lPerson.GUID := TGuid.NewGuid.ToString; TFile.WriteAllText(DATAFILE, GetDefaultSerializer.SerializeCollection(lPeople)); finally lPeople.Free; end; finally _CS.Leave; end; end; class function TServicesFactory.GetPeopleDAL: IPeopleDAL; begin Result := TPeopleDAL.Create; end; procedure TPeopleDAL.DeleteByGUID(GUID: string); var LJPeople: TPeople; I: Integer; begin _CS.Enter; try LJPeople := GetPeople; try for I := 0 to LJPeople.Count - 1 do begin if LJPeople[I].GUID = GUID then begin LJPeople.Delete(i); break; end; end; TFile.WriteAllText(DATAFILE, GetDefaultSerializer.SerializeCollection(LJPeople)); finally LJPeople.Free; end; finally _CS.Leave; end; end; function TPeopleDAL.GetPeople: TPeople; var LData: string; begin _CS.Enter; try Result := TPeople.Create; if TFile.Exists(DATAFILE) then LData := TFile.ReadAllText(DATAFILE).Trim; if not LData.IsEmpty then begin GetDefaultSerializer.DeserializeCollection(LData, Result, TPerson); end; finally _CS.Leave; end; end; function TPeopleDAL.GetPersonByGUID(GUID: string): TPerson; var lPeople: TPeople; lPerson: TPerson; begin Result := nil; lPeople := GetPeople; for lPerson in lPeople do begin if lPerson.GUID = GUID then begin Result := lPeople.Extract(lPerson); Break; end; end; end; { TPerson } procedure TPerson.SetAge(const Value: Integer); begin FAge := Value; end; procedure TPerson.SetFirstName(const Value: string); begin FFirstName := Value; end; procedure TPerson.SetGUID(const Value: string); begin FGUID := Value; end; procedure TPerson.SetItems(const Value: string); begin FItems := Value; end; procedure TPerson.SetLastName(const Value: string); begin FLastName := Value; end; initialization _CS := TCriticalSection.Create; finalization _CS.Free; end.
unit sRadioButton; {$I sDefs.inc} {.$DEFINE LOGGED} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs{$IFNDEF DELPHI5}, Types{$ENDIF}, {$IFDEF TNTUNICODE}TntControls, TntActnList, TntForms, TntClasses, {$ENDIF} StdCtrls, sCommonData, sConst, sDefaults, sFade{$IFDEF LOGGED}, sDebugMsgs{$ENDIF}; type TsRadioButton = class(TRadioButton) {$IFNDEF NOTFORHELP} private FCommonData: TsCommonData; FDisabledKind: TsDisabledKind; FGlyphUnChecked: TBitmap; FGlyphChecked: TBitmap; FTextIndent: integer; FShowFocus: Boolean; FMargin: integer; FadeTimer : TsFadeTimer; FAnimatEvents: TacAnimatEvents; {$IFNDEF DELPHI7UP} FWordWrap : boolean; procedure SetWordWrap(const Value: boolean); {$ENDIF} procedure SetDisabledKind(const Value: TsDisabledKind); procedure SetGlyphChecked(const Value: TBitmap); procedure SetGlyphUnChecked(const Value: TBitmap); procedure SetTextIndent(const Value: integer); procedure SetShowFocus(const Value: Boolean); procedure SetMargin(const Value: integer); procedure SetReadOnly(const Value: boolean); {$IFDEF TNTUNICODE} function GetCaption: TWideCaption; procedure SetCaption(const Value: TWideCaption); function GetHint: WideString; procedure SetHint(const Value: WideString); function IsCaptionStored: Boolean; function IsHintStored: Boolean; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; {$ENDIF} protected FPressed : boolean; FReadOnly: boolean; function GetReadOnly: boolean; virtual; function CanModify : boolean; virtual; function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override; procedure PaintHandler(M : TWMPaint); procedure PaintControl(DC : HDC); procedure DrawCheckText; procedure DrawCheckArea; procedure DrawSkinGlyph(i : integer); procedure PaintGlyph(Bmp : TBitmap; const Index : integer); function SkinGlyphWidth(i : integer) : integer; function SkinGlyphHeight(i : integer) : integer; function SkinCheckRect(i : integer): TRect; function Glyph : TBitmap; function CheckRect: TRect; function GlyphWidth : integer; function GlyphHeight : integer; function GlyphMaskIndex(Checked : boolean) : smallint; procedure PrepareCache; {$IFDEF TNTUNICODE} procedure CreateWindowHandle(const Params: TCreateParams); override; procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; {$ENDIF} public function GetControlsAlignment: TAlignment; override; procedure AfterConstruction; override; constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Invalidate; override; procedure Loaded; override; procedure WndProc(var Message: TMessage); override; published {$IFDEF TNTUNICODE} property Caption: TWideCaption read GetCaption write SetCaption stored IsCaptionStored; property Hint: WideString read GetHint write SetHint stored IsHintStored; {$ENDIF} property AutoSize default True; property Margin : integer read FMargin write SetMargin default 2; {$ENDIF} // NOTFORHELP property AnimatEvents : TacAnimatEvents read FAnimatEvents write FAnimatEvents default [aeGlobalDef]; property SkinData : TsCommonData read FCommonData write FCommonData; property DisabledKind : TsDisabledKind read FDisabledKind write SetDisabledKind default DefDisabledKind; property GlyphChecked : TBitmap read FGlyphChecked write SetGlyphChecked; property GlyphUnChecked : TBitmap read FGlyphUnChecked write SetGlyphUnChecked; property ReadOnly : boolean read GetReadOnly write SetReadOnly default False; property ShowFocus: Boolean read FShowFocus write SetShowFocus default True; property TextIndent : integer read FTextIndent write SetTextIndent default 0; {$IFNDEF DELPHI7UP} property WordWrap : boolean read FWordWrap write SetWordWrap default False; {$ELSE} property WordWrap default False; {$ENDIF} {$IFDEF D2007} property OnMouseEnter; property OnMouseLeave; {$ENDIF} end; implementation uses sGraphUtils, acntUtils, sAlphaGraph, sVclUtils, sMaskData, sStylesimply, sSkinProps, ExtCtrls, sGroupBox, Math, sMessages, sSKinManager{$IFDEF CHECKXP}, UxTheme, Themes{$ENDIF}; { TsRadioButton } {$IFDEF TNTUNICODE} procedure TsRadioButton.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); inherited; end; {$ENDIF} procedure TsRadioButton.AfterConstruction; begin inherited; SkinData.Loaded; end; function TsRadioButton.GetControlsAlignment: TAlignment; begin if not UseRightToLeftAlignment then Result := Alignment else if Alignment = taRightJustify then Result := taLeftJustify else Result := taRightJustify; end; function TsRadioButton.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; var ss : TSize; R : TRect; w, h : integer; begin Result := False; if FCommonData.Skinned then begin if csLoading in ComponentState then Exit; if AutoSize then begin ss := GetStringSize(Font.Handle, Caption); R := CheckRect; NewWidth := WidthOf(R) + 2 * Margin + (ss.cx + FTextIndent + 8) * integer(Caption <> ''); NewHeight := Max(HeightOf(R), 2 * Margin + ss.cy * integer(Caption <> '')) + 2; Result := True; w := NewWidth; h := NewHeight; end; end else begin if AutoSize then begin ss := GetStringSize(Font.Handle, Caption); NewWidth := ss.cx + 20; NewHeight := max(ss.cy + 4, 20); end else begin w := NewWidth; h := NewHeight; Result := inherited CanAutoSize(w, h); NewWidth := w; NewHeight := h; end; end; end; function TsRadioButton.Glyph: TBitmap; begin if Checked then Result := GlyphChecked else Result := GlyphUnChecked; if Result.Empty then Result := nil; end; function TsRadioButton.CheckRect: TRect; var i : integer; begin if (Glyph <> nil) then begin if GetControlsAlignment = taRightJustify then Result := Rect(Margin, (Height - GlyphHeight) div 2, Margin + GlyphWidth, GlyphHeight + (Height - GlyphHeight) div 2) else Result := Rect(Width - GlyphWidth - Margin, (Height - GlyphHeight) div 2, Width - Margin, GlyphHeight + (Height - GlyphHeight) div 2) end else begin i := GlyphMaskIndex(Checked); if SkinData.SkinManager.IsValidImgIndex(i) then Result := SkinCheckRect(i) else Result := Rect(0, 0, 16, 16); end; end; {$IFDEF TNTUNICODE} procedure TsRadioButton.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsWideCharAccel(Message.CharCode, Caption) and CanFocus then begin SetFocus; Result := 1; end else Broadcast(Message); end; {$ENDIF} constructor TsRadioButton.Create(AOwner: TComponent); begin inherited Create(AOwner); FCommonData := TsCommonData.Create(Self, False); FCommonData.COC := COC_TsRadioButton; FCommonData.FOwnerControl := Self; FadeTimer := nil; FMargin := 2; FShowFocus := True; FTextIndent := 0; FDisabledKind := DefDisabledKind; FGlyphChecked := TBitmap.Create; FGlyphUnChecked := TBitmap.Create; FPressed := False; AutoSize := True; FAnimatEvents := [aeGlobalDef]; {$IFNDEF DELPHI7UP} FWordWrap := False; {$ELSE} WordWrap := False; {$ENDIF} end; {$IFDEF TNTUNICODE} procedure TsRadioButton.CreateWindowHandle(const Params: TCreateParams); begin CreateUnicodeHandle(Self, Params, 'BUTTON'); end; procedure TsRadioButton.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; {$ENDIF} destructor TsRadioButton.Destroy; begin StopFading(FadeTimer, FCommonData); if Assigned(FCommonData) then FreeAndNil(FCommonData); if Assigned(FGlyphChecked) then FreeAndNil(FGlyphChecked); if Assigned(FGlyphUnchecked) then FreeAndNil(FGlyphUnChecked); inherited Destroy; end; procedure TsRadioButton.DrawCheckArea; var CheckArea: TRect; i, GlyphCount, GlyphIndex : integer; begin if Glyph <> nil then begin CheckArea := CheckRect; GlyphCount := Glyph.Width div Glyph.Height; if FPressed then GlyphIndex := min(2, GlyphCount - 1) else if ControlIsActive(FCommonData) and not ReadOnly then GlyphIndex := min(1, GlyphCount - 1) else GlyphIndex := 0; PaintGlyph(Glyph, GlyphIndex); end else begin i := GlyphMaskIndex(Checked); if SkinData.SkinManager.IsValidImgIndex(i) then DrawSkinGlyph(i); end; end; procedure TsRadioButton.DrawCheckText; var rText: TRect; Fmt: integer; t, b, w, h, dx : integer; begin if Caption <> '' then begin w := Width - (WidthOf(CheckRect) + FTextIndent + 2 * Margin + 2); rText := Rect(0, 0, w, 0); Fmt := DT_CALCRECT; if WordWrap then Fmt := Fmt or DT_WORDBREAK else Fmt := Fmt or DT_SINGLELINE; AcDrawText(FCommonData.FCacheBMP.Canvas.Handle, Caption, rText, Fmt); h := HeightOf(rText); dx := WidthOf(rText); t := Max((Height - h) div 2, Margin); b := t + h; Fmt := DT_TOP; if Alignment = taRightJustify then begin if IsRightToLeft then begin rText.Right := Width - Margin - WidthOf(CheckRect) - FTextIndent - 4; rText.Left := rText.Right - dx; rText.Top := t; rText.Bottom := b; if not WordWrap then Fmt := DT_RIGHT; end else begin rText := Rect(Width - w - Margin + 2, t, Width - w - Margin + 2 + dx, b); if not WordWrap then Fmt := DT_LEFT; end; end else begin rText := Rect(Margin, t, w + Margin, b); end; OffsetRect(rText, -integer(WordWrap), -1); if WordWrap then Fmt := Fmt or DT_WORDBREAK or DT_CENTER else Fmt := Fmt or DT_SINGLELINE; if UseRightToLeftReading then Fmt := Fmt or DT_RTLREADING; acWriteTextEx(FCommonData.FCacheBmp.Canvas, PacChar(Caption), True, rText, Fmt, FCommonData, ControlIsActive(FCommonData) and not ReadOnly); FCommonData.FCacheBmp.Canvas.Pen.Style := psClear; FCommonData.FCacheBmp.Canvas.Brush.Style := bsSolid; if Focused and ShowFocus then begin dec(rText.Bottom, integer(not WordWrap)); inc(rText.Top); InflateRect(rText, 1, 1); FocusRect(FCommonData.FCacheBmp.Canvas, rText); end; end; end; procedure TsRadioButton.DrawSkinGlyph(i: integer); var R : TRect; Mode : integer; begin if FCommonData.FCacheBmp.Width < 1 then exit; R := SkinCheckRect(i); if FPressed then Mode := 2 else if ControlIsActive(FCommonData) and not ReadOnly then Mode := 1 else Mode := 0; sAlphaGraph.DrawSkinGlyph(FCommonData.FCacheBmp, R.TopLeft, Mode, 1, FCommonData.SkinManager.ma[i], MakeCacheInfo(SkinData.FCacheBmp)); end; {$IFDEF TNTUNICODE} function TsRadioButton.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; function TsRadioButton.GetCaption: TWideCaption; begin Result := TntControl_GetText(Self) end; function TsRadioButton.GetHint: WideString; begin Result := TntControl_GetHint(Self) end; {$ENDIF} function TsRadioButton.GetReadOnly: boolean; begin { v6.33 if (Parent is TsRadioGroup) then begin Result := FReadOnly not TsRadioGroup(Parent).CanModify(TsRadioGroup(Parent).FButtons.IndexOf(Self)) end else } Result := FReadOnly; end; function TsRadioButton.CanModify : boolean; begin Result := True; end; function TsRadioButton.GlyphHeight: integer; begin { if Assigned(Images) and (ImgChecked > -1) and (ImgUnChecked > -1) then begin Result := Images.Height; end else } begin if Glyph <> nil then Result := Glyph.Height else Result := 16; end; end; function TsRadioButton.GlyphMaskIndex(Checked : boolean): smallint; begin if Checked then Result := FCommonData.SkinManager.GetMaskIndex(FCommonData.SkinManager.ConstData.IndexGLobalInfo, s_GLobalInfo, s_RadioButtonChecked) else Result := FCommonData.SkinManager.GetMaskIndex(FCommonData.SkinManager.ConstData.IndexGLobalInfo, s_GLobalInfo, s_RadioButtonUnChecked); end; function TsRadioButton.GlyphWidth: integer; begin { if Assigned(Images) and (ImgChecked > -1) and (ImgUnChecked > -1) then begin if Images.Width mod Images.Height = 0 then Result := Images.Width div (Images.Width div Images.Height) else Result := Images.Width; end else }begin if Glyph <> nil then begin if Glyph.Width mod Glyph.Height = 0 then Result := Glyph.Width div (Glyph.Width div Glyph.Height) else Result := Glyph.Width; end else Result := 16; end; end; procedure TsRadioButton.Invalidate; begin inherited; if AutoSize then WordWrap := False; end; {$IFDEF TNTUNICODE} function TsRadioButton.IsCaptionStored: Boolean; begin Result := TntControl_IsCaptionStored(Self); end; function TsRadioButton.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self) end; {$ENDIF} procedure TsRadioButton.Loaded; begin inherited; SkinData.Loaded; AdjustSize; end; procedure TsRadioButton.PaintControl(DC: HDC); begin if not FCommonData.Updating and not (Assigned(FadeTimer) and FadeTimer.Enabled) then begin PrepareCache; UpdateCorners(FCommonData, 0); BitBlt(DC, 0, 0, Width, Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY); end; end; procedure TsRadioButton.PaintGlyph(Bmp: TBitmap; const Index : integer); var R : TRect; begin if FCommonData.FCacheBmp.Width = 0 then exit; R := CheckRect; if Bmp.PixelFormat = pfDevice then Bmp.HandleType := bmDIB; if Bmp.PixelFormat <> pf32bit then Bmp.PixelFormat := pf32bit; CopyByMask(Rect(R.Left, R.Top, R.Right, R.Bottom), Rect(GlyphWidth * Index, 0, GlyphWidth * (Index + 1), GlyphHeight), FCommonData.FCacheBmp, Bmp, EmptyCI, True); end; procedure TsRadioButton.PaintHandler(M: TWMPaint); var PS: TPaintStruct; DC : hdc; SavedDC: hdc; begin if M.DC = 0 then begin BeginPaint(Handle, PS); DC := GetDC(Handle); end else DC := M.DC; SavedDC := SaveDC(DC); try if not FCommonData.Updating then PaintControl(DC) else FCommonData.Updating := True; finally RestoreDC(DC, SavedDC); if M.DC = 0 then begin ReleaseDC(Handle, DC); EndPaint(Handle, PS); end; end; end; procedure TsRadioButton.PrepareCache; var BGInfo : TacBGInfo; begin InitCacheBmp(SkinData); FCommonData.FCacheBmp.Canvas.Font.Assign(Font); FCommonData.FCacheBmp.Canvas.Lock; BGInfo.DrawDC := FCommonData.FCacheBmp.Canvas.Handle; BGInfo.PleaseDraw := True; BGInfo.Offset := Point(Left, Top); BGInfo.R := Rect(0, 0, Width, Height); GetBGInfo(@BGInfo, Parent); if BGInfo.BgType = btUnknown then begin // If parent is not AlphaControl BGInfo.Bmp := FCommonData.FCacheBmp; BGInfo.BgType := btCache; end; FCommonData.FCacheBmp.Canvas.Unlock; PaintItem(FCommonData, BGInfoToCI(@BGInfo), True, integer(ControlIsActive(FCommonData) and not ReadOnly), Rect(0, 0, FCommonData.FCacheBmp.Width, Height), Point(Left, Top), FCommonData.FCacheBmp, False); DrawCheckText; DrawCheckArea; if not Enabled then BmpDisabledKind(FCommonData.FCacheBmp, FDisabledKind, Parent, BGInfoToCI(@BGInfo), Point(Left, Top)); FCommonData.BGChanged := False end; {$IFDEF TNTUNICODE} procedure TsRadioButton.SetCaption(const Value: TWideCaption); begin TntControl_SetText(Self, Value); end; {$ENDIF} {$IFNDEF DELPHI7UP} procedure TsRadioButton.SetWordWrap(const Value: boolean); begin if FWordWrap <> Value then begin FWordWrap := Value; FCommonData.BGChanged := True; if AutoSize then AutoSize := False; Repaint; end; end; {$ENDIF} procedure TsRadioButton.SetDisabledKind(const Value: TsDisabledKind); begin if FDisabledKind <> Value then begin FDisabledKind := Value; FCommonData.Invalidate; end; end; procedure TsRadioButton.SetGlyphChecked(const Value: TBitmap); begin FGlyphChecked.Assign(Value); if AutoSize then AdjustSize; if Checked then FCommonData.Invalidate; end; procedure TsRadioButton.SetGlyphUnChecked(const Value: TBitmap); begin FGlyphUnChecked.Assign(Value); if AutoSize then AdjustSize; if not Checked then FCommonData.Invalidate; end; {$IFDEF TNTUNICODE} procedure TsRadioButton.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; {$ENDIF} procedure TsRadioButton.SetMargin(const Value: integer); begin if FMargin <> Value then begin FMargin := Value; if AutoSize then AdjustSize; Invalidate; end; end; procedure TsRadioButton.SetReadOnly(const Value: boolean); begin FReadOnly := Value; end; procedure TsRadioButton.SetShowFocus(const Value: Boolean); begin if FShowFocus <> Value then begin FShowFocus := Value; Invalidate; end; end; procedure TsRadioButton.SetTextIndent(const Value: integer); begin if FTextIndent <> Value then begin FTextIndent := Value; if AutoSize then AdjustSize; Invalidate; end; end; function TsRadioButton.SkinCheckRect(i: integer): TRect; var h, w, hdiv : integer; begin h := SkinGlyphHeight(i); w := SkinGlyphWidth(i); hdiv := (Height - h) div 2; if GetControlsAlignment = taRightJustify then begin Result := Rect(Margin, hdiv, Margin + w, h + hdiv); end else begin Result := Rect(Width - w - Margin, hdiv, Width - Margin, h + hdiv); end; end; function TsRadioButton.SkinGlyphHeight(i: integer): integer; begin if Assigned(FCommonData.SkinManager.ma[i].Bmp) then Result := FCommonData.SkinManager.ma[i].Bmp.Height div 2 else Result := HeightOf(FCommonData.SkinManager.ma[i].R) div (FCommonData.SkinManager.ma[i].MaskType + 1); end; function TsRadioButton.SkinGlyphWidth(i: integer): integer; begin if Assigned(FCommonData.SkinManager.ma[i].Bmp) then Result := FCommonData.SkinManager.ma[i].Bmp.Width div 3 else Result := WidthOf(FCommonData.SkinManager.ma[i].R) div FCommonData.SkinManager.ma[i].ImageCount; end; procedure TsRadioButton.WndProc(var Message: TMessage); begin {$IFDEF LOGGED} AddToLog(Message); {$ENDIF} if Message.Msg = SM_ALPHACMD then case Message.WParamHi of AC_CTRLHANDLED : begin Message.Result := 1; Exit end; // AlphaSkins supported AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end; AC_REMOVESKIN : if LongWord(Message.LParam) = LongWord(SkinData.SkinManager) then begin StopFading(FadeTimer, FCommonData); CommonWndProc(Message, FCommonData); if HandleAllocated then SendMessage(Handle, BM_SETCHECK, Integer(Checked), 0); if not (csDesigning in ComponentState) and (uxthemeLib <> 0) then Ac_SetWindowTheme(Handle, nil, nil); Repaint; exit end; AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin SetClassLong(Handle, GCL_STYLE, GetClassLong(Handle, GCL_STYLE) and not CS_VREDRAW and not CS_HREDRAW); StopFading(FadeTimer, FCommonData); CommonWndProc(Message, FCommonData); AdjustSize; Repaint; exit end; AC_PREPARECACHE : PrepareCache; AC_STOPFADING : begin StopFading(FadeTimer, FCommonData); Exit end; AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin StopFading(FadeTimer, FCommonData); CommonWndProc(Message, FCommonData); exit end end; if (FCommonData <> nil) and FCommonData.Skinned(True) then case Message.Msg of CM_MOUSEENTER : if Enabled and not (csDesigning in ComponentState) and not FCommonData.FMouseAbove then begin FCommonData.FMouseAbove := True; DoChangePaint(FadeTimer, FCommonData, False, EventEnabled(aeMouseEnter, FAnimatEvents)); end; CM_MOUSELEAVE : if Enabled and not (csDesigning in ComponentState) then begin FCommonData.FMouseAbove := False; FPressed := False; DoChangePaint(FadeTimer, FCommonData, False, EventEnabled(aeMouseLeave, FAnimatEvents)); end; WM_SETFOCUS, CM_ENTER : if not (csDesigning in ComponentState) then begin if Enabled then begin inherited; FCommonData.BGChanged := True; if FadeTimer = nil then Repaint else FadeTimer.Change; // Fast repaint end; Exit; end; WM_KILLFOCUS, CM_EXIT: if not (csDesigning in ComponentState) then begin if Enabled then begin if FadeTimer <> nil then StopFading(FadeTimer, FCommonData); Perform(WM_SETREDRAW, 0, 0); inherited; Perform(WM_SETREDRAW, 1, 0); FCommonData.FFocused := False; FCommonData.FMouseAbove := False; FCommonData.Invalidate; Exit end; end; end; if not ControlIsReady(Self) then inherited else begin CommonWndProc(Message, FCommonData); if FCommonData.Skinned(True) then begin if Message.Msg = SM_ALPHACMD then case Message.WParamHi of AC_ENDPARENTUPDATE : if FCommonData.Updating or FCommonData.HalfVisible then begin FCommonData.Updating := False; PaintHandler(TWMPaint(MakeMessage(WM_PAINT, 0, 0, 0))); end end else case Message.Msg of WM_ENABLE, WM_NCPAINT : Exit; // Disabling of blinking when switched {$IFDEF CHECKXP} WM_UPDATEUISTATE : begin if SkinData.Skinned and UseThemes and not (csDesigning in ComponentState) and (uxthemeLib <> 0) then Ac_SetWindowTheme(Handle, ' ', ' '); Exit; end; {$ENDIF} CM_ENABLEDCHANGED : begin inherited; Repaint; Exit end; BM_SETSTATE : begin Exit; end; BM_SETCHECK : begin inherited; FCommonData.BGChanged := True; if (FadeTimer <> nil) and (FadeTimer.FadeLevel < FadeTimer.Iterations) then begin FadeTimer.Enabled := False; Repaint; end; case Message.WParam of 0 : Checked := False; 1 : Checked := True; end; if not (csDesigning in ComponentState) then begin if Checked then DoChangePaint(FadeTimer, FCommonData, True, EventEnabled(aeMouseUp, FAnimatEvents), fdUp) else DoChangePaint(FadeTimer, FCommonData, True, EventEnabled(aeMouseUp, FAnimatEvents)); end else FCommonData.Invalidate; Exit; end; WM_ERASEBKGND : begin Message.Result := 1; Exit; end; WM_PRINT : begin SkinData.Updating := False; PaintHandler(TWMPaint(Message)); end; WM_PAINT : begin PaintHandler(TWMPaint(Message)); if not (csDesigning in ComponentState) then Exit; end; CM_TEXTCHANGED : begin if AutoSize then AdjustSize; Repaint; Exit; end; WM_KEYDOWN : if Enabled and not (csDesigning in ComponentState) and (TWMKey(Message).CharCode = VK_SPACE) then begin if ReadOnly then Exit; FPressed := True; if not Focused then begin ClicksDisabled := True; Windows.SetFocus(Handle); ClicksDisabled := False; end; Repaint; if Assigned(OnKeyDown) then OnKeydown(Self, TWMKeyDown(Message).CharCode, KeysToShiftState(word(TWMKeyDown(Message).KeyData))); Exit; end; WM_LBUTTONDBLCLK, WM_LBUTTONDOWN : if not (csDesigning in ComponentState) and Enabled and (DragMode = dmManual) then begin if ReadOnly then Exit; FPressed := True; DoChangePaint(FadeTimer, FCommonData, True, EventEnabled(aeMouseDown, FAnimatEvents)); if not Focused then begin ClicksDisabled := True; Windows.SetFocus(Handle); ClicksDisabled := False; end; if WM_LBUTTONDBLCLK = Message.Msg then begin if Assigned(OnDblClick) then OnDblClick(Self) end else if Assigned(OnMouseDown) then OnMouseDown(Self, mbLeft, KeysToShiftState(TWMMouse(Message).Keys), TWMMouse(Message).XPos, TWMMouse(Message).YPos); Exit; end; WM_KEYUP : if not (csDesigning in ComponentState) and Enabled then begin if ReadOnly then Exit; if FPressed then begin FPressed := False; Checked := True; end; Repaint; if Assigned(OnKeyUp) then OnKeyUp(Self, TWMKey(Message).CharCode, KeysToShiftState(TWMKey(Message).KeyData)); Exit; end; WM_LBUTTONUP : if not (csDesigning in ComponentState) and Enabled then begin if not ReadOnly and CanModify and FPressed then Checked := True; FPressed := False; Repaint; if Assigned(OnMouseUp) then OnMouseUp(Self, mbLeft, KeysToShiftState(TWMMouse(Message).Keys), TWMMouse(Message).XPos, TWMMouse(Message).YPos); Exit; end; end end else case Message.Msg of WM_KEYDOWN, WM_LBUTTONDOWN : FPressed := True; WM_KEYUP, WM_LBUTTONUP : FPressed := False; WM_LBUTTONDBLCLK : if ReadOnly then Exit; BM_SETSTATE, BM_SETCHECK : if not (csCreating in ControlState) and FPressed and ReadOnly then Exit; end; inherited; end; end; end.
{ This unit provides a basic implementation of logging. @author(Kaktushose (https://github.com/Kaktushose)) } unit logging; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { @abstract(An enum describing all available logging levels.) } LoggingLevel = (DEBUG, INFO, WARN, ERROR); { @abstract(This class provides the actual logging functionality.) Use @link(TLogger.SetLevel) to set the logging level. } TLogger = class private name: string; level: LoggingLevel; static; procedure Print(message: string; loggingLevel: LoggingLevel); function CreateStackTrace(e: Exception): string; public { Update the global logging level. } class procedure SetLevel(loggingLevel: LoggingLevel); { Log a debug message. } procedure Debug(message: string); { Log an info message. } procedure Info(message: string); { Log a warn message. } procedure Warn(message: string); { Log a error message. } procedure Error(message: string); { Log a error message and an exception. } procedure Error(message: string; e: Exception); { Log an exception. } procedure Error(e: Exception); { Create a new logger named after a class. } constructor GetLogger(clazz: TClass); { Create a new logger with a custom name. } constructor GetLogger(loggerName: string); { The destructor. } destructor Destroy; override; end; implementation class procedure TLogger.SetLevel(loggingLevel: LoggingLevel); begin level := loggingLevel; end; procedure TLogger.Debug(message: string); begin Print(message, LoggingLevel.DEBUG); end; procedure TLogger.Info(message: string); begin Print(message, LoggingLevel.INFO); end; procedure TLogger.Warn(message: string); begin Print(message, LoggingLevel.WARN); end; procedure TLogger.Error(message: string); begin Print(message, LoggingLevel.ERROR); end; procedure TLogger.Error(message: string; e: Exception); begin if e = nil then begin Error(message); Exit; end; Print(message + sLineBreak + CreateStackTrace(e) , LoggingLevel.ERROR); end; procedure TLogger.Error(e: Exception); begin if e = nil then begin Error('nil'); Exit; end; Print(CreateStackTrace(e), LoggingLevel.ERROR); end; procedure TLogger.Print(message: string; loggingLevel: LoggingLevel); var levelString, fmt: string; begin if loggingLevel < level then Exit; WriteStr(levelString, loggingLevel); fmt := '%s [%s] %-5s %s'; WriteLn(Format(fmt, [TimeToStr(Now), name, LevelString, message])); end; function TLogger.CreateStackTrace(e: Exception): string; begin Result := e.ClassName + ': ' + e.Message + sLineBreak + BackTraceStrFunc(e); end; constructor TLogger.GetLogger(clazz: TClass); begin inherited Create; name := clazz.ClassName; end; constructor TLogger.GetLogger(loggerName: string); begin inherited Create; name := loggerName; end; destructor TLogger.Destroy; begin inherited Destroy; end; end.
unit DTypes; (***************************************************************************** Prozessprogrammierung SS08 Aufgabe: Muehle Typen fuer den Darstellungsrechner. Autor: Alexander Bertram (B_TInf 2616) *****************************************************************************) interface uses RTKernel, RTTextIO, Types; const { Konstanten fuer die Darstellung des Spielfeldes } { Breite des inneren Quadrates } cBoardInnerSquareWidth = 5; { Hoehe des inneren Quadrates } cBoardInnerSquareHeight = 5; { Horizontaler Abstand zwischen den Quadraten } cBoardLineHorizontalMargin = 1; { Vertikaler Abstand zwischen den Quadraten } cBoardLineVerticalMargin = 1; { Spielfeldbreite ausgehend vom inneren Quadrat } cBoardWidth = cBoardInnerSquareWidth + (cFieldSquareCount - 1) * (cBoardLineHorizontalMargin + 1) * 2; { Spielfeldhoehe ausgehend vom inneren Quadrat } cBoardHeight = cBoardInnerSquareHeight + (cFieldSquareCount - 1) * (cBoardLineVerticalMargin + 1) * 2; { Startposition des Spielfeldes } cBoardStartX = 1; cBoardStartY = 1; { Hintergrundfarben } { Spielfeld } cBoardBGColor = BGBlack; { Cursor } cCursorFieldPosBGColor = BGBrown; { Markierte Position } cSelectedFieldPosBGColor = BGMagenta; { Konstanten, die fuer das Kreieren der Spielbretttask noetig sind } cBoardPriority = MainPriority; cBoardStack = cDefaultStack * 5; cBoardTaskName = 'Spielbrett'; { Mailboxslots fuer die Spielbrettmailbox } cBoardMailboxSlots = 10; { Position und Farben fuer die Fenster auf dem Darrstellungsrechner } { Spielbrett } cBoardWindowFirstCol = 32; cBoardWindowFirstRow = 0; cBoardWindowLastCol = cBoardWindowFirstCol + cBoardWidth + 4; cBoardWindowLastRow = cBoardWindowFirstRow + cBoardHeight + 4; cBoardWindowColor = Normal + cBoardBGColor; { Benutzerspielsteine } cUserTokenWindowFirstCol = 0; cUserTokenWindowFirstRow = 0; cUserTokenWindowLastCol = cUserTokenWindowFirstCol + 4; cUserTokenWindowLastRow = cBoardWindowLastRow; cUserTokenWindowColor = Normal + cBoardBGColor; { CPU-Spielsteine } cCPUTokenWindowFirstCol = 75; cCPUTokenWindowFirstRow = 0; cCPUTokenWindowLastCol = cCPUTokenWindowFirstCol + 4; cCPUTokenWindowLastRow = cBoardWindowLastRow; cCPUTokenWindowColor = Normal + cBoardBGColor; { Systemstatus } cSystemStatusWindowFirstCol = 0; cSystemStatusWindowFirstRow = 43; cSystemStatusWindowLastCol = cSystemStatusWindowFirstCol + 79; cSystemStatusWindowLastRow = cSystemStatusWindowFirstRow + 6; cSystemStatusWindowFrameColor = LightRed + cBoardBGColor; cSystemStatusWindowAttribute = Normal + cBoardBGColor; { Spielverlauf } cGameFlowWindowFirstCol = 0; cGameFlowWindowFirstRow = cBoardWindowLastRow + 1; cGameFlowWindowLastCol = cGameFlowWindowFirstCol + 79; cGameFlowWindowLastRow = cGameFlowWindowFirstRow + 15; cGameFlowWindowColor = Normal + cBoardBGColor; cGameFlowWindowTitle = ' Spielablauf '; { Tasten } cKeyWindowFirstCol = 0; cKeyWindowFirstRow = cGameFlowWindowLastRow + 1; cKeyWindowLastCol = cKeyWindowFirstCol + 79; cKeyWindowLastRow = cKeyWindowFirstRow + 8; cKeyWindowColor = Gray; { ASCII-Zeichen fuer das Spielfeld } cBoardUpperLeftCornerChar = #$DA; cBoardHorizontalLineChar = #$C4; cBoardUpperCrossChar = #$C2; cBoardUpperRightCornerChar = #$BF; cBoardVerticalLineChar = #$B3; cBoardCrossChar = #$C5; cBoardLeftCrossChar = #$C3; cBoardRightCrossChar = #$B4; cBoardLowerLeftCornerChar = #$C0; cBoardLowerCrossChar = #$C1; cBoardLowerRightCornerChar = #$D9; { ASCII-Zeichen fuer die Spielsteine } cUserTokenChar = 'o'; cCPUTokenChar = 'o'; type { Spielbrettbreite } TBoardWidth = 0..cBoardWidth - 1; { Spielbretthoehe } TBoardHeight = 0..cBoardHeight - 1; { Lookup-Tabelle fuer die Spielbrettdarstellung } TBoardCharLookupTable = array[TBoardWidth, TBoardHeight] of char; { Nachrichttyp fuer die Kommunikation mit der Spielbretttask } TBoardMessageKind = ( { Initialisierung} bmkInit, { Spielerfarben } bmkPlayerColors, { Aktueller Spieler } bmkCurrentPlayer, { Zugmoeglichkeiten } bmkTokenMovePossibilities, { Cursorbewegung } bmkCursorMove, { Spielfeld } bmkField, { Positionsmarkierung } bmkFieldPositionSelection, { Spielsteinzug } bmkTokenMove, { Spielerstatus } bmkPlayerStage, { Spielenden } bmkGameOver); TBoardMessage = record case Kind: TBoardMessageKind of bmkPlayerColors: ( Colors: TPlayerColors; ); bmkCurrentPlayer: ( Player: TPlayer; ); bmkTokenMovePossibilities: ( TokenMovePossibilities: TMovePossibilities; ); bmkCursorMove: ( Direction: TDirection; ); bmkField: ( Field: TField; ); bmkTokenMove: ( TokenMoveData: TTokenMoveData; ); bmkPlayerStage: ( PlayerStage: TPlayerStage; ); end; implementation end.
{********************************************************} { } { Zeos Database Objects } { Sybase SQL Query and Table components } { } { Copyright (c) 1999-2001 Sergey Seroukhov } { Copyright (c) 1999-2002 Zeos Development Group } { } {********************************************************} unit ZSySqlQuery; interface {$R *.dcr} uses SysUtils, {$IFNDEF LINUX} Windows, {$ENDIF} Db, Classes, ZDirSql, ZDirSySql, DbCommon, ZSySqlCon, ZSySqlTr, ZToken, ZLibSySql, ZSqlExtra, ZQuery, ZSqlTypes, ZSqlItems; {$IFNDEF LINUX} {$INCLUDE ..\Zeos.inc} {$ELSE} {$INCLUDE ../Zeos.inc} {$ENDIF} type TZSySqlOption = (soStoreResult); TZSySqlOptions = set of TZSySqlOption; { Direct Sybase SQL dataset with descendant of TZDataSet } TZCustomSySQLDataset = class(TZDataSet) private FExtraOptions: TZSySqlOptions; FUseConnect: TDirSySQLConnect; FUseTransact: TDirSySQLTransact; procedure SetDatabase(Value: TZSySqlDatabase); procedure SetTransact(Value: TZSySqlTransact); function GetDatabase: TZSySqlDatabase; function GetTransact: TZSySqlTransact; function GetIdentField(Table: string): Integer; protected { Overriding ZDataset methods } procedure QueryRecord; override; procedure UpdateAfterPost(OldData, NewData: PRecordData); override; procedure CreateConnections; override; { Overrided standart methods } procedure InternalClose; override; {$IFDEF WITH_IPROVIDER} { IProvider support } function PSInTransaction: Boolean; override; function PSExecuteStatement(const ASql: string; AParams: TParams; ResultSet: Pointer): Integer; override; procedure PSSetCommandText(const CommandText: string); override; {$ENDIF} public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddTableFields(Table: string; SqlFields: TSqlFields); override; procedure AddTableIndices(Table: string; SqlFields: TSqlFields; SqlIndices: TSqlIndices); override; published property Database: TZSySqlDatabase read GetDatabase write SetDatabase; property Transaction: TZSySqlTransact read GetTransact write SetTransact; property ExtraOptions: TZSySqlOptions read FExtraOptions write FExtraOptions; end; { Direct SySQL query with descendant of TDataSet } TZSySqlQuery = class(TZCustomSySQLDataset) public property MacroCount; property ParamCount; published property MacroChar; property Macros; property MacroCheck; property Params; property ParamCheck; property DataSource; property Sql; property RequestLive; property Database; property Transaction; property Active; end; { Direct SySQL query with descendant of TDataSet } TZSySqlTable = class(TZCustomSySQLDataset) public constructor Create(AOwner: TComponent); override; published property TableName; property ReadOnly default False; property DefaultIndex default True; property Database; property Transaction; property Active; end; implementation uses ZExtra, ZDBaseConst, ZBlobStream, Math; {********** TZCustomSySQLDataset implementation **********} { Class constructor } constructor TZCustomSySQLDataset.Create(AOwner: TComponent); begin inherited Create(AOwner); Query := TDirSySQLQuery.Create(nil, nil); DatabaseType := dtMSSQL; FExtraOptions := [soStoreResult]; FUseConnect := TDirSySQLConnect.Create; FUseTransact := TDirSySQLTransact.Create(FUseConnect); end; { Class destructor } destructor TZCustomSySQLDataset.Destroy; begin inherited Destroy; FUseTransact.Free; FUseConnect.Free; end; { Set connect to database component } procedure TZCustomSySQLDataset.SetDatabase(Value: TZSySqlDatabase); begin inherited SetDatabase(Value); end; { Set connect to transact-server component } procedure TZCustomSySQLDataset.SetTransact(Value: TZSySqlTransact); begin inherited SetTransact(Value); end; { Get connect to database component } function TZCustomSySQLDataset.GetDatabase: TZSySqlDatabase; begin Result := TZSySqlDatabase(DatabaseObj); end; { Get connect to transact-server component } function TZCustomSySQLDataset.GetTransact: TZSySqlTransact; begin Result := TZSySqlTransact(TransactObj); end; { Read query from server to internal buffer } procedure TZCustomSySQLDataset.QueryRecord; var I, Count: Integer; RecordData: PRecordData; FieldDesc: PFieldDesc; TempSmall: SmallInt; TempDouble: Double; TempBool: WordBool; TempDate: DBDATETIME; DateRec: DBDATEREC; TempTime: TDateTime; TimeStamp: TTimeStamp; BlobPtr: PRecordBlob; Cancel: Boolean; begin Count := SqlBuffer.Count; while not Query.Eof and (Count = SqlBuffer.Count) do begin { Go to the record } if SqlBuffer.FillCount > 0 then Query.Next; { Invoke OnProgress event } if Assigned(OnProgress) then begin Cancel := False; OnProgress(Self, psRunning, ppFetching, Query.RecNo+1, MaxIntValue([Query.RecNo+1, Query.RecordCount]), Cancel); if Cancel then Query.Close; end; if Query.EOF then Break; { Getting record } RecordData := SqlBuffer.Add; for I := 0 to SqlBuffer.SqlFields.Count - 1 do begin FieldDesc := SqlBuffer.SqlFields[I]; if FieldDesc.FieldNo < 0 then Continue; if Query.FieldIsNull(FieldDesc.FieldNo) and not (FieldDesc.FieldType in [ftBlob, ftMemo]) then Continue; case FieldDesc.FieldType of ftString, ftBytes: begin SqlBuffer.SetFieldDataLen(FieldDesc, Query.FieldBuffer(FieldDesc.FieldNo), RecordData, Query.FieldSize(FieldDesc.FieldNo)); end; ftSmallInt: begin case Query.FieldType(FieldDesc.FieldNo) of SQLINT1: TempSmall := PByte(Query.FieldBuffer(FieldDesc.FieldNo))^; SQLINT2: TempSmall := PSmallInt(Query.FieldBuffer(FieldDesc.FieldNo))^; end; SqlBuffer.SetFieldData(FieldDesc, @TempSmall, RecordData); end; ftBoolean: begin TempBool := (PByte(Query.FieldBuffer(FieldDesc.FieldNo))^ <> 0); SqlBuffer.SetFieldData(FieldDesc, @TempBool, RecordData); end; ftInteger, ftAutoInc: begin SqlBuffer.SetFieldData(FieldDesc, Query.FieldBuffer(FieldDesc.FieldNo), RecordData); end; ftFloat, ftCurrency: begin dbconvert(TDirSySQLTransact(Query.Transact).Handle, Query.FieldType(FieldDesc.FieldNo), PByte(Query.FieldBuffer(FieldDesc.FieldNo)), Query.FieldSize(FieldDesc.FieldNo), SQLFLT8, @TempDouble, SizeOf(TempDouble)); SqlBuffer.SetFieldData(FieldDesc, @TempDouble, RecordData); end; ftDateTime: begin dbconvert(TDirSySQLTransact(Query.Transact).Handle, Query.FieldType(FieldDesc.FieldNo), PByte(Query.FieldBuffer(FieldDesc.FieldNo)), Query.FieldSize(FieldDesc.FieldNo), SQLDATETIME, @TempDate, SizeOf(TempDate)); dbdatecrack(TDirSySQLTransact(Query.Transact).Handle, @DateRec, @TempDate); // mjd 9/28/2001 - added following code as per bug report if (DateRec.year > 1900) and (DateRec.year < 2200)then begin TimeStamp := DateTimeToTimeStamp(EncodeDate(DateRec.year, DateRec.month+1, DateRec.day) + EncodeTime(DateRec.hour, DateRec.minute, DateRec.second, DateRec.millisecond)); end else begin TimeStamp.Time := 0; TimeStamp.Date := 0; end; { TimeStamp := DateTimeToTimeStamp(EncodeDate(DateRec.year, DateRec.month, DateRec.day) + EncodeTime(DateRec.hour, DateRec.minute, DateRec.second, DateRec.millisecond));} // mjd 9/28/2001 TempTime := TimeStampToMSecs(TimeStamp); SqlBuffer.SetFieldData(FieldDesc, @TempTime, RecordData); end; ftBlob, ftMemo: begin { Initialize blob and memo fields } BlobPtr := PRecordBlob(@RecordData.Bytes[FieldDesc.Offset+1]); BlobPtr.BlobType := btInternal; { Fill not null fields } if not Query.FieldIsNull(FieldDesc.FieldNo) then begin RecordData.Bytes[FieldDesc.Offset] := 0; BlobPtr.Size := Query.FieldSize(FieldDesc.FieldNo); BlobPtr.Data := AllocMem(BlobPtr.Size); System.Move(Query.FieldBuffer(FieldDesc.FieldNo)^, BlobPtr.Data^, BlobPtr.Size); end { Fill null fields } else begin BlobPtr.Size := 0; BlobPtr.Data := nil; end; end; else DatabaseError(SUnknownType + FieldDesc.Alias); end; end; { Filter received record } SqlBuffer.FilterItem(SqlBuffer.Count-1); end; if Query.Eof then Query.Close; end; { Internal close query } procedure TZCustomSySQLDataset.InternalClose; begin inherited InternalClose; { Close lowerlevel connect to database } FUseTransact.Close; FUseConnect.Disconnect; end; {************** Sql-queries processing ******************} { Fill collection with fields } procedure TZCustomSySQLDataset.AddTableFields(Table: string; SqlFields: TSqlFields); var Size: Integer; Decimals: Integer; FieldType: TFieldType; Query: TDirSySQLQuery; Default: string; AutoType: TAutoType; begin Query := TDirSySQLQuery(Transaction.QueryHandle); Query.ShowColumns(Table, ''); while not Query.Eof do begin { Evalute field parameters } Size := StrToIntDef(Query.Field(3), 0); Decimals := StrToIntDef(Query.Field(4), 0); FieldType := SySQLToDelphiTypeDesc(Query.Field(6)); if FieldType <> ftString then Size := 0; Default := Query.Field(7); AutoType := atNone; if Query.Field(10) = '1' then AutoType := atIdentity; if Query.Field(6) = 'timestamp' then AutoType := atTimestamp; { Put new field description } SqlFields.Add(Table, Query.Field(0), '', Query.Field(6), FieldType, Size, Decimals, AutoType, Query.Field(9) = '1', False, Default, btInternal); Query.Next; end; Query.Close; end; { Fill collection with indices } procedure TZCustomSySQLDataset.AddTableIndices(Table: string; SqlFields: TSqlFields; SqlIndices: TSqlIndices); var Buffer, Token: string; KeyType: TKeyType; SortType: TSortType; Query: TDirSySQLQuery; begin Query := TDirSySQLQuery(TransactObj.QueryHandle); Query.ShowIndexes(Table); while not Query.Eof do begin { Define a key type } KeyType := ktIndex; Buffer := Query.Field(1); Token := ''; while (Buffer <> '') and not StrCaseCmp(Token, 'located') do begin Token := StrTok(Buffer, ' ,'); if StrCmpBegin(Token, 'primary') then KeyType := ktPrimary else if (KeyType <> ktPrimary) and StrCaseCmp(Token, 'unique') then KeyType := ktUnique; end; { Define a sorting mode } SortType := stAscending; { Put new index description } SqlIndices.AddIndex(Query.Field(0), Table, Query.Field(2), KeyType, SortType); Query.Next; end; Query.Close; end; { Get auto_increment field of table } function TZCustomSySQLDataset.GetIdentField(Table: string): Integer; var I: Integer; FieldDesc: PFieldDesc; begin Result := -1; for I := 0 to SqlBuffer.SqlFields.Count-1 do begin FieldDesc := SqlBuffer.SqlFields[I]; if (FieldDesc.AutoType = atIdentity) and StrCaseCmp(FieldDesc.Table, Table) then begin Result := I; Exit; end; end; end; { Update record after post updates } procedure TZCustomSySQLDataset.UpdateAfterPost(OldData, NewData: PRecordData); var Index: Integer; FieldDesc: PFieldDesc; begin { Apply identity fields } Index := GetIdentField(SqlParser.Tables[0]); if (OldData.RecordType = ztInserted) and (Index >= 0) then begin FieldDesc := SqlBuffer.SqlFields[Index]; SqlBuffer.SetField(FieldDesc, EvaluteDef('@@IDENTITY'), NewData); end; end; { Create demanded connections } procedure TZCustomSySQLDataset.CreateConnections; begin { Check database and transaction object } if not Assigned(DatabaseObj) then DatabaseError(SConnectNotDefined); if not Assigned(TransactObj) then DatabaseError(STransactNotDefined); { Connect to transact-server } TransactObj.Connect; if not TransactObj.Connected then DatabaseError(SConnectTransactError); { Define database connect by open mode } if soStoreResult in FExtraOptions then begin Query.Connect := DatabaseObj.Handle; Query.Transact := TransactObj.Handle; FetchAll := True; end else begin { Attach to database } FUseConnect.HostName := DatabaseObj.Handle.HostName; FUseConnect.Port := DatabaseObj.Handle.Port; FUseConnect.Database := DatabaseObj.Handle.Database; FUseConnect.Login := DatabaseObj.Handle.Login; FUseConnect.Passwd := DatabaseObj.Handle.Passwd; FUseConnect.Connect; if not FUseConnect.Active then DatabaseError(SConnectError); { Attach to database } //!! FUseTransact.TransIsolation := TransactObj.Handle.TransIsolation; FUseTransact.TransactSafe := TransactObj.Handle.TransactSafe; FUseTransact.Open; if not FUseTransact.Active then DatabaseError(SConnectError); { Assign new connect } Query.Connect := FUseConnect; Query.Transact := FUseTransact; FetchAll := False; end; end; {$IFDEF WITH_IPROVIDER} { IProvider support } { Is in transaction } function TZCustomSySQLDataset.PSInTransaction: Boolean; begin Result := True; end; { Execute an sql statement } function TZCustomSySQLDataset.PSExecuteStatement(const ASql: string; AParams: TParams; ResultSet: Pointer): Integer; begin if Assigned(ResultSet) then begin TDataSet(ResultSet^) := TZSySqlQuery.Create(nil); with TZSySqlQuery(ResultSet^) do begin Sql.Text := ASql; Params.Assign(AParams); Open; Result := RowsAffected; end; end else Result := TransactObj.ExecSql(ASql); end; { Set command query } procedure TZCustomSySQLDataset.PSSetCommandText(const CommandText: string); begin Close; if Self is TZSySqlQuery then TZSySqlQuery(Self).Sql.Text := CommandText else if Self is TZSySqlTable then TZSySqlQuery(Self).TableName := CommandText; end; {$ENDIF} { TZSySqlTable } constructor TZSySqlTable.Create(AOwner: TComponent); begin inherited Create(AOwner); DefaultIndex := True; ReadOnly := False; end; end.
unit UxlMiscCtrls; interface uses Windows, Messages, CommCtrl, UxlWinControl, UxlFunctions, UxlClasses, UxlList, UxlStdCtrls, UxlWinClasses; type TUpDownStruct = record Min: integer; Max: integer; Position: integer; Increment: integer; Buddy: TxlControl; end; TUDChangeEvent = procedure (newpos: integer) of object; TxlUpDown = class (TxlControl) private FBuddy: TxlWinControl; FMin, FMax, FIncrement, FPosition: integer; FOnChange: TUDChangeEvent; procedure SetMin (i_min: integer); procedure SetMax (i_max: integer); protected procedure OnCreateControl (); override; procedure OnDestroyControl (); override; function DoCreateControl (HParent: HWND): HWND; override; public function ProcessNotify (code: integer; lParam: DWORD): DWORD; override; procedure SetBuddy (o_buddy: TxlWinControl); procedure SetPosition (i_pos: integer); procedure SetRange (i_min, i_max: integer); procedure SetIncrement (i_inc: integer); property Min: integer read FMin write SetMin; property Max: integer read FMax write SetMax; property Position: integer read FPosition write SetPosition; property Buddy: TxlWinControl read FBuddy write SetBuddy; property Increment: integer read FIncrement write SetIncrement; property OnChange: TUDChangeEvent read FOnChange write FOnChange; end; type TxlProgressBar = class (TxlControl) protected function DoCreateControl (HParent: HWND): HWND; override; public procedure SetRange (i_min, i_max: cardinal); procedure SetPosition (i_pos: cardinal); procedure IncPosition (i_inc: cardinal); procedure GoStart (); procedure GoEnd (); end; type TxlSlideSuper = class (TxlControl) private FDragMode: boolean; FOnStartSlide: TNotifyEvent; FOnEndSlide: TNotifyEvent; FSlideColor: TColor; protected procedure OnCreateControl (); override; function IsUserClass(): boolean; override; function ProcessMessage (AMessage, wParam, lParam: DWORD): DWORD; override; function IsVertStyle (): boolean; virtual; abstract; procedure f_OnEndSlide (); virtual; public property OnStartSlide: TNotifyEvent read FOnStartSlide write FOnStartSlide; property OnEndSlide: TNotifyEvent read FOnEndSlide write FOnEndSlide; end; TxlVertSlide = class (TxlSlideSuper) protected function DoCreateControl (HParent: HWND): HWND; override; function IsVertStyle (): boolean; override; end; TxlHorzSlide = class (TxlSlideSuper) protected function DoCreateControl (HParent: HWND): HWND; override; function IsVertStyle (): boolean; override; end; TxlSplitterSuper = class (TxlSlideSuper) private FList_Buddy1, FList_Buddy2: TxlObjList; FButton: TxlButton; FOnButtonClick, FOnButtonRightClick: TNotifyEvent; procedure Slide (i_newpos: integer); function GetSlidePos (): integer; procedure f_OnButtonclick (Sender: TObject); procedure f_OnButtonRightclick (Sender: TObject); procedure SetShowButton (value: boolean); protected procedure OnCreateControl (); override; procedure OnDestroyControl (); override; procedure OnSize (clpos: TPos); override; procedure f_OnEndSlide (); override; public procedure SetBuddy (buddy1, buddy2: array of TxlWinControl); overload; procedure SetBuddy (buddy1, buddy2: TxlObjList); overload; procedure ClearBuddy (); property SlidePos: integer read GetSlidePos write Slide; property ShowButton: boolean write SetShowButton; property OnButtonclick: TNotifyEvent read FOnButtonClick write FOnButtonclick; property OnButtonRightClick: TNOtifyEvent read FOnButtonRightclick write FOnButtonRightClick; end; TxlVertSplitter = class (TxlSplitterSuper) protected function DoCreateControl (HParent: HWND): HWND; override; function IsVertStyle (): boolean; override; end; TxlHorzSplitter = class (TxlSplitterSuper) protected function DoCreateControl (HParent: HWND): HWND; override; function IsVertStyle (): boolean; override; end; type TxlHotKey = class (TxlControl) private FOnchange: TNotifyEvent; procedure f_SetHotKey (value: THotKey); function f_GetHotKey (): THotKey; protected function DoCreateControl (HParent: HWND): HWND; override; function ProcessCommand (dwEvent: word): dword; override; public property HotKey: THotKey read f_GetHotKey write f_SetHotKey; property Onchange: TNotifyEvent read FOnChange write FOnChange; end; type TxlDateTimePicker = class (TxlControl) private procedure f_SetDateTime (const value: TSystemTime); protected FFormat: widestring; function DoCreateControl (HParent: HWND): HWND; override; function f_datetimestyle (): DWORD; virtual; function f_GetDateTime (): TSystemTime; public procedure SetFormat (const s_format: widestring); property DateTime: TSystemTime read f_GetDateTime write f_SetDateTime; end; TxlDatePicker = class (TxlDateTimePicker) private procedure f_SetDate (const value: TSystemTime); protected public property Date: TSystemTime read f_GetDateTime write f_SetDate; end; TxlTimePicker = class (TxlDateTimePicker) private procedure f_SetTime (const value: TSystemTime); protected function f_datetimestyle (): DWORD; override; public property Time: TSystemTime read f_GetDateTime write f_SetTime; end; type TTextAlign = (taLeft, taCenter, taRight); TxlStatusBar = class (TxlControl) private protected function DoCreateControl (HParent: HWND): HWND; override; public procedure SetParts (i_widths: array of integer); procedure SetStatusText (i_part: integer; const s_text: widestring; i_align: TTextAlign = taLeft); end; type TToolTipStyle = record TipWidth: integer; InitialTime: integer; AutoPopTime: integer; end; TTipIcon = (tiNone, tiInfo, tiWarning, tiError); TxlToolTipSuper = class (TxlControl) private FStyle: TToolTipStyle; protected function DoCreateControl (HParent: HWND): HWND; override; procedure BringTipToTop (); procedure SetStyle (const value: TToolTipStyle); virtual; procedure SetTipWidth (value: integer); procedure SetColor (i_color: TColor); override; function GetColor (): TColor; override; public property Style: TToolTipStyle read FStyle write SetStyle; property TipWidth: integer write SetTipWidth; end; TxlToolTip = class (TxlToolTipSuper) private FTipList: TxlIntList; procedure f_DoDeleteTool (id: integer); function ToolExists (id: integer): boolean; protected procedure OnCreateControl (); override; procedure OnDestroyControl (); override; public procedure AddTool (id: integer; h_owner: HWND; const rt: TRect; const s_text: widestring); procedure ResetTool (id: integer; const rt: TRect; const s_text: widestring); procedure DeleteTool (id: integer); procedure Clear (); end; TxlTrackingTip = class (TxlToolTipSuper) // parent must be TxlWindow private FToolInfo: ToolInfoW; FInitialTimer: TxlTimer; FAutoPopTimer: Txltimer; FHideTimer: TxlTimer; FHideWhenCursorMove: boolean; FTipPos, FCursorPos: TPoint; procedure f_OnInitialTimer (Sender: TObject); procedure f_OnAutoPopTimer (Sender: TObject); procedure f_OnHideTimer (Sender: TObject); protected procedure OnCreateControl (); override; procedure OnDestroyControl (); override; procedure SetStyle (const value: TToolTipStyle); override; public procedure ShowTip (const s_text: widestring; const s_title: widestring = ''; o_icon: TTipIcon = tiNone); overload; procedure ShowTip (const pt: TPoint; const s_text: widestring; const s_title: widestring = ''; o_icon: TTipIcon = tiNone); overload; procedure HideTip (); property HideWhenCursorMove: boolean read FHideWhenCursorMove write FHideWhenCursorMove; end; type TxlCalendar = class (TxlControl) private protected function DoCreateControl (HParent: HWND): HWND; override; public end; implementation uses SysUtils, UxlCommDlgs, UxlStrUtils, UxlWinDef, UxlWindow; function TxlUpDown.DoCreateControl (HParent: HWND): HWND; begin InitCommonControl (ICC_UPDOWN_CLASS); result := CreateWin32Control (HParent, UPDOWN_CLASS, UDS_ALIGNRIGHT or UDS_ARROWKEYS or UDS_SETBUDDYINT); end; procedure TxlUpDown.OnCreateControl (); begin SetRange (0, 10); SetPosition (1); SetIncrement (1); FBuddy := nil; end; procedure TxlUpDown.OnDestroyControl (); begin DeInitCommonControl(); end; procedure TxlUpDown.SetMin (i_min: integer); begin SetRange (i_min, Max); end; procedure TxlUpDown.SetMax (i_max: integer); begin SetRange (Min, i_max); end; procedure TxlUpDown.SetRange(i_min, i_max: integer); begin Perform (UDM_SETRANGE, 0, MAKELONG(i_max, i_min)); FMin := i_min; FMax := i_max; end; procedure TxlUpDown.SetPosition (i_pos: integer); begin if (i_pos < FMin) or (i_pos > FMax) then exit; Perform (UDM_SETPOS, 0, MakeLong(i_pos, 0)); FPosition := i_pos; if assigned(FBuddy) then // SetBuddy 有时失效,因此此处手动读取与设置 Buddy 的内容 FBuddy.Text := IntToStr (i_pos); end; procedure TxlUpDown.SetBuddy (o_buddy: TxlWinControl); begin FBuddy := o_buddy; Perform (UDM_SETBUDDY, o_buddy.handle, 0); end; procedure TxlUpDown.SetIncrement (i_inc: integer); begin FIncrement := i_inc; end; function TxlUpDown.ProcessNotify (code: integer; lParam: DWORD): DWORD; var pnm: PNMUPDOWN; i_newpos, i_oldpos: integer; begin result := 0; if (code = UDN_DELTAPOS) then begin pnm := PNMUpDown (lParam); if assigned (FBuddy) then // 根据 Buddy 的内容刷新 Position SetPosition (StrToIntDef(FBuddy.text, Position)); i_oldpos := Position; i_newpos := Position + pnm.iDelta * FIncrement; SetPosition (i_newpos); if (Position <> i_oldpos) and assigned (FOnChange) then FOnChange (Position); result := 1; end; end; //------------------------- function TxlProgressBar.DoCreateControl (HParent: HWND): HWND; begin InitCommonControl (ICC_PROGRESS_CLASS); result := CreateWin32Control (HParent, PROGRESS_CLASS, PBS_SMOOTH); end; procedure TxlProgressBar.SetPosition (i_pos: cardinal); begin Perform (PBM_SETPOS, i_pos, 0); end; procedure TxlProgressBar.IncPosition (i_inc: cardinal); begin perform (PBM_DELTAPOS, i_inc, 0); end; procedure TxlProgressBar.SetRange (i_min, i_max: cardinal); begin Perform (PBM_SETRANGE, 0, MakeLparam(i_min, i_max)); end; procedure TxlProgressBar.GoStart (); begin SetPosition (Perform (PBM_GETRANGE, wparam(true), 0)); end; procedure TxlProgressBar.GoEnd (); begin SetPosition (Perform (PBM_GETRANGE, wparam(false), 0)); end; //-------------------------- function TxlHotKey.DoCreateControl (HParent: HWND): HWND; begin InitCommonControl (ICC_HOTKEY_CLASS); result := CreateWin32Control (HParent, 'msctls_hotkey32'); end; procedure TxlHotKey.f_SetHotKey (value: THotKey); begin Perform (HKM_SETHOTKEY, value, 0); if assigned (FOnChange) then FOnChange (self); end; function TxlHotKey.f_GetHotKey (): THotKey; begin result := Perform (HKM_GETHOTKEY, 0, 0); end; function TxlHotKey.ProcessCommand (dwEvent: word): dword; begin result := 0; case dwEvent of EN_CHANGE: if assigned (FOnChange) then FOnChange (self); end; end; //-------------------------- function TxlDateTimePicker.DoCreateControl (HParent: HWND): HWND; begin InitCommonControl (ICC_DATE_CLASSES); result := CreateWin32Control (HParent, DATETIMEPICK_CLASS, f_datetimestyle); FFormat := ''; end; procedure TxlDatePicker.f_SetDate (const value: TSystemTime); begin if FFormat = '' then SetFormat ('yyyy-MM-dd'); f_SetDateTime (value); end; procedure TxlTimePicker.f_SetTime (const value: TSystemTime); begin if FFormat = '' then SetFormat ('HH:mm'); f_SetDateTime (value); end; procedure TxlDateTimePicker.f_SetDateTime (const value: TSystemTime); begin if FFormat = '' then SetFormat ('yyyy-MM-dd HH:mm'); DateTime_SetSystemtime (Fhandle, GDT_VALID, value); end; function TxlDateTimePicker.f_GetDateTime (): TSystemTime; begin DateTime_GetSystemtime (Fhandle, result); end; procedure TxlDateTimePicker.SetFormat(const s_format: widestring); begin FFormat := s_format; DateTime_SetFormatW (Fhandle, pwidechar(s_format)); end; function TxlDateTimePicker.f_datetimestyle (): DWORD; begin result := 0; end; function TxlTimePicker.f_datetimestyle (): DWORD; begin result := DTS_UPDOWN; end; //----------------------------- function TxlCalendar.DoCreateControl (HParent: HWND): HWND; begin InitCommonControl (ICC_DATE_CLASSES); result := CreateWin32Control (HParent, MONTHCAL_CLASS, MCS_DAYSTATE); end; //--------------------------------- const DefBarWidth = 3; procedure TxlSlideSuper.OnCreateControl (); begin inherited; Move (-1, -1, DefBarWidth, DefBarWidth); FSlideColor := GetSysColor (COLOR_BTNFACE); Color := FSlideColor; SetWndStyle (WS_CLIPSIBLINGS, false); end; function TxlSlideSuper.IsUserClass(): boolean; begin result := true; end; function TxlSlideSuper.ProcessMessage (AMessage, wParam, lParam: DWORD): DWORD; var b_processed: boolean; begin result := 0; b_processed := true; case AMessage of WM_LBUTTONDOWN: begin FDragMode := true; self.Color := GetSysColor (COLOR_GRAYTEXT); SetCapture (Fhandle); if assigned (FOnStartSlide) then FOnStartSlide (self); end; WM_MOUSEMOVE: begin if not FDragMode then exit; if IsVertStyle then Left := Parent.CursorPos.x else Top := Parent.CursorPos.y; end; WM_LBUTTONUP: begin self.Hide; // 否则会留下残影 FDragMode := false; ReleaseCapture (); self.Color := FSlideColor; self.Show; f_OnEndSlide; end; else b_processed := false; end; if not b_processed then result := inherited ProcessMessage (AMessage, wParam, lParam); end; procedure TxlSlideSuper.f_OnEndSlide (); begin if assigned (FOnEndSlide) then FOnEndSlide (self); end; //---------------------- procedure TxlSplitterSuper.OnCreateControl (); begin inherited; FList_Buddy1 := TxlObjList.create; FList_Buddy2 := TxlObjList.create; end; procedure TxlSplitterSuper.OnDestroyControl (); begin if assigned (FButton) then FButton.Free; FList_Buddy1.free; FList_Buddy2.free; inherited; end; procedure TxlSplitterSuper.OnSize (clpos: TPos); begin inherited OnSize (clpos); if not assigned (FButton) then exit; with FButton do begin Left := 0; Top := clpos.height div 2 - 10; Width := clpos.Width; Height := 20; end; end; procedure TxlSplitterSuper.SetShowButton(value: boolean); begin if value then begin if assigned (FButton) then exit; FButton := TxlButton.create(self); FButton.OnClick := f_OnButtonClick; FButton.OnRightClick := f_OnButtonRightClick; end else if assigned (FButton) then FreeAndNil (FButton); end; procedure TxlSplitterSuper.f_OnButtonClick (Sender: TObject); begin if assigned (FOnButtonClick) then FOnButtonClick (self); end; procedure TxlSplitterSuper.f_OnButtonRightClick (Sender: TObject); begin if assigned (FOnButtonRightClick) then FOnButtonRightClick (self); end; //----------------------- procedure TxlSplitterSuper.SetBuddy (buddy1, buddy2: array of TxlWinControl); var i: integer; begin ClearBuddy; for i := Low(buddy1) to High(buddy1) do FList_Buddy1.Add (buddy1[i]); for i := Low(buddy2) to High(buddy2) do FList_Buddy2.Add (buddy2[i]); end; procedure TxlSplitterSuper.SetBuddy (buddy1, buddy2: TxlObjList); var i: integer; begin ClearBuddy; for i := buddy1.Low to buddy1.High do FList_Buddy1.Add (buddy1[i]); for i := buddy2.Low to buddy2.High do FList_Buddy2.Add (buddy2[i]); end; procedure TxlSplitterSuper.ClearBuddy (); begin FList_Buddy1.clear; FList_Buddy2.Clear; end; procedure TxlSplitterSuper.Slide (i_newpos: integer); begin if IsVertStyle then self.Left := i_newpos else self.Top := i_newpos; f_OnEndSlide; end; function TxlSplitterSuper.GetSlidePos (): integer; begin if IsVertStyle then result := self.Left else result := self.Top; end; procedure TxlSplitterSuper.f_OnEndSlide (); var i: integer; ctrl: TxlWinControl; begin inherited; if IsVertStyle then begin for i := FList_Buddy1.Low to FList_Buddy1.High do begin ctrl := TxlWinControl(FList_Buddy1[i]); ctrl.Width := self.Left - ctrl.Left; ctrl.Redraw; end; for i := FList_Buddy2.Low to FList_Buddy2.High do begin ctrl := TxlWinControl(FList_Buddy2[i]); ctrl.Width := ctrl.Right - self.Right; ctrl.Left := self.Right; ctrl.Redraw; end; end else begin for i := FList_Buddy1.Low to FList_Buddy1.High do begin ctrl := TxlWinControl(FList_Buddy1[i]); ctrl.Height := self.Top - ctrl.Top; ctrl.Redraw; end; for i := FList_Buddy2.Low to FList_Buddy2.High do begin ctrl := TxlWinControl(FList_Buddy2[i]); ctrl.Height := ctrl.Bottom - self.Bottom; ctrl.Top := self.Bottom; ctrl.Redraw; end; end; // Parent.Update(); end; //------------------------- function TxlVertSlide.DoCreateControl (HParent: HWND): HWND; begin RegisterControlClass ('TxlVertSlide', COLOR_BTNFACE, IDC_HAND); result := CreateWin32Control (HParent, 'TxlVertSlide'); end; function TxlVertSlide.IsVertStyle (): boolean; begin result := true; end; function TxlHorzSlide.DoCreateControl (HParent: HWND): HWND; begin RegisterControlClass ('TxlHorzSlide', COLOR_BTNFACE, IDC_HAND); result := CreateWin32Control (HParent, 'TxlHorzSlide'); end; function TxlHorzSlide.IsVertStyle (): boolean; begin result := false; end; function TxlVertSplitter.DoCreateControl (HParent: HWND): HWND; begin RegisterControlClass ('TxlVertSplitter', COLOR_BTNFACE, IDC_SIZEWE); result := CreateWin32Control (HParent, 'TxlVertSplitter'); end; function TxlVertSplitter.IsVertStyle (): boolean; begin result := true; end; function TxlHorzSplitter.DoCreateControl (HParent: HWND): HWND; begin RegisterControlClass ('TxlHorzSplitter', COLOR_BTNFACE, IDC_SIZENS); result := CreateWin32Control (HParent, 'TxlHorzSplitter'); end; function TxlHorzSplitter.IsVertStyle (): boolean; begin result := false; end; //-------------------------- function TxlStatusBar.DoCreateControl (HParent: HWND): HWND; begin InitCommonControl (ICC_BAR_CLASSES); result := CreateWin32Control (HParent, STATUSCLASSNAME, 0); end; procedure TxlStatusBar.SetParts (i_widths: array of integer); var i: integer; begin for i := Low(i_widths) + 1 to High(i_widths) do begin if i_widths[i] = -1 then break; i_widths[i] := i_widths[i] + i_widths[i-1]; end; perform (SB_SETPARTS, length(i_widths), lparam(@i_widths)); end; procedure TxlStatusBar.SetStatusText (i_part: integer; const s_text: widestring; i_align: TTextAlign = taLeft); var s: widestring; begin case i_align of taCenter: s := #9 + s_text; taRight: s := #9#9 + s_text; else s := s_text; end; Perform (SB_SETTEXTW, i_part, lparam(pwidechar(s))); end; //----------------------------- function TxlToolTipSuper.DoCreateControl (HParent: HWND): HWND; begin InitCommonControl (ICC_BAR_CLASSES); result := CreateWindowExW (WS_EX_TOPMOST, TOOLTIPS_CLASS, nil, WS_POPUP or TTS_NOPREFIX or TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HParent, 0, system.MainInstance, nil); end; procedure TxlToolTipSuper.BringTipToTop (); begin SetWindowPos (Fhandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE); end; procedure TxlToolTipSuper.SetStyle (const value: TToolTipStyle); begin Perform (TTM_SETDELAYTIME, TTDT_INITIAL, value.InitialTime); Perform (TTM_SETDELAYTIME, TTDT_AUTOPOP, value.AutoPopTime); FStyle := value; SetTipWidth (value.TipWidth); end; procedure TxlToolTipSuper.SetTipWidth (value: integer); begin Perform (TTM_SETMAXTIPWIDTH, 0, value); FStyle.TipWidth := value; end; procedure TxlToolTipSuper.SetColor (i_color: TColor); begin Perform (TTM_SETTIPBKCOLOR, i_color, 0); end; function TxlToolTipSuper.GetColor (): TColor; begin result := Perform (TTM_GETTIPBKCOLOR, 0, 0); end; //------------------ procedure TxlToolTip.OnCreateControl (); begin FTipList := TxlIntList.Create; end; procedure TxlToolTip.OnDestroyControl (); begin FTipList.Free; end; procedure TxlToolTip.AddTool (id: integer; h_owner: HWND; const rt: TRect; const s_text: widestring); var ti: TOOLINFOW; begin if ToolExists (id) then ResetTool (id, rt, s_text) else begin with ti do begin cbSize := sizeof (ti); uFlags := TTF_SUBCLASS; hwnd := h_owner; uId := id; hinst := hInstance; lpszText := pwidechar(s_text); rect := rt; end; Perform (TTM_ADDTOOLW, 0, LPARAM(@ti)); BringTipToTop; FTipList.AddByIndex (id, h_owner); end; end; procedure TxlToolTip.DeleteTool (id: integer); begin if not ToolExists (id) then exit; f_DoDeleteTool (id); FTipList.DeleteByIndex (id); end; procedure TxlToolTip.f_DoDeleteTool (id: integer); var ti: ToolInfoW; begin with ti do begin cbSize := sizeof (ti); hwnd := FTipList.ItemsByIndex [id]; uId := id; end; Perform (TTM_DELTOOL, 0, lparam(@ti)); end; function TxlToolTip.ToolExists (id: integer): boolean; begin result := FTipList.IndexValid (id); end; procedure TxlToolTip.ResetTool (id: integer; const rt: TRect; const s_text: widestring); var ti: TOOLINFOW; begin if not ToolExists (id) then exit; with ti do begin cbSize := sizeof (ti); uFlags := TTF_SUBCLASS; hwnd := FTipList.ItemsByIndex [id]; uId := id; rect := rt; lpszText := pwidechar (s_Text); end; Perform (TTM_NEWTOOLRECT, 0, lparam(@ti)); Perform (TTM_UPDATETIPTEXTW, 0, lparam(@ti)); end; procedure TxlToolTip.Clear (); var i: integer; begin for i := FTipList.Low to FTipList.High do f_DoDeleteTool (FTipList.Indexes[i]); FTipList.Clear; end; //----------------------- procedure TxlTrackingTip.OnCreateControl (); begin inherited; with FToolInfo do begin cbSize := sizeof (FToolInfo); uFlags := TTF_TRACK or TTF_ABSOLUTE; hwnd := Fhandle; uId := 0; hinst := hInstance; lpszText := nil; rect.Left := 0; rect.Top := 0; rect.Right := 0; rect.Bottom := 0; end; Perform (TTM_ADDTOOLW, 0, LPARAM(@FToolInfo)); FInitialTimer := TimerCenter.NewTimer; FInitialTimer.OnTimer := f_OnInitialtimer; FAutoPoptimer := TimerCenter.NewTimer; FAutoPopTimer.OnTimer := f_OnAutoPopTimer; FHideTimer := TimerCenter.NewTimer; FHideTimer.Interval := 300; FHideTimer.OnTimer := f_OnHideTimer; end; procedure TxlTrackingTip.OnDestroyControl (); begin TimerCenter.ReleaseTimer (FInitialTimer); TimerCenter.ReleaseTimer (FAutoPopTimer); TimerCenter.ReleaseTimer (FHideTimer); inherited; end; procedure TxlTrackingTip.SetStyle (const value: TToolTipStyle); begin inherited; FInitialTimer.Interval := value.Initialtime; FAutoPopTimer.Interval := value.AutoPoptime; end; procedure TxlTrackingTip.ShowTip (const s_text: widestring; const s_title: widestring = ''; o_icon: TTipIcon = tiNone); begin FTipPos.X := -500; ShowTip (FTipPos, s_text, s_title, o_icon); end; procedure TxlTrackingTip.ShowTip (const pt: TPoint; const s_text: widestring; const s_title: widestring = ''; o_icon: TTipIcon = tiNone); begin FTipPos := pt; HideTip; Perform (TTM_SETTITLEW, Ord(o_icon), lparam(pwidechar(s_title))); FToolInfo.lpszText := pwidechar (s_Text); Perform (TTM_UPDATETIPTEXTW, 0, lparam(@FToolInfo)); if FInitialTimer.Interval > 0 then FInitialTimer.Start else f_OnInitialtimer (self); end; procedure TxlTrackingTip.HideTip (); begin FInitialTimer.Stop; FAutoPopTimer.Stop; FHideTimer.Stop; Perform (TTM_TRACKACTIVATE, BoolToInt(false), lparam(@FToolInfo)); end; procedure TxlTrackingTip.f_OnInitialTimer (Sender: TObject); var rt: TRect; xdif, ydif: integer; begin FInitialTimer.Stop; if FTipPos.X <= -500 then begin GetCursorPos (FTipPos); inc (FTipPos.Y, 20); GetScreenRect (rt); xdif := rt.right - FTipPos.x; ydif := rt.bottom - FTipPos.y; if xdif < FStyle.TipWidth then dec (FTipPos.x, FStyle.TipWidth - xdif); if ydif < 200 then dec (FTipPos.Y, 200 - ydif); end; Perform (TTM_TRACKPOSITION, 0, MAKELPARAM(FTipPos.x, FTipPos.y)); Perform (TTM_TRACKACTIVATE, BoolToInt(true), lparam(@FToolInfo)); if (not Parent.StayOnTop) or ((Parent as TxlWindow).Status = wsMinimize) then BringTipToTop; if FAutoPopTimer.Interval > 0 then FAutoPoptimer.Start; if FHideWhenCursorMove then begin GetCursorPos (FCursorPos); FHideTimer.Start; end; end; procedure TxlTrackingTip.f_OnAutoPopTimer (Sender: TObject); begin HideTip; end; procedure TxlTrackingTip.f_OnHideTimer(Sender: TObject); var pt: TPoint; begin GetCursorPos (pt); if (ABS (pt.x - FCursorPos.x) > 20) or (ABS (pt.Y - FCursorPos.y) > 20) then HideTip; end; end. // 请勿删除! // function f_CalcPosition (const rt: TRect; const ti: ToolInfoW): TPoint; // var scrt, rt2: TRect; // cp: TPoint; // bubblewidth, bubbleheight, dw: integer; // begin // GetCursorPos (cp); // GetScreenRect (scrt); //// dw := SendMessageW (Fhandle, TTM_GETBUBBLESIZE, 0, lparam(@ti)); // rt2 := self.Rect; // Perform (TTM_ADJUSTRECT, BoolToInt(true), lparam(@rt2)); // bubblewidth := rt2.Right - rt2.Left; // bubbleheight := rt2.Bottom - rt2.Top; // HiWord (dw); // // result.x := cp.X; // if PointInRect (cp, rt) then // begin // result.x := cp.x; // result.Y := cp.Y + 20; // end // else // begin // result.X := rt.Left + (rt.Right - rt.Left) div 2; // result.Y := rt.Bottom; // end; // // if result.x + bubblewidth > scrt.Right then // dec (result.x, bubblewidth); // if result.y + bubbleheight > scrt.Bottom then // result.Y := rt.Top - bubbleheight; // end;
unit untCardReaderThread; {$mode objfpc}{$H+} interface uses Classes, SysUtils, untCardReader, untPerson, Dialogs; const CardReaderThreadInterval:integer=100; type TCardReadEventHandler=procedure(Person:TPerson) of object; TCardReadErrorEventHandler=procedure(Error:integer) of object; TCardReadIDEventHandler=procedure(ID:integer) of object; type { TCardReaderThread } TCardReaderThread=class(TThread) private CardReader:TCardReader; Person:TPerson; bolReadOnlyID:boolean; nID:integer; protected procedure Execute; override; public bolSuspend:Boolean; EvtCardRead:TCardReadEventHandler; EvtCardReadError:TCardReadErrorEventHandler; EvtCardReadID:TCardReadIDEventHandler; property OnCardRead:TCardReadEventHandler read EvtCardRead write EvtCardRead; property OnCardReadError:TCardReadErrorEventHandler read EvtCardReadError write EvtCardReadError; property OnCardReadID:TCardReadIDEventHandler read EvtCardReadID write EvtCardReadID; constructor Create(CreateSuspend: boolean; Port:string;BaundRate:integer); destructor Destroy; override; procedure SuspendDevice; procedure ResumeDevice; procedure RaiseCardReadEvent; end; implementation { TCardReaderThread } procedure TCardReaderThread.Execute; var crxError:integer; begin while true do begin while(bolSuspend) do Sleep(100); if not bolReadOnlyID then begin crxError:= CardReader.ReadData(Person); if (crxError = integer(CardReaderErrorType.crxNoError) )then begin CardReader.WriteLastLoginDate; Synchronize(@RaiseCardReadEvent) end else if( Assigned(EvtCardReadError)) then EvtCardReadError(crxError); end else begin crxError:= CardReader.ReadID(nID); if (crxError = integer(CardReaderErrorType.crxNoError) )then begin CardReader.WriteLastLoginDate; Synchronize(@RaiseCardReadEvent) end else if( Assigned(EvtCardReadError)) then EvtCardReadError(crxError); end; Sleep(CardReaderThreadInterval); end; Person.Free; end; constructor TCardReaderThread.Create(CreateSuspend: boolean;Port:string;BaundRate:integer); begin CardReader:=TCardReader.Create(Port, BaundRate); inherited Create(CreateSuspend); bolSuspend:=false; Person:=TPerson.Create; bolReadOnlyID:=false; end; destructor TCardReaderThread.Destroy; begin CardReader.Free; inherited Destroy; end; procedure TCardReaderThread.SuspendDevice; begin bolSuspend:=true; end; procedure TCardReaderThread.ResumeDevice; begin bolSuspend:=false; end; procedure TCardReaderThread.RaiseCardReadEvent; begin if bolReadOnlyID then begin if Assigned(EvtCardReadID) then EvtCardReadID(nID); end else begin if Assigned(EvtCardRead) then EvtCardRead(Person); end; end; end.
unit UBackupAutoSyncInfo; interface uses classes, DateUtils, SysUtils; type // 检测 同步时间 TBackupAutoSyncHandle = class public BackupPathList : TStringList; public procedure Update; private procedure RefreshSynTime( BackupPath : string ); procedure AutoBackup( BackupPath : string ); end; // 等待线程 TBackupAutoSyncThread = class( TThread ) private IsCheckNow : Boolean; LastLocalBackupTime : TDateTime; public constructor Create; procedure CheckNow; destructor Destroy; override; protected procedure Execute; override; private procedure HandleCheck; end; // 控制器 TMyBackupAutoSyncInfo = class public IsRun : Boolean; BackupAutoSyncThread : TBackupAutoSyncThread; public constructor Create; procedure CheckNow; procedure StopSync; end; var MyBackupAutoSyncInfo : TMyBackupAutoSyncInfo; implementation uses UMyBackupInfo, UBackupInfoControl, USettingInfo, ULocalBackupControl, ULocalBackupInfo; { TBackupAutoSyncThread } procedure TBackupAutoSyncThread.CheckNow; begin IsCheckNow := True; end; constructor TBackupAutoSyncThread.Create; begin inherited Create; LastLocalBackupTime := Now; end; destructor TBackupAutoSyncThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TBackupAutoSyncThread.Execute; var StartTime : TDateTime; begin while not Terminated do begin IsCheckNow := False; StartTime := Now; while not Terminated and not IsCheckNow and ( MinutesBetween( Now, StartTime ) < 1 ) do Sleep(100); if Terminated then Break; // 检测 网络备份 同步时间 HandleCheck; end; inherited; end; procedure TBackupAutoSyncThread.HandleCheck; var BackupAutoSyncHandle : TBackupAutoSyncHandle; begin BackupAutoSyncHandle := TBackupAutoSyncHandle.Create; BackupAutoSyncHandle.Update; BackupAutoSyncHandle.Free; end; { TBackupAutoSyncHandle } procedure TBackupAutoSyncHandle.AutoBackup(BackupPath: string); var BackupPathSetLastSyncTimeHandle : TBackupPathSetLastSyncTimeHandle; BackupPathScanHandle : TBackupPathScanHandle; begin // 设置上一次 备份时间 BackupPathSetLastSyncTimeHandle := TBackupPathSetLastSyncTimeHandle.Create( BackupPath ); BackupPathSetLastSyncTimeHandle.SetLastSyncTime( Now ); BackupPathSetLastSyncTimeHandle.Update; BackupPathSetLastSyncTimeHandle.Free; // 开始备份 BackupPathScanHandle := TBackupPathScanHandle.Create( BackupPath ); BackupPathScanHandle.SetIsShowFreeLimt( False ); BackupPathScanHandle.Update; BackupPathScanHandle.Free; end; procedure TBackupAutoSyncHandle.RefreshSynTime(BackupPath: string); var BackupPathRefreshLastSyncTimeHandle : TBackupPathRefreshLastSyncTimeHandle; begin BackupPathRefreshLastSyncTimeHandle := TBackupPathRefreshLastSyncTimeHandle.Create( BackupPath ); BackupPathRefreshLastSyncTimeHandle.Update; BackupPathRefreshLastSyncTimeHandle.Free; end; procedure TBackupAutoSyncHandle.Update; var i : Integer; BackupPath : string; begin BackupPathList := MyBackupPathInfoUtil.ReadBackupPathList; for i := 0 to BackupPathList.Count - 1 do begin BackupPath := BackupPathList[i]; if MyBackupPathInfoUtil.ReadIsAutoSyncTimeOut( BackupPath ) then AutoBackup( BackupPath ) else RefreshSynTime( BackupPath ); end; BackupPathList.Free; end; { TMyBackupAutoSyncInfo } procedure TMyBackupAutoSyncInfo.CheckNow; begin if not IsRun then Exit; BackupAutoSyncThread.CheckNow; end; constructor TMyBackupAutoSyncInfo.Create; begin IsRun := True; BackupAutoSyncThread := TBackupAutoSyncThread.Create; BackupAutoSyncThread.Resume; end; procedure TMyBackupAutoSyncInfo.StopSync; begin IsRun := False; BackupAutoSyncThread.Free; end; end.
unit DelphiZXingQRCodeTestAppMainForm; // Demo app for ZXing QRCode port to Delphi, by Debenu Pty Ltd // www.debenu.com interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DelphiZXingQRCode, Vcl.ExtCtrls, Vcl.StdCtrls; type TForm1 = class(TForm) edtText: TEdit; Label1: TLabel; cmbEncoding: TComboBox; Label2: TLabel; Label3: TLabel; edtQuietZone: TEdit; Label4: TLabel; PaintBox1: TPaintBox; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBox1Paint(Sender: TObject); procedure edtTextChange(Sender: TObject); procedure cmbEncodingChange(Sender: TObject); procedure edtQuietZoneChange(Sender: TObject); private QRCodeBitmap: TBitmap; public procedure Update; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.cmbEncodingChange(Sender: TObject); begin Update; end; procedure TForm1.edtQuietZoneChange(Sender: TObject); begin Update; end; procedure TForm1.edtTextChange(Sender: TObject); begin Update; end; procedure TForm1.FormCreate(Sender: TObject); begin QRCodeBitmap := TBitmap.Create; Update; end; procedure TForm1.FormDestroy(Sender: TObject); begin QRCodeBitmap.Free; end; procedure TForm1.PaintBox1Paint(Sender: TObject); var Scale: Double; begin PaintBox1.Canvas.Brush.Color := clWhite; PaintBox1.Canvas.FillRect(Rect(0, 0, PaintBox1.Width, PaintBox1.Height)); if ((QRCodeBitmap.Width > 0) and (QRCodeBitmap.Height > 0)) then begin if (PaintBox1.Width < PaintBox1.Height) then begin Scale := PaintBox1.Width / QRCodeBitmap.Width; end else begin Scale := PaintBox1.Height / QRCodeBitmap.Height; end; PaintBox1.Canvas.StretchDraw(Rect(0, 0, Trunc(Scale * QRCodeBitmap.Width), Trunc(Scale * QRCodeBitmap.Height)), QRCodeBitmap); end; end; procedure TForm1.Update; var QRCode: TDelphiZXingQRCode; Row, Column: Integer; begin QRCode := TDelphiZXingQRCode.Create; try QRCode.Data := edtText.Text; QRCode.Encoding := TQRCodeEncoding(cmbEncoding.ItemIndex); QRCode.QuietZone := StrToIntDef(edtQuietZone.Text, 4); QRCodeBitmap.SetSize(QRCode.Rows, QRCode.Columns); for Row := 0 to QRCode.Rows - 1 do begin for Column := 0 to QRCode.Columns - 1 do begin if (QRCode.IsBlack[Row, Column]) then begin QRCodeBitmap.Canvas.Pixels[Column, Row] := clBlack; end else begin QRCodeBitmap.Canvas.Pixels[Column, Row] := clWhite; end; end; end; finally QRCode.Free; end; PaintBox1.Repaint; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFCE_MOVIMENTO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfceMovimentoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, NfceCaixaVO, EmpresaVO, NfceTurnoVO, NfceOperadorVO, NfceFechamentoVO, NfceSuprimentoVO, NfceSangriaVO; type [TEntity] [TTable('NFCE_MOVIMENTO')] TNfceMovimentoVO = class(TVO) private FID: Integer; FID_NFCE_CAIXA: Integer; FID_NFCE_OPERADOR: Integer; FID_NFCE_TURNO: Integer; FID_EMPRESA: Integer; FID_GERENTE_SUPERVISOR: Integer; FDATA_ABERTURA: TDateTime; FHORA_ABERTURA: String; FDATA_FECHAMENTO: TDateTime; FHORA_FECHAMENTO: String; FTOTAL_SUPRIMENTO: Extended; FTOTAL_SANGRIA: Extended; FTOTAL_NAO_FISCAL: Extended; FTOTAL_VENDA: Extended; FTOTAL_DESCONTO: Extended; FTOTAL_ACRESCIMO: Extended; FTOTAL_FINAL: Extended; FTOTAL_RECEBIDO: Extended; FTOTAL_TROCO: Extended; FTOTAL_CANCELADO: Extended; FSTATUS_MOVIMENTO: String; FNfceCaixaVO: TNfceCaixaVO; FEmpresaVO: TEmpresaVO; FNfceTurnoVO: TNfceTurnoVO; FNfceOperadorVO: TNfceOperadorVO; FNfceGerenteVO: TNfceOperadorVO; FListaNfceFechamentoVO: TObjectList<TNfceFechamentoVO>; FListaNfceSuprimentoVO: TObjectList<TNfceSuprimentoVO>; FListaNfceSangriaVO: TObjectList<TNfceSangriaVO>; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_NFCE_CAIXA', 'Id Nfce Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfceCaixa: Integer read FID_NFCE_CAIXA write FID_NFCE_CAIXA; [TColumn('ID_NFCE_OPERADOR', 'Id Nfce Operador', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfceOperador: Integer read FID_NFCE_OPERADOR write FID_NFCE_OPERADOR; [TColumn('ID_NFCE_TURNO', 'Id Nfce Turno', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfceTurno: Integer read FID_NFCE_TURNO write FID_NFCE_TURNO; [TColumn('ID_EMPRESA', 'Id Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; [TColumn('ID_GERENTE_SUPERVISOR', 'Id Gerente Supervisor', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdGerenteSupervisor: Integer read FID_GERENTE_SUPERVISOR write FID_GERENTE_SUPERVISOR; [TColumn('DATA_ABERTURA', 'Data Abertura', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataAbertura: TDateTime read FDATA_ABERTURA write FDATA_ABERTURA; [TColumn('HORA_ABERTURA', 'Hora Abertura', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraAbertura: String read FHORA_ABERTURA write FHORA_ABERTURA; [TColumn('DATA_FECHAMENTO', 'Data Fechamento', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataFechamento: TDateTime read FDATA_FECHAMENTO write FDATA_FECHAMENTO; [TColumn('HORA_FECHAMENTO', 'Hora Fechamento', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraFechamento: String read FHORA_FECHAMENTO write FHORA_FECHAMENTO; [TColumn('TOTAL_SUPRIMENTO', 'Total Suprimento', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalSuprimento: Extended read FTOTAL_SUPRIMENTO write FTOTAL_SUPRIMENTO; [TColumn('TOTAL_SANGRIA', 'Total Sangria', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalSangria: Extended read FTOTAL_SANGRIA write FTOTAL_SANGRIA; [TColumn('TOTAL_NAO_FISCAL', 'Total Nao Fiscal', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalNaoFiscal: Extended read FTOTAL_NAO_FISCAL write FTOTAL_NAO_FISCAL; [TColumn('TOTAL_VENDA', 'Total Venda', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalVenda: Extended read FTOTAL_VENDA write FTOTAL_VENDA; [TColumn('TOTAL_DESCONTO', 'Total Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalDesconto: Extended read FTOTAL_DESCONTO write FTOTAL_DESCONTO; [TColumn('TOTAL_ACRESCIMO', 'Total Acrescimo', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalAcrescimo: Extended read FTOTAL_ACRESCIMO write FTOTAL_ACRESCIMO; [TColumn('TOTAL_FINAL', 'Total Final', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalFinal: Extended read FTOTAL_FINAL write FTOTAL_FINAL; [TColumn('TOTAL_RECEBIDO', 'Total Recebido', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalRecebido: Extended read FTOTAL_RECEBIDO write FTOTAL_RECEBIDO; [TColumn('TOTAL_TROCO', 'Total Troco', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalTroco: Extended read FTOTAL_TROCO write FTOTAL_TROCO; [TColumn('TOTAL_CANCELADO', 'Total Cancelado', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalCancelado: Extended read FTOTAL_CANCELADO write FTOTAL_CANCELADO; [TColumn('STATUS_MOVIMENTO', 'Status Movimento', 8, [ldGrid, ldLookup, ldCombobox], False)] property StatusMovimento: String read FSTATUS_MOVIMENTO write FSTATUS_MOVIMENTO; [TAssociation('ID', 'ID_NFCE_CAIXA')] property NfceCaixaVO: TNfceCaixaVO read FNfceCaixaVO write FNfceCaixaVO; [TAssociation('ID', 'ID_NFCE_EMPRESA')] property NfceEmpresaVO: TEmpresaVO read FEmpresaVO write FEmpresaVO; [TAssociation('ID', 'ID_NFCE_TURNO')] property NfceTurnoVO: TNfceTurnoVO read FNfceTurnoVO write FNfceTurnoVO; [TAssociation('ID', 'ID_NFCE_OPERADOR')] property NfceOperadorVO: TNfceOperadorVO read FNfceOperadorVO write FNfceOperadorVO; [TAssociation('ID', 'ID_GERENTE_SUPERVISOR')] property NfceGerenteVO: TNfceOperadorVO read FNfceGerenteVO write FNfceGerenteVO; [TManyValuedAssociation('ID_NFCE_MOVIMENTO', 'ID')] property ListaNfceFechamentoVO: TObjectList<TNfceFechamentoVO> read FListaNfceFechamentoVO write FListaNfceFechamentoVO; [TManyValuedAssociation('ID_NFCE_MOVIMENTO', 'ID')] property ListaNfceSuprimentoVO: TObjectList<TNfceSuprimentoVO> read FListaNfceSuprimentoVO write FListaNfceSuprimentoVO; [TManyValuedAssociation('ID_NFCE_MOVIMENTO', 'ID')] property ListaNfceSangriaVO: TObjectList<TNfceSangriaVO> read FListaNfceSangriaVO write FListaNfceSangriaVO; end; implementation constructor TNfceMovimentoVO.Create; begin inherited; FNfceCaixaVO := TNfceCaixaVO.Create; FEmpresaVO := TEmpresaVO.Create; FNfceTurnoVO := TNfceTurnoVO.Create; FNfceOperadorVO := TNfceOperadorVO.Create; FNfceGerenteVO := TNfceOperadorVO.Create; FListaNfceFechamentoVO := TObjectList<TNfceFechamentoVO>.Create; FListaNfceSuprimentoVO := TObjectList<TNfceSuprimentoVO>.Create; FListaNfceSangriaVO := TObjectList<TNfceSangriaVO>.Create; end; destructor TNfceMovimentoVO.Destroy; begin FreeAndNil(FNfceCaixaVO); FreeAndNil(FEmpresaVO); FreeAndNil(FNfceTurnoVO); FreeAndNil(FNfceOperadorVO); FreeAndNil(FNfceGerenteVO); FreeAndNil(FListaNfceFechamentoVO); FreeAndNil(FListaNfceSuprimentoVO); FreeAndNil(FListaNfceSangriaVO); inherited; end; initialization Classes.RegisterClass(TNfceMovimentoVO); finalization Classes.UnRegisterClass(TNfceMovimentoVO); end.
unit PACCParser; {$i PACC.inc} interface uses SysUtils,Classes,Math,PasMP,PUCU,PACCRawByteStringHashMap,PACCTypes,PACCGlobals,PACCPreprocessor,PACCLexer, PACCAbstractSyntaxTree; type TPACCParser=class public Instance:TObject; Preprocessor:TPACCPreprocessor; Lexer:TPACCLexer; Root:TPACCAbstractSyntaxTreeNodeTranslationUnit; constructor Create(const AInstance:TObject); destructor Destroy; override; procedure Process; end; implementation uses PACCSort,PACCInstance,PACCTarget; var StaticCounter:TPasMPInt32=0; TempVariableCounter:TPasMPInt32=0; function CompareSwitchCases(const a,b:pointer):TPACCInt32; begin result:=PPACCAbstractSyntaxTreeNodeSWITCHStatementCase(a)^.CaseBegin-PPACCAbstractSyntaxTreeNodeSWITCHStatementCase(b)^.CaseBegin; if result=0 then begin result:=PPACCAbstractSyntaxTreeNodeSWITCHStatementCase(a)^.CaseEnd-PPACCAbstractSyntaxTreeNodeSWITCHStatementCase(b)^.CaseEnd; end; end; constructor TPACCParser.Create(const AInstance:TObject); begin inherited Create; Instance:=AInstance; Preprocessor:=TPACCInstance(Instance).Preprocessor; Lexer:=TPACCInstance(Instance).Lexer; Root:=TPACCAbstractSyntaxTreeNodeTranslationUnit.Create(TPACCInstance(Instance),astnkTRANSLATIONUNIT,nil,TPACCInstance(Instance).SourceLocation); end; destructor TPACCParser.Destroy; begin Root.Free; inherited Destroy; end; procedure TPACCParser.Process; const S_TYPEDEF=1; S_EXTERN=2; S_STATIC=4; S_AUTO=8; S_REGISTER=16; DECL_BODY=1; DECL_PARAM=2; DECL_PARAM_TYPEONLY=4; DECL_CAST=8; type PState=^TState; TState=record TokenIndex:TPACCInt32; Token:PPACCLexerToken; PeekedToken:PPACCLexerToken; IsEOF:boolean; end; PCase=^TCase; TCase=record Begin_:TPACCInt; End_:TPACCInt; Label_:TPACCAbstractSyntaxTreeNodeLabel; end; TCases=record Ready:boolean; Cases:array of TCase; Count:TPACCInt; DefaultCaseLabel:TPACCAbstractSyntaxTreeNodeLabel; end; const TokenEOF:TPACCLexerToken=(TokenType:TOK_EOF; SourceLocation:( Source:0; Line:0; Column:0 ); Index:0; PragmaString:''; Constant:( StringValue:''; Encoding:ENCODING_NONE; SignedIntegerValue:0 ); ); var CurrentState:TState; FunctionNameScope:TPACCRawByteStringHashMap; GlobalScope:TPACCRawByteStringHashMap; LocalScope:TPACCRawByteStringHashMap; TagScope:TPACCRawByteStringHashMap; LabelScope:TPACCRawByteStringHashMap; LocalVariables:TPACCAbstractSyntaxTreeNodeList; Labels:TPACCAbstractSyntaxTreeNodeList; UnresolvedLabelUsedNodes:TPACCAbstractSyntaxTreeNodeList; Cases:TCases; CurrentFunctionType:PPACCType; BreakLabel:TPACCAbstractSyntaxTreeNodeLabel; ContinueLabel:TPACCAbstractSyntaxTreeNodeLabel; PragmaPack:TPACCInt32; PragmaPackStack:array of TPACCInt32; PragmaPackStackPointer:TPACCInt32; procedure AddError(const s:TPUCUUTF8String;const SourceLocation:PPACCSourceLocation=nil;const DoAbort:boolean=false); begin TPACCInstance(Instance).AddError(s,SourceLocation,DoAbort); end; procedure AddWarning(const s:TPUCUUTF8String;const SourceLocation:PPACCSourceLocation=nil); begin TPACCInstance(Instance).AddWarning(s,SourceLocation); end; procedure ParsePragma(const PragmaString:TPACCRawByteString;const RelevantSourceLocation:TPACCSourceLocation); var CurrentChar:ansichar; CurrentPosition:TPACCInt32; AtEOI:boolean; function NextChar:ansichar; begin if CurrentPosition<=length(PragmaString) then begin result:=PragmaString[CurrentPosition]; inc(CurrentPosition); end else begin result:=#0; AtEOI:=true; end; CurrentChar:=result; end; procedure SkipWhiteSpace; begin while CurrentChar in [#1..#32] do begin NextChar; end; end; var PragmaCommand,Temp:TPACCRawByteString; begin AtEOI:=false; CurrentPosition:=1; NextChar; while not AtEOI do begin SkipWhiteSpace; if CurrentChar in ['a'..'z','A'..'Z','_'] then begin PragmaCommand:=''; while CurrentChar in ['a'..'z','A'..'Z','_'] do begin PragmaCommand:=PragmaCommand+CurrentChar; NextChar; end; SkipWhiteSpace; if (PragmaCommand='STDC') or (PragmaCommand='stdc') then begin // Silence ignoring without any warning, until implemented break; end else if PragmaCommand='pack' then begin if CurrentChar='(' then begin NextChar; SkipWhiteSpace; if CurrentChar=')' then begin // #pragma pack() NextChar; PragmaPack:=-1; end else begin if CurrentChar in ['a'..'z','A'..'Z','_'] then begin // #pragma pack(push[,n]) // #pragma pack(pop[,n]) Temp:=''; while CurrentChar in ['a'..'z','A'..'Z','_'] do begin Temp:=Temp+CurrentChar; NextChar; end; if Temp='push' then begin if length(PragmaPackStack)<=PragmaPackStackPointer then begin SetLength(PragmaPackStack,(PragmaPackStackPointer+1)*2); end; PragmaPackStack[PragmaPackStackPointer]:=PragmaPack; inc(PragmaPackStackPointer); end else if Temp='pop' then begin if PragmaPackStackPointer>0 then begin dec(PragmaPackStackPointer); PragmaPack:=PragmaPackStack[PragmaPackStackPointer]; end else begin AddWarning('Pragma pack stack underflow',@RelevantSourceLocation); end; end else begin AddWarning('"push" or "pop" expected',@RelevantSourceLocation); end; SkipWhiteSpace; case CurrentChar of ',':begin NextChar; SkipWhiteSpace; end; ')':begin NextChar; SkipWhiteSpace; if CurrentChar=',' then begin NextChar; continue; end else begin AddWarning('Pragma syntax error',@RelevantSourceLocation); break; end; continue; end; else begin AddWarning('Pragma syntax error',@RelevantSourceLocation); end; end; end; if CurrentChar in ['0'..'9'] then begin Temp:=''; while CurrentChar in ['0'..'9'] do begin Temp:=Temp+CurrentChar; NextChar; end; PragmaPack:=StrToIntDef(Temp,-1); if (PragmaPack>0) and ((PragmaPack and (PragmaPack-1))<>0) then begin AddError('Pragma pack be power of 2, but got '+IntToStr(PragmaPack),@RelevantSourceLocation,false); break; end else if PragmaPack<0 then begin AddError('Invalud pragma pack',@RelevantSourceLocation,false); break; end else if PragmaPack=0 then begin PragmaPack:=-1; end; end; if CurrentChar=')' then begin NextChar; end; end; end; end else begin AddWarning('Unknown pragma command "'+PragmaCommand+'", aborting pragma parsing, and ignoring the rest of pragma string',@RelevantSourceLocation); break; end; SkipWhiteSpace; if CurrentChar=',' then begin NextChar; continue; end else begin AddWarning('Pragma syntax error',@RelevantSourceLocation); break; end; end else begin AddWarning('Pragma syntax error',@RelevantSourceLocation); break; end; end; end; function NextToken:PPACCLexerToken; begin repeat inc(CurrentState.TokenIndex); if CurrentState.TokenIndex<Lexer.CountTokens then begin CurrentState.Token:=@Lexer.Tokens[CurrentState.TokenIndex]; if CurrentState.Token^.TokenType=TOK_EOF then begin CurrentState.IsEOF:=true; end; result:=CurrentState.Token; TPACCInstance(Instance).SourceLocation:=result.SourceLocation; if result^.TokenType=TOK_PRAGMA then begin ParsePragma(result.PragmaString,result.SourceLocation); continue; end; end else begin CurrentState.Token:=@TokenEOF; CurrentState.IsEOF:=true; result:=nil; end; break; until false; end; function NextTokenType:TPACCLexerTokenType; begin NextToken; result:=CurrentState.Token^.TokenType; end; function PeekToken(Offset:TPACCInt32=1):PPACCLexerToken; begin repeat if ((CurrentState.TokenIndex+Offset)>=0) and ((CurrentState.TokenIndex+Offset)<Lexer.CountTokens) then begin CurrentState.PeekedToken:=@Lexer.Tokens[CurrentState.TokenIndex+Offset]; result:=CurrentState.PeekedToken; if result^.TokenType=TOK_PRAGMA then begin inc(Offset); continue; end; end else begin CurrentState.PeekedToken:=@TokenEOF; result:=nil; end; break; until false; end; function PeekTokenType(Offset:TPACCInt32=1):TPACCLexerTokenType; begin PeekToken(Offset); result:=CurrentState.PeekedToken^.TokenType; end; function GetScope:TPACCRawByteStringHashMap; begin if assigned(LocalScope) then begin result:=LocalScope; end else begin result:=GlobalScope; end; end; function GetTypeDef(const Name:TPACCRawByteString):PPACCType; var Node:TPACCAbstractSyntaxTreeNode; begin Node:=GetScope[Name]; if assigned(Node) and (Node.Kind=astnkTYPEDEF) then begin result:=TPACCAbstractSyntaxTreeNode(Node).Type_; end else begin result:=nil; end; end; procedure AddFunctionNameVariable(const FunctionName:TPACCRawByteString;const FunctionBody,Variable:TPACCAbstractSyntaxTreeNode); var FunctionNameList:TList; Index:longint; begin if length(FunctionName)>0 then begin FunctionNameList:=FunctionNameScope[FunctionName]; if not assigned(FunctionNameList) then begin FunctionNameList:=TList.Create; TPACCInstance(Instance).AllocatedObjects.Add(FunctionNameList); FunctionNameScope[FunctionName]:=FunctionNameList; end; if (FunctionNameList.Count>0) and assigned(TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionNameList[FunctionNameList.Count-1]).Variable) then begin TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionBody).Variable:=TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionNameList[FunctionNameList.Count-1]).Variable; FunctionNameList.Add(FunctionBody); end else begin FunctionNameList.Add(FunctionBody); if assigned(Variable) then begin for Index:=0 to FunctionNameList.Count-1 do begin TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionNameList[Index]).Variable:=Variable; end; end; end; end; end; function NewASTString(const SourceLocation:TPACCSourceLocation;const Encoding:TPACCEncoding;const Buf:TPACCRawByteString):TPACCAbstractSyntaxTreeNode; var Type_:PPACCType; Body:TPACCRawByteString; Temp16Bit:TPUCUUTF16String; Temp32Bit:TPUCUUTF32String; begin case Encoding of ENCODING_NONE,ENCODING_UTF8:begin Type_:=TPACCInstance(Instance).NewArrayType(TPACCInstance(Instance).TypeCHAR,length(Buf)); Body:=Buf; end; ENCODING_CHAR16:begin Temp16Bit:=PUCUUTF8ToUTF16(Buf); Type_:=TPACCInstance(Instance).NewArrayType(TPACCInstance(Instance).TypeUSHORT,length(Temp16Bit)); SetLength(Body,length(Temp16Bit)*SizeOf(TPUCUUTF16Char)); if length(Temp16Bit)>0 then begin Move(Temp16Bit[1],Body[1],length(Temp16Bit)*SizeOf(TPUCUUTF16Char)); end; end; else {ENCODING_CHAR32,ENCODING_WCHAR:}begin Temp32Bit:=PUCUUTF8ToUTF32(Buf); Type_:=TPACCInstance(Instance).NewArrayType(TPACCInstance(Instance).TypeUINT,length(Temp32Bit)); SetLength(Body,length(Temp32Bit)*SizeOf(TPUCUUTF32Char)); if length(Temp32Bit)>0 then begin Move(Temp32Bit[low(Temp32Bit)],Body[1],length(Temp32Bit)*SizeOf(TPUCUUTF32Char)); end; end; end; result:=TPACCAbstractSyntaxTreeNodeStringValue.Create(TPACCInstance(Instance),astnkSTRING,Type_,SourceLocation,Body,Encoding); end; function NewLabel(const Kind:TPACCAbstractSyntaxTreeNodeKind;const RelevantSourceLocation:TPACCSourceLocation;const LabelName:TPACCRawByteString=''):TPACCAbstractSyntaxTreeNodeLabel; begin result:=TPACCAbstractSyntaxTreeNodeLabel.Create(TPACCInstance(Instance),Kind,nil,RelevantSourceLocation,LabelName); if assigned(Labels) then begin Labels.Add(result); end; end; function IsType(Token:PPACCLexerToken):boolean; begin result:=false; if assigned(Token) then begin case Token^.TokenType of TOK_ALIGNAS, TOK_ATTRIBUTE, TOK_AUTO, TOK_BOOL, TOK_CHAR, TOK_COMPLEX, TOK_CONST, TOK_DOUBLE, TOK_ENUM, TOK_EXTERN, TOK_FLOAT, TOK_IMAGINARY, TOK_INLINE, TOK_INT, TOK_LONG, TOK_NORETURN, TOK_REGISTER, TOK_RESTRICT, TOK_SHORT, TOK_SIGNED1, TOK_SIGNED2, TOK_SIGNED3, TOK_STATIC, TOK_STRUCT, TOK_TYPEDEF, TOK_TYPEOF, TOK_UNION, TOK_UNSIGNED, TOK_VOID, TOK_VOLATILE:begin result:=true; end; TOK_IDENT:begin if TPACCInstance(Instance).Target.CheckCallingConvention(TPACCInstance(Instance).TokenSymbols[Token^.Index].Name)>=0 then begin result:=true; end else begin result:=assigned(GetTypeDef(TPACCInstance(Instance).TokenSymbols[Token^.Index].Name)); end; end; end; end; end; procedure SkipParentheses; var Level:TPACCInt32; begin Level:=0; if CurrentState.Token^.TokenType=TOK_LPAR then begin NextToken; repeat case CurrentState.Token^.TokenType of TOK_EOF:begin AddError('Premature end of input',@CurrentState.Token^.SourceLocation,true); end; TOK_LPAR:begin inc(Level); end; TOK_RPAR:begin if Level=0 then begin NextToken; break; end else begin dec(Level); end; end; end; NextToken; until false; end; end; procedure Expect(const TokenType:TPACCLexerTokenType); begin if CurrentState.Token^.TokenType=TokenType then begin NextToken; end else begin AddError('"'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'" expected',@CurrentState.Token^.SourceLocation,true); end; end; procedure EnsureLValue(const Node:TPACCAbstractSyntaxTreeNode); begin if assigned(Node) and (afConstant in Node.Type_^.Attribute.Flags) then begin AddError('Expression must be a modifiable lvalue',nil,false); end; if (not assigned(Node)) or not (Node.Kind in [astnkLVAR,astnkGVAR,astnkDEREF,astnkSTRUCT_REF]) then begin AddError('lvalue expected',nil,true); end; end; procedure EnsureIntType(const Node:TPACCAbstractSyntaxTreeNode); begin if (not assigned(Node)) or not TPACCInstance(Instance).IsIntType(Node.Type_) then begin AddError('Integer type expected',nil,false); end; end; procedure EnsureArithmeticType(const Node:TPACCAbstractSyntaxTreeNode); begin if (not assigned(Node)) or not TPACCInstance(Instance).IsArithmeticType(Node.Type_) then begin AddError('Arithmetic type expected',nil,false); end; end; procedure EnsureNotVoid(const Type_:PPACCType); begin if assigned(Type_) and (Type_^.Kind=tkVOID) then begin AddError('void is not allowed',nil,false); end; end; procedure SkipTypeQualifiers; begin while CurrentState.Token^.TokenType in [TOK_CONST,TOK_VOLATILE,TOK_RESTRICT] do begin NextToken; end; end; function Wrap(const t:PPACCType;const Node:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; begin if TPACCInstance(Instance).SameArithmeticType(t,Node.Type_) then begin result:=Node; end else begin result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkCONV,t,Node.SourceLocation,Node); end; end; function ValidPointerBinaryOperation(const Op:TPACCAbstractSyntaxTreeNodeKind):boolean; begin result:=Op in [astnkOP_SUB,astnkOP_LT,astnkOP_GT,astnkOP_EQ,astnkOP_NE,astnkOP_GE,astnkOP_LE]; end; function BinaryOperation(const Op:TPACCAbstractSyntaxTreeNodeKind;const lhs,rhs:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; var r:PPACCType; begin if not (assigned(lhs) and assigned(lhs.Type_)) then begin result:=nil; AddError('Internal error 2017-01-08-04-35-0000',nil,true); end else if not (assigned(rhs) and assigned(rhs.Type_)) then begin result:=nil; AddError('Internal error 2017-01-08-04-36-0000',nil,true); end else if lhs.Type_^.Kind=tkPOINTER then begin if rhs.Type_^.Kind=tkPOINTER then begin if not ValidPointerBinaryOperation(Op) then begin AddError('Iinvalid pointer arithmetic operation',nil,false); end; if Op=astnkOP_SUB then begin // C11 6.5.6.9: Pointer subtractions have type ptrdiff_t. if TPACCInstance(Instance).Target.SizeOfPointer=TPACCInstance(Instance).Target.SizeOfInt then begin result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),Op,TPACCInstance(Instance).TypeINT,lhs.SourceLocation,lhs,rhs); end else begin result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),Op,TPACCInstance(Instance).TypeLONG,lhs.SourceLocation,lhs,rhs); end; end else begin // C11 6.5.8.6, 6.5.9.3: Pointer comparisons have type int. result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),Op,TPACCInstance(Instance).TypeINT,lhs.SourceLocation,lhs,rhs); end; end else begin result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),Op,lhs.Type_,lhs.SourceLocation,lhs,rhs); end; end else if rhs.Type_^.Kind=tkPOINTER then begin result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),Op,rhs.Type_,rhs.SourceLocation,rhs,lhs); end else begin if not TPACCInstance(Instance).IsArithmeticType(lhs.Type_) then begin AddError('Internal error 2017-01-01-21-02-0000',nil,true); end; if not TPACCInstance(Instance).IsArithmeticType(rhs.Type_) then begin AddError('Internal error 2017-01-01-21-02-0001',nil,true); end; r:=TPACCInstance(Instance).UsualArithmeticConversion(lhs.Type_,rhs.Type_); result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),Op,r,lhs.SourceLocation,Wrap(r,lhs),Wrap(r,rhs)); end; end; procedure EnsureAssignable(const ToType,FromType:PPACCType); begin if not (((TPACCInstance(Instance).IsArithmeticType(ToType) or (ToType^.Kind=tkPOINTER)) and (TPACCInstance(Instance).IsArithmeticType(FromType) or (FromType^.Kind=tkPOINTER))) or TPACCInstance(Instance).IsSameStruct(ToType,FromType)) then begin AddError('Incompatible types',nil,false); end; end; procedure ParseDeclaration(const Block:TPACCAbstractSyntaxTreeNodeList;const IsGlobal,IsTop:boolean); forward; function ParseIntegerExpression:TPACCInt64; forward; function ParseCastType:PPACCType; forward; function ParseCastExpression:TPACCAbstractSyntaxTreeNode; forward; function ParseExpression:TPACCAbstractSyntaxTreeNode; forward; function ParseCompoundStatement:TPACCAbstractSyntaxTreeNode; forward; function ParseAssignmentExpression:TPACCAbstractSyntaxTreeNode; forward; function ParseGeneric:TPACCAbstractSyntaxTreeNode; var Type_:PPACCType; ConstantExpression,DefaultExpression,TypeExpression,MatchExpression:TPACCAbstractSyntaxTreeNode; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; Expect(TOK_LPAR); ConstantExpression:=ParseAssignmentExpression; Expect(TOK_COMMA); DefaultExpression:=nil; MatchExpression:=nil; repeat case CurrentState.Token^.TokenType of TOK_RPAR:begin NextToken; break; end; TOK_DEFAULT:begin if assigned(DefaultExpression) then begin AddError('Default expression specified twice',@RelevantSourceLocation,false); end; NextToken; Expect(TOK_COLON); DefaultExpression:=ParseAssignmentExpression; end; else begin Type_:=ParseCastType; Expect(TOK_COLON); TypeExpression:=ParseAssignmentExpression; if (not assigned(MatchExpression)) and TPACCInstance(Instance).AreTypesCompatible(ConstantExpression.Type_,Type_) then begin MatchExpression:=TypeExpression; end; end; end; case CurrentState.Token^.TokenType of TOK_COMMA:begin NextToken; end; TOK_RPAR:begin NextToken; break; end; else begin AddError('")" or "," expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',@CurrentState.Token^.SourceLocation,true); end; end; until false; if assigned(MatchExpression) then begin result:=MatchExpression; end else if assigned(DefaultExpression) then begin result:=DefaultExpression; end else begin result:=nil; AddError('No matching generic selection',@RelevantSourceLocation,false); end; end; function ParseStringValue(out Encoding:TPACCEncoding):TPACCRawByteString; var FirstError:boolean; begin if CurrentState.Token^.TokenType=TOK_CSTR then begin result:=CurrentState.Token^.Constant.StringValue; Encoding:=CurrentState.Token^.Constant.Encoding; NextToken; FirstError:=true; while CurrentState.Token^.TokenType=TOK_CSTR do begin if (Encoding<>ENCODING_NONE) and (CurrentState.Token^.Constant.Encoding<>ENCODING_NONE) and (Encoding<>CurrentState.Token^.Constant.Encoding) then begin if FirstError then begin FirstError:=false; AddError('Unsupported non-standard concatenation of string literals',@CurrentState.Token^.SourceLocation,false); end; end else begin if Encoding=ENCODING_NONE then begin Encoding:=CurrentState.Token^.Constant.Encoding; end; result:=result+CurrentState.Token^.Constant.StringValue; end; NextToken; end; end else begin Encoding:=ENCODING_NONE; Expect(TOK_CSTR); end; end; function ParsePrimaryExpression:TPACCAbstractSyntaxTreeNode; var Type_:PPACCType; Node,Variable:TPACCAbstractSyntaxTreeNode; Name,StringValue:TPACCRawByteString; RelevantSourceLocation:TPACCSourceLocation; Encoding:TPACCEncoding; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; case CurrentState.Token^.TokenType of TOK_LPAR:begin NextToken; if CurrentState.Token^.TokenType=TOK_LBRA then begin NextToken; result:=ParseCompoundStatement; Expect(TOK_RPAR); Type_:=TPACCInstance(Instance).TypeVOID; if assigned(result) and (result is TPACCAbstractSyntaxTreeNodeStatements) and (TPACCAbstractSyntaxTreeNodeStatements(result).Children.Count>0) then begin Node:=TPACCAbstractSyntaxTreeNodeStatements(result).Children[TPACCAbstractSyntaxTreeNodeStatements(result).Children.Count-1]; if assigned(Node) and assigned(Node.Type_) then begin Type_:=Node.Type_; end; end; result.Type_:=Type_; end else begin result:=ParseExpression; Expect(TOK_RPAR); end; end; TOK_GENERIC:begin NextToken; result:=ParseGeneric; end; TOK_IDENT:begin Name:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; result:=GetScope[Name]; NextToken; if assigned(result) then begin if result.Type_^.Kind=tkFUNCTION Then begin Variable:=result; result:=TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration.Create(TPACCInstance(Instance),astnkFUNCDESG,result.Type_,result.SourceLocation,Name,nil,nil,nil); TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(result).Variable:=Variable; AddFunctionNameVariable(Name,result,Variable); end; end else begin if CurrentState.Token^.TokenType=TOK_LPAR then begin AddWarning('assume returning int: '+Name+'()',@CurrentState.Token^.SourceLocation); result:=TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration.Create(TPACCInstance(Instance),astnkFUNCDESG,TPACCInstance(Instance).NewFunctionType(TPACCInstance(Instance).TypeINT,nil,true,false),CurrentState.Token^.SourceLocation,Name,nil,nil,nil); AddFunctionNameVariable(Name,result,nil); end else begin result:=nil; AddError('Undeclared variable: '+Name,@RelevantSourceLocation,false); end; end; end; TOK_CINT:begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeINT,RelevantSourceLocation,CurrentState.Token^.Constant.SignedIntegerValue); NextToken; end; TOK_CUINT:begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeUINT,RelevantSourceLocation,CurrentState.Token^.Constant.UnsignedIntegerValue); NextToken; end; TOK_CCHAR:begin case CurrentState.Token^.Constant.Encoding of ENCODING_NONE,ENCODING_UTF8:begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeUCHAR,RelevantSourceLocation,CurrentState.Token^.Constant.UnsignedIntegerValue); end; ENCODING_CHAR16:begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeUSHORT,RelevantSourceLocation,CurrentState.Token^.Constant.UnsignedIntegerValue); end; else begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeUINT,RelevantSourceLocation,CurrentState.Token^.Constant.UnsignedIntegerValue); end; end; NextToken; end; TOK_CSTR:begin StringValue:=ParseStringValue(Encoding); result:=NewASTString(RelevantSourceLocation,Encoding,StringValue); end; TOK_CFLOAT:begin result:=TPACCAbstractSyntaxTreeNodeFloatValue.Create(TPACCInstance(Instance),astnkFLOAT,TPACCInstance(Instance).TypeFLOAT,RelevantSourceLocation,CurrentState.Token^.Constant.FloatValue); NextToken; end; TOK_CDOUBLE:begin result:=TPACCAbstractSyntaxTreeNodeFloatValue.Create(TPACCInstance(Instance),astnkFLOAT,TPACCInstance(Instance).TypeDOUBLE,RelevantSourceLocation,CurrentState.Token^.Constant.DoubleValue); NextToken; end; TOK_CLDOUBLE:begin result:=TPACCAbstractSyntaxTreeNodeFloatValue.Create(TPACCInstance(Instance),astnkFLOAT,TPACCInstance(Instance).TypeLDOUBLE,RelevantSourceLocation,CurrentState.Token^.Constant.DoubleValue); NextToken; end; TOK_CLLONG:begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeLLONG,RelevantSourceLocation,CurrentState.Token^.Constant.SignedIntegerValue); NextToken; end; TOK_CULLONG:begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeULLONG,RelevantSourceLocation,CurrentState.Token^.Constant.UnsignedIntegerValue); NextToken; end; else begin if not (CurrentState.Token^.TokenType in KeywordTokens) then begin AddError('Internal error 2017-01-02-03-28-0000',@RelevantSourceLocation,true); end; result:=nil; end; end; end; function ParseFunctionArguments(const Parameters:TPPACCTypes):TPACCAbstractSyntaxTreeNodeList; var Index:longint; ArgumentNode:TPACCAbstractSyntaxTreeNode; ParameterType:PPACCType; begin result:=TPACCAbstractSyntaxTreeNodeList.Create; TPACCInstance(Instance).AllocatedObjects.Add(result); Index:=0; repeat if CurrentState.Token^.TokenType=TOK_RPAR then begin NextToken; break; end else begin ArgumentNode:=TPACCInstance(Instance).TypeConversion(ParseAssignmentExpression); if Index<length(Parameters) then begin ParameterType:=Parameters[Index]; inc(Index); end else begin if TPACCInstance(Instance).IsFloatType(ArgumentNode.Type_) then begin ParameterType:=TPACCInstance(Instance).TypeDOUBLE; end else if TPACCInstance(Instance).IsIntType(ArgumentNode.Type_) then begin ParameterType:=TPACCInstance(Instance).TypeINT; end else begin ParameterType:=ArgumentNode.Type_; end; end; EnsureAssignable(ParameterType,ArgumentNode.Type_); if ParameterType^.Kind<>ArgumentNode.Type_^.Kind then begin ArgumentNode:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkCONV,ParameterType,ArgumentNode.SourceLocation,ArgumentNode); end; result.Add(ArgumentNode); case CurrentState.Token^.TokenType of TOK_COMMA:begin NextToken; end; TOK_RPAR:begin NextToken; break; end; else begin AddError('")" or "," expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',@CurrentState.Token^.SourceLocation,true); end; end; end; until false; end; function ParseFunctionCall(const Node:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; var Desg:TPACCAbstractSyntaxTreeNode; begin if (Node.Kind=astnkADDR) and (TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand.Kind=astnkFUNCDESG) then begin Desg:=TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand; result:=TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration.Create(TPACCInstance(Instance),astnkFUNCCALL,Desg.Type_^.ReturnType,Desg.SourceLocation,TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(Desg).FunctionName,Desg.Type_,nil,nil); AddFunctionNameVariable(TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(Desg).FunctionName,result,nil); TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(result).Parameters:=ParseFunctionArguments(Desg.Type_^.Parameters); end else begin if (Node.Type_^.Kind=tkPOINTER) and (Node.Type_^.ChildTYpe^.Kind=tkFUNCTION) then begin result:=TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration.Create(TPACCInstance(Instance),astnkFUNCPTR_CALL,Node.Type_^.ChildType^.ReturnType,Node.SourceLocation,TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(Node).FunctionName,nil,Node,nil); AddFunctionNameVariable(TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(Node).FunctionName,result,nil); TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(result).Parameters:=ParseFunctionArguments(Node.Type_^.ChildType^.Parameters); end else begin result:=nil; AddError('Internal error 2017-01-02-17-56-0000',nil,true); end; end; end; function ParseStructField(const Node:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; var Index:longint; Type_,FieldType:PPACCType; Name:TPACCRawByteString; begin Type_:=Node.Type_; if (not assigned(Type_)) or (Type_^.Kind<>tkSTRUCT) then begin AddError('Struct or union type expected',nil,true); end; if CurrentState.Token^.TokenType=TOK_IDENT then begin Name:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; NextToken; FieldType:=nil; for Index:=0 to length(Type_^.Fields)-1 do begin if Type_^.Fields[Index].Name=Name then begin FieldType:=Type_^.Fields[Index].Type_; break; end; end; if assigned(FieldType) then begin result:=TPACCAbstractSyntaxTreeNodeStructReference.Create(TPACCInstance(Instance),astnkSTRUCT_REF,FieldType,Node.SourceLocation,Node,Name); end else begin AddError('Struct/union has no such field with the name "'+Name+'"',nil,false); result:=nil; end; end else begin AddError('Field name expected',nil,true); result:=nil; end; end; function ParseSubscriptionExpression(const Node:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; var SubscriptionExpression:TPACCAbstractSyntaxTreeNode; begin SubscriptionExpression:=ParseExpression; if assigned(SubscriptionExpression) then begin Expect(TOK_RBRK); result:=BinaryOperation(astnkOP_ADD,TPACCInstance(Instance).TypeConversion(Node),TPACCInstance(Instance).TypeConversion(SubscriptionExpression)); result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkDEREF,result.Type_^.ChildType,result.SourceLocation,result); end else begin AddError('Subscription expected',nil,true); result:=nil; end; end; function ParsePostfixExpressionTail(const Node:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; var Type_:PPACCType; begin result:=Node; if assigned(result) then begin repeat case CurrentState.Token^.TokenType of TOK_LPAR:begin NextToken; result:=TPACCInstance(Instance).TypeConversion(result); Type_:=result.Type_; if (Type_^.Kind<>tkPOINTER) or ((not assigned(Type_^.ChildType)) or (Type_^.ChildType^.Kind<>tkFUNCTION)) then begin AddError('Function expected',nil,false); end; result:=ParseFunctionCall(result); continue; end; TOK_LBRK:begin NextToken; result:=ParseSubscriptionExpression(result); continue; end; TOK_DOT:begin NextToken; result:=ParseStructField(result); continue; end; TOK_ARROW:begin if result.Type_^.Kind<>tKPOINTER then begin AddError('Pointer type expected',nil,false); end; result:=ParseStructField(TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkDEREF,result.Type_^.ChildType,CurrentState.Token^.SourceLocation,result)); NextToken; continue; end; TOK_DEC:begin EnsureLValue(result); result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkOP_POST_DEC,result.Type_,CurrentState.Token^.SourceLocation,result); NextToken; end; TOK_INC:begin EnsureLValue(result); result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkOP_POST_INC,result.Type_,CurrentState.Token^.SourceLocation,result); NextToken; end; else begin break; end; end; until false; end; end; function ParsePostfixExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParsePostfixExpressionTail(ParsePrimaryExpression); end; function ParseUnaryExpression:TPACCAbstractSyntaxTreeNode; var Type_:PPACCType; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; case CurrentState.Token^.TokenType of TOK_SIZEOF:begin NextToken; if CurrentState.Token^.TokenType=TOK_LPAR then begin NextToken; Type_:=ParseCastType; Expect(TOK_RPAR); end else begin Type_:=ParseUnaryExpression.Type_; end; if Type_^.Kind in [tkVOID,tkFUNCTION] then begin // sizeof on void or function type is a GNU extension result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeULONG,RelevantSourceLocation,1); end else if Type_^.Size>0 then begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeULONG,RelevantSourceLocation,Type_^.Size); end else begin result:=nil; AddError('Internal error 2017-01-02-03-05-0000',nil,true); end; end; TOK_ALIGNOF:begin NextToken; Expect(TOK_LPAR); Type_:=ParseCastType; Expect(TOK_RPAR); result:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeINT,RelevantSourceLocation,Type_^.Alignment); end; TOK_DEC:begin NextToken; result:=TPACCInstance(Instance).TypeConversion(ParseUnaryExpression); EnsureLValue(result); result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkOP_PRE_DEC,result.Type_,RelevantSourceLocation,result); end; TOK_INC:begin NextToken; result:=TPACCInstance(Instance).TypeConversion(ParseUnaryExpression); EnsureLValue(result); result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkOP_PRE_INC,result.Type_,RelevantSourceLocation,result); end; TOK_LAND:begin NextToken; if CurrentState.Token^.TokenType=TOK_IDENT then begin result:=TPACCAbstractSyntaxTreeNodeGOTOStatementOrLabelAddress.Create(TPACCInstance(Instance),astnkOP_LABEL_ADDR,TPACCInstance(Instance).NewPointerType(TPACCInstance(Instance).TypeVOID),RelevantSourceLocation,nil,TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name); NextToken; UnresolvedLabelUsedNodes.Add(result); end else begin result:=nil; AddError('Label name expected after &&, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; end; TOK_AND:begin NextToken; result:=ParseCastExpression; if result.Kind=astnkFUNCDESG then begin result:=TPACCInstance(Instance).TypeConversion(result); end else begin EnsureLValue(result); if result.Kind in [astnkLVAR,astnkGVAR] then begin TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(result).MustOnStack:=true; end; result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkADDR,TPACCInstance(Instance).NewPointerType(result.Type_),RelevantSourceLocation,result); end; end; TOK_MUL:begin NextToken; result:=TPACCInstance(Instance).TypeConversion(ParseCastExpression); if result.Type_^.Kind<>tkPOINTER then begin AddError('Pointer type expected',nil,false); end else if result.Type_^.Kind<>tkFUNCTION then begin result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkDEREF,result.Type_^.ChildType,RelevantSourceLocation,result); end; end; TOK_ADD:begin NextToken; result:=ParseCastExpression; end; TOK_SUB:begin NextToken; result:=TPACCInstance(Instance).TypeConversion(ParseCastExpression); EnsureArithmeticType(result); if TPACCInstance(Instance).IsIntType(result.Type_) then begin result:=BinaryOperation(astnkOP_SUB,TPACCInstance(Instance).TypeConversion(TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,result.Type_,RelevantSourceLocation,0)),TPACCInstance(Instance).TypeConversion(result)); end else begin result:=BinaryOperation(astnkOP_SUB,TPACCAbstractSyntaxTreeNodeFloatValue.Create(TPACCInstance(Instance),astnkINTEGER,result.Type_,RelevantSourceLocation,0.0),result); end; end; TOK_NOT:begin NextToken; result:=TPACCInstance(Instance).TypeConversion(ParseCastExpression); if TPACCInstance(Instance).IsIntType(result.Type_) then begin result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkOP_NOT,result.Type_,RelevantSourceLocation,result); end else begin AddError('Integer type expected',nil,false); end; end; TOK_LNOT:begin NextToken; result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkOP_LOG_NOT,TPACCInstance(Instance).TypeINT,RelevantSourceLocation,TPACCInstance(Instance).TypeConversion(ParseCastExpression)); end; else begin result:=ParsePostfixExpression; end; end; end; procedure ParseInitializerList(const List:TPACCAbstractSyntaxTreeNodeList;const Type_:PPACCType;const Offset:TPACCInt;const Designated:boolean); procedure AssignString(const List:TPACCAbstractSyntaxTreeNodeList;const Type_:PPACCType;const p:TPACCRawByteString;const Offset:TPACCInt); var Index,Len:TPACCInt; begin Len:=length(p); if Type_^.ArrayLength<0 then begin Type_^.ArrayLength:=Len+1; Type_^.Size:=Len+1; end; Index:=0; while (Index<Type_^.ArrayLength) and (Index<Len) do begin List.Add(TPACCAbstractSyntaxTreeNodeInitializer.Create(TPACCInstance(Instance),astnkINIT,nil,CurrentState.Token^.SourceLocation,TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeCHAR,CurrentState.Token^.SourceLocation,TPACCUInt8(ansichar(p[Index+1]))),Offset+Index,TPACCInstance(Instance).TypeCHAR)); inc(Index); end; while Index<Type_^.ArrayLength do begin List.Add(TPACCAbstractSyntaxTreeNodeInitializer.Create(TPACCInstance(Instance),astnkINIT,nil,CurrentState.Token^.SourceLocation,TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeCHAR,CurrentState.Token^.SourceLocation,0),Offset+Index,TPACCInstance(Instance).TypeCHAR)); inc(Index); end; end; procedure SortInitializerList(const List:TPACCAbstractSyntaxTreeNodeList); var Index,Count:TPACCInt; begin Index:=0; Count:=List.Count; while (Index+1)<Count do begin if TPACCAbstractSyntaxTreeNodeInitializer(List[Index]).InitializionOffset>TPACCAbstractSyntaxTreeNodeInitializer(List[Index+1]).InitializionOffset then begin List.Exchange(Index,Index+1); if Index>0 then begin dec(Index); end else begin inc(Index); end; end else begin inc(Index); end; end; end; procedure SkipToClosedBrace; var IgnoredExpression:TPACCAbstractSyntaxTreeNode; begin repeat case CurrentState.Token^.TokenType of TOK_RBRA:begin NextToken; break; end; TOK_DOT:begin NextToken; NextToken; Expect(TOK_ASSIGN); end; end; IgnoredExpression:=ParseAssignmentExpression; if assigned(IgnoredExpression) then begin AddWarning('Excessive initializer'); if CurrentState.Token^.TokenType=TOK_COMMA then begin NextToken; end; end else begin break; end; until false; end; procedure ParseInitializerElement(const List:TPACCAbstractSyntaxTreeNodeList;const Type_:PPACCType;const Offset:TPACCInt;Designated:boolean); var Expression:TPACCAbstractSyntaxTreeNode; begin if CurrentState.Token^.TokenType=TOK_ASSIGN then begin Expect(TOK_ASSIGN); end; if Type_^.Kind in [tkARRAY,tkSTRUCT] then begin ParseInitializerList(List,Type_,Offset,Designated); end else if CurrentState.Token^.TokenType=TOK_LBRA Then begin NextToken; ParseInitializerElement(List,Type_,Offset,true); Expect(TOK_RBRA); end else begin Expression:=ParseAssignmentExpression; EnsureAssignable(Type_,Expression.Type_); List.Add(TPACCAbstractSyntaxTreeNodeInitializer.Create(TPACCInstance(Instance),astnkINIT,nil,Expression.SourceLocation,Expression,Offset,Type_)); end; end; procedure ParseArrayInitializerList(const List:TPACCAbstractSyntaxTreeNodeList;const Type_:PPACCType;const Offset:TPACCInt;const Designated:boolean); procedure ParseArrayInitializers(const List:TPACCAbstractSyntaxTreeNodeList;const Type_:PPACCType;const Offset:TPACCInt;Designated:boolean); var Index,ElementSize,ExpressionIndex:TPACCInt; HasBrace,Flexible,SawClosedBrace:boolean; begin HasBrace:=CurrentState.Token^.TokenType=TOK_LBRA; if HasBrace then begin NextToken; end; Flexible:=Type_^.ArrayLength<0; ElementSize:=Type_^.ChildType^.Size; SawClosedBrace:=false; Index:=0; while Flexible or (Index<Type_^.ArrayLength) do begin if CurrentState.Token^.TokenType=TOK_RBRA then begin if HasBrace then begin NextToken; SawClosedBrace:=true; break; end; end; if (CurrentState.Token^.TokenType in [TOK_DOT,TOK_LBRK]) and (HasBrace or Designated) then begin exit; end; if CurrentState.Token^.TokenType=TOK_LBRK then begin NextToken; ExpressionIndex:=ParseIntegerExpression; if (ExpressionIndex<0) or ((Type_^.ArrayLength<=ExpressionIndex) and not Flexible) then begin AddError('Array designator exceeds array bounds: '+IntToStr(ExpressionIndex),nil,false); end; Expect(TOK_RBRK); Index:=ExpressionIndex; end; ParseInitializerElement(List,Type_^.ChildType,Offset+(TPACCInt64(ElementSize)*Index),Designated); if CurrentState.Token^.TokenType=TOK_COMMA then begin NextToken; end; Designated:=false; inc(Index); end; if HasBrace and not SawClosedBrace then begin SkipToClosedBrace; end; if Type_^.ArrayLength<0 then begin Type_^.ArrayLength:=Index; Type_^.Size:=Index*TPACCInt64(ElementSize); end; end; begin ParseArrayInitializers(List,Type_,Offset,Designated); SortInitializerList(List); end; procedure ParseStructInitializerList(const List:TPACCAbstractSyntaxTreeNodeList;const Type_:PPACCType;const Offset:TPACCInt;const Designated:boolean); procedure ParseStructInitializers(const List:TPACCAbstractSyntaxTreeNodeList;const Type_:PPACCType;const Offset:TPACCInt;Designated:boolean); var Index,FieldIndex:TPACCInt; HasBrace,SawClosedBrace:boolean; FieldName:TPACCRawByteString; FieldType:PPACCType; Keys:TPACCStructFields; begin HasBrace:=CurrentState.Token^.TokenType=TOK_LBRA; if HasBrace then begin NextToken; end; SawClosedBrace:=false; Keys:=Type_^.Fields; try Index:=0; repeat if CurrentState.Token^.TokenType=TOK_RBRA then begin if HasBrace then begin NextToken; SawClosedBrace:=true; break; end; end; if (CurrentState.Token^.TokenType in [TOK_DOT,TOK_LBRK]) and (HasBrace or Designated) then begin exit; end; if CurrentState.Token^.TokenType=TOK_DOT then begin NextToken; if CurrentState.Token^.TokenType=TOK_IDENT then begin FieldName:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; NextToken; end else begin FieldName:=''; AddError('Malformed desginated initializer',nil,true); end; FieldType:=nil; for FieldIndex:=0 to length(Type_.Fields)-1 do begin if Type_.Fields[FieldIndex].Name=FieldName then begin FieldType:=Type_.Fields[FieldIndex].Type_; break; end; end; if not assigned(FieldType) then begin AddError('Field does not exist: '+FieldName,nil,false); end; Keys:=Type_^.Fields; Index:=0; while Index<length(Keys) do begin if Keys[Index].Name=FieldName then begin break; end; end; Designated:=true; end else begin if Index<length(Keys) then begin FieldName:=Keys[Index].Name; FieldType:=Keys[Index].Type_; inc(Index); end else begin break; end; end; ParseInitializerElement(List,FieldType,Offset+FieldType^.Offset,Designated); if CurrentState.Token^.TokenType=TOK_COMMA then begin NextToken; end; Designated:=false; until not (tfStruct in Type_^.Flags); if HasBrace and not SawClosedBrace then begin SkipToClosedBrace; end; finally Keys:=nil; end; end; begin ParseStructInitializers(List,Type_,Offset,Designated); SortInitializerList(List); end; var Encoding:TPACCEncoding; begin if TPACCInstance(Instance).IsStringType(Type_) then begin if CurrentState.Token^.TokenType=TOK_CSTR then begin AssignString(List,Type_,ParseStringValue(Encoding),Offset); exit; end else if (CurrentState.Token^.TokenType=TOK_LBRA) and (PeekTokenType(1)=TOK_CSTR) then begin NextToken; AssignString(List,Type_,ParseStringValue(Encoding),Offset); Expect(TOK_RBRA); exit; end; end; case Type_^.Kind of tkARRAY:begin ParseArrayInitializerList(List,Type_,Offset,Designated); end; tkSTRUCT:begin ParseStructInitializerList(List,Type_,Offset,Designated); end; else begin ParseArrayInitializerList(List,TPACCInstance(Instance).NewArrayType(Type_,1),Offset,Designated); end; end; end; function ParseDeclarationInitializer(const Type_:PPACCType):TPACCAbstractSyntaxTreeNodeList; var Node:TPACCAbstractSyntaxTreeNode; begin result:=TPACCAbstractSyntaxTreeNodeList.Create; TPACCInstance(Instance).AllocatedObjects.Add(result); if (CurrentState.Token^.TokenType=TOK_LBRA) or TPACCInstance(Instance).IsStringType(Type_) then begin ParseInitializerList(result,Type_,0,false); end else begin Node:=TPACCInstance(Instance).TypeConversion(ParseAssignmentExpression); if TPACCInstance(Instance).IsArithmeticType(Node.Type_) and (Node.Type_^.Kind<>Type_^.Kind) then begin Node:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkCONV,Type_,Node.SourceLocation,Node); end; if (Node.Type_^.Kind=tkPOINTER) and (Type_^.Kind=tkPOINTER) and not TPACCInstance(Instance).AreTypesEqual(Node.Type_,Type_) then begin if Type_^.ChildType^.Kind<>tkVOID then begin AddWarning('Initialization from incompatible pointer type',@Node.SourceLocation); end; end; result.Add(TPACCAbstractSyntaxTreeNodeInitializer.Create(TPACCInstance(Instance),astnkINIT,nil,Node.SourceLocation,Node,0,Type_)); end; end; function ParseCompoundLiteral(const Type_:PPACCType):TPACCAbstractSyntaxTreeNode; var Name:TPACCRawByteString; begin Name:='_$TEMP$'+IntToStr(TPasMPInterlocked.Increment(TempVariableCounter)); result:=TPACCAbstractSyntaxTreeNodeLocalGlobalVariable.Create(TPACCInstance(Instance),astnkLVAR,Type_,CurrentState.Token^.SourceLocation,Name,0); TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(result).LocalVariableInitialization:=ParseDeclarationInitializer(Type_); TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(result).MustOnStack:=true; Assert(assigned(LocalScope)); LocalScope[Name]:=result; if assigned(LocalVariables) then begin TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(result).Index:=LocalVariables.Add(result); end else begin TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(result).Index:=-1; end; end; function ParseCastExpression:TPACCAbstractSyntaxTreeNode; var Type_:PPACCType; RelevantSourceLocation:TPACCSourceLocation; begin if (CurrentState.Token^.TokenType=TOK_LPAR) and IsType(PeekToken(1)) then begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; NextToken; Type_:=ParseCastType; Expect(TOK_RPAR); if CurrentState.Token^.TokenType=TOK_LBRA then begin result:=ParsePostfixExpressionTail(ParseCompoundLiteral(Type_)); end else begin result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkOP_CAST,Type_,RelevantSourceLocation,ParseCastExpression); end; end else begin result:=ParseUnaryExpression; end; end; function ParseMultiplicativeExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseCastExpression; repeat case CurrentState.Token^.TokenType of TOK_MUL:begin NextToken; result:=BinaryOperation(astnkOP_MUL,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseCastExpression)); end; TOK_DIV:begin NextToken; result:=BinaryOperation(astnkOP_DIV,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseCastExpression)); end; TOK_MOD:begin NextToken; result:=BinaryOperation(astnkOP_MOD,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseCastExpression)); end; else begin break; end; end; until false; end; function ParseAdditiveExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseMultiplicativeExpression; repeat case CurrentState.Token^.TokenType of TOK_ADD:begin NextToken; result:=BinaryOperation(astnkOP_ADD,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseMultiplicativeExpression)); end; TOK_SUB:begin NextToken; result:=BinaryOperation(astnkOP_SUB,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseMultiplicativeExpression)); end; else begin break; end; end; until false; end; function ParseShiftExpression:TPACCAbstractSyntaxTreeNode; var Op:TPACCAbstractSyntaxTreeNodeKind; Right:TPACCAbstractSyntaxTreeNode; begin result:=ParseAdditiveExpression; Op:=astnkNONE; repeat case CurrentState.Token^.TokenType of TOK_SHL:begin NextToken; Op:=astnkOP_SHL; end; TOK_SHR:begin NextToken; if tfUnsigned in result.Type_^.Flags then begin Op:=astnkOP_SHR; end else begin Op:=astnkOP_SAR; end; end; else begin break; end; end; Right:=ParseAdditiveExpression; EnsureIntType(result); EnsureIntType(Right); result:=BinaryOperation(Op,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(Right)); until false; end; function ParseRelationalExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseShiftExpression; repeat case CurrentState.Token^.TokenType of TOK_LT:begin NextToken; result:=BinaryOperation(astnkOP_LT,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseShiftExpression)); end; TOK_GT:begin NextToken; result:=BinaryOperation(astnkOP_GT,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseShiftExpression)); end; TOK_LE:begin NextToken; result:=BinaryOperation(astnkOP_LE,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseShiftExpression)); end; TOK_GE:begin NextToken; result:=BinaryOperation(astnkOP_GE,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseShiftExpression)); end; else begin break; end; end; result.Type_:=TPACCInstance(Instance).TypeINT; until false; end; function ParseEqualityExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseRelationalExpression; case CurrentState.Token^.TokenType of TOK_EQ:begin NextToken; result:=BinaryOperation(astnkOP_EQ,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseRelationalExpression)); end; TOK_NE:begin NextToken; result:=BinaryOperation(astnkOP_NE,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseRelationalExpression)); end; end; end; function ParseBitAndExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseEqualityExpression; while CurrentState.Token^.TokenType=TOK_AND do begin NextToken; result:=BinaryOperation(astnkOP_AND,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseEqualityExpression)); end; end; function ParseBitXorExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseBitAndExpression; while CurrentState.Token^.TokenType=TOK_XOR do begin NextToken; result:=BinaryOperation(astnkOP_XOR,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseBitAndExpression)); end; end; function ParseBitOrExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseBitXorExpression; while CurrentState.Token^.TokenType=TOK_OR do begin NextToken; result:=BinaryOperation(astnkOP_OR,TPACCInstance(Instance).TypeConversion(result),TPACCInstance(Instance).TypeConversion(ParseBitXorExpression)); end; end; function ParseLogicalAndExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseBitOrExpression; while CurrentState.Token^.TokenType=TOK_LAND do begin NextToken; result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),astnkOP_LOG_AND,TPACCInstance(Instance).TypeINT,result.SourceLocation,result,ParseBitOrExpression); end; end; function ParseLogicalOrExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseLogicalAndExpression; while CurrentState.Token^.TokenType=TOK_LOR do begin NextToken; result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),astnkOP_LOG_OR,TPACCInstance(Instance).TypeINT,result.SourceLocation,result,ParseLogicalAndExpression); end; end; function ParseCommaExpression:TPACCAbstractSyntaxTreeNode; forward; function ParseConditionalExpression:TPACCAbstractSyntaxTreeNode; forward; function ParseConditionalExpressionEx(const Condition:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; var Then_,Else_:TPACCAbstractSyntaxTreeNode; t,u,r:PPACCType; begin result:=Condition; if CurrentState.Token^.TokenType=TOK_QUEST then begin NextToken; Then_:=TPACCInstance(Instance).TypeConversion(ParseCommaExpression); Expect(TOK_COLON); Else_:=TPACCInstance(Instance).TypeConversion(ParseConditionalExpression); if assigned(Then_) then begin t:=Then_.Type_; end else begin t:=result.Type_; end; u:=Else_.Type_; // C11 6.5.15p5: if both types are arithemtic type, the result type is the result of the usual arithmetic conversions. if TPACCInstance(Instance).IsArithmeticType(t) and TPACCInstance(Instance).IsArithmeticType(u) then begin r:=TPACCInstance(Instance).UsualArithmeticConversion(t,u); if assigned(Then_) then begin result:=TPACCAbstractSyntaxTreeNodeIFStatementOrTernaryOperator.Create(TPACCInstance(Instance),astnkTERNARY,r,result.SourceLocation,result,Wrap(r,Then_),Wrap(r,Else_)); end else begin result:=TPACCAbstractSyntaxTreeNodeIFStatementOrTernaryOperator.Create(TPACCInstance(Instance),astnkTERNARY,r,result.SourceLocation,result,nil,Wrap(r,Else_)); end; end else begin result:=TPACCAbstractSyntaxTreeNodeIFStatementOrTernaryOperator.Create(TPACCInstance(Instance),astnkTERNARY,u,result.SourceLocation,result,Then_,Else_); end; end; end; function ParseConditionalExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseConditionalExpressionEx(ParseLogicalOrExpression); end; function ParseAssignmentExpression:TPACCAbstractSyntaxTreeNode; var Op:TPACCAbstractSyntaxTreeNodeKind; Right:TPACCAbstractSyntaxTreeNode; begin result:=ParseLogicalOrExpression; case CurrentState.Token^.TokenType of TOK_QUEST:begin result:=ParseConditionalExpressionEx(result); end; TOK_ASSIGN:begin NextToken; Right:=TPACCInstance(Instance).TypeConversion(ParseAssignmentExpression); EnsureLValue(result); if TPACCInstance(Instance).IsArithmeticType(result.Type_) and (result.Type_.Kind<>Right.Type_.Kind) then begin Right:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance), astnkCONV, result.Type_, Right.SourceLocation, Right); end; result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance), astnkOP_ASSIGN, result.Type_, result.SourceLocation, result, Right); end; TOK_A_ADD,TOK_A_SUB,TOK_A_MUL,TOK_A_DIV,TOK_A_MOD,TOK_A_AND,TOK_A_OR,TOK_A_XOR,TOK_A_SHL,TOK_A_SHR:begin // 6.5.16.2 Compound assignment // A compound assignment of the form E1 op = E2 is equivalent to the simple assignment // exüression E1 = E1 op (E2), except that the lvalue E1 is >>>>>>evaluated only once<<<<<<<, and with // respect to an indeterminately-sequenced function call, the operation of a compound // assignment is a single evaluation. case CurrentState.Token^.TokenType of TOK_A_ADD:begin Op:=astnkOP_ADD; end; TOK_A_SUB:begin Op:=astnkOP_SUB; end; TOK_A_MUL:begin Op:=astnkOP_MUL; end; TOK_A_DIV:begin Op:=astnkOP_DIV; end; TOK_A_MOD:begin Op:=astnkOP_MOD; end; TOK_A_AND:begin Op:=astnkOP_AND; end; TOK_A_OR:begin Op:=astnkOP_OR; end; TOK_A_XOR:begin Op:=astnkOP_XOR; end; TOK_A_SHL:begin Op:=astnkOP_SHL; end; else {TOK_A_SHR:}begin if tfUnsigned in result.Type_^.Flags then begin Op:=astnkOP_SHR; end else begin Op:=astnkOP_SAR; end; end; end; NextToken; Right:=TPACCInstance(Instance).TypeConversion(ParseAssignmentExpression); EnsureLValue(result); if result.Kind in [astnkLVAR,astnkGVAR] then begin Right:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance), Op, result.Type_, result.SourceLocation, result, Right); if TPACCInstance(Instance).IsArithmeticType(result.Type_) and (result.Type_.Kind<>Right.Type_.Kind) then begin Right:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance), astnkCONV, result.Type_, Right.SourceLocation, Right); end; result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance), astnkOP_ASSIGN, result.Type_, result.SourceLocation, result, Right); end else begin Right:=BinaryOperation(Op, TPACCInstance(Instance).TypeConversion(TPACCAbstractSyntaxTreeNode.Create(TPACCInstance(Instance),astnkOP_ASSIGN_SRC,result.Type_,result.SourceLocation)), Right); if TPACCInstance(Instance).IsArithmeticType(result.Type_) and (result.Type_.Kind<>Right.Type_.Kind) then begin Right:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance), astnkCONV, result.Type_, Right.SourceLocation, Right); end; result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance), astnkOP_ASSIGN_OP, result.Type_, result.SourceLocation, result, Right); end; end; end; end; function ParseCommaExpression:TPACCAbstractSyntaxTreeNode; var Expression:TPACCAbstractSyntaxTreeNode; begin result:=ParseAssignmentExpression; while CurrentState.Token^.TokenType=TOK_COMMA do begin NextToken; Expression:=ParseAssignmentExpression; result:=TPACCAbstractSyntaxTreeNodeBinaryOperator.Create(TPACCInstance(Instance),astnkOP_COMMA,Expression.Type_,result.SourceLocation,result,Expression); end; end; function ParseExpressionOptional:TPACCAbstractSyntaxTreeNode; begin result:=ParseCommaExpression; end; function ParseExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseCommaExpression; if not assigned(result) then begin AddError('Expression expected',nil,true); end; end; function ParseIntegerExpression:TPACCInt64; begin result:=TPACCInstance(Instance).EvaluateIntegerExpression(ParseConditionalExpression,nil); end; function ParseFunctionDefinition:pointer; begin result:=nil; end; function ParseDeclaratorSpecifier(ResultStorageClass:PPACCInt32;var Attribute:TPACCAttribute):PPACCType; forward; function ParseDeclarator(out Name:TPACCRawByteString;const BaseType:PPACCType;const Parameters:TPACCAbstractSyntaxTreeNodeList;Context:TPACCInt32):PPACCType; function ParseDeclaratorFunction(const BaseType:PPACCType;const Parameters:TPACCAbstractSyntaxTreeNodeList):PPACCType; function ParseDeclaratorFunctionParameterList(const ParameterVariables:TPACCAbstractSyntaxTreeNodeList;const ReturnType:PPACCType):PPACCType; function ParseFunctionParameter(out Name:TPACCRawByteString;Optional:boolean):PPACCType; var StorageClass,CallingConvention:TPACCInt32; BaseType:PPACCType; Attribute:TPACCAttribute; begin StorageClass:=0; Attribute:=PACCEmptyAttribute; BaseType:=TPACCInstance(Instance).TypeINT; if IsType(CurrentState.Token) then begin BaseType:=ParseDeclaratorSpecifier(@StorageClass,Attribute); end else if Optional then begin AddError('Type expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; if Optional then begin result:=ParseDeclarator(Name,BaseType,nil,DECL_PARAM_TYPEONLY); end else begin result:=ParseDeclarator(Name,BaseType,nil,DECL_PARAM); end; result^.Attribute:=Attribute; case result^.Kind of tkARRAY:begin // C11 6.7.6.3p7: Array of T is adjusted to pointer to T in a function parameter list. result:=TPACCInstance(Instance).NewPointerType(result^.ChildType); end; tkFUNCTION:begin // C11 6.7.6.3p8: Function is adjusted to pointer to function in a function parameter list. result:=TPACCInstance(Instance).NewPointerType(result); end; else begin // We must do nothing in this case end; end; end; procedure ParseDeclaratorParameters(var ParameterTypes:TPPACCTypes;const ParameterVariables:TPACCAbstractSyntaxTreeNodeList;out Ellipsis:boolean); var TypeOnly:boolean; Count,Index:TPACCInt32; Name:TPACCRawByteString; CurrentType:PPACCType; RelevantSourceLocation:TPACCSourceLocation; Variable:TPACCAbstractSyntaxTreeNode; begin TypeOnly:=not assigned(ParameterVariables); Count:=length(ParameterTypes); repeat RelevantSourceLocation:=CurrentState.Token^.SourceLocation; if CurrentState.Token^.TokenType=TOK_ELLIPSIS then begin NextToken; if Count=0 then begin AddError('At least one parameter is required before "..."',nil,false); end; Expect(TOK_RPAR); Ellipsis:=true; break; end else begin CurrentType:=ParseFunctionParameter(Name,TypeOnly); EnsureNotVoid(CurrentType); Index:=Count; inc(Count); if length(ParameterTypes)<Count then begin SetLength(ParameterTypes,Count*2); end; ParameterTypes[Index]:=CurrentType; if not TypeOnly then begin Variable:=TPACCAbstractSyntaxTreeNodeLocalGlobalVariable.Create(TPACCInstance(Instance),astnkLVAR,CurrentType,RelevantSourceLocation,Name,0); ParameterVariables.Add(Variable); end; case CurrentState.Token^.TokenType of TOK_RPAR:begin NextToken; break; end; TOK_COMMA:begin NextToken; end; else begin AddError('")" or "," expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; end; end; until false; SetLength(ParameterTypes,Count); end; procedure ParseDeclaratorParametersOldStyle(const ParameterVariables:TPACCAbstractSyntaxTreeNodeList); var Name:TPACCRawByteString; begin repeat if CurrentState.Token^.TokenType=TOK_IDENT then begin Name:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; ParameterVariables.Add(TPACCAbstractSyntaxTreeNodeLocalGlobalVariable.Create(TPACCInstance(Instance),astnkLVAR,TPACCInstance(Instance).TypeINT,CurrentState.Token^.SourceLocation,Name,0)); NextToken; case CurrentState.Token^.TokenType of TOK_RPAR:begin NextToken; break; end; TOK_COMMA:begin NextToken; end; else begin AddError('")" or "," expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; end; end else begin AddError('Identifier expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; until false; end; var ParameterTypes:TPPACCTypes; Ellipsis:boolean; begin if (CurrentState.Token^.TokenType=TOK_VOID) and (PeekTokenType(1)=TOK_RPAR) then begin // C11 6.7.6.3p10: A parameter list with just "void" specifies that the function has no parameters. NextToken; NextToken; result:=TPACCInstance(Instance).NewFunctionType(ReturnType,nil,false,false); end else begin case CurrentState.Token^.TokenType of TOK_RPAR:begin // C11 6.7.6.3p14: K&R-style un-prototyped declaration or function definition having no parameters. NextToken; result:=TPACCInstance(Instance).NewFunctionType(ReturnType,nil,true,true); end; TOK_ELLIPSIS:begin result:=nil; AddError('At least one parameter is required before "..."',nil,false); end; else begin if IsType(CurrentState.Token) then begin ParameterTypes:=nil; try Ellipsis:=false; ParseDeclaratorParameters(ParameterTypes,ParameterVariables,Ellipsis); result:=TPACCInstance(Instance).NewFunctionType(ReturnType,ParameterTypes,Ellipsis,false); finally ParameterTypes:=nil; end; end else begin if assigned(ParameterVariables) then begin ParseDeclaratorParametersOldstyle(ParameterVariables); ParameterTypes:=nil; try SetLength(ParameterTypes,ParameterVariables.Count); result:=TPACCInstance(Instance).NewFunctionType(ReturnType,ParameterTypes,false,true); finally ParameterTypes:=nil; end; end else begin result:=nil; AddError('Invalid function definition',nil,true); end; end; end; end; end; end; begin case BaseType^.Kind of tkFUNCTION:begin result:=nil; AddError('Function returning a function',nil,true); end; tkARRAY:begin result:=nil; AddError('Function returning an array',nil,true); end; else begin result:=ParseDeclaratorFunctionParameterList(Parameters,BaseType); end; end; end; function ParseDeclaratorTail(const BaseType:PPACCType;const Parameters:TPACCAbstractSyntaxTreeNodeList):PPACCType; forward; function ParseDeclaratorArray(const BaseType:PPACCType):PPACCType; var Len:TPACCInt64; begin if CurrentState.Token^.TokenType=TOK_RBRK then begin NextToken; Len:=-1; end else begin Len:=ParseIntegerExpression; Expect(TOK_RBRK); end; result:=ParseDeclaratorTail(BaseType,nil); if assigned(result) and (result^.Kind=tKFUNCTION) then begin AddError('Array of functions',nil,false); end; result:=TPACCInstance(Instance).NewArrayType(result,Len); end; function ParseDeclaratorTail(const BaseType:PPACCType;const Parameters:TPACCAbstractSyntaxTreeNodeList):PPACCType; begin case CurrentState.Token^.TokenType of TOK_LPAR:begin NextToken; result:=ParseDeclaratorFunction(BaseType,Parameters); end; TOK_LBRK:begin NextToken; result:=ParseDeclaratorArray(BaseType); end; else begin result:=BaseType; end; end; end; var Stub:PPACCType; begin case CurrentState.Token^.TokenType of TOK_LPAR:begin NextToken; if IsType(CurrentState.Token) then begin result:=ParseDeclaratorFunction(BaseType,Parameters); end else begin Stub:=TPACCInstance(Instance).NewStubType; TPACCInstance(Instance).CopyFromTypeToType(BaseType,Stub); result:=ParseDeclarator(Name,Stub,Parameters,Context); Expect(TOK_RPAR); TPACCInstance(Instance).CopyFromTypeToType(ParseDeclaratorTail(BaseType,Parameters),Stub); end; end; TOK_MUL:begin NextToken; SkipTypeQualifiers; result:=ParseDeclarator(Name,TPACCInstance(Instance).NewPointerType(BaseType),Parameters,Context); end; else begin if CurrentState.Token^.TokenType=TOK_IDENT then begin if Context in [DECL_CAST] then begin result:=nil; AddError('Identifier is not expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end else begin Name:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; NextToken; result:=ParseDeclaratorTail(BaseType,Parameters); end; end else if Context in [DECL_BODY,DECL_PARAM] then begin result:=nil; AddError('Identifier, "(" or "*" are expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end else begin result:=ParseDeclaratorTail(BaseType,Parameters); end; end; end; end; function ParseAbstractDeclarator(const BaseType:PPACCType):PPACCType; var n:TPACCRawByteString; begin result:=ParseDeclarator(n,BaseType,nil,DECL_CAST); end; function ParseCastType:PPACCType; var Attribute:TPACCAttribute; begin Attribute:=PACCEmptyAttribute; result:=ParseAbstractDeclarator(ParseDeclaratorSpecifier(nil,Attribute)); result^.Attribute:=Attribute; end; procedure ParseStaticAssert; var Value:TPACCInt64; Msg:TPACCRawByteString; Encoding:TPACCEncoding; begin Expect(TOK_LPAR); Value:=ParseIntegerExpression; Expect(TOK_COMMA); if CurrentState.Token^.TokenType=TOK_CSTR then begin Msg:=ParseStringValue(Encoding); end else begin AddError('string expected as the second argument for _Static_assert, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); Msg:=''; end; Expect(TOK_RPAR); Expect(TOK_SEMICOLON); if Value=0 then begin AddError('_Static_assert failure: '+IntToStr(Value)+' '+Msg,nil,true); end; end; procedure ParseDeclarationOrStatement(const List:TPACCAbstractSyntaxTreeNodeList); forward; function ParseStatement:TPACCAbstractSyntaxTreeNode; forward; function ParseBooleanExpression:TPACCAbstractSyntaxTreeNode; begin result:=ParseExpression; if TPACCInstance(Instance).IsFloatType(result.Type_) then begin result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkCONV,TPACCInstance(Instance).TypeBOOL,result.SourceLocation,result); end; end; function ParseAssemblerStatement(const IsGlobal:boolean):TPACCAbstractSyntaxTreeNode; procedure ParseAssemblerOperands(const IsOutput:boolean;const Operands:TPACCAbstractSyntaxTreeNodeList); var Expression:TPACCAbstractSyntaxTreeNode; Identifier,Constraint:TPACCRawByteString; Operand:TPACCAbstractSyntaxTreeNodeAssemblerOperand; RelevantSourceLocation:TPACCSourceLocation; Encoding:TPACCEncoding; begin if CurrentState.Token^.TokenType<>TOK_COLON then begin repeat RelevantSourceLocation:=CurrentState.Token^.SourceLocation; Identifier:=''; if CurrentState.Token^.TokenType=TOK_LBRK then begin NextToken; if CurrentState.Token^.TokenType=TOK_IDENT then begin Identifier:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; NextToken; end else begin AddError('Identifier expected',@CurrentState.Token^.SourceLocation,true); end; Expect(TOK_RBRK); end; if CurrentState.Token^.TokenType=TOK_CSTR then begin Constraint:=ParseStringValue(Encoding); Expect(TOK_LPAR); Expression:=ParseExpression; Expect(TOK_RPAR); if IsOutput then begin EnsureLValue(Expression); end else begin if pos('m',Constraint)=0 then begin Expression:=TPACCInstance(Instance).TypeConversion(Expression); end; end; Operand:=TPACCAbstractSyntaxTreeNodeAssemblerOperand.Create(TPACCInstance(Instance),astnkASSEMBLER_OPERAND,nil,RelevantSourceLocation,Identifier,Constraint,Expression); Operands.Add(Operand); if CurrentState.Token^.TokenType=TOK_COMMA then begin NextToken; continue; end else begin break; end; end else begin AddError('String constant expected',@CurrentState.Token^.SourceLocation,true); end; until false; end; end; procedure ParseClobbers(const Clobbers:TStringList); var RelevantSourceLocation:TPACCSourceLocation; Encoding:TPACCEncoding; begin if CurrentState.Token^.TokenType<>TOK_COLON then begin repeat RelevantSourceLocation:=CurrentState.Token^.SourceLocation; if CurrentState.Token^.TokenType=TOK_CSTR then begin Clobbers.Add(ParseStringValue(Encoding)); if CurrentState.Token^.TokenType=TOK_COMMA then begin NextToken; continue; end else begin break; end; end else begin AddError('String constant expected',@RelevantSourceLocation,true); end; until false; end; end; procedure ParseLabels(const Gotos:TPACCAbstractSyntaxTreeNodeList); var RelevantSourceLocation:TPACCSourceLocation; LabelName:TPACCRawByteString; begin if CurrentState.Token^.TokenType<>TOK_COLON then begin repeat RelevantSourceLocation:=CurrentState.Token^.SourceLocation; if CurrentState.Token^.TokenType=TOK_IDENT then begin LabelName:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; Gotos.Add(TPACCAbstractSyntaxTreeNodeGOTOStatementOrLabelAddress.Create(TPACCInstance(Instance),astnkGOTO,nil,RelevantSourceLocation,nil,LabelName)); if assigned(UnresolvedLabelUsedNodes) then begin UnresolvedLabelUsedNodes.Add(result); end else begin AddError('Internal error 2017-01-09-07-50-0000',nil,true); end; NextToken; if CurrentState.Token^.TokenType=TOK_COMMA then begin NextToken; continue; end else begin break; end; end else begin AddError('String constant expected',@CurrentState.Token^.SourceLocation,true); end; until false; end; end; var Code:TPACCRawByteString; RelevantSourceLocation:TPACCSourceLocation; IsVolatile,WithGotos:boolean; Encoding:TPACCEncoding; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; IsVolatile:=CurrentState.Token^.TokenType=TOK_VOLATILE; if IsVolatile then begin NextToken; end; WithGotos:=CurrentState.Token^.TokenType=TOK_GOTO; if WithGotos then begin NextToken; end; Expect(TOK_LPAR); if CurrentState.Token^.TokenType=TOK_CSTR then begin Code:=ParseStringValue(Encoding); result:=TPACCAbstractSyntaxTreeNodeAssembler.Create(TPACCInstance(Instance),astnkASSEMBLER,nil,RelevantSourceLocation,IsGlobal,IsVolatile,WithGotos,Code); TPACCAbstractSyntaxTreeNodeAssembler(result).InputOperands:=TPACCAbstractSyntaxTreeNodeList.Create; TPACCInstance(Instance).AllocatedObjects.Add(TPACCAbstractSyntaxTreeNodeAssembler(result).InputOperands); TPACCAbstractSyntaxTreeNodeAssembler(result).OutputOperands:=TPACCAbstractSyntaxTreeNodeList.Create; TPACCInstance(Instance).AllocatedObjects.Add(TPACCAbstractSyntaxTreeNodeAssembler(result).OutputOperands); TPACCAbstractSyntaxTreeNodeAssembler(result).Gotos:=TPACCAbstractSyntaxTreeNodeList.Create; TPACCInstance(Instance).AllocatedObjects.Add(TPACCAbstractSyntaxTreeNodeAssembler(result).Gotos); if CurrentState.Token^.TokenType=TOK_COLON then begin NextToken; ParseAssemblerOperands(true,TPACCAbstractSyntaxTreeNodeAssembler(result).OutputOperands); if CurrentState.Token^.TokenType=TOK_COLON then begin NextToken; ParseAssemblerOperands(false,TPACCAbstractSyntaxTreeNodeAssembler(result).InputOperands); if CurrentState.Token^.TokenType=TOK_COLON then begin NextToken; ParseClobbers(TPACCAbstractSyntaxTreeNodeAssembler(result).Clobbers); if WithGotos then begin Expect(TOK_COLON); ParseLabels(TPACCAbstractSyntaxTreeNodeAssembler(result).Gotos); end; end else if WithGotos then begin Expect(TOK_COLON); end; end else if WithGotos then begin Expect(TOK_COLON); end; end else if WithGotos then begin Expect(TOK_COLON); end; Expect(TOK_RPAR); if CurrentState.Token^.TokenType=TOK_SEMICOLON then begin Expect(TOK_SEMICOLON); end; end else begin result:=nil; AddError('Assembler code expected',@RelevantSourceLocation,false); end; end; function ParseIFStatement:TPACCAbstractSyntaxTreeNode; var ConditionNode,ThenNode,ElseNode:TPACCAbstractSyntaxTreeNode; begin Expect(TOK_LPAR); ConditionNode:=ParseBooleanExpression; Expect(TOK_RPAR); ThenNode:=ParseStatement; if CurrentState.Token^.TokenType=TOK_ELSE then begin NextToken; ElseNode:=ParseStatement; end else begin ElseNode:=nil; end; result:=TPACCAbstractSyntaxTreeNodeIFStatementOrTernaryOperator.Create(TPACCInstance(Instance),astnkIF,nil,ConditionNode.SourceLocation,ConditionNode,ThenNode,ElseNode); end; function ParseFORStatement:TPACCAbstractSyntaxTreeNode; var LoopBreakLabel,LoopContinueLabel,OldBreakLabel,OldContinueLabel:TPACCAbstractSyntaxTreeNodeLabel; OriginalLocalScope:TPACCRawByteStringHashMap; InitializationNode,ConditionNode,StepNode,BodyNode:TPACCAbstractSyntaxTreeNode; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; OriginalLocalScope:=LocalScope; LocalScope:=nil; try LocalScope:=TPACCRawByteStringHashMap.Create; LocalScope.Parent:=OriginalLocalScope; Expect(TOK_LPAR); if CurrentState.Token^.TokenType=TOK_SEMICOLON then begin InitializationNode:=nil; NextToken; end else begin InitializationNode:=TPACCAbstractSyntaxTreeNodeStatements.Create(TPACCInstance(Instance),astnkSTATEMENTS,nil,CurrentState.Token^.SourceLocation); ParseDeclarationOrStatement(TPACCAbstractSyntaxTreeNodeStatements(InitializationNode).Children); end; if CurrentState.Token^.TokenType=TOK_SEMICOLON then begin ConditionNode:=nil; NextToken; end else begin ConditionNode:=ParseExpressionOptional; if assigned(ConditionNode) and TPACCInstance(Instance).IsFloatType(ConditionNode.Type_) then begin ConditionNode:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkCONV,TPACCInstance(Instance).TypeBOOL,ConditionNode.SourceLocation,ConditionNode); end; Expect(TOK_SEMICOLON); end; if CurrentState.Token^.TokenType<>TOK_RPAR then begin StepNode:=ParseExpressionOptional; end else begin StepNode:=nil; end; Expect(TOK_RPAR); OldBreakLabel:=BreakLabel; OldContinueLabel:=ContinueLabel; try LoopBreakLabel:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); LoopContinueLabel:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); BreakLabel:=LoopBreakLabel; ContinueLabel:=LoopContinueLabel; BodyNode:=ParseStatement; finally BreakLabel:=OldBreakLabel; ContinueLabel:=OldContinueLabel; end; finally FreeAndNil(LocalScope); LocalScope:=OriginalLocalScope; end; result:=TPACCAbstractSyntaxTreeNodeFORStatement.Create(TPACCInstance(Instance),astnkFOR,nil,RelevantSourceLocation,InitializationNode,ConditionNode,StepNode,BodyNode,LoopBreakLabel,LoopContinueLabel); end; function ParseWHILEStatement:TPACCAbstractSyntaxTreeNode; var LoopBreakLabel,LoopContinueLabel,OldBreakLabel,OldContinueLabel:TPACCAbstractSyntaxTreeNodeLabel; OriginalLocalScope:TPACCRawByteStringHashMap; ConditionNode,BodyNode:TPACCAbstractSyntaxTreeNode; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; Expect(TOK_LPAR); ConditionNode:=ParseBooleanExpression; Expect(TOK_RPAR); OriginalLocalScope:=LocalScope; LocalScope:=nil; try LocalScope:=TPACCRawByteStringHashMap.Create; LocalScope.Parent:=OriginalLocalScope; OldBreakLabel:=BreakLabel; OldContinueLabel:=ContinueLabel; try LoopBreakLabel:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); LoopContinueLabel:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); BreakLabel:=LoopBreakLabel; ContinueLabel:=LoopContinueLabel; BodyNode:=ParseStatement; finally BreakLabel:=OldBreakLabel; ContinueLabel:=OldContinueLabel; end; finally FreeAndNil(LocalScope); LocalScope:=OriginalLocalScope; end; result:=TPACCAbstractSyntaxTreeNodeWHILEOrDOStatement.Create(TPACCInstance(Instance),astnkWHILE,nil,RelevantSourceLocation,ConditionNode,BodyNode,LoopBreakLabel,LoopContinueLabel); end; function ParseDOStatement:TPACCAbstractSyntaxTreeNode; var LoopBreakLabel,LoopContinueLabel,OldBreakLabel,OldContinueLabel:TPACCAbstractSyntaxTreeNodeLabel; OriginalLocalScope:TPACCRawByteStringHashMap; ConditionNode,BodyNode:TPACCAbstractSyntaxTreeNode; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; OriginalLocalScope:=LocalScope; LocalScope:=nil; try LocalScope:=TPACCRawByteStringHashMap.Create; LocalScope.Parent:=OriginalLocalScope; OldBreakLabel:=BreakLabel; OldContinueLabel:=ContinueLabel; try LoopBreakLabel:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); LoopContinueLabel:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); BreakLabel:=LoopBreakLabel; ContinueLabel:=LoopContinueLabel; BodyNode:=ParseStatement; finally BreakLabel:=OldBreakLabel; ContinueLabel:=OldContinueLabel; end; finally FreeAndNil(LocalScope); LocalScope:=OriginalLocalScope; end; Expect(TOK_WHILE); Expect(TOK_LPAR); ConditionNode:=ParseBooleanExpression; Expect(TOK_RPAR); Expect(TOK_SEMICOLON); result:=TPACCAbstractSyntaxTreeNodeWHILEOrDOStatement.Create(TPACCInstance(Instance),astnkDO,nil,RelevantSourceLocation,ConditionNode,BodyNode,LoopBreakLabel,LoopContinueLabel); end; function ParseRETURNStatement:TPACCAbstractSyntaxTreeNode; var RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; if CurrentState.Token^.TokenType<>TOK_SEMICOLON then begin result:=ParseExpressionOptional; end else begin result:=nil; end; Expect(TOK_SEMICOLON); if assigned(result) then begin result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkCONV,CurrentFunctionType^.ReturnType,result.SourceLocation,result); end; result:=TPACCAbstractSyntaxTreeNodeReturnStatement.Create(TPACCInstance(Instance),astnkRETURN,nil,RelevantSourceLocation,result); end; function ParseSWITCHStatement:TPACCAbstractSyntaxTreeNode; var Index:TPACCInt; ExpressionNode,BodyNode:TPACCAbstractSyntaxTreeNode; OldCases:TCases; CurrentCase:PCase; SwitchCases:TPACCAbstractSyntaxTreeNodeSWITCHStatementCases; SwitchCase:PPACCAbstractSyntaxTreeNodeSWITCHStatementCase; OldBreakLabel,SwitchBreakLabel:TPACCAbstractSyntaxTreeNodeLabel; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; SwitchCases:=nil; Expect(TOK_LPAR); ExpressionNode:=TPACCInstance(Instance).TypeConversion(ParseExpression); EnsureIntType(ExpressionNode); Expect(TOK_RPAR); OldCases:=Cases; OldBreakLabel:=BreakLabel; try Cases.Ready:=true; Cases.Cases:=nil; Cases.Count:=0; Cases.DefaultCaseLabel:=nil; SwitchBreakLabel:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); BreakLabel:=SwitchBreakLabel; BodyNode:=ParseStatement; SetLength(SwitchCases,Cases.Count); for Index:=0 to Cases.Count-1 do begin SwitchCase:=@SwitchCases[Index]; CurrentCase:=@Cases.Cases[Index]; SwitchCase^.CaseBegin:=CurrentCase^.Begin_; SwitchCase^.CaseEnd:=CurrentCase^.End_; SwitchCase^.CaseLabel:=CurrentCase^.Label_; end; if length(SwitchCases)>1 then begin UntypedDirectIntroSort(@SwitchCases[0],0,length(SwitchCases)-1,sizeof(TPACCAbstractSyntaxTreeNodeSWITCHStatementCase),CompareSwitchCases); end; result:=TPACCAbstractSyntaxTreeNodeSWITCHStatement.Create(TPACCInstance(Instance),astnkSWITCH,nil,RelevantSourceLocation,ExpressionNode,BodyNode,SwitchBreakLabel,Cases.DefaultCaseLabel,SwitchCases); finally Cases:=OldCases; BreakLabel:=OldBreakLabel; SwitchCases:=nil; end; end; function ParseLabelTail(const CurrentLabel:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; forward; function ParseCASELabel:TPACCAbstractSyntaxTreeNode; procedure CheckDuplicates; var Index,Last:TPACCInt; x,y:PCase; begin Last:=Cases.Count-1; x:=@Cases.Cases[Last]; for Index:=0 to Last-1 do begin y:=@Cases.Cases[Index]; if (x^.Begin_>y^.End_) or (x^.End_<y^.Begin_) then begin // Do nothing end else begin if x^.Begin_=x^.End_ then begin AddError('Duplicate case value: '+IntToStr(x^.Begin_),nil,false); end else begin AddError('Duplicate case value range: '+IntToStr(x^.Begin_)+' .. '+IntToStr(x^.End_),nil,false); end; end; end; end; var Label_:TPACCAbstractSyntaxTreeNodeLabel; Begin_,End_,Index:TPACCInt; CurrentCase:PCase; var RelevantSourceLocation:TPACCSourceLocation; begin if Cases.Ready then begin result:=nil; RelevantSourceLocation:=CurrentState.Token^.SourceLocation; Label_:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); Begin_:=ParseIntegerExpression; if CurrentState.Token^.TokenType=TOK_ELLIPSIS then begin NextToken; End_:=ParseIntegerExpression; if Begin_>End_ then begin AddError('Invalid case value range: '+IntToStr(Begin_)+' .. '+IntToStr(End_),nil,false); end; end else begin End_:=Begin_; end; Expect(TOK_COLON); Index:=Cases.Count; inc(Cases.Count); if length(Cases.Cases)<Cases.Count then begin SetLength(Cases.Cases,Cases.Count*2); end; CurrentCase:=@Cases.Cases[Index]; CurrentCase^.Begin_:=Begin_; CurrentCase^.End_:=End_; CurrentCase^.Label_:=Label_; CheckDuplicates; result:=ParseLabelTail(Label_); end else begin result:=nil; AddError('Case statement is not allowed outside switch statement',nil,true); end; end; function ParseDEFAULTLabel:TPACCAbstractSyntaxTreeNode; var RelevantSourceLocation:TPACCSourceLocation; begin if Cases.Ready then begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; if assigned(Cases.DefaultCaseLabel) then begin AddError('Duplicate default case statement',nil,false); end; Cases.DefaultCaseLabel:=NewLabel(astnkHIDDEN_LABEL,RelevantSourceLocation); Expect(TOK_COLON); result:=ParseLabelTail(Cases.DefaultCaseLabel); end else begin result:=nil; AddError('Default case statement is not allowed outside switch statement',nil,true); end; end; function ParseBREAKStatement:TPACCAbstractSyntaxTreeNode; var RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; if not assigned(BreakLabel) then begin AddError('Invalid break statement',nil,false); end; Expect(TOK_SEMICOLON); result:=TPACCAbstractSyntaxTreeNodeBREAKOrCONTINUEStatement.Create(TPACCInstance(Instance),astnkBREAK,nil,RelevantSourceLocation,BreakLabel); end; function ParseCONTINUEStatement:TPACCAbstractSyntaxTreeNode; var RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; if not assigned(ContinueLabel) then begin AddError('Invalid continue statement',nil,false); end; Expect(TOK_SEMICOLON); result:=TPACCAbstractSyntaxTreeNodeBREAKOrCONTINUEStatement.Create(TPACCInstance(Instance),astnkCONTINUE,nil,RelevantSourceLocation,ContinueLabel); end; function ParseGOTOStatement:TPACCAbstractSyntaxTreeNode; var LabelName:TPACCRawByteString; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; case CurrentState.Token^.TokenType of TOK_MUL:begin NextToken; result:=ParseCastExpression; if result.Type_^.Kind<>tkPOINTER then begin AddError('Pointer expected for computed goto',nil,false); end; result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(TPACCInstance(Instance),astnkCOMPUTED_GOTO,nil,RelevantSourceLocation,result); end; TOK_IDENT:begin LabelName:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; NextToken; Expect(TOK_SEMICOLON); result:=TPACCAbstractSyntaxTreeNodeGOTOStatementOrLabelAddress.Create(TPACCInstance(Instance),astnkGOTO,nil,RelevantSourceLocation,nil,LabelName); if assigned(UnresolvedLabelUsedNodes) then begin UnresolvedLabelUsedNodes.Add(result); end else begin AddError('Internal error 2017-01-04-02-14-0000',nil,true); end; end; else begin result:=nil; AddError('Identifier expected',nil,true); end; end; end; function ParseLabelTail(const CurrentLabel:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; var Statement:TPACCAbstractSyntaxTreeNode; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; Statement:=ParseStatement; result:=TPACCAbstractSyntaxTreeNodeStatements.Create(TPACCInstance(Instance),astnkSTATEMENTS,nil,RelevantSourceLocation); TPACCAbstractSyntaxTreeNodeStatements(result).Children.Add(CurrentLabel); if assigned(Statement) then begin TPACCAbstractSyntaxTreeNodeStatements(result).Children.Add(Statement); end; end; function ParseLabel:TPACCAbstractSyntaxTreeNode; var LabelName:TPACCRawByteString; RelevantSourceLocation:TPACCSourceLocation; begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; LabelName:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; if assigned(LabelScope[LabelName]) then begin AddError('Duplicate label: '+LabelName,nil,false); end; NextToken; Expect(TOK_COLON); result:=NewLabel(astnkLABEL,RelevantSourceLocation,LabelName); LabelScope[LabelName]:=result; result:=ParseLabelTail(result); end; function ParseStatement:TPACCAbstractSyntaxTreeNode; begin case CurrentState.Token^.TokenType of TOK_LBRA:begin NextToken; result:=ParseCompoundStatement; end; TOK_ASM:begin NextToken; result:=ParseAssemblerStatement(false); end; TOK_IF:begin NextToken; result:=ParseIFStatement; end; TOK_FOR:begin NextToken; result:=ParseFORStatement; end; TOK_WHILE:begin NextToken; result:=ParseWHILEStatement; end; TOK_DO:begin NextToken; result:=ParseDOStatement; end; TOK_RETURN:begin NextToken; result:=ParseRETURNStatement; end; TOK_SWITCH:begin NextToken; result:=ParseSWITCHStatement; end; TOK_CASE:begin NextToken; result:=ParseCASELabel; end; TOK_DEFAULT:begin NextToken; result:=ParseDEFAULTLabel; end; TOK_BREAK:begin NextToken; result:=ParseBREAKStatement; end; TOK_CONTINUE:begin NextToken; result:=ParseCONTINUEStatement; end; TOK_GOTO:begin NextToken; result:=ParseGOTOStatement; end; else begin if (CurrentState.Token^.TokenType=TOK_IDENT) and (PeekTokenType(1)=TOK_COLON) then begin result:=ParseLabel; end else begin result:=ParseExpressionOptional; Expect(TOK_SEMICOLON); end; end; end; end; procedure ParseDeclarationOrStatement(const List:TPACCAbstractSyntaxTreeNodeList); var Statement:TPACCAbstractSyntaxTreeNode; begin case CurrentState.Token^.TokenType of TOK_EOF:begin AddError('Premature end of input',nil,true); end; TOK_STATIC_ASSERT:begin NextToken; ParseStaticAssert; end; else begin if IsType(CurrentState.Token) then begin ParseDeclaration(List,false,false); end else begin Statement:=ParseStatement; if assigned(Statement) then begin List.Add(Statement); end; end; end; end; end; function ParseCompoundStatement:TPACCAbstractSyntaxTreeNode; var OriginalLocalScope:TPACCRawByteStringHashMap; begin result:=TPACCAbstractSyntaxTreeNodeStatements.Create(TPACCInstance(Instance),astnkSTATEMENTS,nil,CurrentState.Token^.SourceLocation); try OriginalLocalScope:=LocalScope; LocalScope:=nil; try LocalScope:=TPACCRawByteStringHashMap.Create; LocalScope.Parent:=OriginalLocalScope; repeat if CurrentState.Token^.TokenType=TOK_RBRA then begin NextToken; break; end else begin ParseDeclarationOrStatement(TPACCAbstractSyntaxTreeNodeStatements(result).Children); end; until false; finally FreeAndNil(LocalScope); LocalScope:=OriginalLocalScope; end; except FreeAndNil(result); raise; end; end; function ParseDeclaratorSpecifier(ResultStorageClass:PPACCInt32;var Attribute:TPACCAttribute):PPACCType; function ParseBitSize(const Name:TPACCRawByteString;const Type_:PPACCType):TPACCInt; var MaxSize:TPACCInt64; begin if TPACCInstance(Instance).IsIntType(Type_) then begin result:=ParseIntegerExpression; if Type_^.Kind=tkBOOL then begin MaxSize:=1; end else begin MaxSize:=Type_^.Size shl 3; end; if (result<0) or (MaxSize<result) then begin AddError('Invalid bitfield Size',nil,false); end else if (result=0) and (length(Name)>0) then begin AddError('Zero-width bitfield needs to be unnamed',nil,false); end; end else begin result:=0; AddError('Non-integer type can''t be a bitfield',nil,false); end; end; function ComputePadding(const Offset,Alignment:TPACCInt64):TPACCInt64; begin result:=Offset mod Alignment; if result<>0 then begin result:=Alignment-result; end; end; procedure SquashUnnamedStruct(var Fields:TPACCStructFields;var Count:TPACCInt;const Unnamed:PPACCType;const Offset:TPACCInt64); var UnnamedIndex,Index:TPACCInt; begin for UnnamedIndex:=0 to length(Unnamed^.Fields)-1 do begin Index:=Count; inc(Count); if length(Fields)<Count then begin SetLength(Fields,Count*2); end; Fields[Index].Name:=Unnamed^.Fields[UnnamedIndex].Name; Fields[Index].Type_:=TPACCInstance(Instance).CopyType(Unnamed^.Fields[UnnamedIndex].Type_); inc(Fields[Index].Type_.Offset,Offset); end; end; function UpdateStructOffsets(var Size:TPACCInt64;var Alignment:TPACCInt;const Fields:TPACCStructFields;const MaxAlignment:TPACCInt32):TPACCStructFields; var InputIndex,Index,Count:TPACCInt; Offset,BitOffset,Bit,Room:TPACCInt64; FieldName:TPACCRawByteString; FieldType:PPACCType; procedure FinishBitfield; begin inc(Offset,(BitOffset+7) shr 3); BitOffset:=0; end; begin result:=nil; Offset:=0; BitOffset:=0; Index:=0; Count:=0; try for InputIndex:=0 to length(Fields)-1 do begin FieldName:=Fields[InputIndex].Name; FieldType:=Fields[InputIndex].Type_; if length(FieldName)>0 then begin // C11 6.7.2.1p14: Each member is aligned to its natural boundary. // As a result the entire struct is aligned to the largest among its members. // Unnamed fields will never be accessed, so they shouldn't be taken into account // when calculating alignment. Alignment:=max(Alignment,Min(MaxAlignment,FieldType^.Alignment)); end; if (length(FieldName)=0) and (FieldType^.Kind=tkSTRUCT) then begin // C11 6.7.2.1p13: Anonymous struct FinishBitfield; inc(Offset,ComputePadding(Offset,Min(MaxAlignment,FieldType^.Alignment))); SquashUnnamedStruct(result,Count,FieldType,Offset); inc(Offset,FieldType^.Size); end else if FieldType^.BitSize=0 then begin // C11 6.7.2.1p12: The zero-Size bit-field indicates the end of the current run of the bit-fields. FinishBitfield; inc(Offset,ComputePadding(Offset,Min(MaxAlignment,FieldType^.Alignment))); BitOffset:=0; end else begin if FieldType^.BitSize>0 then begin Bit:=FieldType^.Size shl 3; Room:=Bit-(((Offset shl 3)+BitOffset) mod Bit); if FieldType^.BitSize<=Room then begin FieldType^.Offset:=Offset; FieldType^.BitOffset:=BitOffset; end else begin FinishBitfield; inc(Offset,ComputePadding(Offset,Min(MaxAlignment,FieldType^.Alignment))); FieldType^.Offset:=Offset; FieldType^.BitOffset:=0; end; inc(BitOffset,FieldType^.BitSize); end else begin FinishBitfield; inc(Offset,ComputePadding(Offset,Min(MaxAlignment,FieldType^.Alignment))); FieldType^.Offset:=Offset; inc(Offset,FieldType^.Size); end; if length(FieldName)>0 then begin Index:=Count; inc(Count); if length(result)<Count then begin SetLength(result,Count*2); end; result[Index].Name:=FieldName; result[Index].Type_:=FieldType; end; end; end; FinishBitfield; Size:=Offset+ComputePadding(Offset,Alignment); finally SetLength(result,Count); end; end; function UpdateUnionOffsets(var Size:TPACCInt64;var Alignment:TPACCInt;const Fields:TPACCStructFields;const MaxAlignment:TPACCInt32):TPACCStructFields; var InputIndex,Index,Count:TPACCInt; MaxSize:TPACCInt64; FieldName:TPACCRawByteString; FieldType:PPACCType; begin result:=nil; MaxSize:=0; Index:=0; Count:=0; try for InputIndex:=0 to length(Fields)-1 do begin FieldName:=Fields[InputIndex].Name; FieldType:=Fields[InputIndex].Type_; MaxSize:=max(MaxSize,FieldType^.Size); Alignment:=max(Alignment,Min(MaxAlignment,FieldType^.Alignment)); if (length(FieldName)=0) and (FieldType^.Kind=tkSTRUCT) then begin SquashUnnamedStruct(result,Count,FieldType,0); end else begin FieldType^.Offset:=0; if FieldType^.BitSize>=0 then begin FieldType^.BitOffset:=0; end; if length(FieldName)>0 then begin Index:=Count; inc(Count); if length(result)<Count then begin SetLength(result,Count*2); end; result[Index].Name:=FieldName; result[Index].Type_:=FieldType; end; end; end; Size:=MaxSize+ComputePadding(MaxSize,Alignment); finally SetLength(result,Count); end; end; function ParseStructUnionDefinition(const IsStruct:boolean;var StructFields:TPACCStructFields):PPACCType; function ParseStructFields(const IsStruct:boolean):TPACCStructFields; var BaseType,FieldType:PPACCType; Index,Count:TPACCInt; Name:TPACCRawByteString; Fields:TPACCStructFields; Attribute:TPACCAttribute; begin result:=nil; if CurrentState.Token^.TokenType=TOK_LBRA then begin Fields:=nil; Count:=0; try NextToken; repeat if CurrentState.Token^.TokenType=TOK_STATIC_ASSERT then begin NextToken; ParseStaticAssert; end else begin if IsType(CurrentState.Token) then begin Attribute:=PACCEmptyAttribute; BaseType:=ParseDeclaratorSpecifier(nil,Attribute); BaseType.Attribute:=Attribute; if Attribute.Alignment>=0 then begin BaseType.Alignment:=Attribute.Alignment; end; if (BaseType^.Kind=tkSTRUCT) and (CurrentState.Token^.TokenType=TOK_SEMICOLON) then begin Index:=Count; inc(Count); if length(Fields)<Count then begin SetLength(Fields,Count*2); end; Fields[Index].Name:=''; Fields[Index].Type_:=BaseType; end else begin repeat Name:=''; FieldType:=ParseDeclarator(Name,BaseType,nil,DECL_PARAM_TYPEONLY); EnsureNotVoid(FieldType); FieldType:=TPACCInstance(Instance).CopyType(FieldType); if CurrentState.Token^.TokenType=TOK_COLON then begin NextToken; FieldType^.BitSize:=ParseBitSize(Name,FieldType); end else begin FieldType^.BitSize:=-1; end; Index:=Count; inc(Count); if length(Fields)<Count then begin SetLength(Fields,Count*2); end; Fields[Index].Name:=Name; Fields[Index].Type_:=FieldType; case CurrentState.Token^.TokenType of TOK_COMMA:begin NextToken; end; TOK_RBRA:begin AddWarning('Missing '';'' at the end of field list'); break; end; else begin Expect(TOK_SEMICOLON); break; end; end; until false; end; end else begin break; end; end; until false; Expect(TOK_RBRA); finally SetLength(Fields,Count); end; if (Count>0) and (Count=length(Fields)) then begin for Index:=0 to Count-1 do begin Name:=Fields[Index].Name; FieldType:=Fields[Index].Type_; if (FieldType^.Kind=tkARRAY) and (FieldType^.ArrayLength<0) then begin if Index<>(Count-1) then begin AddError('Flexible member "'+Name+'" may only appear as the last member',nil,false); end else if Count=1 then begin AddError('Flexible member "'+Name+'" with no other fields',nil,false); end else begin FieldType^.Size:=0; FieldType^.ArrayLength:=0; end; end; end; end; end; result:=Fields; end; var Tag:TPACCRawByteString; begin if CurrentState.Token^.TokenType=TOK_IDENT then begin Tag:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; if length(Tag)>0 then begin result:=TagScope[Tag]; if assigned(result) then begin if ((result^.Kind=tkENUM) or ((tfStruct in result^.Flags)<>IsStruct)) then begin AddError('Declarations of "'+Tag+'" does not match',nil,true); end; end else begin result:=TPACCInstance(Instance).NewStructType(IsStruct); TagScope[Tag]:=result; end; end; NextToken; end else begin result:=TPACCInstance(Instance).NewStructType(IsStruct); end; StructFields:=ParseStructFields(IsStruct); end; procedure FinalizeStructUnion(const Type_:PPACCType;const StructFields:TPACCStructFields); var Alignment:TPACCInt; MaxAlignment:TPACCInt32; Size:TPACCInt64; FinalizedFields:TPACCStructFields; begin Size:=0; Alignment:=1; if afPacked in Type_^.Attribute.Flags then begin MaxAlignment:=1; end else if PragmaPack>0 then begin MaxAlignment:=PragmaPack; end else begin MaxAlignment:=TPACCInstance(Instance).Target.MaximumAlignment; end; if tfStruct in Type_^.Flags then begin FinalizedFields:=UpdateStructOffsets(Size,Alignment,StructFields,MaxAlignment); end else begin FinalizedFields:=UpdateUnionOffsets(Size,Alignment,StructFields,MaxAlignment); end; Type_^.Alignment:=Alignment; if length(FinalizedFields)>0 then begin Type_^.Fields:=FinalizedFields; Type_^.Size:=Size; end; end; function ParseEnumDefinition:PPACCType; var Tag,Name:TPACCRawByteString; Type_:PPACCType; Value:TPACCInt; ConstantValueNode:TPACCAbstractSyntaxTreeNode; RelevantSourceLocation:TPACCSourceLocation; First:boolean; begin First:=true; if CurrentState.Token^.TokenType=TOK_IDENT then begin Tag:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; if length(Tag)>0 then begin Type_:=TagScope[Tag]; if assigned(Type_) and (Type_^.Kind<>tkENUM) then begin AddError('Declarations of "'+Tag+'" does not match',nil,true); end; First:=Type_^.MinValue>Type_^.MaxValue; end; NextToken; end else begin Tag:=''; end; if First then begin Type_^.MinValue:=high(TPACCInt32); Type_^.MaxValue:=low(TPACCInt32); end; if CurrentState.Token^.TokenType=TOK_LBRA then begin if length(Tag)>0 then begin TagScope[Tag]:=TPACCInstance(Instance).TypeENUM; end; Value:=0; repeat if CurrentState.Token^.TokenType=TOK_RBRA then begin NextToken; break; end; if CurrentState.Token^.TokenType=TOK_IDENT then begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; Name:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; NextToken; if CurrentState.Token^.TokenType=TOK_ASSIGN then begin NextToken; Value:=ParseIntegerExpression; end; ConstantValueNode:=TPACCAbstractSyntaxTreeNodeIntegerValue.Create(TPACCInstance(Instance),astnkINTEGER,TPACCInstance(Instance).TypeINT,RelevantSourceLocation,Value); GetScope[Name]:=ConstantValueNode; if First then begin First:=false; Type_^.MinValue:=Value; Type_^.MaxValue:=Value; end else begin Type_^.MinValue:=Min(Type_^.MinValue,Value); Type_^.MaxValue:=Min(Type_^.MaxValue,Value); end; inc(Value); case CurrentState.Token^.TokenType of TOK_COMMA:begin NextToken; end; TOK_RBRA:begin NextToken; break; end; else begin AddError('"}" or "," expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; end; end else begin AddError('Identifier expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; until false; end else begin if (length(Tag)=0) or not assigned(TagScope[Tag]) then begin AddError('enum tag "'+Tag+'" is not defined',nil,true); end; end; result:=TPACCInstance(Instance).TypeINT; end; function ParseAlignAs:TPACCInt32; var Type_:PPACCType; begin // C11 6.7.5. Valid form of _Alignof is either _Alignas(type-name) or _Alignas(constant-expression). Expect(TOK_LPAR); if IsType(CurrentState.Token) then begin Type_:=ParseCastType; result:=Type_^.Alignment; end else begin result:=ParseIntegerExpression; end; Expect(TOK_RPAR); end; function ParseTypeOf:PPACCType; begin Expect(TOK_LPAR); if IsType(CurrentState.Token) then begin result:=ParseCastType; end else begin result:=ParseCommaExpression.Type_; end; Expect(TOK_RPAR); end; const KIND_VOID=1; KIND_BOOL=2; KIND_CHAR=3; KIND_INT=4; KIND_FLOAT=5; KIND_DOUBLE=6; SIZE_SHORT=1; SIZE_LONG=2; SIZE_LONG_LONG=3; SIGNED_SIGNED=1; SIGNED_UNSIGNED=2; var StorageClass,Kind,Size,Signed,Alignment,Value,TemporaryCallingConvention,CallingConvention:TPACCInt32; UserType,Definition:PPACCType; TypeFlags:TPACCTypeFlags; AttributeName:TPACCRawByteString; StructFields:TPACCStructFields; RelevantSourceLocation:TPACCSourceLocation; FromTypeDef:boolean; procedure Error; begin AddError('Type mismatch: '+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType],nil,true); end; procedure ErrorCheck; begin if ((Kind=KIND_BOOL) and (Size<>0) and (Signed<>0)) or ((Size=SIZE_SHORT) and (Kind<>0) and (Kind<>KIND_INT)) or ((Size=SIZE_LONG) and (Kind<>0) and (Kind<>KIND_INT) and (Kind<>KIND_DOUBLE)) or ((Signed<>0) and (Kind in [KIND_VOID,KIND_FLOAT,KIND_DOUBLE])) or (assigned(UserType) and ((Kind<>0) or (Size<>0) or (Signed<>0))) then begin Error; end; end; procedure ParseAttributeOrDeclSpec(const IsDeclSpec:boolean); begin Expect(TOK_LPAR); if not IsDeclSpec then begin Expect(TOK_LPAR); end; while CurrentState.Token^.TokenType<>TOK_RPAR do begin if CurrentState.Token^.TokenType=TOK_IDENT then begin RelevantSourceLocation:=CurrentState.Token^.SourceLocation; AttributeName:=TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name; NextToken; if length(AttributeName)>0 then begin TemporaryCallingConvention:=TPACCInstance(Instance).Target.CheckCallingConvention(AttributeName); if TemporaryCallingConvention>=0 then begin if CallingConvention>=0 then begin AddError('Duplicate calling convention specifier "'+AttributeName+'"',@RelevantSourceLocation,false); end; CallingConvention:=TemporaryCallingConvention; end else begin if (AttributeName='aligned') or (AttributeName='__aligned__') then begin if CurrentState.Token^.TokenType=TOK_LPAR then begin Expect(TOK_LPAR); Value:=ParseIntegerExpression; if Value<0 then begin AddError('Negative alignment: '+IntToStr(Value),nil,false); end else begin // C11 6.7.5p6: alignas(0) should have no effect. if (Value>0) and ((Alignment<0) or (Value<Alignment)) then begin Alignment:=Value; end; end; Expect(TOK_RPAR); end else begin Value:=TPACCInstance(Instance).Target.MaximumAlignment; if (Value>0) and ((Alignment<0) or (Value<Alignment)) then begin Alignment:=Value; end; end; end else begin AddWarning('Unknown attribute specifier "'+AttributeName+'", ignoring',@RelevantSourceLocation); if CurrentState.Token^.TokenType=TOK_LPAR then begin SkipParentheses; end; end; end; end else if (AttributeName='packed') or (AttributeName='__packed__') then begin Include(Attribute.Flags,afPacked); end else if (AttributeName='noinline') or (AttributeName='__noinline__') then begin Include(Attribute.Flags,afNoInline); end else if (AttributeName='noreturn') or (AttributeName='__noreturn__') then begin Include(Attribute.Flags,afNoReturn); end else if (AttributeName='const') or (AttributeName='__const__') then begin Include(Attribute.Flags,afConstant); end else if (AttributeName='volatile') or (AttributeName='__volatile__') then begin Include(Attribute.Flags,afVolatile); end else if (AttributeName='restrict') or (AttributeName='__restrict__') then begin Include(Attribute.Flags,afRestrict); end else begin AddError('Attribute name expect',@CurrentState.Token^.SourceLocation,true); end; end else begin AddError('Attribute name expect',@CurrentState.Token^.SourceLocation,true); end; case CurrentState.Token^.TokenType of TOK_COMMA:begin NextToken; end; TOK_RPAR:begin break; end; else begin AddError('")" or "," expected',@CurrentState.Token^.SourceLocation,true); end; end; end; if not IsDeclSpec then begin Expect(TOK_RPAR); end; Expect(TOK_RPAR); end; begin result:=nil; StorageClass:=0; TypeFlags:=[]; if IsType(CurrentState.Token) then begin UserType:=nil; Kind:=0; Size:=0; Signed:=0; Alignment:=-1; CallingConvention:=-1; StructFields:=nil; FromTypeDef:=false; repeat if CurrentState.Token^.TokenType=TOK_EOF then begin AddError('Premature end of input',nil,true); end; if (Kind=0) and (CurrentState.Token^.TokenType=TOK_IDENT) and not assigned(UserType) then begin Definition:=GetTypeDef(TPACCInstance(Instance).TokenSymbols[CurrentState.Token^.Index].Name); if assigned(Definition) then begin NextToken; if assigned(UserType) then begin Error; end else begin UserType:=Definition; ErrorCheck; FromTypeDef:=true; end; end; end; if not (CurrentState.Token^.TokenType in KeywordTokens) then begin break; end; case CurrentState.Token^.TokenType of TOK_TYPEDEF:begin if StorageClass<>0 then begin Error; end; StorageClass:=S_TYPEDEF; NextToken; end; TOK_EXTERN:begin if StorageClass<>0 then begin Error; end; StorageClass:=S_EXTERN; NextToken; end; TOK_STATIC:begin if StorageClass<>0 then begin Error; end; StorageClass:=S_STATIC; NextToken; end; TOK_AUTO:begin if StorageClass<>0 then begin Error; end; StorageClass:=S_AUTO; NextToken; end; TOK_REGISTER:begin if StorageClass<>0 then begin Error; end; StorageClass:=S_REGISTER; NextToken; end; TOK_CONST:begin NextToken; Include(Attribute.Flags,afConstant); end; TOK_VOLATILE:begin NextToken; Include(Attribute.Flags,afVolatile); end; TOK_RESTRICT:begin NextToken; Include(Attribute.Flags,afRestrict); end; TOK_INLINE:begin NextToken; Include(Attribute.Flags,afInline); end; TOK_NORETURN:begin NextToken; Include(Attribute.Flags,afNoReturn); end; TOK_VOID:begin if Kind<>0 then begin Error; end; Kind:=KIND_VOID; NextToken; end; TOK_BOOL:begin if Kind<>0 then begin Error; end; Kind:=KIND_BOOL; NextToken; end; TOK_CHAR:begin if Kind<>0 then begin Error; end; Kind:=KIND_CHAR; NextToken; end; TOK_INT:begin if Kind<>0 then begin Error; end; Kind:=KIND_INT; NextToken; end; TOK_FLOAT:begin if Kind<>0 then begin Error; end; Kind:=KIND_FLOAT; NextToken; end; TOK_DOUBLE:begin if Kind<>0 then begin Error; end; Kind:=KIND_DOUBLE; NextToken; end; TOK_SIGNED1,TOK_SIGNED2,TOK_SIGNED3:begin if Signed<>0 then begin Error; end; Signed:=SIGNED_SIGNED; NextToken; end; TOK_UNSIGNED:begin if Signed<>0 then begin Error; end; Signed:=SIGNED_UNSIGNED; NextToken; end; TOK_SHORT:begin if Size<>0 then begin Error; end; Size:=SIZE_SHORT; NextToken; end; TOK_STRUCT:begin if assigned(UserType) then begin Error; end; NextToken; UserType:=ParseStructUnionDefinition(true,StructFields); end; TOK_UNION:begin if assigned(UserType) then begin Error; end; NextToken; UserType:=ParseStructUnionDefinition(false,StructFields); end; TOK_ENUM:begin if assigned(UserType) then begin Error; end; NextToken; UserType:=ParseEnumDefinition; end; TOK_ALIGNAS:begin NextToken; Value:=ParseAlignAs; if Value<0 then begin AddError('Negative alignment: '+IntToStr(Value),nil,false); end else begin // C11 6.7.5p6: alignas(0) should have no effect. if (Value>0) and ((Alignment<0) or (Value<Alignment)) then begin Alignment:=Value; end; end; end; TOK_LONG:begin if Size<>0 then begin Error; end; Size:=SIZE_LONG; NextToken; end; TOK_TYPEOF:begin if assigned(UserType) then begin Error; end; NextToken; UserType:=ParseTypeOf; FromTypeDef:=true; end; TOK_ATTRIBUTE:begin NextToken; ParseAttributeOrDeclSpec(false); end; TOK_DECLSPEC:begin NextToken; ParseAttributeOrDeclSpec(true); end; else begin break; end; end; ErrorCheck; until false; if assigned(ResultStorageClass) then begin ResultStorageClass^:=StorageClass; end; if assigned(UserType) then begin if FromTypeDef then begin if TypeFlags<>[] then begin result:=TPACCInstance(Instance).CopyType(UserType); result^.Flags:=result^.Flags+TypeFlags; if afPacked in Attribute.Flags then begin Attribute.Alignment:=1; end; end else begin result:=UserType; end; end else begin result:=UserType; result^.Flags:=result^.Flags+TypeFlags; case result^.Kind of tkSTRUCT:begin FinalizeStructUnion(result,StructFields); if afPacked in Attribute.Flags then begin Attribute.Alignment:=1; end; end; tkENUM:begin if afPacked in Attribute.Flags then begin Exclude(Attribute.Flags,afPacked); if (result^.MinValue>=low(TPACCInt8)) and (result^.MaxValue<=high(TPACCInt8)) then begin result:=TPACCInstance(Instance).TypeCHAR; end else if (result^.MinValue>=low(TPACCInt16)) and (result^.MaxValue<=high(TPACCInt16)) then begin result:=TPACCInstance(Instance).TypeSHORT; end else begin result:=TPACCInstance(Instance).TypeINT; end; end; end; else begin if afPacked in Attribute.Flags then begin Attribute.Alignment:=1; end; end; end; end; end else begin if (Alignment>=0) and ((Alignment and (Alignment-1))<>0) then begin AddError('Alignment must be power of 2, but got '+IntToStr(Alignment),nil,false); end; case Kind of KIND_VOID:begin result:=TPACCInstance(Instance).TypeVOID; end; KIND_BOOL:begin result:=TPACCInstance(Instance).NewNumbericType(tkBOOL,false); end; KIND_CHAR:begin result:=TPACCInstance(Instance).NewNumbericType(tkCHAR,Signed=SIGNED_UNSIGNED); end; KIND_FLOAT:begin result:=TPACCInstance(Instance).NewNumbericType(tkFLOAT,false); end; KIND_DOUBLE:begin if Size=SIZE_LONG then begin result:=TPACCInstance(Instance).NewNumbericType(tkLDOUBLE,false); end else begin result:=TPACCInstance(Instance).NewNumbericType(tkDOUBLE,false); end; end; end; if not assigned(result) then begin case Size of SIZE_SHORT:begin result:=TPACCInstance(Instance).NewNumbericType(tkSHORT,Signed=SIGNED_UNSIGNED); end; SIZE_LONG:begin result:=TPACCInstance(Instance).NewNumbericType(tkLONG,Signed=SIGNED_UNSIGNED); end; SIZE_LONG_LONG:begin result:=TPACCInstance(Instance).NewNumbericType(tkLLONG,Signed=SIGNED_UNSIGNED); end; else begin result:=TPACCInstance(Instance).NewNumbericType(tkINT,Signed=SIGNED_UNSIGNED); end; end; if not assigned(result) then begin AddError('Internal error: 2016-12-31-21-58-0000',nil,true); end; end; if afPacked in Attribute.Flags then begin Attribute.Alignment:=1; end else if Alignment>=0 then begin Attribute.Alignment:=Alignment; end; result^.Flags:=result^.Flags+TypeFlags; end; if CallingConvention>=0 then begin if Attribute.CallingConvention<0 then begin Attribute.CallingConvention:=CallingConvention; end else begin AddError('Calling convention already defined',nil,false); end; end; end else begin AddError('Type name expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; end; function ParseDeclaratorWithOptionalSpecifier(StorageClass:PPACCInt32;var Attribute:TPACCAttribute):PPACCType; begin if IsType(CurrentState.Token) then begin result:=ParseDeclaratorSpecifier(StorageClass,Attribute); end else begin AddWarning('Type specifier missing, assuming int'); result:=TPACCInstance(Instance).TypeINT; end; end; procedure ParseDeclaration(const Block:TPACCAbstractSyntaxTreeNodeList;const IsGlobal,IsTop:boolean); procedure ParseOldstyleParameterTypes(const Parameters:TPACCAbstractSyntaxTreeNodeList); var Index,OtherIndex:TPACCInt32; OriginalLocalScope:TPACCRawByteStringHashMap; ParameterVariables:TPACCAbstractSyntaxTreeNodeList; Declaration,Variable,Parameter:TPACCAbstractSyntaxTreeNode; Found:boolean; begin ParameterVariables:=TPACCAbstractSyntaxTreeNodeList.Create; try OriginalLocalScope:=LocalScope; try LocalScope:=nil; repeat if CurrentState.Token^.TokenType=TOK_LBRA then begin break; end else if not IsType(CurrentState.Token) then begin AddError('K&R-style declarator expected, but got "'+TPACCLexer(TPACCInstance(Instance).Lexer).TokenStrings[CurrentState.Token^.TokenType]+'"',nil,true); end; ParseDeclaration(ParameterVariables,false,false); until false; finally LocalScope:=OriginalLocalScope; end; for Index:=0 to ParameterVariables.Count-1 do begin Declaration:=ParameterVariables[Index]; if assigned(Declaration) and (Declaration.Kind=astnkDECL) then begin Variable:=TPACCAbstractSyntaxTreeNodeDeclaration(Declaration).DeclarationVariable; if assigned(Variable) and (Variable.Kind=astnkLVAR) then begin Found:=false; for OtherIndex:=0 to Parameters.Count-1 do begin Parameter:=Parameters[OtherIndex]; if assigned(Parameter) and (Parameter.Kind=astnkLVAR) then begin if TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Parameter).VariableName=TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Variable).VariableName then begin Parameter.Type_:=Variable.Type_; Found:=true; break; end; end else begin AddError('Internal error 2017-01-01-17-17-0000',nil,true); end; end; if not Found then begin AddError('Missing parameter: '+TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Variable).VariableName,nil,false); end; end else begin AddError('Internal error 2017-01-01-17-15-0000',nil,true); end; end else begin AddError('Internal error 2017-01-01-17-14-0000',nil,true); end; end; finally for Index:=0 to ParameterVariables.Count-1 do begin ParameterVariables[Index].Free; ParameterVariables[Index]:=nil; end; ParameterVariables.Free; end; end; procedure BackfillLabels; var Index:longint; Node,LabelNode:TPACCAbstractSyntaxTreeNode; begin for Index:=0 to UnresolvedLabelUsedNodes.Count-1 do begin Node:=UnresolvedLabelUsedNodes[Index]; if Node is TPACCAbstractSyntaxTreeNodeGOTOStatementOrLabelAddress then begin LabelNode:=LabelScope[TPACCAbstractSyntaxTreeNodeGOTOStatementOrLabelAddress(Node).LabelName]; if assigned(LabelNode) and (LabelNode is TPACCAbstractSyntaxTreeNodeLabel) then begin TPACCAbstractSyntaxTreeNodeGOTOStatementOrLabelAddress(Node).Label_:=TPACCAbstractSyntaxTreeNodeLabel(LabelNode); end else begin if Node.Kind=astnkGOTO then begin AddError('Invalid GOTO label: '+TPACCAbstractSyntaxTreeNodeGOTOStatementOrLabelAddress(Node).LabelName,@Node.SourceLocation,false); end else begin AddError('Invalid unary && label: '+TPACCAbstractSyntaxTreeNodeGOTOStatementOrLabelAddress(Node).LabelName,@Node.SourceLocation,false); end; end; end else begin AddError('Internal error 2017-01-07-21-02-0000',@Node.SourceLocation,true); end; end; end; var StorageClass,Index:TPACCInt32; BaseType,CurrentType:PPACCType; Name:TPACCRawByteString; Variable:TPACCAbstractSyntaxTreeNodeLocalGlobalVariable; OriginalLocalScope,OtherOriginalLocalScope:TPACCRawByteStringHashMap; InitializationList:TPACCAbstractSyntaxTreeNodeList; Parameters:TPACCAbstractSyntaxTreeNodeList; FunctionName,FunctionBody,Parameter:TPACCAbstractSyntaxTreeNode; First:boolean; RelevantSourceLocation:TPACCSourceLocation; Attribute:TPACCAttribute; begin if CurrentState.Token^.TokenType=TOK_SEMICOLON then begin NextToken; end else begin StorageClass:=0; Attribute:=PACCEmptyAttribute; Parameters:=nil; RelevantSourceLocation:=CurrentState.Token^.SourceLocation; BaseType:=ParseDeclaratorWithOptionalSpecifier(@StorageClass,Attribute); if CurrentState.Token^.TokenType=TOK_SEMICOLON then begin NextToken; end else begin First:=true; try repeat RelevantSourceLocation:=CurrentState.Token^.SourceLocation; Name:=''; if IsTop and First then begin Parameters:=TPACCAbstractSyntaxTreeNodeList.Create; end else begin Parameters:=nil; end; First:=false; CurrentType:=ParseDeclarator(Name,TPACCInstance(Instance).CopyIncompleteType(BaseType),Parameters,DECL_BODY); if assigned(Parameters) and assigned(CurrentType) and ((CurrentState.Token^.TokenType=TOK_LBRA) or IsType(CurrentState.Token)) then begin // Function definition TPACCInstance(Instance).AllocatedObjects.Add(Parameters); if tfOldStyle in CurrentType^.Flags then begin if (not assigned(Parameters)) or (Parameters.Count=0) then begin Exclude(CurrentType^.Flags,tfVarArgs); end; ParseOldstyleParameterTypes(Parameters); CurrentType^.Parameters:=nil; SetLength(CurrentType^.Parameters,Parameters.Count); for Index:=0 to Parameters.Count-1 do begin CurrentType^.Parameters[Index]:=Parameters[Index].Type_; end; end; if StorageClass=S_STATIC then begin Include(CurrentType^.Flags,tfStatic); end else begin Exclude(CurrentType^.Flags,tfStatic); end; CurrentType^.Attribute:=Attribute; Variable:=TPACCAbstractSyntaxTreeNodeLocalGlobalVariable.Create(TPACCInstance(Instance),astnkGVAR,CurrentType,RelevantSourceLocation,Name,0); Assert(assigned(GlobalScope)); GlobalScope[Name]:=Variable; OriginalLocalScope:=LocalScope; try Expect(TOK_LBRA); LabelScope:=TPACCRawByteStringHashMap.Create; try UnresolvedLabelUsedNodes:=TPACCAbstractSyntaxTreeNodeList.Create; try LocalScope:=TPACCRawByteStringHashMap.Create; LocalScope.Parent:=GlobalScope; CurrentFunctionType:=CurrentType; OtherOriginalLocalScope:=LocalScope; try LocalScope:=TPACCRawByteStringHashMap.Create; LocalScope.Parent:=OtherOriginalLocalScope; FunctionName:=NewASTString(CurrentState.Token^.SourceLocation,ENCODING_NONE,Name); LocalScope['__func__']:=FunctionName; LocalScope['__FUNCTION__']:=FunctionName; LocalVariables:=TPACCAbstractSyntaxTreeNodeList.Create; TPACCInstance(Instance).AllocatedObjects.Add(LocalVariables); Labels:=TPACCAbstractSyntaxTreeNodeList.Create; TPACCInstance(Instance).AllocatedObjects.Add(Labels); for Index:=0 to Parameters.Count-1 do begin Parameter:=Parameters[Index]; if assigned(Parameter) and (Parameter.Kind=astnkLVAR) then begin if length(TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Parameter).VariableName)>0 then begin LocalScope[TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Parameter).VariableName]:=Parameter; end; if assigned(LocalVariables) then begin TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Parameter).Index:=LocalVariables.Add(Parameter); end else begin TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Parameter).Index:=-1; end; end; end; FunctionBody:=TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration.Create(TPACCInstance(Instance),astnkFUNC,CurrentType,RelevantSourceLocation,Name,nil,nil,nil); AddFunctionNameVariable(Name,FunctionBody,Variable); TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionBody).Parameters:=Parameters; TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionBody).LocalVariables:=LocalVariables; TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionBody).Labels:=Labels; TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionBody).Variable:=Variable; TPACCAbstractSyntaxTreeNodeFunctionCallOrFunctionDeclaration(FunctionBody).Body:=ParseCompoundStatement; Parameters:=nil; finally CurrentFunctionType:=nil; FreeAndNil(LocalScope); LocalScope:=OtherOriginalLocalScope; LocalVariables:=nil; Labels:=nil; end; Block.Add(FunctionBody); BackfillLabels; finally FreeAndNil(UnresolvedLabelUsedNodes); end; finally FreeAndNil(LabelScope); end; finally FreeAndNil(LocalScope); LocalScope:=OriginalLocalScope; end; break; end else begin // Definition FreeAndNil(Parameters); if StorageClass=S_STATIC then begin Include(CurrentType^.Flags,tfStatic); end else begin Exclude(CurrentType^.Flags,tfStatic); end; if StorageClass=S_TYPEDEF then begin GetScope[Name]:=TPACCAbstractSyntaxTreeNode.Create(TPACCInstance(Instance),astnkTYPEDEF,CurrentType,RelevantSourceLocation); end else if (tfStatic in CurrentType^.Flags) and not IsGlobal then begin EnsureNotVoid(CurrentType); // Local static Variable:=TPACCAbstractSyntaxTreeNodeLocalGlobalVariable.Create(TPACCInstance(Instance),astnkGVAR,CurrentType,RelevantSourceLocation,Name,0); Assert(assigned(LocalScope)); LocalScope[Name]:=Variable; InitializationList:=nil; if CurrentState.Token^.TokenType=TOK_ASSIGN then begin NextToken; OriginalLocalScope:=LocalScope; try LocalScope:=nil; try InitializationList:=ParseDeclarationInitializer(CurrentType); finally LocalScope.Free; end; finally LocalScope:=OriginalLocalScope; end; end; Root.Children.Add(TPACCAbstractSyntaxTreeNodeDeclaration.Create(TPACCInstance(Instance),astnkDECL,nil,RelevantSourceLocation,Variable,InitializationList)); end else begin EnsureNotVoid(CurrentType); if IsGlobal then begin Variable:=TPACCAbstractSyntaxTreeNodeLocalGlobalVariable.Create(TPACCInstance(Instance),astnkGVAR,CurrentType,RelevantSourceLocation,Name,0); Assert(assigned(GlobalScope)); GlobalScope[Name]:=Variable; end else begin Variable:=TPACCAbstractSyntaxTreeNodeLocalGlobalVariable.Create(TPACCInstance(Instance),astnkLVAR,CurrentType,RelevantSourceLocation,Name,0); Assert(assigned(LocalScope)); LocalScope[Name]:=Variable; if assigned(LocalVariables) then begin TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Variable).Index:=LocalVariables.Add(Variable); end else begin TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Variable).Index:=-1; end; TPACCAbstractSyntaxTreeNodeLocalGlobalVariable(Variable).MustOnStack:=not (TPACCInstance(Instance).IsArithmeticType(CurrentType) or (CurrentType^.Kind=tkPOINTER)); end; if CurrentState.Token^.TokenType=TOK_ASSIGN then begin NextToken; Block.Add(TPACCAbstractSyntaxTreeNodeDeclaration.Create(TPACCInstance(Instance),astnkDECL,nil,RelevantSourceLocation,Variable,ParseDeclarationInitializer(CurrentType))); end else if (StorageClass<>S_EXTERN) and (CurrentType^.Kind<>tkFUNCTION) then begin Block.Add(TPACCAbstractSyntaxTreeNodeDeclaration.Create(TPACCInstance(Instance),astnkDECL,nil,RelevantSourceLocation,Variable,nil)); end else if IsGlobal then begin Block.Add(TPACCAbstractSyntaxTreeNodeDeclaration.Create(TPACCInstance(Instance),astnkEXTERN_DECL,nil,RelevantSourceLocation,Variable,nil)); end else begin AddError('Internal error 2017-01-18-04-38-0000',nil,true); end; end; case CurrentState.Token^.TokenType of TOK_SEMICOLON:begin NextToken; break; end; TOK_COMMA:begin NextToken; continue; end; else begin AddError(''';'' or '','' expected',nil,true); end; end; end; until false; finally Parameters:=nil; end; end; end; end; begin if Lexer.CountTokens>0 then begin FunctionNameScope:=TPACCRawByteStringHashMap.Create; GlobalScope:=TPACCRawByteStringHashMap.Create; LocalScope:=nil; TagScope:=TPACCRawByteStringHashMap.Create; LabelScope:=nil; LocalVariables:=nil; Labels:=nil; UnresolvedLabelUsedNodes:=nil; Cases.Ready:=false; Cases.Cases:=nil; Cases.Count:=0; Cases.DefaultCaseLabel:=nil; CurrentFunctionType:=nil; BreakLabel:=nil; ContinueLabel:=nil; PragmaPack:=-1; PragmaPackStack:=nil; PragmaPackStackPointer:=0; try CurrentState.IsEOF:=false; CurrentState.TokenIndex:=-1; NextToken; FreeAndNil(Root); try Root:=TPACCAbstractSyntaxTreeNodeTranslationUnit.Create(TPACCInstance(Instance),astnkTRANSLATIONUNIT,nil,CurrentState.Token^.SourceLocation); while CurrentState.Token^.TokenType<>TOK_EOF do begin case CurrentState.Token^.TokenType of TOK_ASM:begin NextToken; Root.Children.Add(ParseAssemblerStatement(true)); end; else begin ParseDeclaration(Root.Children,true,true); end; end; end; except FreeAndNil(Root); Root:=TPACCAbstractSyntaxTreeNodeTranslationUnit.Create(TPACCInstance(Instance),astnkTRANSLATIONUNIT,nil,TPACCInstance(Instance).SourceLocation); raise; end; finally PragmaPackStack:=nil; LabelScope.Free; TagScope.Free; LocalScope.Free; GlobalScope.Free; LocalVariables.Free; Labels.Free; UnresolvedLabelUsedNodes.Free; FunctionNameScope.Free; Finalize(Cases); end; end; end; end.