Scripts discussion (1)

Discuss and announce AkelPad plugins
Locked
  • Author
  • Message
KDJ
Offline
Posts: 1949
Joined: Sat Mar 06, 2010 7:40 pm
Location: Poland

Post by KDJ »

Infocatcher wrote:Hack:

Code: Select all

sTarget   = sTarget.replace(/'/g, "'");
& #38;#39; (without space)
Thanks, this method was able to write "'".
Indeed, it looks like a forum bug.

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

Post by KDJ »

FeyFre wrote:KDJ
What about this ?
Important: The Google Translate API has been officially deprecated as of May 26, 2011. Due to the substantial economic burden caused by extensive abuse, the number of requests you may make per day will be limited and the API will be shut off completely on December 1, 2011. For website translations, we encourage you to use the Google Translate Element.
Money, money, money...
I hope, that it no our translator has caused substantial economic burden on Google.

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

Post by Infocatcher »

But we still can request http://translate.google.com/?eotf=1&fil ... test&tl=ru and parse result HTML.

DV
Offline
Posts: 1291
Joined: Thu Nov 16, 2006 11:53 am
Location: Kyiv, Ukraine

Post by DV »

FeyFre wrote:У меня на Укр раскладке на комбинации Alt+Ctrl+u(или Alt+Ctrl+г) забинден ввод буква "ґ"
Добавлено в новом

Code: Select all

/*************************************************************************
 *  KeySubst.js  v.0.5                                                   *
 *  (C) DV, May-June 2011                                                *
 *  Thanks to: Instructor, FeyFre                                        *
 *************************************************************************/
/*  Examples:                                                            *
 *    -"Eng as Rus" Call("Scripts::Main", 1, "KeySubst.js")              *
 *    -"Eng as Rus" Call("Scripts::Main", 1, "KeySubst.js", `-to=rus`)   *
 *    -"Eng as Ukr" Call("Scripts::Main", 1, "KeySubst.js", `-to=ukr`)   *
 *************************************************************************/

var alph = [
 /* eng=0 */ [ "`1234567890-=\\qwertyuiop[]asdfghjkl;\'zxcvbnm,./`",
               "~!@#$%^&*()_+|QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~",
               // special key combinations...
               "\u0055",
               "\u0055" ],
 /* rus=1 */ [ "ё1234567890-=\\йцукенгшщзхъфывапролджэячсмитьбю.ё",
               "Ё!"№;%:?*()_+/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё",
               // special key combinations...
               "",
               "" ],
 /* ukr=2 */ [ "\'1234567890-=\\йцукенгшщзхїфівапролджєячсмитьбю.ё",
               "\'!"№;%:?*()_+/ЙЦУКЕНГШЩЗХЇФІВАПРОЛДЖЄЯЧСМИТЬБЮ,Ё",
               // special key combinations...
               "ґ",
               "Ґ" ]
]; // Note: trailing 'ё' is needed for Ukrainian because of ` to ' hack.

var eng = 0;
var rus = 1;
var ukr = 2;

var isRusDefault = false; // else Ukr is default
var argTo;
if (isRusDefault)
{
  argTo = (getScriptArg("-to").toLowerCase() == "ukr") ? ukr : rus;
}
else
{
  argTo = (getScriptArg("-to").toLowerCase() == "rus") ? rus : ukr;
}
var hWndMain = AkelPad.GetMainWnd();
var hWndEdit = AkelPad.GetEditWnd();
var oSys = AkelPad.SystemFunction();

AkelPad.ScriptNoMutex();

var mutexName = "KeySubst_js_" + hWndMain + "_" + hWndEdit;
var hMutex;
if (hMutex = oSys.Call("kernel32::CreateMutex" + _TCHAR, 0, 1, mutexName))
{
  if (oSys.GetLastError() == 183 /*ERROR_ALREADY_EXISTS*/)
  {
    oSys.Call("kernel32::CloseHandle", hMutex);
    oSys.Call("user32::SendMessage" + _TCHAR, hWndEdit, 0x0100 /*WM_KEYDOWN*/, 0xC0, 0);
    WScript.Quit();
  }
}

var lpOldEditProc;
if (lpOldEditProc = AkelPad.WindowSubClass(hWndEdit, EditCallback))
{
  //Message loop
  AkelPad.WindowGetMessage();

  AkelPad.WindowUnsubClass(hWndEdit);
  oSys.Call("kernel32::CloseHandle", hMutex);
}

function EditCallback(hWnd, uMsg, wParam, lParam)
{
  if (uMsg == 0x0102 /*WM_CHAR*/)
  {
    var ch = convertSymbolCode(hWnd, wParam, 0);
    if (ch != 0)
    {
      oSys.Call("user32::CallWindowProc" + _TCHAR, lpOldEditProc, hWnd, uMsg, ch, lParam);
      AkelPad.SendMessage(hWnd, 3377 /*AEM_UPDATECARET*/, 0, 0);
      //Skip internal CallWindowProc
      return 1;
    }
  }
  else if ( (uMsg == 0x0100 /*WM_KEYDOWN*/) ||
            (uMsg == 0x0104 /*WM_SYSKEYDOWN*/) )
  {
    var nCtrlState = oSys.Call("user32::GetKeyState", 0x11 /*VK_CONTROL: Ctrl*/);
    var nAltState = oSys.Call("user32::GetKeyState", 0x12 /*VK_MENU: Alt*/)
    var nAltGrState = oSys.Call("user32::GetKeyState", 0xA5 /*VK_RMENU: AltGr*/)

    if (wParam == 0xC0 /*VK_OEM_3: (`~)*/)
    {
      if ((lParam == 0) || ((nCtrlState & 0x80) && !(nAltState & 0x80)))
      {
        //Exit message loop
        oSys.Call("user32::PostQuitMessage", 0);
        //Skip internal CallWindowProc
        return 1;
      }
    }

    var nSet = 0;
    if (((nCtrlState & 0x80) && (nAltState & 0x80)) || 
        (nAltGrState & 0x80))
    {
      nSet = 1;
    }
    // check special key combinations...
    if (nSet != 0)
    {
      var ch = convertSymbolCode(hWnd, wParam, nSet);
      if (ch != 0)
      {
        oSys.Call("user32::PostMessage" + _TCHAR, hWnd, 0x0102 /*WM_CHAR*/, ch, lParam);
        //Skip internal CallWindowProc
        return 1;
      }
    }
  }
  else if (uMsg == 0x0002 /*WM_DESTROY*/)
  {
    //Exit message loop
    oSys.Call("user32::PostQuitMessage", 0);
  }
}

function convertSymbolCode(hWnd, wParam, nSet)
{
  var nLangId = getEditLangId(hWnd);
  var nLangFrom = eng;
  var nLangTo = argTo;
  if (nLangId == 1049) /* rus */
  {
    nLangFrom = rus;
    nLangTo = eng;
  }
  else if (nLangId == 1058) /* ukr */
  {
    nLangFrom = ukr;
    nLangTo = eng;
  }

  if (nSet == 0)
  {
    // characters
    var nCase = 0;
    var ch = String.fromCharCode(wParam);
    var i = alph[nLangFrom][nCase].indexOf(ch);
    if (i < 0)
    {
      nCase = 1;
      i = alph[nLangFrom][nCase].indexOf(ch);
    }
    if (i >= 0)
    {
      if (i < alph[nLangTo][nCase].length)
      {
        ch = alph[nLangTo][nCase].charCodeAt(i);
        return ch;
      }
    }
  }
  else
  {
    // codes
    var nShiftState = oSys.Call("user32::GetKeyState", 0x10 /*VK_SHIFT: Shift*/);
    var nCase = (nShiftState & 0x80) ? (2*nSet + 1) : (2*nSet);
    var i;
    for (i = 0; i < alph[nLangFrom][nCase].length; i++)
    {
      if (alph[nLangFrom][nCase].charCodeAt(i) == wParam)
      {
        var ch = alph[nLangTo][nCase].charCodeAt(i);
        return ch;
      }
    }
  }
  return 0;
}

function getEditLangId(hEdit)
{
  var nEditThreadId = oSys.Call("user32::GetWindowThreadProcessId", hEdit, 0);
  var nLang = oSys.Call("user32::GetKeyboardLayout", nEditThreadId);
  return (nLang & 0xFFFF);
}

function getScriptArg(argName)
{
  var s = "";
  argName = argName.toLowerCase();
  for (var n = 0; n < WScript.Arguments.length; n++)
  {
    var t = WScript.Arguments(n);
    var a = t.split("=");
    if (a[0].toLowerCase() == argName)
    {
      s = a[1];
      break;
    }
  }
  return s;
}
. Данный код предполагает также реакцию на AltGr+U, но почему-то комбинация AltGr+U (а также некоторые другие, например AltGr+W) не возвращает код клавиши U в wParam.

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

Post by FeyFre »

DV
Потому что акселератор занимает Ctrl+Alt+U (какой-то плагин например), и до окна редактирования не доходит. Мне в таких случаях помогает HotKeys плагин(назначено на Command(-1))

Под мой частный случай подстроено - это хорошо, только это только мой частный случай - я сам себе редактировал раскладку(MSKLC), и не только "Ґ" у меня на AltGr стоит.

DV
Offline
Posts: 1291
Joined: Thu Nov 16, 2006 11:53 am
Location: Kyiv, Ukraine

Post by DV »

FeyFre wrote:Под мой частный случай подстроено - это хорошо, и не только "Ґ" у меня на AltGr стоит.
Добавить ещё символов под Ctrl+Alt легко: в массиве английских символов (special key combinations) после \u0055 вставить другие коды клавиш, плюс соответствующие буквы в массиве украинских символов (special key combinations) после ґ.
Добавить комбинации на Alt или Ctrl можно в EditCallback, введя nSet=2 (и т.д.) и добавив соответствующие строки в массивы символов в alph для использующихся языков.
То есть рабочая база с возможностью расширения функционала уже есть. А основная идея была, напомню, получить возможность печати русских и украинских букв в системе, в которой эти раскладки вообще могут быть не установлены.

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

Post by KDJ »

Translator.js
Added: translation using Google Dictionary.
If the length of the source text does not exceed 30 characters and no contain whitespaces, Google Dictionary is used.

DV
Offline
Posts: 1291
Joined: Thu Nov 16, 2006 11:53 am
Location: Kyiv, Ukraine

Post by DV »

И опять

Code: Select all

/*****************************************************************************
 *  KeySubst.js  v.0.6                                                       *
 *  (C) DV, May-June 2011                                                    *
 *  Thanks to: Instructor, FeyFre                                            *
 *****************************************************************************/
/*  Examples:
     -"En->Ru,Ru->En" Call("Scripts::Main", 1, "KeySubst.js", `-to=rus,eng`)
     -"En->Uk,Uk->En" Call("Scripts::Main", 1, "KeySubst.js", `-to=ukr,eng`)
     -"En->Ru,Uk->Ru" Call("Scripts::Main", 1, "KeySubst.js", `-to=rus,rus`)
     -"En->Uk,Ru->Uk" Call("Scripts::Main", 1, "KeySubst.js", `-to=ukr,ukr`)
     -"En->En,Uk->Ru" Call("Scripts::Main", 1, "KeySubst.js", `-to=eng,rus`)
     -"En->En,Ru->Uk" Call("Scripts::Main", 1, "KeySubst.js", `-to=eng,ukr`)
 *****************************************************************************/

var alph = [
 /* eng=0 */ [ "`1234567890-=\\qwertyuiop[]asdfghjkl;\'zxcvbnm,./`",
               "~!@#$%^&*()_+|QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?~",
               // special key combinations...
               "\u0055",
               "\u0055" ],
 /* rus=1 */ [ "ё1234567890-=\\йцукенгшщзхъфывапролджэячсмитьбю.ё",
               "Ё!\"№;%:?*()_+/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё",
               // special key combinations...
               "\u0055",
               "\u0055" ],
 /* ukr=2 */ [ "\'1234567890-=\\йцукенгшщзхїфівапролджєячсмитьбю.ё",
               "\'!\"№;%:?*()_+/ЙЦУКЕНГШЩЗХЇФІВАПРОЛДЖЄЯЧСМИТЬБЮ,Ё",
               // special key combinations...
               "ґ",
               "Ґ" ]
]; // Note: trailing 'ё' is needed for Ukrainian because of ` to ' hack.

var eng = 0;
var rus = 1;
var ukr = 2;

var default_langTo1 = rus; // rus: En->Ru
var default_langTo2 = eng; // eng: Ru->En,Uk->En
var langTo1 = -1;
var langTo2 = -1;
var argLangTo = getScriptArg("-to").toLowerCase().split(",");
if (argLangTo.length > 0)
{
  langTo1 = getLang(argLangTo[0]);
  if (argLangTo.length > 1)
  {
    langTo2 = getLang(argLangTo[1]);
  }
}
var hWndMain = AkelPad.GetMainWnd();
var hWndEdit = AkelPad.GetEditWnd();
var oSys = AkelPad.SystemFunction();

AkelPad.ScriptNoMutex();

var mutexName = "KeySubst_js_" + hWndMain + "_" + hWndEdit;
var hMutex;
if (hMutex = oSys.Call("kernel32::CreateMutex" + _TCHAR, 0, 1, mutexName))
{
  if (oSys.GetLastError() == 183 /*ERROR_ALREADY_EXISTS*/)
  {
    oSys.Call("kernel32::CloseHandle", hMutex);
    oSys.Call("user32::SendMessage" + _TCHAR, hWndEdit, 0x0100 /*WM_KEYDOWN*/, 0xC0, 0);
    WScript.Quit();
  }
}

var lpOldEditProc;
if (lpOldEditProc = AkelPad.WindowSubClass(hWndEdit, EditCallback))
{
  //Message loop
  AkelPad.WindowGetMessage();

  AkelPad.WindowUnsubClass(hWndEdit);
  oSys.Call("kernel32::CloseHandle", hMutex);
}

function EditCallback(hWnd, uMsg, wParam, lParam)
{
  if (uMsg == 0x0102 /*WM_CHAR*/)
  {
    var ch = convertSymbolCode(hWnd, wParam, 0);
    if (ch != 0)
    {
      oSys.Call("user32::CallWindowProc" + _TCHAR, lpOldEditProc, hWnd, uMsg, ch, lParam);
      AkelPad.SendMessage(hWnd, 3377 /*AEM_UPDATECARET*/, 0, 0);
      //Skip internal CallWindowProc
      return 1;
    }
  }
  else if ( (uMsg == 0x0100 /*WM_KEYDOWN*/) ||
            (uMsg == 0x0104 /*WM_SYSKEYDOWN*/) )
  {
    var nCtrlState = oSys.Call("user32::GetKeyState", 0x11 /*VK_CONTROL: Ctrl*/);
    var nAltState = oSys.Call("user32::GetKeyState", 0x12 /*VK_MENU: Alt*/)
    var nAltGrState = oSys.Call("user32::GetKeyState", 0xA5 /*VK_RMENU: AltGr*/)

    if (wParam == 0xC0 /*VK_OEM_3: (`~)*/)
    {
      if ((lParam == 0) || ((nCtrlState & 0x80) && !(nAltState & 0x80)))
      {
        //Exit message loop
        oSys.Call("user32::PostQuitMessage", 0);
        //Skip internal CallWindowProc
        return 1;
      }
    }

    var nSet = 0;
    if (((nCtrlState & 0x80) && (nAltState & 0x80)) ||
        (nAltGrState & 0x80))
    {
      nSet = 1;
    }
    // check special key combinations...
    if (nSet != 0)
    {
      var ch = convertSymbolCode(hWnd, wParam, nSet);
      if (ch != 0)
      {
        oSys.Call("user32::PostMessage" + _TCHAR, hWnd, 0x0102 /*WM_CHAR*/, ch, lParam);
        //Skip internal CallWindowProc
        return 1;
      }
    }
  }
  else if (uMsg == 0x0002 /*WM_DESTROY*/)
  {
    //Exit message loop
    oSys.Call("user32::PostQuitMessage", 0);
  }
}

function convertSymbolCode(hWnd, wParam, nSet)
{
  var nLangId = getEditLangId(hWnd);
  var nLangFrom = eng;
  var nLangTo = (langTo1 == -1) ? default_langTo1 : langTo1;
  if (nLangId == 1049) /* rus */
  {
    nLangFrom = rus;
    nLangTo = (langTo2 == -1) ? default_langTo2 : langTo2;
  }
  else if (nLangId == 1058) /* ukr */
  {
    nLangFrom = ukr;
    nLangTo = (langTo2 == -1) ? default_langTo2 : langTo2;
  }

  if (nLangTo != nLangFrom)
  {
    if (nSet == 0)
    {
      // characters
      var nCase = 0;
      var ch = String.fromCharCode(wParam);
      var i = alph[nLangFrom][nCase].indexOf(ch);
      if (i < 0)
      {
        nCase = 1;
        i = alph[nLangFrom][nCase].indexOf(ch);
      }
      if (i >= 0)
      {
        if (i < alph[nLangTo][nCase].length)
        {
          ch = alph[nLangTo][nCase].charCodeAt(i);
          return ch;
        }
      }
    }
    else
    {
      // codes
      var nShiftState = oSys.Call("user32::GetKeyState", 0x10 /*VK_SHIFT: Shift*/);
      var nCase = (nShiftState & 0x80) ? (2*nSet + 1) : (2*nSet);
      var i;
      for (i = 0; i < alph[nLangFrom][nCase].length; i++)
      {
        if (alph[nLangFrom][nCase].charCodeAt(i) == wParam)
        {
          var ch = alph[nLangTo][nCase].charCodeAt(i);
          if (ch != wParam)
            return ch;
        }
      }
    }
  }
  return 0;
}

function getEditLangId(hEdit)
{
  var nEditThreadId = oSys.Call("user32::GetWindowThreadProcessId", hEdit, 0);
  var nLang = oSys.Call("user32::GetKeyboardLayout", nEditThreadId);
  return (nLang & 0xFFFF);
}

function getLang(s)
{
  var lang = -1;
  if (s == "eng")
    lang = eng;
  else if (s == "rus")
    lang = rus;
  else if (s == "ukr")
    lang = ukr;
  return lang;
}

function getScriptArg(argName)
{
  var s = "";
  argName = argName.toLowerCase();
  for (var n = 0; n < WScript.Arguments.length; n++)
  {
    var t = WScript.Arguments(n);
    var a = t.split("=");
    if (a[0].toLowerCase() == argName)
    {
      s = a[1];
      break;
    }
  }
  return s;
}
:) Добавлен второй аргумент параметра -to, указывающий, что делать, если язык ввода не английский. Это добавило возможность набирать украинские буквы при русской раскладке или русские буквы при украинской раскладке (см. примеры в коде).

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

