Jump to content
Korean Random
EvilAlex

Создание инсталляторов для модпаков на базе Inno Setup

Recommended Posts

Spasiba Zdelal no  camandnaea straka pacajit posli tavo ca ea klicaiu na knopcu Завершить...

U menea v instaleatore sti 2 raza CurStepChanged  v raznih failov adin v idp i ftaroi v BackUpPage kak i daiot asibbcu kak mojna izbejati atu prablemu?

Я так понимаю читать все 200 стр. Вам лень?

Вот тут есть пример.

  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

Я так понимаю читать все 200 стр. Вам лень?

Вот тут есть пример.

уже 201 :)

Просто при наличии пробелов в пути, необходимо использовать двойные кавычки "...". Это правило командной строки.

и как тогда в Exec нужно писать?

Share this post


Link to post

Short link
Share on other sites

Ea iscal no ne nashol zdela tack kak ti mne atpravil no ne rabotaie  stavil numeratiiu i ne ashibku ne daiot no script ne rabotaet

Share this post


Link to post

Short link
Share on other sites

Ea iscal no ne nashol zdela tack kak ti mne atpravil no ne rabotaie  stavil numeratiiu i ne ashibku ne daiot no script ne rabotaet

покажи как сделал

Share this post


Link to post

Short link
Share on other sites

покажи как сделал

 

 

procedure ExtractResourcesFile(UnPack, Files, ToPlace: String);
var
  ResultCode: Integer;
begin
  Exec(UnPack, 'x -y' + ' ' + Files + ' ' + '-o' + ToPlace, '', SW_Show, ewWaitUntilTerminated, ResultCode);
end;

procedure ExtractResources;
begin
  ExtractTemporaryFile('7zA.exe');
  CreateDir(ExpandConstant('{app}\res_mods'));
  CreateDir(ExpandConstant('{app}\{#MyAppName2}'));
  CreateDir(ExpandConstant('{app}\{#MyAppName2}\Download'));
  FileCopy(ExpandConstant('{tmp}\7zA.exe'), ExpandConstant('{app}\{#MyAppName2}\Download\7zA.exe'), False);

  If (IsComponentSelected('KMP\Bla\1')) and (FileExists(ExpandConstant('{app}\{#MyAppName2}\Download\xvmfresh.7z'))) then
begin
  ExtractResourcesFile(ExpandConstant('{app}\{#MyAppName2}\Download\7zA.exe'), ExpandConstant('{app}\{#MyAppName2}\Download\xvmfresh.7z'), ExpandConstant('{app}\res_mods'));
end;
  If (IsComponentSelected('KMP\Bla\2')) and (FileExists(ExpandConstant('{app}\{#MyAppName2}\Download\hangar_2.7z'))) then
begin
  ExtractResourcesFile(ExpandConstant('{app}\{#MyAppName2}\Download\7zA.exe'), ExpandConstant('{app}\{#MyAppName2}\Download\hangar_2.7z'), ExpandConstant('{app}\res_mods'));
end;
  //DelTree(ExpandConstant('{app}\{#MyAppName2}\Download'), True, True, True);
//end;
end;



procedure CurStepChanged1(CurStep: TSetupStep);
begin
  If CurStep = ssPostInstall then
begin
  ExtractResources;
end;
end;

procedure CurPageChanged(CurPageID: Integer);

begin
  if IsComponentSelected('KMP\Bla\1') then
begin
  idpAddFile('http://proreduceri.tk/xvmfresh.7z', ExpandConstant('{app}\{#MyAppName2}\Download\xvmfresh.7z'));
end;
  if IsComponentSelected('KMP\Bla\2') then
begin
  idpAddFile('http://proreduceri.tk/xvmfresh.7z', ExpandConstant('{app}\{#MyAppName2}\Download\hangar_2.7z'));
  begin
  if IsComponentSelected('KMP\Bla') then
  CreateDir(ExpandConstant('{app}\{#MyAppName2}'));
  CreateDir(ExpandConstant('{app}\{#MyAppName2}\Download'));
  //begin
    //if CurPageID = wpReady then
//end;
end;
end;
end;

procedure IDPdownload();
begin
  idpDownloadAfter(wpReady);
end;

Edited by asterix93

Share this post


Link to post

Short link
Share on other sites

procedure ExtractResourcesFile(UnPack, Files, ToPlace: String);
var
  ResultCode: Integer;
begin
  Exec(UnPack, 'x -y' + ' ' + Files + ' ' + '-o' + ToPlace, '', SW_Show, ewWaitUntilTerminated, ResultCode);
end;

