Total Commander Forum Index Total Commander
Форум поддержки пользователей Total Commander
Сайты: Все о Total Commander | Totalcmd.net | Ghisler.com | RU.TCKB
 
 RulesRules   SearchSearch   FAQFAQ   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Single Post  Topic: Скрипты PowerPro - опыт новичка 
Author Message
Вахмурка



PostPosted: Mon Aug 29, 2005 22:27    Post subject: Reply with quote

Скрипт 8. Загрузка панели

Для редактирования панели (button bar) необходимо следующее:
1. Выбрать в меню Configuration\Change Button Bar;
2. Найти нужную панель (а лично у меня их 32 глобальных и 5 локальных!);
3. Нажать ОК;
4. Ответить на вопрос.

Куда проше сделать это одним щелчком крысы или одной горячей клавишей, запустив простенький скрипт:
Code:

local hwnd = win.handle("c=TTOTAL_CMD")
win.postmessage(hwnd, 0x400+51, 498, 0)
*keys {enter}
win.sendkeys(arg(1))
*keys ^{enter}{tab}{enter}{tab}{enter}

1. В качестве параметра передаем полное имя панели, например, ("D:\Utils\TotalCmd\Some.BAR").
2. Данный скрипт, в отличие от остальных, НЕ работает в раскладках, отличных от латинской. Русские имена директорий и файлов также будут обрабатываться НЕВЕРНО. Скорее всего, исправлению ситуации поможет плагин unicode. Я не использую русские имена, поэтому и нужды в этом у меня нет. Кто напишет универсальный скрипт, не зависящий ни от раскладки, ни от кодировки имен - честь ему и хвала.
3. Для загрузки панели по умолчанию (как правило, DEFAULT.BAR) последняя строчка должна иметь вид
Code:

*keys ^{enter}{tab}{enter}{enter}

поэтому разумно иметь два разных скрипта - для DEFAULT.BAR (и повесить на него горячую клавишу) и для всех остальных - с вызовом через кнопку. Желающие могут пойти другим путем - через плагин ini всякий раз восстанавливать ключ Buttonbar одноименного раздела в файле конфигурации. Мне кажется, это сложнее.


Скрипт 9. Копирование даты и времени. Версия 2.0

Предыдущая версия скрипта (см. Скрипт 5) имела некоторые недостатки, в частности необходимость менять эскейп-символ в настройках PowerPro, низкая дуракоупорность и неправильное отображение символа &. Во всем остальном скрипты идентичны.
Code:

local Create, Modify, Source, Target, Date, Time, Temp, FormDate, FormTime, Mess, Result

Source = arg(2)
Target = arg(1)

for(i = 1; i <= 2; i = i + 1)
   if(file.isfolder(arg(i)) == 1) do
      Mess = "Parameter 1 (source): " ++ arg(1) ++ "\nParameter 2 (target): "
      Mess = Mess ++ arg(2) ++ "\nParameter " ++ i
      Mess = Mess ++ " must be a file rather than a folder!"
      mpDlgCaption = "Error"
      mpIcon = "ERROR"
      mpDlgText = Mess
      Result = MiscPlugin.MessageBox(1, "OK")
      quit
   endif
endfor

@start

Create = file.getdate(Source, "c")
Modify = file.getdate(Source, "m")

Date = select(Create, 8)
Time = select(Create, 7, 14)
Temp = select(Create, 9, 14)

FormDate = formatdate("longdate", Date)
FormTime = formattime("HH:mm:ss", Temp)

Mess = "Source file " ++ Source ++ ":\n\n" ++ "Creation Date && Time:\n" ++ FormDate ++ ", " ++ FormTime

Date = select(Modify, 8)
Time = select(Modify, 7, 14)
Temp = select(Modify, 9, 14)

FormDate = formatdate("longdate", Date)
FormTime = formattime("HH:mm:ss", Temp)

Mess = Mess ++ "\n\nModification Date && Time:\n" ++ FormDate ++ ", " ++ FormTime

Create = file.getdate(Target, "c")
Modify = file.getdate(Target, "m")

Date = select(Create, 8)
Time = select(Create, 7, 14)
Temp = select(Create, 9, 14)

FormDate = formatdate("longdate", Date)
FormTime = formattime("HH:mm:ss", Temp)

Mess = Mess ++ "\n\n\nTarget file " ++ Target ++ ":\n\n" ++ "Creation Date && Time:\n" ++ FormDate ++ ", " ++ FormTime

