Scripts discussion (3)

Discuss and announce AkelPad plugins
Locked
  • Author
  • Message
Offline
Site Admin
Posts: 6403
Joined: Thu Jul 06, 2006 7:20 am

Post by Instructor »

Skif_off
if(fso.FileExists(pAkelPlugsDir + "\\HexSel.dll"))

Offline
Posts: 1162
Joined: Sun Oct 20, 2013 11:44 am

Post by Skif_off »

Instructor
Спасибо, забыл экранировать обратный слеш :)

Code: Select all

// InsertUnicodeChar.js
//with HexSel plugin http://akelpad.sourceforge.net/forum/viewtopic.php?p=26700#p26700
//without HexSel plugin http://akelpad.sourceforge.net/forum/viewtopic.php?p=26702#p26702
// Version: 2014-11-29 (x86/x64)
// Authors:
// - idea & first version: Skif_off;
// - development: KDJ, VladSh, Instructor.
//
// Insert Unicode Char
//
// Usage:
// Call("Scripts::Main", 1, "InsertUnicodeChar.js")

var hMainWnd      = AkelPad.GetMainWnd();
var pAkelPlugsDir = AkelPad.GetAkelDir(4);
var fso           = new ActiveXObject("Scripting.FileSystemObject");
var sHex          = "002F";
var sText         = "";
var i;

if (AkelPad.GetEditWnd())
{
  for (;;)
  {
    sHex = AkelPad.InputBox(hMainWnd, "Insert characters from hex codes", "Four digits hex codes:", sHex);

    if (! sHex)
      break;
    else if (/[^a-f\d]+/i.test(sHex))
      AkelPad.MessageBox(hMainWnd, "Hex digits only (0-9, A-F).", "Error", 0x10 /*MB_ICONERROR*/);
    else
    {
      if(fso.FileExists(pAkelPlugsDir + "\\HexSel.dll"))
      {
        AkelPad.Call("HexSel::Main", 1, 10, "", "", sHex);
      }
      else
      {
        if (sHex = sHex.substr(0, Math.floor(sHex.length / 4) * 4))
        {
          for (i = 0; i < sHex.length; i += 4)
            sText += String.fromCharCode(parseInt(sHex.substr(i, 4), 16));

          AkelPad.ReplaceSel(sText);
        }
      }
      break;
    }
  }
}

Offline
Posts: 276
Joined: Mon Jun 20, 2011 8:33 am
Location: Электросталь

Post by yozhic »

KDJ
У Вас в скрипте LinesSelectCopyMoveDuplicate.js маленькая ошибочка:

Code: Select all

// Usage:
// Call("Scripts::Main", 1, "LinesSelectMoveDuplicate.js"[, "Action Shift"])
// Action:
В примере имя скрипта указано неправильно. Поправьте, пожалуйста, а то люди копируют и потом не могут понять, почему не работает :)

KDJ
Offline
Posts: 1949
Joined: Sat Mar 06, 2010 7:40 pm
Location: Poland

Post by KDJ »


KDJ
Offline
Posts: 1949
Joined: Sat Mar 06, 2010 7:40 pm
Location: Poland

Post by KDJ »

Instructor
I have a problem with CreatePipe function:

Code: Select all

if (typeof AkelPad == "undefined")
{
  try
  {
    AkelPad  = new ActiveXObject("AkelPad.Document");
    var _X64 = AkelPad.Constants._X64;
  }
  catch (oError)
  {
    WScript.Echo("You need to register Scripts.dll");
    WScript.Quit();
  }
}

var oSys       = AkelPad.SystemFunction();
var nSASize    = _X64 ? 24 : 12 /*sizeof(SECURITY_ATTRIBUTES)*/;
var lpSA       = AkelPad.MemAlloc(nSASize);
var lpOutRead  = AkelPad.MemAlloc(_X64 ? 8 : 4);
var lpOutWrite = AkelPad.MemAlloc(_X64 ? 8 : 4);
var nBufSize   = 65536;
var hOutRead;
var hOutWrite;

AkelPad.MemCopy(lpSA,             nSASize, 3 /*DT_DWORD*/); //nLength
AkelPad.MemCopy(lpSA + (_X64 ?  8 : 4), 0, 2 /*DT_QWORD*/); //lpSecurityDescriptor
AkelPad.MemCopy(lpSA + (_X64 ? 16 : 8), 1, 3 /*DT_DWORD*/); //bInheritHandle