procedure ExtractResources;
begin
  ExtractTemporaryFile('7zA.exe');
  CreateDir(ExpandConstant('{app}\res_mods'));
  CreateDir(ExpandConstant('{app}\{#MyAppName2}'));
  CreateDir(ExpandConstant('{app}\{#MyAppName2}\Download'));
  FileCopy(ExpandConstant('{tmp}\7zA.exe'), ExpandConstant('{app}\{#MyAppName2}\Download\7zA.exe'), False);

  If (IsComponentSelected('KMP\Bla\1')) and (FileExists(ExpandConstant('{app}\{#MyAppName2}\Download\xvmfresh.7z'))) then
begin
  ExtractResourcesFile(ExpandConstant('{app}\{#MyAppName2}\Download\7zA.exe'), ExpandConstant('{app}\{#MyAppName2}\Download\xvmfresh.7z'), ExpandConstant('{app}\res_mods'));
end;
  If (IsComponentSelected('KMP\Bla\2')) and (FileExists(ExpandConstant('{app}\{#MyAppName2}\Download\hangar_2.7z'))) then
begin
  ExtractResourcesFile(ExpandConstant('{app}\{#MyAppName2}\Download\7zA.exe'), ExpandConstant('{app}\{#MyAppName2}\Download\hangar_2.7z'), ExpandConstant('{app}\res_mods'));
end;
  //DelTree(ExpandConstant('{app}\{#MyAppName2}\Download'), True, True, True);
//end;
end;



procedure CurStepChanged1(CurStep: TSetupStep);
begin
  If CurStep = ssPostInstall then
begin
  ExtractResources;
end;
end;

procedure CurPageChanged(CurPageID: Integer);

begin
  if IsComponentSelected('KMP\Bla\1') then
begin
  idpAddFile('http://proreduceri.tk/xvmfresh.7z', ExpandConstant('{app}\{#MyAppName2}\Download\xvmfresh.7z'));
end;
  if IsComponentSelected('KMP\Bla\2') then
begin
  idpAddFile('http://proreduceri.tk/xvmfresh.7z', ExpandConstant('{app}\{#MyAppName2}\Download\hangar_2.7z'));
  begin
  if IsComponentSelected('KMP\Bla') then
  CreateDir(ExpandConstant('{app}\{#MyAppName2}'));
  CreateDir(ExpandConstant('{app}\{#MyAppName2}\Download'));
  //begin
    //if CurPageID = wpReady then
//end;
end;
end;
end;

procedure IDPdownload();
begin
  idpDownloadAfter(wpReady);
end;

ты почему закоментил wpReady? где главная процедура CurStepChanged?

Share this post


Link to post

Short link
Share on other sites

как правильно зарегистрировать шрифт windows c инсталляторe тak

Root: HKLM; SubKey: SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts; ValueType: string; ValueName: Arial (TrueType); ValueData: {win}\fonts; Flags: uninsdeletekey

Share this post


Link to post

Short link
Share on other sites

 

как правильно зарегистрировать шрифт windows c инсталляторe тak

Root: HKLM; SubKey: SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts; ValueType: string; ValueName: Arial (TrueType); ValueData: {win}\fonts; Flags: uninsdeletekey

в смысле? не понял

  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

haciu reghistriravati shrift dlea XVM

зачем? через секцию files устанавливай его

  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

A kak ea iscal no ne nashol liba ea ne pravilna iscal

 

зачем? через секцию files устанавливай его

Share this post


Link to post

Short link
Share on other sites

A kak ea iscal no ne nashol liba ea ne pravilna iscal

[Files]
Source: "XVMSymbol_15.0.ttf"; DestDir: "{fonts}"; Flags: onlyifdoesntexist uninsneveruninstall; FontInstall: "XVMSymbol_15.0";
Edited by Dark_Knight_MiX
  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

aaaa spasiba ea prooval tam kak ea pisal no ne palucilas


a esli u menea v papke nescalisimbolov mojna zdelati 

Source: "MODS\XVM\XVM_Font\*.ttf"; DestDir: "{fonts}"; Flags: onlyifdoesntexist uninsneveruninstall; FontInstall: "*.ttf"; Components: KMP\XVM;
Edited by asterix93

Share this post


Link to post

Short link
Share on other sites

 

aaaa spasiba ea prooval tam kak ea pisal no ne palucilas

a esli u menea v papke nescalisimbolov mojna zdelati 

Source: "MODS\XVM\XVM_Font\*.ttf"; DestDir: "{fonts}"; Flags: onlyifdoesntexist uninsneveruninstall; FontInstall: "*.ttf"; Components: KMP\XVM;

вроде нет

Share this post


Link to post

Short link
Share on other sites

 

 

a esli u menea v papke nescalisimbolov mojna zdelati
Нет. Каждый шрифт должен устанавливаться индивидуально, с указанием его точного имени.