Date = select(Modify, 8)
Time = select(Modify, 7, 14)
Temp = select(Modify, 9, 14)

FormDate = formatdate("longdate", Date)
FormTime = formattime("HH:mm:ss", Temp)

Mess = Mess ++ "\n\nModification Date && Time:\n" ++ FormDate ++ ", " ++ FormTime ++ "\n\nProceed with copying date from Source to Target?\n(Choose 'Exchange' to exchange Source with Target)"

mpDlgCaption = "Copy Date && Time"
mpIcon = "путь к иконке\CopyDate.ico"
mpDlgText = Mess
Result = MiscPlugin.MessageBox(1, "&Go!", "E&xchange", "&Cancel")

if(Result == "&Go!") do
   Create = file.getdate(Source, "c")
   Date = select(Create, 8)
   Time = select(Create, 9, 14)
   file.setdate(Target, "c", Date, Time)
   Create = file.getdate(Source, "m")
   Date = select(Create, 8)
   Time = select(Create, 9, 14)
   file.setdate(Target, "m", Date, Time)
elseif(Result == "E&xchange") do
   Mess = Source
   Source = Target
   Target = Mess
   jump start
endif

Для работы необходим плагин MiscPlugin, который можно скачать с сайта PowerPro ftp://powerpro.dyndns.org/PPlugins.zip.


Скрипт 10. Слияние панелей

При редактировании панелей бывает необходимо перенести кнопку с одной панели на другую. Это можно сделать так:
1. Открываем первую панель;
2. Копируем кнопку в буфер;
3. Открываем вторую панель;
4. Вставляем кнопку.

Если же требуется скопировать несколько кнопок, все это необходимо проделывать для каждой. Скучно. Можно достичь той же цели с помощью текстового редактора, но это не сильно веселее - приходится вручную править кучу цифр.

Скрипт сливает вместе две панели, образуя новую с именем _temp.bar.
Code:

local Mess, Result, Key, Number

local First = arg(1)
local Second = arg(2)
mpDlgCaption = "Wrong Parameter"
mpIcon = "ERROR"

if(file.isfolder(First) == 1) do
   mpDlgText = "First bar is " ++ First ++ "\nIt must be a file rather than a folder"
   if(MiscPlugin.MessageBox(1, "&Quit", "&Pick file") == "&Quit") do
      quit
   endif
   First = pickfile(file.listfiles("путь к ТС\*.bar", 0), "Pick First Bar File")
   if(not pproflag(0)) do
      quit
   endif
endif

if(file.type(First) != "bar") do
   mpDlgText = "First bar is " ++ First ++ "\It should have the BAR extension."
   if(MiscPlugin.MessageBox(1, "&Continue", "&Pick file") == "&Pick file") do
      First = pickfile(file.listfiles("путь к ТС\*.bar", 0), "Pick First Bar File")
      if(not pproflag(0)) do
         quit
      endif
   endif
endif

if(file.isfolder(Second) == 1) do
   mpDlgText = "Second bar is " ++ Second ++ "\nIt must be a file rather than a folder"
   if(MiscPlugin.MessageBox(1, "&Quit", "&Pick file") == "&Quit") do
      quit
   endif
   Second = pickfile(file.listfiles("путь к ТС\*.bar", 0), "Pick Second Bar File")
   if(not pproflag(0)) do
      quit
   endif
endif

if(file.type(Second) != "bar") do
   mpDlgText = "Second bar is " ++ Second ++ "\It should have the BAR extension."
   if(MiscPlugin.MessageBox(1, "&Continue", "&Pick file") == "&Pick file") do
      Second = pickfile(file.listfiles("путь к ТС\*.bar", 0), "Pick Second Bar File")
      if(not pproflag(0)) do
         quit
      endif
   endif
endif

@start

Mess = "Second bar " ++ Second ++ " will be appended to the First bar " ++ First ++"\n\n(Choose 'Exchange' to exchange First with Second)"
mpDlgCaption = "Merge Bars"
mpIcon = "INFORMATION"
mpDlgText = Mess
Result = MiscPlugin.MessageBox(1, "&Go!", "E&xchange", "&Cancel")

if(Result == "&Cancel") do
   quit
elseif(Result == "E&xchange") do
   Mess = First
   First = Second
   Second = Mess
   jump start
endif

local Target = "путь к ТС\_temp.bar"

if(file.copy(First, Target) == 0) do
   Mess = "Failure copying " ++ First ++ " to " ++ Result
   messagebox ("ok error", Mess, "FILE plugin error #1")
   quit
endif