if (oSys.Call("Kernel32::CreatePipe", lpOutRead, lpOutWrite, lpSA, nBufSize))
{
  hOutRead  = AkelPad.MemRead(lpOutRead,  2 /*DT_QWORD*/);
  hOutWrite = AkelPad.MemRead(lpOutWrite, 2 /*DT_QWORD*/);

  WScript.Echo("Pipe has been created.\nhOutRead: " + hOutRead + "\nhOutWrite: " + hOutWrite);

  oSys.Call("Kernel32::CloseHandle", hOutRead);
  oSys.Call("Kernel32::CloseHandle", hOutWrite);
}
else
  WScript.Echo("Last error code: " + oSys.GetLastError());

AkelPad.MemFree(lpSA);
AkelPad.MemFree(lpOutRead);
AkelPad.MemFree(lpOutWrite);

This script works on WinXP x86 and on Win7 x64 with AkelPad x86. Works also as Activex (x86 and x64).
If run it on Win7 x64 in AkelPad x64 window, CreatePipe fails and last error is 998 - ERROR_NOACCESS ("Invalid access to memory location").
Please help me.

Offline
Posts: 1873
Joined: Mon Aug 06, 2007 1:07 pm
Contact:

Post by Infocatcher »

VladSh wrote:По backupVersion.js 0.1.5pre2.
Там уже 0.1.5pre3 образовалась, кое-что уже подправлено.
VladSh wrote:Параметр forceDate (при "-forceDate=false -dateType=1") на файле, не имеющем информации о версии, почему-то влияет на выдачу сообщения "Не удалось определить версию файла!"; хотя может так и должно быть.
Не совсем понятно назначение этого флага. Думал, что если true, то будет брать дату файла, а если нет, то текущую. Или наоборот...))
Не, -forceDate=true только отключает поиск версии в самом файле (и берет дату модификации файла).
VladSh wrote:При вызове с параметрами "-warnings=false -forceDate=false -dateType=1" на файле, не имеющем информации о версии, сначала сохранило с минутами, затем с секундами, а на 3-й раз выдало оригинальное имя файла, что не очень хорошо.
Хм, подробную дату в последний запрос вписывать?

Offline
Site Admin
Posts: 6403
Joined: Thu Jul 06, 2006 7:20 am

Post by Instructor »

KDJ
AkelPad.MemCopy(lpSA + (_X64 ? 16 : 8), 0, 3 /*DT_DWORD*/); //bInheritHandle
or
if (oSys.Call("Kernel32::CreatePipe", lpOutRead, lpOutWrite, 0, nBufSize))

Offline
Posts: 2248
Joined: Tue Aug 07, 2007 2:03 pm
Location: Vinnitsa, Ukraine

Post by FeyFre »

Instructor, KDJ желает что-бы хендлы были унаследованы, именно для этого и вся затея со структурой SECURITY_ATTRIBUTES.

KDJ, trying to reproduce, but currently my 64bit development environment is broken. For now I can advice you workaround(while I looking for cause): let Security Atttributes parameter default(pass NULL). Result handles cannot be inherited. Next step: use DuplicateHnadle WINAPI function to create inheritable handles. Just temporary workaround :( (Well, in most cases I know people use DuplicateHandle, because in most cases they need to make inheritable only one end of pipe, not both)

KDJ
Offline
Posts: 1949
Joined: Sat Mar 06, 2010 7:40 pm
Location: Poland

Post by KDJ »

Instructor and FeyFre thank you very much.

But the error is in another place. I found, it is here:
var _X64 = AkelPad.Constants._X64;
Without "var" all works fine.

Tests:

Code: Select all

WScript.Echo("typeof AkelPad: " + typeof AkelPad + "\ntypeof _X64: " + typeof _X64);
if (typeof AkelPad == "undefined") {
  try {
    AkelPad  = new ActiveXObject("AkelPad.Document");
    var _X64 = AkelPad.Constants._X64;
  }
  catch (oError) {
    WScript.Echo("You need to register Scripts.dll");
    WScript.Quit();
  }
}
WScript.Echo("typeof AkelPad: " + typeof AkelPad + "\ntypeof _X64: " + typeof _X64);

Code: Select all

WScript.Echo("typeof AkelPad: " + typeof AkelPad + "\ntypeof _X64: " + typeof _X64);
if (typeof AkelPad == "undefined") {
  try {
    AkelPad  = new ActiveXObject("AkelPad.Document");
    _X64 = AkelPad.Constants._X64;
  }
  catch (oError) {
    WScript.Echo("You need to register Scripts.dll");
    WScript.Quit();
  }
}
WScript.Echo("typeof AkelPad: " + typeof AkelPad + "\ntypeof _X64: " + typeof _X64);


If the tests you run in AkelPad window:
ActiveX_1.js: typeof _X64: "undefined"
ActiveX_2.js: typeof _X64: "number"

Offline
Site Admin
Posts: 6403
Joined: Thu Jul 06, 2006 7:20 am

Post by Instructor »

KDJ wrote:If the tests you run in AkelPad window:
ActiveX_1.js: typeof _X64: "undefined"
ActiveX_2.js: typeof _X64: "number"
Interesting, behaviour :)