Изучай.

  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

Нет. Каждый шрифт должен устанавливаться индивидуально, с указанием его точного имени.

Изучай.

 

mda ata harosaea stuca ea neznal sto esti spasiba

Share this post


Link to post

Short link
Share on other sites

Иннот, замени wpWelcome на wpSelectDir.

Вот так сделал все равно пустые папки и ничего не копируется

; BackUpPage - отдельная страница для реализации резервного копирования файлов с выбором параметров

; Автор: AtotIK

 

#include "SHFileOperation.iss";

 

varBackupPage: TWizardPage;DeleteRadioButton, MoveRadioButton, NoneRadioButton: TNewRadioButton;constBackupDescText ='Во избежание проблем совместимости и конфликтов между модификациями рекомендуется удалить уже установленные на данный момент в игровом клиенте.' #13#13 'Выберите необходимый пункт из представленных. При этом будет очищено содержимое папки "res_mods\0.9.13", удалена папка "res_mods\xvm" или созданы резервные копии Ваших файлов.';DeleteDescText ='Установщик удалит все файлы в папках.';MoveDescText ='Установщик сделает резервную копию всех файлов в папках.';NoneDescText ='Установщик оставит всё как есть.';function BackupCheck_1(): Boolean;varBackupDescLabel, DeleteDescLabel, MoveDescLabel, NoneDescLabel: TLabel;beginBackupPage:=CreateCustomPage(wpSelectDir, 'Создание резервных копий файлов перед установкой', 'Пожалуйста, прочтите следующую важную информацию перед тем, как продолжить.');BackupDescLabel:=TLabel.Create(WizardForm);BackupDescLabel.Parent:=BackupPage.Surface;BackupDescLabel.Left:=0;BackupDescLabel.Top:=0;BackupDescLabel.Width:=BackupPage.SurfaceWidth;BackupDescLabel.Height:=90;BackupDescLabel.AutoSize:=False;BackupDescLabel.Wordwrap:=True;BackupDescLabel.Caption:=BackupDescText;DeleteRadioButton:=TNewRadioButton.Create(WizardForm);DeleteRadioButton.Parent:=BackupPage.Surface;DeleteRadioButton.Checked:=False;DeleteRadioButton.Top:=95;DeleteRadioButton.Width:=BackupPage.SurfaceWidth;DeleteRadioButton.Font.Style:=[fsBold];DeleteRadioButton.Font.Size:=9;DeleteRadioButton.Caption:='Удалить файлы'DeleteDescLabel:=TLabel.Create(WizardForm);DeleteDescLabel.Parent:=BackupPage.Surface;DeleteDescLabel.Left:=18;DeleteDescLabel.Top:=DeleteRadioButton.Top + DeleteRadioButton.Height + 4;DeleteDescLabel.Width:=BackupPage.SurfaceWidth;DeleteDescLabel.Height:=40;DeleteDescLabel.AutoSize:=False;DeleteDescLabel.Wordwrap:=True;DeleteDescLabel.Caption:=DeleteDescText;MoveRadioButton:=TNewRadioButton.Create(WizardForm);MoveRadioButton.Parent:=BackupPage.Surface;MoveRadioButton.Checked:=True;MoveRadioButton.Top:=140;MoveRadioButton.Width:=BackupPage.SurfaceWidth;MoveRadioButton.Font.Style:=[fsBold];MoveRadioButton.Font.Size:=9;MoveRadioButton.Caption:='Сделать резервную копию файлов'MoveDescLabel:=TLabel.Create(WizardForm);MoveDescLabel.Parent:=BackupPage.Surface;MoveDescLabel.Left:=18;MoveDescLabel.Top:=MoveRadioButton.Top + MoveRadioButton.Height + 4;MoveDescLabel.Width:=BackupPage.SurfaceWidth;MoveDescLabel.Height:=40;MoveDescLabel.AutoSize:=False;MoveDescLabel.Wordwrap:=True;MoveDescLabel.Caption:=MoveDescText;NoneRadioButton:=TNewRadioButton.Create(WizardForm);NoneRadioButton.Parent:=BackupPage.Surface;NoneRadioButton.Checked:=False;NoneRadioButton.Top:=185;NoneRadioButton.Width:=BackupPage.SurfaceWidth;NoneRadioButton.Font.Style:=[fsBold];NoneRadioButton.Font.Size:=9;NoneRadioButton.Caption:='Ничего не трогать'NoneDescLabel:=TLabel.Create(WizardForm);NoneDescLabel.Parent:=BackupPage.Surface;NoneDescLabel.Left:=18;NoneDescLabel.Top:=NoneRadioButton.Top + NoneRadioButton.Height + 4;NoneDescLabel.Width:=BackupPage.SurfaceWidth;NoneDescLabel.Height:=40;NoneDescLabel.AutoSize:=False;NoneDescLabel.Wordwrap:=True;NoneDescLabel.Caption:=NoneDescText;end;function BackupCheck_2(): Boolean;beginIf DeleteRadioButton.Checked thenbeginDelTree(ExpandConstant('{app}\res_mods\0.9.13'), True, True, True);DelTree(ExpandConstant('{app}\res_mods\xvm'), True, True, True);CreateDir(ExpandConstant('{app}\res_mods\0.9.13'));end;end;function BackupCheck_3(): Boolean;beginIf MoveRadioButton.Checked thenbeginMoveDir(ExpandConstant('{app}\res_mods\0.9.13\'),ExpandConstant('{app}\res_mods\backup\0.9.13'));

