代码拉取完成,页面将自动刷新
////////////////////////////////////////////////////////////////////////////////
// 主窗口单元
unit Main;
interface
uses
Windows, SysUtils, Classes, Graphics, Forms, Controls, Menus,
StdCtrls, Dialogs, Buttons, Messages, ExtCtrls, ComCtrls, StdActns,
ActnList, ToolWin, ImgList, Contnrs, jpeg, AppEvnts,
Setting, Category, PythonEngine, WrapDelphi, PythonGUIInputOutput, XPMan;
const
{ 界面文字 }
t_ProductName = '游戏数据编辑器';
t_SoftwareName = 'GameEditor';
t_Version = '1.2 r1';
t_BuildDate = '120321';
t_Company = '浙江凯迅信息技术有限公司';
t_Copyright = '版权所有 (C) 2008-2012 凯迅科技';
t_Website = 'http://www.kaixungame.com';
t_Programmers = '陈涛 12501566@qq.com'#10 +
' fictiony@china.com';
{ 非类目分页标识 }
CATALOG_MANAGE = -1; //类目管理
CATALOG_SETTING = -2; //类目设置
DATABASE_MANAGE = -3; //数据库管理
ACCOUNT_MANAGE = -4; //用户权限管理
PYTHON_TEST = -5; //脚本测试
type
{ 子窗口动作:关闭、激活、更新类目设置、重置类目列表、断开数据库连接 }
TPageAction = (paClose, paActive, paUpdate, paReset, paDisconnect);
{ 主窗口类 }
TMainForm = class(TForm)
MainMenu: TMainMenu;
MIUser: TMenuItem;
MIWindow: TMenuItem;
MIHelp: TMenuItem;
N1: TMenuItem;
MIUserExit: TMenuItem;
MIWindowCascade: TMenuItem;
MIWindowTileHorizontal: TMenuItem;
MIWindowArrangeAll: TMenuItem;
MIHelpAbout: TMenuItem;
MIWindowMinimizeAll: TMenuItem;
StatusBar: TStatusBar;
MainActions: TActionList;
ACUserExit: TAction;
ACWindowCascade: TWindowCascade;
ACWindowTileHorizontal: TWindowTileHorizontal;
ACWindowArrangeAll: TWindowArrange;
ACWindowMinimizeAll: TWindowMinimizeAll;
ACHelpAbout: TAction;
ACWindowTileVertical: TWindowTileVertical;
MIWindowTileVertical: TMenuItem;
CommonToolBar: TToolBar;
T3: TToolButton;
LargeIcons: TImageList;
SmallIcons: TImageList;
TBHelpAbout: TToolButton;
CategorySmallIcons: TImageList;
CategoryLargeIcons: TImageList;
MICategory: TMenuItem;
CategoryBtnScroller: TPageScroller;
PageTabPanel: TPanel;
PageTabBar: TTabControl;
CategoryToolBar: TToolBar;
ACWindowCloseAll: TAction;
MIWindowCloseAll: TMenuItem;
MIConfig: TMenuItem;
ACConfigCategoryManage: TAction;
ACConfigCategorySetting: TAction;
MIConfigCategoryManage: TMenuItem;
MIConfigCategorySetting: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
ACWindowLast: TAction;
MIWindowLast: TMenuItem;
TBConfigCategorySetting: TToolButton;
PageTabMenu: TPopupMenu;
ACWindowClose: TAction;
MIPageCloseAll: TMenuItem;
N4: TMenuItem;
MIPageTileVertical: TMenuItem;
MIPageClose: TMenuItem;
N5: TMenuItem;
MIWindowClose: TMenuItem;
MIPageCategorySetting: TMenuItem;
PagePanelMenu: TPopupMenu;
N11: TMenuItem;
MIPageTileVertical2: TMenuItem;
MIPageCloseAll2: TMenuItem;
MIPageCascade: TMenuItem;
MIPageTileHorizontal: TMenuItem;
MIPageArrangeAll: TMenuItem;
MIPageMinimizeAll: TMenuItem;
ACConfigAccountManage: TAction;
MIConfigAccountManage: TMenuItem;
ACConfigSuperAdminPwd: TAction;
MIConfigSuperAdminPwd: TMenuItem;
AppEvents: TApplicationEvents;
PYE: TPythonEngine;
PYM: TPythonModule;
PYW: TPyDelphiWrapper;
ACHelpPythonTest: TAction;
TBHelpPythonTest: TToolButton;
MIHelpPythonTest: TMenuItem;
N6: TMenuItem;
PYO: TPythonGUIInputOutput;
ACWindowSwitch1: TAction;
ACWindowSwitch2: TAction;
ACWindowSwitch3: TAction;
ACWindowSwitch4: TAction;
ACWindowSwitch5: TAction;
ACUserLogin: TAction;
TBUserLogin: TToolButton;
ToolButton2: TToolButton;
N7: TMenuItem;
MIUserLogin: TMenuItem;
T1: TToolButton;
N8: TMenuItem;
ACUserSetPassword: TAction;
MIUserSetPassword: TMenuItem;
ACUserLogout: TAction;
MIUserLogout: TMenuItem;
PYFunc: TPythonModule;
ACUserReconnect: TAction;
MIUserReconnect: TMenuItem;
ACConfigDatabaseManage: TAction;
MIConfigDatabaseManage: TMenuItem;
N9: TMenuItem;
ACConfigDatabaseSelect: TAction;
MIConfigDatabaseSelect: TMenuItem;
ACUserCustomBackImage: TAction;
MIUserCustomBackImage: TMenuItem;
ACUserOriginBackImage: TAction;
MIUserOriginBackImage: TMenuItem;
BrowseBackImageDialog: TOpenDialog;
MainToolBar: TPanel;
CategoryAssortToolBar: TToolBar;
TBSelectAssort: TSpeedButton;
AssortMenu: TPopupMenu;
ACSelectAssort: TAction;
ACShowAllCategories: TAction;
MIShowAllCategories: TMenuItem;
N10: TMenuItem;
N12: TMenuItem;
N13: TMenuItem;
ACAddToFavorites: TAction;
ACRemoveFromFavorites: TAction;
MIPageAddToFavorites: TMenuItem;
MIPageRemoveFromFavorites: TMenuItem;
ACShowFavorites: TAction;
MIShowFavorites: TMenuItem;
procedure ACHelpAboutExecute(Sender: TObject);
procedure ACUserExitExecute(Sender: TObject);
procedure PageTabBarGetImageIndex(Sender: TObject; TabIndex: Integer;
var ImageIndex: Integer);
procedure CategoryBtnScrollerScroll(Sender: TObject; Shift: TShiftState;
X, Y: Integer; Orientation: TPageScrollerOrientation;
var Delta: Integer);
procedure FormCreate(Sender: TObject);
procedure ACWindowCloseAllExecute(Sender: TObject);
procedure ACWindowCloseAllUpdate(Sender: TObject);
procedure ACWindowLastExecute(Sender: TObject);
procedure ACWindowLastUpdate(Sender: TObject);
procedure ACConfigCategoryManageExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure PageTabBarChange(Sender: TObject);
procedure PageTabBarStartDrag(Sender: TObject;
var DragObject: TDragObject);
procedure PageTabBarEndDrag(Sender, Target: TObject; X, Y: Integer);
procedure PageTabBarDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure PageTabBarMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ACWindowCloseExecute(Sender: TObject);
procedure ACConfigCategorySettingUpdate(Sender: TObject);
procedure ACConfigCategorySettingExecute(Sender: TObject);
procedure ACConfigAccountManageExecute(Sender: TObject);
procedure ACSetPwdExecute(Sender: TObject);
procedure AppEventsHint(Sender: TObject);
procedure ACHelpPythonTestExecute(Sender: TObject);
procedure ACWindowSwitchExecute(Sender: TObject);
procedure ACSuperAdminLevelUpdate(Sender: TObject);
procedure ACAdminLevelUpdate(Sender: TObject);
procedure ACUserLoginExecute(Sender: TObject);
procedure ACUserSetPasswordUpdate(Sender: TObject);
procedure ACOperatorLevelUpdate(Sender: TObject);
procedure ACUserLogoutExecute(Sender: TObject);
procedure PYFuncInitialization(Sender: TObject);
procedure ACUserReconnectExecute(Sender: TObject);
procedure ACUserReconnectUpdate(Sender: TObject);
procedure ACConfigDatabaseManageExecute(Sender: TObject);
procedure ACDBAvailableUpdate(Sender: TObject);
procedure ACConfigDatabaseSelectExecute(Sender: TObject);
procedure ACConfigDatabaseSelectUpdate(Sender: TObject);
procedure ACUserCustomBackImageExecute(Sender: TObject);
procedure ACUserOriginBackImageExecute(Sender: TObject);
procedure ACSelectAssortExecute(Sender: TObject);
procedure ACShowAssortExecute(Sender: TObject);
procedure ACAddToFavoritesExecute(Sender: TObject);
procedure ACAddToFavoritesUpdate(Sender: TObject);
procedure ACRemoveFromFavoritesExecute(Sender: TObject);
procedure ACRemoveFromFavoritesUpdate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
protected
_PageList: TObjectList; //已打开的分页列表(每项为一个分页窗口引用)
_Account: String; //当前账户名(空表示尚未登录)
_OperLevel: TOperateLevel; //当前操作权限级别
_BackImage: String; //当前背景图文件名
_Favorites: TStringList; //账户类目收藏夹列表
_Authorities: TStringList; //账户权限缓存列表
//刷新类目列表
procedure _RefreshCategoryList(Clear: Boolean = False; Favorites: TStrings = nil);
//刷新工具栏按钮
procedure _RefreshToolBarBtns(Sender: TObject);
//打开类目分页
procedure _OpenCategoryPage(Sender: TObject);
//刷新状态栏数据库显示
procedure _RefreshDBStatus;
//刷新状态栏操作权限显示
procedure _RefreshOperLevelStatus;
//检验操作权限级别
function _CheckOperLevel(LeastLevel: TOperateLevel = olOperator): Boolean;
//选择指定数据库
procedure _SelectDatabase(Index: Integer = -1);
//设置背景图
procedure _SetBackImage(FileName: String = '');
//更新类目收藏夹列表
procedure _UpdateFavorites;
//Python接口方法
function Wrap_StringsObjectAsInt(PSelf, Args: PPyObject): PPyObject; cdecl;
function Wrap_GetCanvas(PSelf, Args: PPyObject): PPyObject; cdecl;
function Wrap_ShowProgress(PSelf, Args: PPyObject): PPyObject; cdecl;
function Wrap_CloseProgress(PSelf, Args: PPyObject): PPyObject; cdecl;
function Wrap_LoadPicture(PSelf, Args: PPyObject): PPyObject; cdecl;
function Wrap_DrawPicture(PSelf, Args: PPyObject): PPyObject; cdecl;
function Wrap_CachePicture(PSelf, Args: PPyObject): PPyObject; cdecl;
function Wrap_ClearPictureCache(PSelf, Args: PPyObject): PPyObject; cdecl;
function Wrap_GetCategoryNames(PSelf, Args: PPyObject): PPyObject; cdecl;
public
//当前账户名(只读)
property Account: String read _Account;
//当前操作权限级别(只读)
property OperLevel: TOperateLevel read _OperLevel;
//分页窗口动作处理
procedure PageActionDeal(Child: TForm; Action: TPageAction);
//创建分页子窗口
procedure CreatePageWindow(Index: Integer; Category: TCategoryItem = nil);
//检验类目设置信息
function VerifyCategorySetting(Category: TCategoryItem): Boolean;
//获取类目操作权限
function GetCategoryAuthority(Category: TCategoryItem): TAuthorityLevel;
//载入脚本文件
function LoadScriptFile(FileName: String): String; overload;
function LoadScriptFile(FileName, Args: String; Return: String = ''): PPyObject; overload;
//调用脚本
function CallScript(Script, Input: PPyObject; NoReturn: Boolean = False): PPyObject;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
Math, ShellAPI, StrUtils, WrapDelphiVCL, WrapDelphiTypes, WrapDelphiEvents, PyWrap,
ChildWin, About, UIUtils, FileUtils, DatabaseManage, CategoryManage, CategorySetting,
TextInput, OptionsCategory, TreeCategory, CategoryPage, OptionsPage, TreePage,
PythonTest, AccountManage, OperProgress, RecordPropEdit, DatabaseSelect;
////////////////////////////////////////////////////////////////////////////////
// 界面处理
{ 窗体事件 }
procedure TMainForm.FormCreate(Sender: TObject);
begin
Randomize;
_PageList := TObjectList.Create(False);
_Account := '';
_OperLevel := olNone;
_BackImage := '';
_Favorites := TStringList.Create;
_Authorities := TStringList.Create;
//读取配置信息
try
AppSetting.Load(ParamStr(1));
except
MessageBox(Handle, PChar('读取配置信息失败,请检查配置文件内容是否正确!'#10#10 + AppSetting.SettingFile),
'错误', MB_ICONERROR or MB_OK or MB_DEFBUTTON1);
WindowState := wsMinimized;
PostMessage(Handle, WM_CLOSE, 0, 0);
Exit;
end;
//初始化界面
Application.Title := t_ProductName;
Caption := t_ProductName + ' :: ' + t_SoftwareName;
ACHelpAbout.Caption := Format(ACHelpAbout.Caption, [t_SoftwareName]);
PageTabBar.Tabs.Clear;
AppEventsHint(nil);
_RefreshDBStatus;
_RefreshOperLevelStatus;
//刷新类目列表并选择数据库
_RefreshCategoryList(True);
Show;
ACConfigDatabaseSelect.Execute;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
_PageList.Free;
_Favorites.Free;
_Authorities.Free;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
ACWindowCloseAll.Execute;
CanClose := _PageList.Count = 0;
end;
procedure TMainForm.AppEventsHint(Sender: TObject);
begin
with StatusBar.Panels[2] do
if Application.Hint = '' then
Text := Format(' 欢迎使用%s! (版本 %s - build %s)', [t_ProductName, t_Version, t_BuildDate])
else if AnsiStartsStr('·', Application.Hint) then
Text := Application.Hint
else
Text := ' 工具提示: ' + GetLongHint(Application.Hint);
end;
{ 用户菜单事件 }
procedure TMainForm.ACUserLoginExecute(Sender: TObject);
var
acc, pwd: String;
begin
//输入账户名并验证是否存在
acc := '';
repeat
if not InputText('用户登录', '请输入账户名', acc) then Exit;
until acc <> '';
if AppSetting.CheckAccount(acc) then
begin
if not AppSetting.CheckAccountPwd(acc) then
begin
//验证密码
pwd := '';
if not InputText('用户登录', '请输入登录密码', pwd, 0, True) then Exit;
if not AppSetting.CheckAccountPwd(acc, pwd) then
begin
MessageBox(Handle, '您输入的密码不正确!', '错误', MB_ICONERROR or MB_OK or MB_DEFBUTTON1);
Exit;
end;
end;
//更新当前用户
if AppSetting.GetAccountAdmin(acc) then
_OperLevel := olAdmin
else
begin
_OperLevel := olOperator;
_Authorities.Clear;
end;
_Account := acc;
_Favorites.Clear;
_RefreshOperLevelStatus;
_RefreshCategoryList(False, AppSetting.GetAccountFavorites(acc));
_SetBackImage(AppSetting.GetAccountBackImage(acc));
MessageBox(Handle, PChar(Format('欢迎您,%s !您当前的权限为:%s。', [acc,
IfThen(_OperLevel = olAdmin, '管理员', '操作员')])), '信息', MB_ICONINFORMATION or MB_OK or MB_DEFBUTTON1);
end else
MessageBox(Handle, PChar(Format('用户 %s 不存在!', [acc])), '错误', MB_ICONERROR or MB_OK or MB_DEFBUTTON1);
end;
procedure TMainForm.ACSetPwdExecute(Sender: TObject);
var
acc, title, pwd, pwd2: String;
begin
acc := IfThen(Sender = ACUserSetPassword, _Account, '');
title := IfThen(acc = '', '设置超级管理员密码', '设置用户登录密码');
//验证原密码
if not AppSetting.CheckAccountPwd(acc) then
begin
pwd := '';
if not InputText(title, '请输入原密码', pwd, 0, True) then Exit;
if not AppSetting.CheckAccountPwd(acc, pwd) then
begin
MessageBox(Handle, '您输入的原密码不正确!', '错误', MB_ICONERROR or MB_OK or MB_DEFBUTTON1);
Exit;
end;
end;
//输入新密码
repeat
pwd := '';
if not InputText(title, '请输入新密码(空表示取消原密码)', pwd, 0, True) then Exit;
if pwd = '' then Break;
pwd2 := '';
if not InputText(title, '请再次输入一遍新密码', pwd2, 0, True) then Exit;
if pwd2 = pwd then Break;
MessageBox(Handle, '您两次输入的密码不相同,请重试!', '错误' + DIALOG_CAPTION_SUFFIX,
MB_ICONERROR or MB_OK or MB_DEFBUTTON1);
until False;
//设置新密码
AppSetting.SetAccountPwd(acc, pwd);
if pwd = '' then
MessageBox(Handle, PChar(Format(IfThen(acc = '', '超级管理员的', '用户 %s 的操作') + '密码已清除!',
[acc])), '信息' + DIALOG_CAPTION_SUFFIX, MB_ICONINFORMATION or MB_OK or MB_DEFBUTTON1)
else
MessageBox(Handle, PChar(Format(IfThen(acc = '', '超级管理员的新', '用户 %s 的新操作') + '密码设置成功!',
[acc])), '信息' + DIALOG_CAPTION_SUFFIX, MB_ICONINFORMATION or MB_OK or MB_DEFBUTTON1);
end;
procedure TMainForm.ACUserLogoutExecute(Sender: TObject);
begin
_Account := '';
_OperLevel := olNone;
_Favorites.Clear;
_RefreshOperLevelStatus;
_RefreshCategoryList;
if Sender <> nil then
_SetBackImage(AppSetting.CurDB.BackImage);
end;
procedure TMainForm.ACUserSetPasswordUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := _Account <> '';
end;
procedure TMainForm.ACUserCustomBackImageExecute(Sender: TObject);
var
file_name: String;
begin
file_name := AbstractFileName(AppSetting.GetAccountBackImage(_Account));
if DirectoryExists(ExtractFileDir(file_name)) then
BrowseBackImageDialog.FileName := file_name;
if not BrowseBackImageDialog.Execute then Exit;
file_name := RelativeFileName(BrowseBackImageDialog.FileName);
AppSetting.SetAccountBackImage(_Account, file_name);
_SetBackImage(file_name);
end;
procedure TMainForm.ACUserOriginBackImageExecute(Sender: TObject);
begin
AppSetting.SetAccountBackImage(_Account, '');
_SetBackImage(AppSetting.CurDB.BackImage);
end;
procedure TMainForm.ACUserReconnectExecute(Sender: TObject);
begin
AppSetting.ADOConn.Connected := False;
end;
procedure TMainForm.ACUserReconnectUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := AppSetting.ADOConn.Connected;
end;
procedure TMainForm.ACUserExitExecute(Sender: TObject);
begin
Close;
end;
{ 配置菜单事件 }
procedure TMainForm.ACConfigCategorySettingExecute(Sender: TObject);
begin
CreatePageWindow(CATALOG_SETTING, TMDICategoryPage(ActiveMDIChild).Category);
end;
procedure TMainForm.ACConfigCategorySettingUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := ActiveMDIChild is TMDICategoryPage;
end;
procedure TMainForm.ACConfigCategoryManageExecute(Sender: TObject);
begin
CreatePageWindow(CATALOG_MANAGE);
end;
procedure TMainForm.ACConfigAccountManageExecute(Sender: TObject);
begin
if _CheckOperLevel(olSuperAdmin) then CreatePageWindow(ACCOUNT_MANAGE);
end;
procedure TMainForm.ACConfigDatabaseManageExecute(Sender: TObject);
begin
CreatePageWindow(DATABASE_MANAGE);
end;
procedure TMainForm.ACConfigDatabaseSelectExecute(Sender: TObject);
var
dlg: TDBSelectForm;
begin
if AppSetting.DBConfigList.Count > 1 then
begin
dlg := TDBSelectForm.Create(Self);
try
if dlg.ShowModal = mrOk then
_SelectDatabase(dlg.DBListBox.ItemIndex);
finally
dlg.Free;
end;
end else
_SelectDatabase(0);
end;
procedure TMainForm.ACConfigDatabaseSelectUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := AppSetting.DBConfigList.Count > Min(0, AppSetting.CurDBIndex) + 1;
end;
{ 窗口菜单事件 }
procedure TMainForm.ACWindowLastExecute(Sender: TObject);
begin
MDIChildren[1].BringToFront;
end;
procedure TMainForm.ACWindowLastUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := _PageList.Count > 1;
end;
procedure TMainForm.ACWindowCloseAllExecute(Sender: TObject);
var
i: Integer;
begin
for i := _PageList.Count - 1 downto 0 do
TForm(_PageList[i]).Close;
end;
procedure TMainForm.ACWindowCloseAllUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := _PageList.Count > 0;
end;
procedure TMainForm.ACWindowCloseExecute(Sender: TObject);
begin
ActiveMDIChild.Close;
end;
procedure TMainForm.ACWindowSwitchExecute(Sender: TObject);
begin
with Sender as TAction do
if Tag < _PageList.Count then
TForm(_PageList[Tag]).BringToFront;
end;
{ 帮助菜单事件 }
procedure TMainForm.ACHelpAboutExecute(Sender: TObject);
var
dlg: TAboutDlg;
begin
dlg := TAboutDlg.Create(Self);
try
dlg.ShowModal;
finally
dlg.Free;
end;
end;
procedure TMainForm.ACHelpPythonTestExecute(Sender: TObject);
begin
CreatePageWindow(PYTHON_TEST);
end;
{ 其他菜单事件 }
procedure TMainForm.ACDBAvailableUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := AppSetting.CurDBIndex >= 0;
end;
procedure TMainForm.ACOperatorLevelUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := _OperLevel >= olOperator;
end;
procedure TMainForm.ACAdminLevelUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := _OperLevel >= olAdmin;
end;
procedure TMainForm.ACSuperAdminLevelUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := _OperLevel = olSuperAdmin;
end;
procedure TMainForm.ACSelectAssortExecute(Sender: TObject);
var
pt: TPoint;
begin
pt := TBSelectAssort.ClientToScreen(Point(0, TBSelectAssort.Height));
AssortMenu.Popup(pt.X, pt.Y);
end;
procedure TMainForm.ACShowAssortExecute(Sender: TObject);
begin
_RefreshToolBarBtns(Sender);
end;
procedure TMainForm.ACAddToFavoritesExecute(Sender: TObject);
begin
_Favorites.Add(TMDICategoryPage(ActiveMDIChild).Category.Caption);
_UpdateFavorites;
end;
procedure TMainForm.ACAddToFavoritesUpdate(Sender: TObject);
begin
ACConfigCategorySettingUpdate(Sender);
if TAction(Sender).Enabled then
ACUserSetPasswordUpdate(Sender);
if TAction(Sender).Enabled then
TAction(Sender).Enabled := _Favorites.IndexOf(TMDICategoryPage(ActiveMDIChild).Category.Caption) < 0;
end;
procedure TMainForm.ACRemoveFromFavoritesExecute(Sender: TObject);
begin
_Favorites.Delete(_Favorites.IndexOf(TMDICategoryPage(ActiveMDIChild).Category.Caption));
_UpdateFavorites;
end;
procedure TMainForm.ACRemoveFromFavoritesUpdate(Sender: TObject);
begin
ACConfigCategorySettingUpdate(Sender);
if TAction(Sender).Enabled then
ACUserSetPasswordUpdate(Sender);
if TAction(Sender).Enabled then
TAction(Sender).Enabled := _Favorites.IndexOf(TMDICategoryPage(ActiveMDIChild).Category.Caption) >= 0;
end;
{ 工具栏事件 }
procedure TMainForm.CategoryBtnScrollerScroll(Sender: TObject;
Shift: TShiftState; X, Y: Integer; Orientation: TPageScrollerOrientation;
var Delta: Integer);
begin
Delta := IfThen(Delta > 0, 20, -20);
end;
{ 分页标签栏事件 }
procedure TMainForm.PageTabBarChange(Sender: TObject);
begin
if GetDraggingIndex(Sender) >= 0 then Exit; //若正在拖拽则忽略
TForm(_PageList[PageTabBar.TabIndex]).BringToFront;
end;
procedure TMainForm.PageTabBarGetImageIndex(Sender: TObject;
TabIndex: Integer; var ImageIndex: Integer);
begin
if _PageList = nil then Exit; //避免窗口初始化时出错
ImageIndex := Max(-1, TForm(_PageList[TabIndex]).Tag);
end;
procedure TMainForm.PageTabBarMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
index: Integer;
begin
index := PageTabBar.IndexOfTabAt(X, Y);
if index < 0 then Exit;
case Button of
mbLeft:
PageTabBar.BeginDrag(False);
mbRight:
TForm(_PageList[index]).BringToFront;
mbMiddle:
TForm(_PageList[index]).Close;
end;
end;
procedure TMainForm.PageTabBarStartDrag(Sender: TObject;
var DragObject: TDragObject);
begin
StartDragListItem(Sender);
end;
procedure TMainForm.PageTabBarEndDrag(Sender, Target: TObject; X,
Y: Integer);
var
from, index: Integer;
begin
from := GetDraggingIndex(Sender);
index := EndDragListItem(Sender, True);
if (Target = nil) or (index < 0) then Exit;
_PageList.Move(from, index);
PageTabBar.Tabs.Move(from, index); //手动移动以确保图标显示正确
end;
procedure TMainForm.PageTabBarDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
begin
Accept := DraggingListItem(Sender, X, Y);
end;
////////////////////////////////////////////////////////////////////////////////
// 保护方法
{ 刷新类目列表
- @Clear: 是否清空重建(False表示仅更新工具按钮和菜单项)
- @Favorites: 类目收藏夹列表(若未指定,则不更改当前收藏夹)
}
procedure TMainForm._RefreshCategoryList(Clear: Boolean; Favorites: TStrings);
var
i: Integer;
ci: TCategoryItem;
mi, pmi: TMenuItem;
no_assort: Boolean; //是否有未分类的类目
begin
//清除原菜单及图标
if Clear then
begin
CategoryLargeIcons.Clear;
CategorySmallIcons.Clear;
ClearRecordPropEditDlgList;
end else
begin
//更新各分页和记录引用属性编辑框缓存的权限
for i := _PageList.Count - 1 downto 0 do
PostMessage(TForm(_PageList[i]).Handle, UM_UPDATE_OPER_LEVEL, 0, 0);
UpdateRecordPropEditDlgOperLevel;
end;
MICategory.Clear;
while AssortMenu.Items.Count > 3 do
AssortMenu.Items.Delete(3);
//重建类目菜单
no_assort := False;
for i := 0 to AppSetting.CategoryList.Count - 1 do
begin
ci := AppSetting.CategoryList[i];
with ci do
begin
if Clear then
begin
CategoryLargeIcons.AddIcon(LargeIcon);
CategorySmallIcons.AddIcon(SmallIcon);
end;
if not IsUsable or Hidden or (GetCategoryAuthority(ci) = alNone) then Continue;
//添加到收藏夹
if Favorites <> nil then
if Favorites.IndexOf(Caption) >= 0 then
_Favorites.Add(Caption);
//添加到类目菜单
mi := TMenuItem.Create(MICategory);
mi.Tag := i;
mi.ImageIndex := i;
mi.Caption := Format('- %s %s', [TypeFlag, ci.Caption]);
mi.Hint := Format('%s%s - %s', [TypeFlag, TypeName, ci.Caption]);
mi.OnClick := _OpenCategoryPage;
if Assort <> '' then
begin
//创建分类子菜单
pmi := MICategory.Find(Assort);
if pmi = nil then
begin
pmi := TMenuItem.Create(MICategory);
pmi.Caption := Assort;
pmi.SubMenuImages := CategorySmallIcons;
MICategory.Add(pmi);
pmi.Add(mi);
//添加分类选择菜单项
mi := TMenuItem.Create(AssortMenu);
mi.Tag := i;
mi.ImageIndex := 13;
mi.Caption := Assort;
mi.OnClick := _RefreshToolBarBtns;
AssortMenu.Items.Add(mi);
end else
pmi.Add(mi);
end else
begin
MICategory.Add(mi);
no_assort := True;
end;
end;
end;
//设置分类选择菜单
if no_assort then
begin
mi := TMenuItem.Create(AssortMenu);
mi.Tag := -1;
mi.Caption := '(未分类)';
mi.OnClick := _RefreshToolBarBtns;
AssortMenu.Items.Add(mi);
end;
//若收藏夹列表与给定的不同,则更新到数据库
if Favorites <> nil then
if Favorites.CommaText <> _Favorites.CommaText then
_UpdateFavorites;
//刷新工具栏
if _Favorites.Count > 0 then
_RefreshToolBarBtns(ACShowFavorites)
else
_RefreshToolBarBtns(ACShowAllCategories);
end;
{ 刷新工具栏按钮
- @Sender: 来源控件,其Tag属性指代关联的类目序号(取其所属分类),Tag为-1表示未分类,
Tag为-2表示收藏夹,Tag为-100表示全部类目
}
procedure TMainForm._RefreshToolBarBtns(Sender: TObject);
var
i: Integer;
ci: TCategoryItem;
show_assort: String;
begin
for i := CategoryToolBar.ControlCount - 1 downto 0 do
CategoryToolBar.Controls[i].Free;
CategoryBtnScroller.Position := 0;
//判断要显示的分类
TBSelectAssort.Tag := TComponent(Sender).Tag;
if TBSelectAssort.Tag = -1 then
TBSelectAssort.Caption := '(未分类)'
else if TBSelectAssort.Tag = -2 then
TBSelectAssort.Caption := '(收藏夹)'
else if TBSelectAssort.Tag = -100 then
TBSelectAssort.Caption := '(全部)'
else
begin
show_assort := AppSetting.CategoryList[TBSelectAssort.Tag].Assort;
TBSelectAssort.Caption := show_assort;
end;
TBSelectAssort.Width := Max(40, Canvas.TextWidth(TBSelectAssort.Caption) + 8);
//重建工具栏
for i := 0 to AppSetting.CategoryList.Count - 1 do
begin
ci := AppSetting.CategoryList[i];
with ci do
begin
if not IsUsable or Hidden or (GetCategoryAuthority(ci) = alNone) then Continue;
//判断分类筛选
case TBSelectAssort.Tag of
-1: if Assort <> '' then Continue;
-2: if _Favorites.IndexOf(Caption) < 0 then Continue;
-100: ; //全显示
else if Assort <> show_assort then Continue;
end;
//添加到工具栏
with TToolButton.Create(CategoryToolBar) do
begin
Left := 10000; //确保在最右侧显示
Tag := i;
ImageIndex := i;
Hint := Format('%s %s', [ci.Caption, TypeFlag]);
OnClick := _OpenCategoryPage;
Parent := CategoryToolBar;
end;
end;
end;
end;
{ 打开类目分页 }
procedure TMainForm._OpenCategoryPage(Sender: TObject);
begin
CreatePageWindow(TComponent(Sender).Tag);
end;
{ 刷新状态栏数据库显示 }
procedure TMainForm._RefreshDBStatus;
begin
if AppSetting.CurDBIndex < 0 then
StatusBar.Panels[0].Text := ' (未指定数据库)'
else
StatusBar.Panels[0].Text := IfThen(AppSetting.CurDB.Caption = '', ' (无标题)', ' ' + AppSetting.CurDB.Caption);
end;
{ 刷新状态栏操作权限显示 }
procedure TMainForm._RefreshOperLevelStatus;
begin
StatusBar.Panels[1].Text := Format(' [%s] %s', [IfThen(_OperLevel = olSuperAdmin, '超级管理员',
IfThen(_OperLevel = olAdmin, '管理员', IfThen(_OperLevel = olOperator, '操作员', '尚未登录'))), _Account]);
//设置Python参数
PYW.DefineVar('Account', _Account);
PYW.DefineVar('OperLevel', _OperLevel);
end;
{ 检验操作权限级别
- @LeastLevel: 至少需达到的级别
}
function TMainForm._CheckOperLevel(LeastLevel: TOperateLevel): Boolean;
var
pwd: String;
begin
Result := _OperLevel >= LeastLevel;
if Result then Exit;
//需超级管理员
if LeastLevel = olSuperAdmin then
begin
//验证密码
pwd := '';
if not InputText('本操作需超级管理员权限', '请输入超级管理员密码', pwd, 0, True) then Exit;
if not AppSetting.CheckAccountPwd('', pwd) then
begin
MessageBox(Handle, '您输入的密码不正确!', '错误', MB_ICONERROR or MB_OK or MB_DEFBUTTON1);
Exit;
end;
//更新权限
_OperLevel := olSuperAdmin;
_RefreshOperLevelStatus;
_RefreshCategoryList;
MessageBox(Handle, '您当前的权限为:超级管理员。', '信息', MB_ICONINFORMATION or MB_OK or MB_DEFBUTTON1);
//需操作员
end else if _Account = '' then
ACUserLogin.Execute;
Result := _OperLevel >= LeastLevel;
end;
{ 选择指定数据库 }
procedure TMainForm._SelectDatabase(Index: Integer);
begin
if Index = AppSetting.CurDBIndex then Exit;
//注销用户并清除当前背景图
ACUserLogoutExecute(nil);
_SetBackImage;
//切换数据库并显示背景图
AppSetting.ADOConn.Connected := False;
AppSetting.CurDBIndex := Index;
_RefreshDBStatus;
if Index < 0 then Exit;
_SetBackImage(AppSetting.CurDB.BackImage);
//检验操作权限
try
if AppSetting.CheckAccountPwd('') then
begin
_OperLevel := olSuperAdmin;
_RefreshOperLevelStatus;
_RefreshCategoryList;
end else
_CheckOperLevel;
except
MessageBox(Handle, PChar('检验操作权限失败!'#10#10 + AppSetting.LastDBErr),
'错误', MB_ICONERROR or MB_OK or MB_DEFBUTTON1);
end;
end;
{ 设置背景图 }
procedure TMainForm._SetBackImage(FileName: String);
begin
if _BackImage = FileName then Exit;
_BackImage := FileName;
//擦除当前背景图
if Brush.Bitmap <> nil then
begin
Brush.Bitmap.Free;
Brush.Bitmap := nil;
Brush.Color := clBtnShadow;
Hide;
Show; //闪烁一次,以确保背景图擦除
end;
//绘制新背景图
if FileName <> '' then
begin
Brush.Bitmap := TBitmap.Create;
if LoadPicture(Brush.Bitmap, AbstractFileName(FileName)) then
begin
Hide;
Show; //闪烁一次,以确保背景图重绘
end else
begin
Brush.Bitmap.Free;
Brush.Bitmap := nil;
end;
end;
end;
{ 更新类目收藏夹列表 }
procedure TMainForm._UpdateFavorites;
begin
AppSetting.SetAccountFavorites(_Account, _Favorites);
if TBSelectAssort.Tag = -2 then
_RefreshToolBarBtns(ACShowFavorites);
end;
////////////////////////////////////////////////////////////////////////////////
// Python接口方法
procedure TMainForm.PYFuncInitialization(Sender: TObject);
begin
with Sender as TPythonModule do
begin
AddDelphiMethod('StringsObjectAsInt', Wrap_StringsObjectAsInt,
'StringsObjectAsInt(Strings: DelphiStrings, Index: int): int');
AddDelphiMethod('GetCanvas', Wrap_GetCanvas,
'GetCanvas(Control: DelphiObject): DelphiCanvas');
AddDelphiMethod('ShowProgress', Wrap_ShowProgress,
'ShowProgress(Caption: str, Hint: str, Progress: int = 0, Max: int = 100): bool');
AddDelphiMethod('CloseProgress', Wrap_CloseProgress,
'CloseProgress()');
AddDelphiMethod('LoadPicture', Wrap_LoadPicture,
'LoadPicture(Image: DelphiGraphic, FileName: str): bool');
AddDelphiMethod('DrawPicture', Wrap_DrawPicture,
'DrawPicture(Canvas: DelphiCanvas, Dest: DelphiRect, FileName: str, Source: DelphiRect = None): bool');
AddDelphiMethod('CachePicture', Wrap_CachePicture,
'CachePicture(FileName: str): DelphiBitmap');
AddDelphiMethod('ClearPictureCache', Wrap_ClearPictureCache,
'ClearPictureCache(FileName: str = '''')');
AddDelphiMethod('GetCategoryNames', Wrap_GetCategoryNames,
'GetCategoryNames(): list (每项: str)');
end;
end;
{ 字符串列表项Object值取整数 }
function TMainForm.Wrap_StringsObjectAsInt(PSelf, Args: PPyObject): PPyObject;
var
strings: PPyObject;
obj: TObject;
index: Integer;
begin
Result := nil;
with GetPythonEngine do
begin
if PyArg_ParseTuple(Args, 'Oi:StringsObjectAsInt', [@strings, @index]) = 0 then Exit;
if not CheckObjAttribute(strings, 'Strings', TStrings, obj) then Exit;
if obj = nil then Exit;
Result := PyInt_FromLong(Integer(TStrings(obj).Objects[index]));
end;
end;
{ 获取控件画布 }
function TMainForm.Wrap_GetCanvas(PSelf, Args: PPyObject): PPyObject;
var
control: PPyObject;
obj: TObject;
begin
Result := nil;
with GetPythonEngine do
begin
if PyArg_ParseTuple(Args, 'O:GetCanvas', [@control]) = 0 then Exit;
if not CheckObjAttribute(control, 'Control', TObject, obj) then Exit;
if obj = nil then Exit;
if obj is TCustomForm then
Result := PYW.Wrap(TCustomForm(obj).Canvas)
else if obj is TCustomCombo then
Result := PYW.Wrap(TCustomCombo(obj).Canvas)
else if obj is TCustomHeaderControl then
Result := PYW.Wrap(TCustomHeaderControl(obj).Canvas)
else if obj is TCustomListBox then
Result := PYW.Wrap(TCustomListBox(obj).Canvas)
else if obj is TCustomListView then
Result := PYW.Wrap(TCustomListView(obj).Canvas)
else if obj is TCustomStatusBar then
Result := PYW.Wrap(TCustomStatusBar(obj).Canvas)
else if obj is TCustomTabControl then
Result := PYW.Wrap(TCustomTabControl(obj).Canvas)
else if obj is TCustomTreeView then
Result := PYW.Wrap(TCustomTreeView(obj).Canvas)
else if obj is TImage then
Result := PYW.Wrap(TImage(obj).Canvas)
else if obj is TToolBar then
Result := PYW.Wrap(TToolBar(obj).Canvas)
else
Result := ReturnNone;
end;
end;
{ 显示操作进度 }
function TMainForm.Wrap_ShowProgress(PSelf, Args: PPyObject): PPyObject;
var
caption, hint: PChar;
progress, max: Integer;
begin
Result := nil;
with GetPythonEngine do
begin
progress := 0;
max := 100;
if PyArg_ParseTuple(Args, 'ss|ii:ShowProgress', [@caption, @hint, @progress, @max]) = 0 then Exit;
Result := PyBool_FromLong(Integer(ShowProgress(caption, hint, progress, max)));
end;
end;
{ 关闭操作进度 }
function TMainForm.Wrap_CloseProgress(PSelf, Args: PPyObject): PPyObject;
begin
Result := nil;
with GetPythonEngine do
begin
if PyArg_ParseTuple(Args, ':CloseProgress', []) = 0 then Exit;
CloseProgress;
Result := ReturnNone;
end;
end;
{ 装载图片 }
function TMainForm.Wrap_LoadPicture(PSelf, Args: PPyObject): PPyObject;
var
image: PPyObject;
obj: TObject;
fn: PChar;
begin
Result := nil;
with GetPythonEngine do
begin
if PyArg_ParseTuple(Args, 'Os:LoadPicture', [@image, @fn]) = 0 then Exit;
if not CheckObjAttribute(image, 'Image', TGraphic, obj) then Exit;
if obj = nil then Exit;
Result := PyBool_FromLong(Integer(LoadPicture(TGraphic(obj), fn)));
end;
end;
{ 绘制图片 }
function TMainForm.Wrap_DrawPicture(PSelf, Args: PPyObject): PPyObject;
var
canvas, dst, src: PPyObject;
obj: TObject;
dst_rect, src_rect: TRect;
fn: PChar;
begin
Result := nil;
with GetPythonEngine do
begin
src := Py_None;
if PyArg_ParseTuple(Args, 'OOs|O:DrawPicture', [@canvas, @dst, @fn, @src]) = 0 then Exit;
if not CheckObjAttribute(canvas, 'Canvas', TCanvas, obj) then Exit;
if obj = nil then Exit;
if not CheckRectAttribute(dst, 'Dest', dst_rect) then Exit;
if src = Py_None then
src_rect := Rect(0, 0, 0, 0)
else
if not CheckRectAttribute(src, 'Source', src_rect) then Exit;
Result := PyBool_FromLong(Integer(DrawPicture(TCanvas(obj), dst_rect, fn, src_rect)));
end;
end;
{ 获取缓存图片 }
function TMainForm.Wrap_CachePicture(PSelf, Args: PPyObject): PPyObject;
var
fn: PChar;
begin
Result := nil;
with GetPythonEngine do
begin
if PyArg_ParseTuple(Args, 's:CachePicture', [@fn]) = 0 then Exit;
Result := PYW.Wrap(CachePicture(fn));
end;
end;
{ 清除图片缓存 }
function TMainForm.Wrap_ClearPictureCache(PSelf, Args: PPyObject): PPyObject;
var
fn: PChar;
begin
Result := nil;
with GetPythonEngine do
begin
fn := '';
if PyArg_ParseTuple(Args, '|s:ClearPictureCache', [@fn]) = 0 then Exit;
ClearPictureCache(fn);
Result := ReturnNone;
end;
end;
{ 获取类目名称列表 }
function TMainForm.Wrap_GetCategoryNames(PSelf, Args: PPyObject): PPyObject;
begin
Result := nil;
with GetPythonEngine do
begin
if PyArg_ParseTuple(Args, ':GetCategoryNames', []) = 0 then Exit;
Result := StringsToPyList(AppSetting.CategoryList.Captions(True));
end;
end;
////////////////////////////////////////////////////////////////////////////////
// 公有方法
{ 子窗口动作处理 }
procedure TMainForm.PageActionDeal(Child: TForm; Action: TPageAction);
var
i: Integer;
begin
case Action of
paClose: //关闭
begin
i := _PageList.IndexOf(Child);
_PageList.Delete(i);
PageTabBar.Tabs.Delete(i);
if _PageList.Count = 0 then
PageTabPanel.Visible := False;
end;
paActive: //激活
PageTabBar.TabIndex := _PageList.IndexOf(Child);
paUpdate: //更新类目设置
begin
RefSettingFile := TMDICategorySetting(Child).Category.SettingFile;
//重置类目设置信息
for i := 0 to AppSetting.CategoryList.Count - 1 do
with AppSetting.CategoryList[i] do
if SettingFile = RefSettingFile then
ReloadSetting;
//自动更新相关类目分页
for i := 0 to _PageList.Count - 1 do
begin
if _PageList[i] is TMDICategoryPage then
with _PageList[i] as TMDICategoryPage do
if Category.SettingFile = RefSettingFile then
begin
PostMessage(Handle, UM_REFRESH_CONTENT, 0, 0);
Continue;
end;
//自动更新其他分页的引用属性
if Child <> _PageList[i] then
PostMessage(TForm(_PageList[i]).Handle, UM_REFRESH_REF_PROP, 0, 0);
end;
//删除相关记录引用属性编辑框缓存
ClearRecordPropEditDlgList(TMDICategorySetting(Child).Category.Caption);
end;
paReset: //重置类目列表
begin
//关闭所有类目分页,重置所有类目设置页的引用属性
for i := _PageList.Count - 1 downto 0 do
if _PageList[i] is TMDICategoryPage then
PostMessage(TForm(_PageList[i]).Handle, WM_CLOSE, 0, 0)
else if _PageList[i] is TMDICategorySetting then
PostMessage(TForm(_PageList[i]).Handle, UM_REFRESH_REF_PROP, 0, 0);
_RefreshCategoryList(True);
end;
paDisconnect: //断开数据库连接
_SelectDatabase;
end;
end;
{ 创建分页子窗口
- @Index: 类目序号(<0表示非类目分页,记录在子窗口的Tag中)
- @Category: 关联的类目项(当Index为CATALOG_SETTING时用到)
}
procedure TMainForm.CreatePageWindow(Index: Integer; Category: TCategoryItem);
var
i: Integer;
child: TForm;
cap: String;
begin
//判断该页是否已打开
for i := 0 to _PageList.Count - 1 do
begin
child := TForm(_PageList[i]);
if child.Tag <> Index then Continue;
case Index of
CATALOG_SETTING:
if Category.SettingFile <> TMDICategorySetting(child).Category.SettingFile then Continue;
PYTHON_TEST:
Continue;
end;
child.BringToFront;
Exit;
end;
//创建分页窗口
case Index of
CATALOG_MANAGE: //类目管理
begin
cap := '类目管理';
child := TMDICategoryManage.Create(Self);
end;
CATALOG_SETTING: //类目设置信息
begin
if GetCategoryAuthority(Category) < alOwner then
begin
MessageBox(Handle, PChar(Format('您需要拥有类目「%s」的所有权才能修改类目设置!',
[Category.Caption])), '警告', MB_ICONWARNING or MB_OK or MB_DEFBUTTON1);
Exit;
end;
if not VerifyCategorySetting(Category) then Exit;
cap := Format('设置「%s」', [Category.Caption]);
case Category.CategoryType of
ctOptions: child := TMDIOptionsCategory.Create(Self, Category);
ctTree: child := TMDITreeCategory.Create(Self, Category);
else child := TMDICategorySetting.Create(Self, Category);
end;
end;
DATABASE_MANAGE: //数据库管理
begin
cap := '数据库管理';
child := TMDIDatabaseManage.Create(Self);
end;
ACCOUNT_MANAGE: //用户权限管理
begin
cap := '用户权限管理';
child := TMDIAccountManage.Create(Self);
end;
PYTHON_TEST: //Python脚本测试
begin
cap := '脚本测试';
child := TMDIPythonTest.Create(Self);
end;
else //类目分页
begin
Category := AppSetting.CategoryList[Index];
if not VerifyCategorySetting(Category) then Exit;
cap := Category.Caption;
case Category.CategoryType of
ctOptions: child := TMDIOptionsPage.Create(Self, Category);
ctTree: child := TMDITreePage.Create(Self, Category);
else child := TMDICategoryPage.Create(Self, Category);
end;
end;
end;
//添加分页标签
child.Tag := Index;
_PageList.Add(child);
PageTabBar.Tabs.Add(cap);
//首个窗口自动最大化
if _PageList.Count = 1 then
begin
child.WindowState := wsMaximized;
PageTabPanel.Visible := True;
end;
end;
{ 检验类目设置信息 }
function TMainForm.VerifyCategorySetting(Category: TCategoryItem): Boolean;
begin
if Category.Setting = nil then
begin
Result := False;
MessageBox(Handle, PChar(Format('读取类目「%s」的设置信息失败!请检查类目配置文件是否正确。',
[Category.Caption])), '错误', MB_ICONERROR or MB_OK or MB_DEFBUTTON1);
end else
Result := True;
end;
{ 获取类目操作权限 }
function TMainForm.GetCategoryAuthority(Category: TCategoryItem): TAuthorityLevel;
var
index: Integer;
begin
case _OperLevel of
olNone:
Result := alNone;
olOperator:
begin
index := _Authorities.IndexOf(Category.DBTable);
if index < 0 then
begin
Result := AppSetting.GetAccountAuthority(_Account, Category.DBTable);
_Authorities.AddObject(Category.DBTable, TObject(Result));
end else
Result := TAuthorityLevel(_Authorities.Objects[index]);
end;
else
Result := alOwner;
end;
end;
{ 载入脚本文件
- @Args: 参数变量(若指定,则脚本将编译为函数返回,调用时改为执行函数,用于优化)
- @Return: 要返回的变量
- @Result: 脚本文件内容
}
function TMainForm.LoadScriptFile(FileName: String): String;
begin
Result := '';
if FileName = '' then Exit;
try
Result := TrimRight(LoadTextFile(AbstractFileName(FileName)));
except
end;
end;
function TMainForm.LoadScriptFile(FileName, Args, Return: String): PPyObject;
var
script: String;
locals: PPyObject;
begin
Result := nil;
script := LoadScriptFile(FileName);
if script = '' then Exit;
script := Format('def script( %s ):'#13#10' %s'#13#10,
[Args, StringReplace(script, #10, #10' ', [rfReplaceAll])]);
if Return <> '' then
script := script + Format(' return %s'#13#10, [Return]);
with GetPythonEngine do
try
locals := PyDict_Copy(PyModule_GetDict(GetMainModule));
try
ExecString(script, locals, locals);
Result := PyDict_GetItemString(locals, 'script');
if Result <> nil then
Py_INCREF(Result);
finally
Py_XDECREF(locals);
end;
except
end;
end;
{ 调用脚本 }
function TMainForm.CallScript(Script, Input: PPyObject; NoReturn: Boolean): PPyObject;
begin
with GetPythonEngine do
begin
Result := PyEval_CallObjectWithKeywords(Script, nil, Input);
if Result = nil then RaiseError;
if not NoReturn then Exit;
Py_DECREF(Result);
Result := nil;
end;
end;
end.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。