Post by KDJ »

Does anyone know, where can find a description of Yandex Translate API?

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

Post by Infocatcher »

KDJ
Seems like no official API for now: http://api.yandex.ru/.

But with something like Firebug you can see requests:

Code: Select all

http://translate.yandex.ru/tr.json/translate?callback=json.c(0)&lang=en-ru&text=Test&srv=tr-text&id=0a8caf7c-0-0&reason=submit
(forum don't understand this as URL)
or
http://translate.yandex.ru/tr.json/tran ... son=submit

http://translate.yandex.ru/v1.16/js/tr.js:

Code: Select all

Tr.prototype.sendQuery = function(text) {
    var ref = this;
    var task = this.task;
    var args = { lang: task.lang, text: text, srv: "tr-text"
      , id: task.id + "-" + (task.index - 1), reason: task.reason };
    var query = { args: args, url: this.url + "/translate", method: "GET", task: task
      , callback: function(result, error) { ref.onResponse(query, result, error) } };
    if (this.protocol == "xml")
        ajax.sendQuery(query);
    else
        json.sendQuery(query);
}

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

Post by KDJ »

Infocatcher
Thank you for the information.
Indeed, it seems that there is no official description.
I have found yet this:
http://slovari.yandex.ru/async/translat ... %20Request
You can also use POST method.
And, I don't know what is "cid".

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

Post by Infocatcher »

alignWithSpaces-test.js
Added possibility to remove spaces.
Added own dialog window.

Image Image

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

Post by KDJ »

Translator.js
Added: translation by Yandex.

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

Post by FeyFre »

Infocatcher, чуть-офтопну: форум http://translate.yandex.ru/tr.json/translate?callback=json.c(0)&lang=en-ru&text=Test&srv=tr-text&id=0a8caf7c-0-0&reason=submit не считает ссылкой потому что скобки круглыt должны быть ( = %28 и ) = %29

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

Post by Infocatcher »

FeyFre
А, ну да. Все бы ничего, но в том сообщении у меня еще и весь текст пропадал при предпросмотре, когда я в виде ссылки делал. :)

KDJ wrote:Added: translation by Yandex.
Compare:
http://slovari.yandex.ru/async/translat ... 0%B4%D0%B0 (doesn't translate)
http://translate.yandex.ru/tr.json/tran ... son=submit (translate to Ukrainian)
Locked