MoveDir(ExpandConstant('{app}\res_mods\xvm\'),ExpandConstant('{app}\res_mods\backup\xvm'));

CreateDir(ExpandConstant('{app}\res_mods\0.9.13'));

DelTree(ExpandConstant('{app}\res_mods\xvm'), True, True, True);

end;

end;

 

procedure CurStepChanged(CurStep: TSetupStep);

begin

If CurStep=ssInstall then

begin

BackupCheck_2();

BackupCheck_3();

end;

end;

 

procedure InitializeWizard();

begin

BackupCheck_1();

end;


-zav-, самый простой вариант сделать backup можно вот так:

 

[Files]
Source: "{app}\res\scripts\*.*"; DestDir: "{app}\Backup\res\scripts"; Flags: external skipifsourcedoesntexist createallsubdirs recursesubdirs uninsneveruninstall; BeforeInstall: HideInstallPath;
Source: "Work\Scripts\*.*"; DestDir: "{app}"; Flags: overwritereadonly ignoreversion recursesubdirs createallsubdirs; BeforeInstall: ShowInstallPath;

[UninstallRun]
Filename: "xcopy.exe"; Parameters: """{app}\Backup\res\scripts\*.*"" ""{app}\res\scripts\"" /S /E /C /H /R /Y /F"; Flags: runhidden;

[UninstallDelete]
Type: filesandordirs; Name: "{app}\Backup";

[_____________________Code]
procedure HideInstallPath();
begin
  WizardForm.StatusLabel.Caption:='Создание резервных копий файлов...';
  WizardForm.FileNameLabel.Visible:=False;
end;

procedure ShowInstallPath();
begin
  WizardForm.FileNameLabel.Visible:=True;
  WizardForm.StatusLabel.Caption:=SetupMessage(msgStatusExtractFiles);
end;
Но проверкой тут и не пахнет. Можно сделать через мой пример backup'а, но там проблемы с классами в Unicode-версии Inno Setup - не все файлы копирует из папки-исходника.

Если готов использовать ANSI-версию, то сделаю на основе своего примера.

#include "SHFileOperation.iss";
#define CUR_DIR "res\scripts" ;
#define BAK_DIR "Backup\res\scripts" ;

[___________________________________________Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
    ThereIsFolders: Boolean;
begin
    ThereIsFolders := (DirExists(AddBackslash(WizardDirValue()) + '{#CUR_DIR}') and (not DirExists(AddBackslash(WizardDirValue()) + '{#BAK_DIR}')) );
    if ThereIsFolders then
    if CurStep=ssInstall then
    CopyDir(ExpandConstant('{app}\res\scripts\'),ExpandConstant('{app}\Backup\res\scripts'));
end;

procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
  if CurUninstallStep = usPostUninstall then
    begin
      MoveDir(ExpandConstant('{app}\Backup\res\scripts\'),ExpandConstant('{app}\res\scripts'));
      DelTree(ExpandConstant('{app}\Backup'), True, True, True);
    end;
end;
"SHFileOperation.iss" возьмёшь из моего примера на предыдущих станицах. Так будет проверять на наличие папки.

 

А подскажите мне просто надо папку res_mods бекапить и все что в ней как это сделать и ваш скрипт так и не нашел помогите ткните носом

Share this post


Link to post

Short link
Share on other sites

 

 

Вот так сделал все равно пустые папки и ничего не копируется
Учитывайте кодировку компилятора.

Share this post


Link to post

Short link
Share on other sites

Вроде доделал. Объясняю как работает:

Через #include подключается файл, в котором описаны функции работы с файлами и папками. В частности тут это - MoveDir. Нужна версия Inno Setup с установленным препроцессором.

Страница создаётся после начальной. Выбираете действие и спокойно идете дальше по установке. Как только инсталлятор переходит на процесс установки (страница ssInstall) запускается чекер, который смотрит какой пункт был выбран и исходя из этого запускает нужную функцию на исполнение. В первом варианте удаляются папки 0.8.11 и xvm, потом создаётся пустая папка 0.8.11. Во втором варианте папки 0.8.11 и xvm переносятся в res_mods\backup. После создаётся пустая папка 0.8.11. Третий вариант создаётся как "заглушка", ничего не происходит при его выборе.

Если не нужны надписи вверху страницы (там где картинка), то оставляйте пустые кавычки в строке:

BackupPage:=CreateCustomPage(wpWelcome, '', '');
Тогда нужно будет ещё скрыть белый фон, на котором эти надписи отображаются. В InitializeWizard() добавьте:

WizardForm.PageNameLabel.Hide;
WizardForm.PageDescriptionLabel.Hide;
Поле этого страница будет выглядить примерно вот так:

7a11cfb9f052.png

В общем спрашивайте, если что-то не понятно. Вроде всё доступно написал.

 

Все папки создаются пустые и в 0.9.13. один файл создается ignoremodpackconfig.info в нем написано:Бро!

Ну как так-то?

Мы же просто хотим знать, какие моды пользуются наибольшей популярностью, чтобы развивать и улучшать их =(

Пробовал и ansi версию и Unicode все одно и тоже..

 

В чем проблемка? Гуру помогите...

вот код:

; BackUpPage - отдельная страница для реализации резервного копирования файлов с выбором параметров
; Автор: AtotIK

#include "SHFileOperation.iss";

[Code]
var
  BackupPage: TWizardPage;
  DeleteRadioButton, MoveRadioButton, NoneRadioButton: TNewRadioButton;

const
  BackupDescText =
    'Во избежание проблем совместимости и конфликтов между модификациями рекомендуется удалить уже установленные на данный момент в игровом клиенте.' #13#13 'Выберите необходимый пункт из представленных. При этом будет очищено содержимое папки "res_mods\0.9.13", удалена папка "res_mods\xvm" или созданы резервные копии Ваших файлов.';
  DeleteDescText =
    'Установщик удалит все файлы в папках.';
  MoveDescText =
    'Установщик сделает резервную копию всех файлов в папках.';
  NoneDescText =
    'Установщик оставит всё как есть.';

function BackupCheck_1(): Boolean;
var
  BackupDescLabel, DeleteDescLabel, MoveDescLabel, NoneDescLabel: TLabel;
begin
  BackupPage:=CreateCustomPage(wpSelectDir, 'Создание резервных копий файлов перед установкой', 'Пожалуйста, прочтите следующую важную информацию перед тем, как продолжить.');
  BackupDescLabel:=TLabel.Create(WizardForm);
  BackupDescLabel.Parent:=BackupPage.Surface;
  BackupDescLabel.Left:=0;
  BackupDescLabel.Top:=0;
  BackupDescLabel.Width:=BackupPage.SurfaceWidth; 
  BackupDescLabel.Height:=90;
  BackupDescLabel.AutoSize:=False;
  BackupDescLabel.Wordwrap:=True;
  BackupDescLabel.Caption:=BackupDescText;

  DeleteRadioButton:=TNewRadioButton.Create(WizardForm);
  DeleteRadioButton.Parent:=BackupPage.Surface;
  DeleteRadioButton.Checked:=False;
  DeleteRadioButton.Top:=95;
  DeleteRadioButton.Width:=BackupPage.SurfaceWidth;
  DeleteRadioButton.Font.Style:=[fsBold];
  DeleteRadioButton.Font.Size:=9;
  DeleteRadioButton.Caption:='Удалить файлы'
  DeleteDescLabel:=TLabel.Create(WizardForm);
  DeleteDescLabel.Parent:=BackupPage.Surface;
  DeleteDescLabel.Left:=18;
  DeleteDescLabel.Top:=DeleteRadioButton.Top + DeleteRadioButton.Height + 4;
  DeleteDescLabel.Width:=BackupPage.SurfaceWidth; 
  DeleteDescLabel.Height:=40;
  DeleteDescLabel.AutoSize:=False;
  DeleteDescLabel.Wordwrap:=True;
  DeleteDescLabel.Caption:=DeleteDescText;

  MoveRadioButton:=TNewRadioButton.Create(WizardForm);
  MoveRadioButton.Parent:=BackupPage.Surface;
  MoveRadioButton.Checked:=True;
  MoveRadioButton.Top:=140;
  MoveRadioButton.Width:=BackupPage.SurfaceWidth;
  MoveRadioButton.Font.Style:=[fsBold];
  MoveRadioButton.Font.Size:=9;
  MoveRadioButton.Caption:='Сделать резервную копию файлов'
  MoveDescLabel:=TLabel.Create(WizardForm);
  MoveDescLabel.Parent:=BackupPage.Surface;
  MoveDescLabel.Left:=18;
  MoveDescLabel.Top:=MoveRadioButton.Top + MoveRadioButton.Height + 4;
  MoveDescLabel.Width:=BackupPage.SurfaceWidth; 
  MoveDescLabel.Height:=40;
  MoveDescLabel.AutoSize:=False;
  MoveDescLabel.Wordwrap:=True;
  MoveDescLabel.Caption:=MoveDescText;

  NoneRadioButton:=TNewRadioButton.Create(WizardForm);
  NoneRadioButton.Parent:=BackupPage.Surface;
  NoneRadioButton.Checked:=False;
  NoneRadioButton.Top:=185;
  NoneRadioButton.Width:=BackupPage.SurfaceWidth;
  NoneRadioButton.Font.Style:=[fsBold];
  NoneRadioButton.Font.Size:=9;
  NoneRadioButton.Caption:='Ничего не трогать'
  NoneDescLabel:=TLabel.Create(WizardForm);
  NoneDescLabel.Parent:=BackupPage.Surface;
  NoneDescLabel.Left:=18;
  NoneDescLabel.Top:=NoneRadioButton.Top + NoneRadioButton.Height + 4;
  NoneDescLabel.Width:=BackupPage.SurfaceWidth; 
  NoneDescLabel.Height:=40;
  NoneDescLabel.AutoSize:=False;
  NoneDescLabel.Wordwrap:=True;
  NoneDescLabel.Caption:=NoneDescText;
end;

function BackupCheck_2(): Boolean;
begin
  If DeleteRadioButton.Checked then
begin
  DelTree(ExpandConstant('{app}\res_mods\0.9.13'), True, True, True);
  DelTree(ExpandConstant('{app}\res_mods\xvm'), True, True, True);
  CreateDir(ExpandConstant('{app}\res_mods\0.9.13'));
end;
end;

function BackupCheck_3(): Boolean;
begin
  If MoveRadioButton.Checked then
begin
  MoveDir(ExpandConstant('{app}\res_mods\0.9.13\'),ExpandConstant('{app}\res_mods\backup\0.9.13'));
  MoveDir(ExpandConstant('{app}\res_mods\xvm\'),ExpandConstant('{app}\res_mods\backup\xvm'));
  CreateDir(ExpandConstant('{app}\res_mods\0.9.13'));
  DelTree(ExpandConstant('{app}\res_mods\xvm'), True, True, True);
end;
end;

procedure CurStepChanged(CurStep: TSetupStep);
begin
  If CurStep=ssInstall then
begin
  BackupCheck_2();
  BackupCheck_3();
end;
end;

procedure InitializeWizard();
begin
  BackupCheck_1();
end; 
;***************************************************************;
;****************** SHFileOperation.iss ************************;
;***************************************************************;
;* Include this file in project. Example:
;* #include "SHFileOperation.iss"
;***************************************************************;
;************************ 1 ************************************;
;* function CopyDir(const fromDir, toDir: string): Boolean;
;* Example 1 (without <fromDir> trailing backslash):
;*     CopyDir('C:\TMP\MyApp', 'C:\TMP\Backup');
;* Result: C:\TMP\Backup\MyApp\..all <MyApp> subdirs and files
;* Example 2 (with <fromDir> trailing backslash):
;*     CopyDir('C:\TMP\MyApp\', 'C:\TMP\Backup');
;* Result: C:\TMP\Backup\..all <MyApp> subdirs and files
;***************************************************************;
;************************ 2 ************************************;
;* function MoveDir(const fromDir, toDir: string): Boolean;
;* Example 1 (without <fromDir> trailing backslash):
;*     MoveDir('C:\TMP\MyApp', 'C:\TMP\Backup');
;* Result: C:\TMP\Backup\MyApp\..all <MyApp> subdirs and files
;* Example 2 (with <fromDir> trailing backslash):
;*     MoveDir('C:\TMP\MyApp\', 'C:\TMP\Backup');
;* Result: C:\TMP\Backup\..all <MyApp> subdirs and files
;***************************************************************;
;************************ 3 ************************************;
;* function DelDir(dir: string; toRecycle: Boolean): Boolean;
;*   If <toRecycle> is True, <dir> deleted in Recycle Bin.
;***************************************************************;
;************************ 4 ************************************;
;* function RenameDir(const fromDir, toDir: string): Boolean;
;***************************************************************;
;***************************************************************;
;***************************************************************;

[Code]
#ifdef UNICODE
type
     PChar = PAnsiChar;
#endif
type
   TSHFileOpStruct =  record
     Wnd: HWND;
     wFunc: UINT;
     pFrom: PAnsiChar;
     pTo: PAnsiChar;
     fFlags: Word; // FILEOP_FLAGS;
     fAnyOperationsAborted: BOOL;
     hNameMappings: HWND; // Pointer;
     lpszProgressTitle: PAnsiChar; { only used if FOF_SIMPLEPROGRESS }
   end;

const
// use in wFunc
   { $EXTERNALSYM FO_MOVE }
   FO_MOVE           = $0001;
   { $EXTERNALSYM FO_COPY }
   FO_COPY           = $0002;
   { $EXTERNALSYM FO_DELETE }
   FO_DELETE         = $0003;
   { $EXTERNALSYM FO_RENAME }
   FO_RENAME         = $0004;
// use in fFlags
   { $EXTERNALSYM FOF_MULTIDESTFILES }
   FOF_MULTIDESTFILES         = $0001;
   { $EXTERNALSYM FOF_CONFIRMMOUSE }
   FOF_CONFIRMMOUSE           = $0002;
   { $EXTERNALSYM FOF_SILENT }
   FOF_SILENT                 = $0004;  { don't create progress/report }
   { $EXTERNALSYM FOF_RENAMEONCOLLISION }
   FOF_RENAMEONCOLLISION      = $0008;
   { $EXTERNALSYM FOF_NOCONFIRMATION }
   FOF_NOCONFIRMATION         = $0010;  { Don't prompt the user. }
   { $EXTERNALSYM FOF_WANTMAPPINGHANDLE }
   FOF_WANTMAPPINGHANDLE      = $0020;  { Fill in
SHFILEOPSTRUCT.hNameMappings
                                          Must be freed using
SHFreeNameMappings }
   { $EXTERNALSYM FOF_ALLOWUNDO }
   FOF_ALLOWUNDO              = $0040;
   { $EXTERNALSYM FOF_FILESONLY }
   FOF_FILESONLY              = $0080;  { on *.*, do only files }
   { $EXTERNALSYM FOF_SIMPLEPROGRESS }
   FOF_SIMPLEPROGRESS         = $0100;  { means don't show names of files }
   { $EXTERNALSYM FOF_NOCONFIRMMKDIR }
   FOF_NOCONFIRMMKDIR         = $0200;  { don't confirm making any
needed dirs }
   { $EXTERNALSYM FOF_NOERRORUI }
   FOF_NOERRORUI              = $0400;  { don't put up error UI }


function SHFileOperation(const lpFileOp: TSHFileOpStruct):Integer;
external '[email protected] stdcall';

{****************************************************************}
{****************************************************************}
{****************************************************************}

function BackupDir(const fromDir, toDir: string; IsMove: Boolean): Boolean;
var
  fos: TSHFileOpStruct;
  _fromDir, _toDir: string;
  SR: TFindRec;
  res: Boolean;
begin
    ForceDirectories(toDir);
  if IsMove then
    fos.wFunc  := FO_MOVE else
    fos.wFunc  := FO_COPY;
    fos.fFlags := FOF_FILESONLY or FOF_SILENT or
               FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR;
    _fromDir:= AddBackslash(fromDir);
    _toDir  := AddBackslash(toDir);
  if (Length(fromDir) = Length(_fromDir)) then
    begin
        res:= FindFirst(_fromDir + '*', SR);
      try
        while res do
        begin
          if (SR.Name <> '') and (SR.Name <> '.') and (SR.Name <> '..') then
          begin
            if SR.Attributes = FILE_ATTRIBUTE_DIRECTORY then
              begin
                _fromDir:= _fromDir + SR.Name + #0#0;
                _toDir  := _toDir + #0#0;
                fos.pFrom  := PAnsiChar(_fromDir);
                fos.pTo    := PAnsiChar(_toDir);
              end else
              begin
                _fromDir:= _fromDir + SR.Name + #0#0;
                _toDir  := _toDir   + SR.Name + #0#0;
                fos.pFrom  := PAnsiChar(_fromDir);
                fos.pTo    := PAnsiChar(_toDir);
              end;
                Result := (0 = ShFileOperation(fos));
                _fromDir:= ExtractFilePath(_fromDir);
                _toDir:= ExtractFilePath(_toDir);
          end;
          res := FindNext(SR);
        end;
      finally
        FindClose(SR);
      end;
    end else
    begin
      _fromDir:= RemoveBackslashUnlessRoot(_fromDir) + #0#0;
      _toDir  := RemoveBackslashUnlessRoot(_toDir)   + #0#0;
      fos.pFrom  := PAnsiChar(_fromDir);
      fos.pTo    := PAnsiChar(_toDir);
      Result := (0 = ShFileOperation(fos));
    end;
end;

{****************************************************************}
function MoveDir(const fromDir, toDir: string): Boolean;
begin
  Result := BackupDir(fromDir, toDir, True);
end;

{****************************************************************}
function CopyDir(const fromDir, toDir: string): Boolean;
begin
  Result := BackupDir(fromDir, toDir, False);
end;

{****************************************************************}
function DelDir(dir: string; toRecycle: Boolean): Boolean;
var
  fos: TSHFileOpStruct;
  _dir: string;
begin
    _dir:= RemoveBackslashUnlessRoot(dir) + #0#0;
    fos.wFunc  := FO_DELETE;
    fos.fFlags := FOF_SILENT or FOF_NOCONFIRMATION;
  if toRecycle then
    fos.fFlags := fos.fFlags or FOF_ALLOWUNDO;
    fos.pFrom  := PAnsiChar(_dir);
  Result := (0 = ShFileOperation(fos));
end;

{****************************************************************}
function RenameDir(const fromDir, toDir: string): Boolean;
var
  fos: TSHFileOpStruct;
  _fromDir, _toDir: string;
begin
    _fromDir:= RemoveBackslashUnlessRoot(fromDir) + #0#0;
    _toDir  := RemoveBackslashUnlessRoot(toDir) + #0#0;
    fos.wFunc  := FO_RENAME;
    fos.fFlags := FOF_FILESONLY or FOF_ALLOWUNDO or
              FOF_SILENT or FOF_NOCONFIRMATION;
    fos.pFrom  := PAnsiChar(_fromDir);
    fos.pTo    := PAnsiChar(_toDir);
  Result := (0 = ShFileOperation(fos));
end;
{****************************************************************}
{****************************************************************}
{****************************************************************}
function FilesMaskOperation(const fromDir, toDir, fileMask: string;
         FileOp: Integer; EmptyDirRemove: Boolean; toRecycle: Boolean): Boolean;
var
  fos: TSHFileOpStruct;
  _fromDir, _toDir: string;
  FSR, DSR: TFindRec;
  FindResult: Boolean;
  APath: string;
begin
  APath := AddBackslash(fromDir);
  FindResult := FindFirst(APath + fileMask, FSR);
  try
    while FindResult do
    begin
      if FSR.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0 then
        begin
          Case FileOp of
            FO_COPY:
              begin
                fos.wFunc  := FO_COPY;
              end;
            FO_MOVE:
              begin
                fos.wFunc  := FO_MOVE;
              end;
            FO_DELETE:
              begin
                fos.wFunc  := FO_DELETE;
                if toRecycle then fos.fFlags := fos.fFlags or FOF_ALLOWUNDO;
              end;
            FO_RENAME:
              begin
                fos.wFunc  := FO_RENAME;
              end;
          else
            ;
          end;
            fos.fFlags := fos.fFlags or FOF_FILESONLY or FOF_SILENT or
                   FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR;
            _fromDir:= APath + FSR.Name + #0#0;
            _toDir:= AddBackslash(toDir) + FSR.Name + #0#0;
            ForceDirectories(ExtractFilePath(_toDir));
            fos.pFrom  := PChar(_fromDir);
            fos.pTo    := PChar(_toDir);
            Result := (0 = ShFileOperation(fos));
        end;
      FindResult := FindNext(FSR);
    end;
    FindResult := FindFirst(APath + '*.*', DSR);
    while FindResult do
    begin
      if ((DSR.Attributes and FILE_ATTRIBUTE_DIRECTORY) = FILE_ATTRIBUTE_DIRECTORY) and
        not ((DSR.Name = '.') or (DSR.Name = '..')) then
{Recursion} FilesMaskOperation(APath + DSR.Name,
                               AddBackslash(toDir) + DSR.Name,
                               fileMask, FileOp, EmptyDirRemove, toRecycle);
      FindResult := FindNext(DSR);
    end;
  finally
    FindClose(FSR);
    FindClose(DSR);
    if EmptyDirRemove then RemoveDir(APath);
  end;
end;

function CopyFiles(const fromDir, toDir, fileMask: string): Boolean;
begin
  Result := FilesMaskOperation(fromDir, toDir, fileMask,
         FO_COPY, False, False);
end;

function MoveFiles(const fromDir, toDir, fileMask: string): Boolean;
begin
  Result := FilesMaskOperation(fromDir, toDir, fileMask,
         FO_MOVE, True, False);
end;

function DelFiles(const fromDir, fileMask: string; toRecycle: Boolean ): Boolean;
begin
  Result := FilesMaskOperation(fromDir, '', fileMask,
         FO_DELETE, True, toRecycle);
end; 

Edited by Nowik1971

Share this post


Link to post

Short link
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...