Offline
Posts: 2248
Joined: Tue Aug 07, 2007 2:03 pm
Location: Vinnitsa, Ukraine

Post by FeyFre »

Interesting, behaviour
Without "var" all works fine.
Well, this is intended behavior by language specification.
Declaring variable using var keyword is actually creating Environment Record(ER) in topmost so called Lexical Environments(LE) scoped by compound statement(i.e. local variable, i.e. automatic variable in terms of C/C++). After exiting try's body LE is destroyed(actually just unreference. It will be destroyed after all references will be unreferenced), so binding to such _X64 variable not known/accessible anymore.
Operation assigning to some identifier value a bit longer than it can appears. First it searches for binding in topmost LE(if found - assigns, end). Than it searches in next LE... then in next, ... and next.... last LE in this chain we know as Global Environment. If identifier not bound by "var" keyword to specific(i.e currently topmost) LE, it will be bound to Global Environment.

*There are may appear some tricks in described process if context is in strict mode.
More info at Identifier Resolution

Offline
Site Admin
Posts: 6403
Joined: Thu Jul 06, 2006 7:20 am

Post by Instructor »

FeyFre wrote:After exiting try's body LE is destroyed(actually just unreference. It will be destroyed after all references will be unreferenced), so binding to such _X64 variable not known/accessible anymore.
Yes, but what is interesting is that execution never goes to try's block.
If the tests you run in AkelPad window:

Offline
Posts: 1873
Joined: Mon Aug 06, 2007 1:07 pm
Contact:

Post by Infocatcher »

Instructor
This is variable hoisting, example:

Code: Select all

WScript.Echo("" + x); // undefined
if(false) {
	var x = 1;
}
So, all variables inside function "block" will be actually created (with undefined value) before function (or global code) execution.
https://developer.mozilla.org/en-US/doc ... r_hoisting

Offline
Posts: 3234
Joined: Wed Nov 29, 2006 1:19 pm
Location: Киев, Русь
Contact:

Post by VladSh »

Infocatcher wrote:
VladSh wrote:При вызове с параметрами "-warnings=false -forceDate=false -dateType=1" на файле, не имеющем информации о версии, сначала сохранило с минутами, затем с секундами, а на 3-й раз выдало оригинальное имя файла, что не очень хорошо.
Хм, подробную дату в последний запрос вписывать?
Думаю, да. Потому что это надо помнить, что "если файл без даты, значит исходный не пересохранялся и его сохранять не надо". Раз уж начали добавлять к файлу дату, то было бы логично видеть её там и дальше.
Infocatcher wrote:Не, -forceDate=true только отключает поиск версии в самом файле (и берет дату модификации файла).
Ага, понятно.
Лучше в описание к этому аргументу добавить, что "поиск версии в таком случае отключается".
Подскажите, плз, какие передать параметры, чтобы оно сначала смотрело версию, далее:
- если версия найдена, пыталась добавить дату;
- если не найдена, то просто работало с датами.
Хотелось бы обойтись одной такой универсальной строкой, - я чего-то прошлый раз упустил из виду (недотестил), что -forceDate=true игнорирует версию.

KDJ
Offline
Posts: 1949
Joined: Sat Mar 06, 2010 7:40 pm
Location: Poland

Post by KDJ »

FindReplaceEx.js
Added: "Bookmark" and "Unmark" buttons in "Find/Replace" dialog.
Locked