local Buttons1 = ini.get(First, "Buttonbar", "Buttoncount")
if(ini_status != "OK") do
   messagebox ("ok error", ini_status, "INI plugin error #1")
   quit
endif

local Buttons2 = ini.get(Second, "Buttonbar", "Buttoncount")
if(ini_status != "OK") do
   messagebox ("ok error", ini_status, "INI plugin error #2")
   quit
endif

Result = ini.set(Target, "Buttonbar", "Buttoncount", Buttons1 + Buttons2)
if(Result != "OK") do
   messagebox ("ok error", Result, "INI plugin error #3")
   quit
endif

v = vec.create(6)
if(v == 0) do
   messagebox ("ok error", "Failure creating vector", "VEC plugin Error")
   quit
endif

v[0] = "button"
v[1] = "cmd"
v[2] = "param"
v[3] = "path"
v[4] = "menu"
v[5] = "iconic"

for(i = 1; i <= Buttons2; i = i + 1)
   Number = i + Buttons1
   for(j = 0; j <= 5; j = j + 1)
      Key = v[j] ++ i
      if(ini.check_exists(Second, "Buttonbar", Key) != 3) do
         break
      endif
      Mess = ini.get(Second, "Buttonbar", Key)
      if(ini_status != "OK") do
         messagebox ("ok error", ini_status, "INI plugin error #4")
         quit
      endif
      Key = v[j] ++ Number
      Result = ini.set(Target, "Buttonbar", Key, Mess)
         if(Result != "OK") do
            messagebox ("ok error", Result, "INI plugin error #5")
            quit
         endif
   endfor
endfor

vec.destroy(v)
vec.unload
ini.unload

Mess = "First bar " ++ First ++ " and Second bar " ++ Second
Mess = Mess ++ "\nare successfully merged in " ++ Target
mpDlgCaption = "Congratulations!"
mpIcon = "QUESTION"
mpDlgText = Mess
Result = MiscPlugin.MessageBox(1, "&Open Bar", "to &First", "to &Second", "&to...", "&Quit")

if(Result == "&Open Bar") do
   runfile.LoadBar(Target)
elseif(Result == "to &First") do
   Result = file.move(Target, First)
      if(Result == 0) do
         Mess = "Failure renaming " ++ Target ++ " to " ++ First
         messagebox ("ok error", Mess, "FILE plugin error #2")
         quit
      endif
elseif(Result == "to &Second") do
   Result = file.move(Target, Second)
      if(Result == 0) do
         Mess = "Failure renaming " ++ Target ++ " to " ++ Second
         messagebox ("ok error", Mess, "FILE plugin error #3")
         quit
      endif
elseif(Result == "&to...") do
@NewName
   Key = inputcancel("New name for bar")
   Key = "путь к ТС\" ++ Key ++ ".bar"
   if(file.validpath(Key) == 1) do
      Mess = "File " ++ Key ++ " already exists! Overwrite?"
      Result = messagebox("yesno warning", Mess, "Warning")
      if(Result == 7) do
         jump NewName
      endif
   Result = file.move(Target, Key)
      if(Result == 0) do
         Mess = "Failure renaming " ++ Target ++ " to " ++ Key
         messagebox ("ok error", Mess, "FILE plugin error #4")
         quit
      endif
   endif
endif

1. Не забудьте заменить слова "путь к..." на истинные пути.
2. В скрипт передаются те же параметры, что и в скрипты 5 и 9. Впрочем, скрипт достаточно дуракоупорен - строго говоря, параметры могут быть любыми.
3. Для работы скрипта необходимы плагины: file, vec, miscplugin и ini. Первые два входят в стандартную поставку, на последние два ссылка после Скрипта 9.
4. При вызове плагина ini мне не удалось заставить команды error_dialog_off и raiseErrors работать так, как описано в руководстве. Зато функция check_exists меня полностью удовлетворила.
5. Поясню вещи, которые и так очевидны из кода. После успешного создания суммарной панели _temp.bar предлагается следующее:
"Open Bar": Загрузить новую панель для редактирования;
"to First" и "to Second": переименовать ее в первую и вторую соответственно - удобно, если целью являлся перенос нескольких кнопок;
"to...": ввести имя для новой панели.
6. Созданная панель является сугубо временной (что подчеркивает имя) и при следующем запуске скрипта будет затерта.
7. LoadBar - имя файла, содержащего Скрипт 8.
View user's profile Send private message Send e-mail Visit poster's website


Powered by phpBB © 2001, 2005 phpBB Group