Scripts collection

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

Post by KDJ »

GUI for PDFtk Server - manipulating PDF documents. Part 3.

Code: Select all

function Ranges()
{
  var aEven = [["",     sTxtAll],
               ["even", sTxtEven],
               ["odd",  sTxtOdd]];
  var aRotation = [["",      sTxtNone],
                   ["north", sTxtNorth + " (0°)"],
                   ["east",  sTxtEast  + " (90°)"],
                   ["south", sTxtSouth + " (180°)"],
                   ["west",  sTxtWest  + " (270°)"],
                   ["left",  sTxtLeft  + " (-90°)"],
                   ["right", sTxtRight + " (+90°)"],
                   ["down",  sTxtDown  + " (+180°)"]];
  var aRange = aPDF[nPDF].R.split(/ /);
  var nRange = 0;
  var oRect  = {};
  var nWAY2;
  var bCloseCB;

  var aWnd       = [];
  var IDRPDFS    = 2000;
  var IDRRANGELV = 2001;
  var IDRPAGESG  = 2002;
  var IDRFROMS   = 2003;
  var IDRFROME   = 2004;
  var IDRFROMB   = 2005;
  var IDRTOS     = 2006;
  var IDRTOE     = 2007;
  var IDRTOB     = 2008;
  var IDRLASTS   = 2009;
  var IDREVENS   = 2010;
  var IDREVENCB  = 2011;
  var IDRROTS    = 2012;
  var IDRROTCB   = 2013;
  var IDRNEWB    = 2014;
  var IDRREMOVEB = 2015;
  var IDRCLEARB  = 2016;
  var IDRUPB     = 2017;
  var IDRDOWNB   = 2018;
  var IDROKB     = 2019;
  var IDRCANCELB = 2020;

  aWnd[IDRPDFS]    = {X:  10, Y:  10, W: 380, H:  13, T: oFSO.GetFileName(aPDF[nPDF].F),   C: "STATIC",        S: 0x50000080 /*WS_CHILD|WS_VISIBLE|SS_NOPREFIX*/};
  aWnd[IDRRANGELV] = {X:  10, Y:  30, W: 160, H: 193,                                      C: "SysListView32", S: 0x5081800D /*WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP|LVS_NOSORTHEADER|LVS_SHOWSELALWAYS|LVS_SINGLESEL|LVS_REPORT*/};
  aWnd[IDRPAGESG]  = {X: 180, Y:  35, W: 170, H: 144, T: sTxtPages,                        C: "BUTTON",        S: 0x50000307 /*WS_CHILD|WS_VISIBLE|BS_CENTER|BS_GROUPBOX*/};
  aWnd[IDRFROMS]   = {X: 190, Y:  50, W:  70, H:  13, T: sTxtFrom,                         C: "STATIC",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/};
  aWnd[IDRFROME]   = {X: 190, Y:  65, W:  70, H:  21,                                      C: "EDIT",          S: 0x50010000 /*WS_CHILD|WS_VISIBLE|WS_TABSTOP*/, ES: 0x00000200 /*WS_EX_CLIENTEDGE*/};
  aWnd[IDRFROMB]   = {X: 190, Y:  90, W:  70, H:  16, T: sTxtFromEnd,                      C: "BUTTON",        S: 0x50010003 /*WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_AUTOCHECKBOX*/};
  aWnd[IDRTOS]     = {X: 270, Y:  50, W:  70, H:  13, T: sTxtTo,                           C: "STATIC",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/};
  aWnd[IDRTOE]     = {X: 270, Y:  65, W:  70, H:  21,                                      C: "EDIT",          S: 0x50010000 /*WS_CHILD|WS_VISIBLE|WS_TABSTOP*/, ES: 0x00000200 /*WS_EX_CLIENTEDGE*/};
  aWnd[IDRTOB]     = {X: 270, Y:  90, W:  70, H:  16, T: sTxtFromEnd,                      C: "BUTTON",        S: 0x50010003 /*WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_AUTOCHECKBOX*/};
  aWnd[IDRLASTS]   = {X: 190, Y: 110, W: 150, H:  13, T: "e = " + sTxtNumLastPage,         C: "STATIC",        S: 0x50000001 /*WS_CHILD|WS_VISIBLE|SS_CENTER*/};
  aWnd[IDREVENS]   = {X: 210, Y: 130, W: 110, H:  13, T: sTxtEven + "/" + sTxtOdd + ":",   C: "STATIC",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/};
  aWnd[IDREVENCB]  = {X: 210, Y: 145, W: 110, H: 100,                                      C: "COMBOBOX",      S: 0x50010003 /*WS_CHILD|WS_VISIBLE|WS_TABSTOP|CBS_DROPDOWNLIST*/};
  aWnd[IDRROTS]    = {X: 210, Y: 187, W: 110, H:  13, T: sTxtRotation + ":",               C: "STATIC",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/};
  aWnd[IDRROTCB]   = {X: 210, Y: 202, W: 110, H: 300,                                      C: "COMBOBOX",      S: 0x50010003 /*WS_CHILD|WS_VISIBLE|WS_TABSTOP|CBS_DROPDOWNLIST*/};
  aWnd[IDRNEWB]    = {X: 360, Y:  30, W:  70, H:  23, T: sTxtNew,                          C: "BUTTON",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/, K: "Insert"};
  aWnd[IDRREMOVEB] = {X: 360, Y:  55, W:  70, H:  23, T: sTxtRemove,                       C: "BUTTON",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/, K: "Alt+Del"};
  aWnd[IDRCLEARB]  = {X: 360, Y:  80, W:  70, H:  23, T: sTxtClear,                        C: "BUTTON",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/, K: "Shift+Alt+Del"};
  aWnd[IDRUPB]     = {X: 360, Y: 105, W:  70, H:  23, T: sTxtMoveUp,                       C: "BUTTON",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/, K: "Alt+Up"};
  aWnd[IDRDOWNB]   = {X: 360, Y: 130, W:  70, H:  23, T: sTxtMoveDown,                     C: "BUTTON",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/, K: "Alt+Down"};
  aWnd[IDROKB]     = {X: 360, Y: 175, W:  70, H:  23, T: sTxtOK,                           C: "BUTTON",        S: 0x50000001 /*WS_CHILD|WS_VISIBLE|BS_DEFPUSHBUTTON*/};
  aWnd[IDRCANCELB] = {X: 360, Y: 200, W:  70, H:  23, T: sTxtCancel,                       C: "BUTTON",        S: 0x50000000 /*WS_CHILD|WS_VISIBLE*/};

  GetWindowPos(0, oRect);
  nWAY2 = oRect.Y + oRect.H;
  GetWindowPos(aDlg[IDPDFLV].HWND, oRect);
  aWnd.W = Scale.X(440) + oSys.Call("User32::GetSystemMetrics", 7 /*SM_CXFIXEDFRAME*/) * 2;
  aWnd.H = Scale.Y(233) + oSys.Call("User32::GetSystemMetrics", 8 /*SM_CYFIXEDFRAME*/) * 2 + oSys.Call("User32::GetSystemMetrics", 4 /*SM_CYCAPTION*/);
  aWnd.X = oRect.X + (oRect.W - aWnd.W) / 2;
  GetItemRectLV(aDlg[IDPDFLV].HWND, nPDF, oRect);
  aWnd.Y = (oRect.Y2 + aWnd.H < nWAY2) ? oRect.Y2 + 2 : oRect.Y1 - aWnd.H - 2;
  aWnd.T = sTxtPagesToCopy + "/" + sTxtRotation;

  oSys.Call("User32::CreateWindowExW",
    0,              //dwExStyle
    sClass,         //lpClassName
    aWnd.T,         //lpWindowName
    0x90C80000,     //dwStyle=WS_POPUP|WS_VISIBLE|WS_CAPTION|WS_SYSMENU
    aWnd.X,         //x
    aWnd.Y,         //y
    aWnd.W,         //nWidth
    aWnd.H,         //nHeight
    hDlg,           //hWndParent
    0,              //hMenu
    hInstDLL,       //hInstance
    RangeCallback); //Script function callback. To use it class must be registered by WindowRegisterClass.

  nOutPages  -= aPDF[nPDF].OP;
  nOutRanges -= aPDF[nPDF].OR;

  oSys.Call("User32::EnableWindow", hDlg, 0);
  AkelPad.WindowGetMessage();

  nOutPages  += aPDF[nPDF].OP;
  nOutRanges += aPDF[nPDF].OR;

  function RangeCallback(hWnd, uMsg, wParam, lParam)
  {
    var nID, nCode, i;

    if (uMsg == 1 /*WM_CREATE*/)
    {
      aWnd.HWND = hWnd;

      if (! hMainWnd)
        SendMessage(hWnd, 128 /*WM_SETICON*/, 0 /*ICON_SMALL*/, hIconSmall);

      for (i = IDRPDFS; i < aWnd.length; ++i)
      {
        aWnd[i].HWND = oSys.Call("User32::CreateWindowExW",
          aWnd[i].ES,         //dwExStyle
          aWnd[i].C,          //lpClassName
          aWnd[i].T,          //lpWindowName
          aWnd[i].S,          //dwStyle
          Scale.X(aWnd[i].X), //x
          Scale.Y(aWnd[i].Y), //y
          Scale.X(aWnd[i].W), //nWidth
          Scale.Y(aWnd[i].H), //nHeight
          hWnd,               //hWndParent
          i,                  //ID
          hInstDLL,           //hInstance
          0);                 //lpParam
        SendMessage(aWnd[i].HWND, 48 /*WM_SETFONT*/, hGuiFont, 1);
      }

      SendMessage(aWnd[IDRFROME].HWND, 197 /*EM_SETLIMITTEXT*/, 6, 0);
      SendMessage(aWnd[IDRTOE].HWND,   197 /*EM_SETLIMITTEXT*/, 6, 0);

      for (i = 0; i < aEven.length; ++i)
        SendMessage(aWnd[IDREVENCB].HWND, 323 /*CB_ADDSTRING*/, i, aEven[i][1]);

      for (i = 0; i < aRotation.length; ++i)
        SendMessage(aWnd[IDRROTCB].HWND, 323 /*CB_ADDSTRING*/, i, aRotation[i][1]);

      FillRangeLV();

      aWnd.Focus = aWnd[IDRRANGELV].HWND;
    }

    else if (uMsg == 0x8001 /*WM_APP+1*/)
      oSys.Call("User32::SetFocus", lParam);

    else if (uMsg == 6 /*WM_ACTIVATE*/)
    {
      if (wParam == 0 /*WA_INACTIVE*/)
        aWnd.Focus = oSys.Call("User32::GetFocus");
    }

    else if (uMsg == 7 /*WM_SETFOCUS*/)
      oSys.Call("User32::SetFocus", aWnd.Focus);

    else if (uMsg == 256 /*WM_KEYDOWN*/)
    {
      nID = oSys.Call("User32::GetDlgCtrlID", oSys.Call("User32::GetFocus"))

      if (wParam == 0x0D /*VK_RETURN*/)
      {
        if ((nID < IDRNEWB) && bCloseCB && ! Ctrl() && ! Shift())
          PostMessage(hWnd, 273 /*WM_COMMAND*/, IDROKB, 0);
      }
      else if ((nID == IDRRANGELV) && ! Ctrl() && ! Shift())
      {
        if (wParam == 0x2D /*VK_INSERT*/)
          PostMessage(hWnd, 273 /*WM_COMMAND*/, IDRNEWB, 0);
        else if (wParam == 0x5D /*VK_APPS*/)
          MenuRangeLV();
      }
    }

    else if (uMsg == 260 /*WM_SYSKEYDOWN*/)
    {
      if (oSys.Call("User32::GetFocus") == aWnd[IDRRANGELV].HWND)
      {
        if (wParam == 0x2E /*VK_DELETE*/)
          PostMessage(hWnd, 273 /*WM_COMMAND*/, Shift() ? IDRCLEARB : IDRREMOVEB, 0);
        else if (wParam == 0x26 /*VK_UP*/)
        {
          if (! Shift())
            PostMessage(hWnd, 273 /*WM_COMMAND*/, IDRUPB, 0);
        }
        else if (wParam == 0x28 /*VK_DOWN*/)
        {
          if (! Shift())
            PostMessage(hWnd, 273 /*WM_COMMAND*/, IDRDOWNB, 0);
        }
      }
    }

    else if (uMsg == 78 /*WM_NOTIFY*/)
    {
      if (wParam == IDRRANGELV)
      {
        switch (AkelPad.MemRead(_PtrAdd(lParam, _X64 ? 16 : 8), 3 /*DT_DWORD*/))
        {
          case -101 : //LVN_ITEMCHANGED
            if (AkelPad.MemRead(_PtrAdd(lParam, _X64 ? 32 : 20) /*NMLISTVIEW.uNewState*/, 3 /*DT_DWORD*/) & 0x2 /*LVIS_SELECTED*/)
            {
              nRange = GetCurSelLV(aWnd[IDRRANGELV].HWND);
              SetPages();
              EnableControlsRange();
            }
            break;
          case -2 : //NM_CLICK
          case -3 : //NM_DBLCLK
            if (AkelPad.MemRead(_PtrAdd(lParam, _X64 ? 24 : 12) /*NMITEMACTIVATE.iItem*/, 3 /*DT_DWORD*/) == -1)
              SetCurSelLV(aWnd[IDRRANGELV].HWND, GetCurFocLV(aWnd[IDRRANGELV].HWND));
            break;
          case -5 : //NM_RCLICK
          case -6 : //NM_RDBLCLK
            if (AkelPad.MemRead(_PtrAdd(lParam, _X64 ? 24 : 12) /*NMITEMACTIVATE.iItem*/, 3 /*DT_DWORD*/) == -1)
              SetCurSelLV(aWnd[IDRRANGELV].HWND, GetCurFocLV(aWnd[IDRRANGELV].HWND));
            MenuRangeLV(_PtrAdd(lParam, _X64 ? 44 : 32) /*NMITEMACTIVATE.ptAction*/);
            break;
          }
      }
    }

    else if (uMsg == 273 /*WM_COMMAND*/)
    {
      nID      = LoWord(wParam);
      nCode    = HiWord(wParam);
      bCloseCB = 1;

      if ((nID == IDRFROME) || (nID == IDRTOE))
      {
        if (nCode == 0x0300 /*EN_CHANGE*/)
          SetRange();
          EnableControlsRange();
      }

      else if ((nID == IDRFROMB) || (nID == IDRTOB))
        SetRange();

      else if ((nID == IDREVENCB) || (nID == IDRROTCB))
      {
        if ((nCode == 1 /*CBN_SELCHANGE*/) || (nCode == 8 /*CBN_CLOSEUP*/))
        {
          SetRange();
          EnableControlsRange();

          if (nCode == 8 /*CBN_CLOSEUP*/)
            bCloseCB = 0;
        }
      }

      else if ((nID >= IDRNEWB) && (nID <= IDRDOWNB))
      {
        if (oSys.Call("User32::IsWindowEnabled", aWnd[nID].HWND))
        {
          if (nID == IDRNEWB)
            NewRange();
          else if (nID == IDRREMOVEB)
            RemoveRange();
          else if (nID == IDRCLEARB)
            ClearRange();
          else if (nID == IDRUPB)
            MoveUpRange();
          else
            MoveDownRange();

          for (i = IDRNEWB; i <= IDRDOWNB; ++i)
            SendMessage(aWnd[i].HWND, 244 /*BM_SETSTYLE*/, 0 /*BS_PUSHBUTTON*/, 1);
          SendMessage(aWnd[IDROKB].HWND, 244 /*BM_SETSTYLE*/, 1 /*BS_DEFPUSHBUTTON*/, 1);
          EnableControlsRange();
          PostMessage(hWnd, 0x8001 /*WM_APP+1*/, 0, aWnd[IDRRANGELV].HWND);
        }
      }

      else if (nID == IDROKB)
      {
        aPDF[nPDF].R = aRange.join(" ");
        CheckRanges(nPDF);
        PostMessage(hWnd, 16 /*WM_CLOSE*/, 0, 0);
      }

      else if ((nID == IDRCANCELB) || (nID == 2 /*IDCANCEL*/))
        PostMessage(hWnd, 16 /*WM_CLOSE*/, 0, 0);
    }

    else if (uMsg == 16 /*WM_CLOSE*/)
    {
      oSys.Call("User32::EnableWindow", hDlg, 1);
      oSys.Call("User32::DestroyWindow", hWnd);
    }

    else if (uMsg == 2 /*WM_DESTROY*/)
      oSys.Call("User32::PostQuitMessage", 0);

    return 0;
  }

  function EnableControlsRange()
  {
    var nFrom      = SendMessage(aWnd[IDRFROME].HWND, 14 /*WM_GETTEXTLENGTH*/, 0, 0);
    var nTo        = SendMessage(aWnd[IDRTOE].HWND,   14 /*WM_GETTEXTLENGTH*/, 0, 0);
    var nEven      = SendMessage(aWnd[IDREVENCB].HWND, 327 /*CB_GETCURSEL*/, 0, 0);
    var nRot       = SendMessage(aWnd[IDRROTCB].HWND,  327 /*CB_GETCURSEL*/, 0, 0);
    var lpLVCOLUMN = AkelPad.MemAlloc(_X64 ? 56 : 44 /*sizeof(LVCOLUMN)*/);
    var lpText     = AkelPad.MemAlloc(64);

    oSys.Call("User32::EnableWindow", aWnd[IDRFROMB].HWND,   (nFrom || (aRange.length > 1)));
    oSys.Call("User32::EnableWindow", aWnd[IDRTOS].HWND,     (nFrom || (aRange.length > 1)));
    oSys.Call("User32::EnableWindow", aWnd[IDRTOE].HWND,     (nFrom || (aRange.length > 1)));
    oSys.Call("User32::EnableWindow", aWnd[IDRTOB].HWND,     (nFrom || (aRange.length > 1)) && nTo);
    oSys.Call("User32::EnableWindow", aWnd[IDRNEWB].HWND,    nFrom);
    oSys.Call("User32::EnableWindow", aWnd[IDRREMOVEB].HWND, aRange.length > 1);
    oSys.Call("User32::EnableWindow", aWnd[IDRCLEARB].HWND,  (nFrom || (aRange.length > 1)) || (nEven > 0) || (nRot > 0));
    oSys.Call("User32::EnableWindow", aWnd[IDRUPB].HWND,     nRange > 0);
    oSys.Call("User32::EnableWindow", aWnd[IDRDOWNB].HWND,   nRange < aRange.length - 1);

    AkelPad.MemCopy(lpText, sTxtRanges + (aRange.length ? " (" + (nRange + 1) + "/" + aRange.length + ")" : ""), 1 /*DT_UNICODE*/);
    AkelPad.MemCopy(lpLVCOLUMN, 4 /*LVCF_TEXT*/, 3 /*DT_DWORD*/); //mask
    AkelPad.MemCopy(_PtrAdd(lpLVCOLUMN, _X64 ? 16 : 12), lpText, 2 /*DT_QWORD*/);
    SendMessage(aWnd[IDRRANGELV].HWND, 4192 /*LVM_SETCOLUMNW*/, 0, lpLVCOLUMN);
    AkelPad.MemFree(lpLVCOLUMN);
    AkelPad.MemFree(lpText);
  }

  function SetPages()
  {
    var aP = aRange[nRange].split(/-/);
    var aMatch;
    var i;

    if (! aP[1]) aP[1] = "";

    i = 0;
    if (aMatch = aRange[nRange].match(/north|east|south|west|left|right|down/))
    {
      for (; i < aRotation.length; ++i)
      {
        if (aRotation[i][0] == aMatch[0])
          break;
      }
    }
    SendMessage(aWnd[IDRROTCB].HWND, 334 /*CB_SETCURSEL*/, i, 0);

    i = 0;
    if (aMatch = aRange[nRange].match(/even|odd/))
    {
      for (; i < aEven.length; ++i)
      {
        if (aEven[i][0] == aMatch[0])
          break;
      }
    }
    SendMessage(aWnd[IDREVENCB].HWND, 334 /*CB_SETCURSEL*/, i, 0);

    SendMessage(aWnd[IDRFROMB].HWND, 241 /*BM_SETCHECK*/, /^r/.test(aP[0]), 0);
    SendMessage(aWnd[IDRTOB].HWND,   241 /*BM_SETCHECK*/, /^r/.test(aP[1]), 0);

    if (/end|\d+/.test(aP[0]))
      aP[0] = aP[0].replace(/^r?(e(?=nd)|\d+).*/, "$1");
    else
      aP[0] = "";

    SetWindowText(aWnd[IDRFROME].HWND, aP[0]);
    SetWindowText(aWnd[IDRTOE].HWND,   aP[1].replace(/^r?(e(?=nd)|\d+).*/, "$1"));
  }

  function SetRange()
  {
    var sFrom = GetWindowText(aWnd[IDRFROME].HWND);
    var sTo   = GetWindowText(aWnd[IDRTOE].HWND);

    if (sFrom || (aRange.length > 1))
    {
      if (sFrom.toLowerCase() == "e")
        sFrom = "end";
      else if (/^0*[1-9]\d*$/.test(sFrom))
        sFrom = parseInt(sFrom, 10).toString();
      else
        sFrom = "1";

      if (SendMessage(aWnd[IDRFROMB].HWND, 240 /*BM_GETCHECK*/, 0, 0))
        sFrom = "r" + sFrom;
    }
    else
    {
      sFrom = aEven[SendMessage(aWnd[IDREVENCB].HWND, 327 /*CB_GETCURSEL*/, 0, 0)][0];
      sTo   = "";
    }

    if (sTo)
    {
      if (sTo.toLowerCase() == "e")
        sTo = "end";
      else if (/^0*[1-9]\d*$/.test(sTo))
        sTo = parseInt(sTo, 10).toString();
      else
        sTo = aPDF[nPDF].TP;

      if (SendMessage(aWnd[IDRTOB].HWND, 240 /*BM_GETCHECK*/, 0, 0))
        sTo = "r" + sTo;

      sTo = "-" + sTo + aEven[SendMessage(aWnd[IDREVENCB].HWND, 327 /*CB_GETCURSEL*/, 0, 0)][0];
    }

    aRange[nRange] = sFrom + sTo + aRotation[SendMessage(aWnd[IDRROTCB].HWND, 327 /*CB_GETCURSEL*/, 0, 0)][0];
    SetItemTextLV(aWnd[IDRRANGELV].HWND, nRange, 0, aRange[nRange] ? aRange[nRange] : sTxtAll);
  }

  function FillRangeLV()
  {
    var lpLVCOLUMN = AkelPad.MemAlloc(_X64 ? 56 : 44 /*sizeof(LVCOLUMN)*/);
    var i;

    AkelPad.MemCopy(lpLVCOLUMN, 4 /*LVCF_TEXT*/, 3 /*DT_DWORD*/); //mask
    AkelPad.MemCopy(_PtrAdd(lpLVCOLUMN, _X64 ? 16 : 12), AkelPad.MemStrPtr(sTxtRanges), 2 /*DT_QWORD*/); //pszText
    SendMessage(aWnd[IDRRANGELV].HWND, 4193 /*LVM_INSERTCOLUMNW*/, 0, lpLVCOLUMN);
    AkelPad.MemFree(lpLVCOLUMN);

    for (i = 0; i < aRange.length; ++i)
      InsertItemLV(aWnd[IDRRANGELV].HWND, i, aRange[i]);

    SendMessage(aWnd[IDRRANGELV].HWND, 4150 /*LVM_SETEXTENDEDLISTVIEWSTYLE*/, 0, 0x0421 /*LVS_EX_INFOTIP|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES*/);
    SendMessage(aWnd[IDRRANGELV].HWND, 4126 /*LVM_SETCOLUMNWIDTH*/, 0, -2 /*LVSCW_AUTOSIZE_USEHEADER*/);
    SetCurSelLV(aWnd[IDRRANGELV].HWND, nRange);
  }

  function MenuRangeLV(lpPoint)
  {
    var MF_STRING = 0x0000;
    var MF_GRAYED = 0x0001;
    var hMenu     = oSys.Call("User32::CreatePopupMenu");
    var oRect;
    var nX, nY;
    var nCmd;
    var i;

    //menu from mouse r-click
    if (lpPoint)
    {
      oSys.Call("User32::ClientToScreen", aWnd[IDRRANGELV].HWND, lpPoint);
      nX = AkelPad.MemRead(_PtrAdd(lpPoint, 0), 3 /*DT_DWORD*/);
      nY = AkelPad.MemRead(_PtrAdd(lpPoint, 4), 3 /*DT_DWORD*/);
    }
    //menu from keyboard
    else
    {
      oRect = {};
      GetItemRectLV(aWnd[IDRRANGELV].HWND, nRange, oRect);
      nX = oRect.X1;
      nY = oRect.Y2;
    }

    for (i = IDRNEWB; i <= IDRDOWNB; ++i)
      oSys.Call("User32::AppendMenuW", hMenu, oSys.Call("User32::IsWindowEnabled", aWnd[i].HWND) ? MF_STRING : MF_GRAYED, i, aWnd[i].T + "\t" + aWnd[i].K);

    nCmd = oSys.Call("User32::TrackPopupMenu", hMenu, 0x0180 /*TPM_NONOTIFY|TPM_RETURNCMD*/, nX, nY, 0, aWnd.HWND, 0);

    oSys.Call("User32::DestroyMenu", hMenu);

    if (nCmd)
      PostMessage(aWnd.HWND, 273 /*WM_COMMAND*/, nCmd, 0);
  }

  function NewRange()
  {
    aRange.splice(nRange, 0, aRange[nRange]);
    InsertItemLV(aWnd[IDRRANGELV].HWND, nRange, aRange[nRange]);
    SetCurSelLV(aWnd[IDRRANGELV].HWND, ++nRange);
  }

  function RemoveRange()
  {
    aRange.splice(nRange, 1);
    DeleteItemLV(aWnd[IDRRANGELV].HWND, nRange);

    if (nRange >= aRange.length)
      --nRange;

    SetCurSelLV(aWnd[IDRRANGELV].HWND, nRange);
  }

  function ClearRange()
  {
    aRange.length = 1;
    SendMessage(aWnd[IDRRANGELV].HWND, 4105 /*LVM_DELETEALLITEMS*/, 0, 0);

    aRange[0] = "";
    InsertItemLV(aWnd[IDRRANGELV].HWND, 0, aRange[0]);
    SetCurSelLV(aWnd[IDRRANGELV].HWND, 0);
  }

  function MoveUpRange()
  {
    aRange.splice(nRange - 1, 0, aRange[nRange]);
    aRange.splice(nRange + 1, 1);
    DeleteItemLV(aWnd[IDRRANGELV].HWND, nRange--);
    InsertItemLV(aWnd[IDRRANGELV].HWND, nRange);
    SetCurSelLV(aWnd[IDRRANGELV].HWND, nRange);
  }

  function MoveDownRange()
  {
    aRange.splice(nRange + 2, 0, aRange[nRange]);
    aRange.splice(nRange, 1);
    DeleteItemLV(aWnd[IDRRANGELV].HWND, nRange++);
    InsertItemLV(aWnd[IDRRANGELV].HWND, nRange);
    SetCurSelLV(aWnd[IDRRANGELV].HWND, nRange);
  }
}

function Open()
{
  if (oFSO.FileExists(aPDF[nPDF].F))
  {
    if (IsReaderExists())
      AkelPad.Exec('"' + sPDFReader + '" "' + aPDF[nPDF].F + '"');
  }
  else
    MsgBox(aPDF[nPDF].F + "\n\n" + sTxtNoFile);
}

function Refresh(bAll)
{
  var nPDFCur = nPDF;
  var oFile   = {};
  var sOutput;
  var aMatch;
  var sPass;
  var bDelete;
  var i;

  if (! IsPDFtkExists())
    return;

  bRefreshing = 1;
  EnableControlsDlg();

  nTotalPages = 0;
  nOutPages   = 0;
  nOutRanges  = 0;

  for (i = 0; i < aPDF.length; ++i)
  {
    if ((! bAll) && aPDF[i].TP)
    {
      nTotalPages += aPDF[i].TP;
      nOutPages   += aPDF[i].OP;
      nOutRanges  += aPDF[i].OR;
    }
    else
    {
      SetCurSelLV(aDlg[IDPDFLV].HWND, i);
      SetItemTextLV(aDlg[IDPDFLV].HWND, i, 1, sTxtReading);

      if (oFile[aPDF[i].F.toUpperCase()])
      {
        aPDF[i].P  = oFile[aPDF[i].F.toUpperCase()].P;
        aPDF[i].TP = oFile[aPDF[i].F.toUpperCase()].TP;
        SetItemTextLV(aDlg[IDPDFLV].HWND, i, 1, aPDF[i].TP);
        CheckRanges(i);
        nTotalPages += aPDF[i].TP;
        nOutPages   += aPDF[i].OP;
        nOutRanges  += aPDF[i].OR;
      }
      else
      {
        sPass = aPDF[i].P;

        for (;;)
        {
          sOutput = RunCmd('"' + sPDFtkExe + '" "' + aPDF[i].F + '" input_pw "' + sPass + '" dump_data_annots');
          aMatch  = sOutput.match(/NumberOfPages: (\d+)/);

          if (aMatch && (aMatch.length == 2))
          {
            aPDF[i].P  = sPass;
            aPDF[i].TP = parseInt(aMatch[1]);
            SetItemTextLV(aDlg[IDPDFLV].HWND, i, 1, aPDF[i].TP);
            CheckRanges(i);
            nTotalPages += aPDF[i].TP;
            nOutPages   += aPDF[i].OP;
            nOutRanges  += aPDF[i].OR;
            break;
          }
          else
          {
            if ((nExitCode == 1) && /OWNER PASSWORD REQUIRED/.test(sOutput))
            {
              if (oFile[aPDF[i].F.toUpperCase()])
                sPass = oFile[aPDF[i].F.toUpperCase()].P;
              else
              {
                sPass = EnterPassword(oFSO.GetFileName(aPDF[i].F), sPass);

                if (typeof sPass != "string")
                {
                  bDelete = 1;
                  break;
                }
              }
            }
            else
            {
              bDelete = 1;
              break;
            }
          }
        }

        if (bDelete)
        {
          if (i <= nPDFCur)
            --nPDFCur;

          aPDF.splice(i, 1);
          DeleteItemLV(aDlg[IDPDFLV].HWND, i);
        }
      }
    }

    if (bDelete)
    {
      bDelete = 0;
      --i;
    }
    else
      oFile[aPDF[i].F.toUpperCase()] = {P: aPDF[i].P, TP: aPDF[i].TP};
  }

  bRefreshing = 0;
  oSys.Call("User32::UpdateWindow", aDlg[IDPDFLV].HWND);
  SetCurSelLV(aDlg[IDPDFLV].HWND, nPDFCur);
  EnableControlsDlg();

  if (aPDF.length)
  {
    if (! bCreating)
    {
      SetDefButton();
      PostMessage(hDlg, 0x8001 /*WM_APP+1*/, 0, aDlg[IDPDFLV].HWND);
    }
  }
  else
    SetDefButton(IDADDB, IDADDB);
}

function CheckRanges(nPDF)
{
  var aR;
  var nFrom;
  var nTo;
  var nTmp;
  var aMatch;
  var i;

  aPDF[nPDF].OP = 0;
  aR = aPDF[nPDF].R.toLowerCase().replace(/^ +| +$/g, "").split(/ +/);

  for (i = 0; i < aR.length; ++i)
  {
    aR[i] = aR[i].replace(/^-+|-+$/g, "").split(/-+/, 2);

    if (aR[i][0])
    {
      if (/^r?(end|\d+)(north|east|south|west|left|right|down)?$/.test(aR[i][0]))
      {
        aMatch = aR[i][0].match(/end|\d+/);

        if (aMatch[0] == "end")
          nFrom = aPDF[nPDF].TP;
        else
        {
          nFrom = parseInt(aMatch[0], 10);

          if (nFrom == 0)
            nFrom = 1;
          else if (nFrom > aPDF[nPDF].TP)
            nFrom = aPDF[nPDF].TP;

          aR[i][0] = aR[i][0].replace(/\d+/, nFrom.toString());
        }

        if (/^r/.test(aR[i][0]))
          nFrom = aPDF[nPDF].TP - nFrom + 1;

        if (/north|east|south|west|left|right|down/.test(aR[i][0]))
          aR[i][1] = "";

        nTo = nFrom;
      }
      else if (/^(even|odd)?(north|east|south|west|left|right|down)?$/.test(aR[i][0]))
      {
        aR[i][1] = "";
        nFrom    = 1;
        nTo      = aPDF[nPDF].TP;

        if (nFrom == nTo)
          aR[i][0] = aR[i][0].replace(/even|odd/, "");
        else
        {
          if (/even/.test(aR[i][0]))
          {
            if ((nFrom % 2) == 1)
              ++nFrom;
            if ((nTo % 2) == 1)
              --nTo;
            nTo = nFrom + (nTo - nFrom) / 2;
          }
          else if (/odd/.test(aR[i][0]))
          {
            if ((nFrom % 2) == 0)
              ++nFrom;
            if ((nTo % 2) == 0)
              --nTo;
            nTo = nFrom + (nTo - nFrom) / 2;
          }
        }
      }
      else
        aR[i][0] = "";
    }

    if (! aR[i][0])
    {
      aR[i][1] = "";
      nFrom    = 1;
      nTo      = aPDF[nPDF].TP;
    }

    if (aR[i][1])
    {
      if (/^r?(end|\d+)(even|odd)?(north|east|south|west|left|right|down)?$/.test(aR[i][1]))
      {
        aMatch = aR[i][1].match(/end|\d+/);

        if (aMatch[0] == "end")
          nTo = aPDF[nPDF].TP;
        else
        {
          nTo = parseInt(aMatch[0], 10);

          if (nTo == 0)
            nTo = 1;
          else if (nTo > aPDF[nPDF].TP)
            nTo = aPDF[nPDF].TP;

          aR[i][1] = aR[i][1].replace(/\d+/, nTo.toString());
        }

        if (/^r/.test(aR[i][1]))
          nTo = aPDF[nPDF].TP - nTo + 1;

        if (nFrom == nTo)
          aR[i][1] = aR[i][1].replace(/even|odd/, "");
        else
        {
          if (nFrom > nTo)
          {
            nTmp  = nFrom;
            nFrom = nTo;
            nTo   = nTmp;
          }

          if (/even/.test(aR[i][1]))
          {
            if ((nFrom % 2) == 1)
              ++nFrom;
            if ((nTo % 2) == 1)
              --nTo;
            nTo = nFrom + (nTo - nFrom) / 2;
          }
          else if (/odd/.test(aR[i][1]))
          {
            if ((nFrom % 2) == 0)
              ++nFrom;
            if ((nTo % 2) == 0)
              --nTo;
            nTo = nFrom + (nTo - nFrom) / 2;
          }
        }
      }
      else
        aR[i][1] = "";
    }

    aR[i] = aR[i][0] + (aR[i][1] ? ("-" + aR[i][1]) : "");
    aPDF[nPDF].OP += nTo - nFrom + 1;
  }

  aPDF[nPDF].R  = aR.join(" ");
  aPDF[nPDF].OR = aR.length;
  SetItemTextLV(aDlg[IDPDFLV].HWND, nPDF, 2, aPDF[nPDF].R ? aPDF[nPDF].R : sTxtAll);
  SetItemTextLV(aDlg[IDPDFLV].HWND, nPDF, 3, aPDF[nPDF].OP);
}

function Create()
{
  if (IsPDFtkExists())
  {
    if (! oFSO.FolderExists(sLastDir))
      sLastDir = sScriptDir;

    if (nTab == 0)
      Collate();
    else if (nTab == 1)
      Shuffle();
    else if (nTab == 2)
      Split();
    else if (nTab == 3)
      Watermark();
    else if (nTab == 4)
      Bookmarks();
    else if (nTab == 5)
      PDFInfo();
  }
}

function Collate()
{
  var sOutFile;
  var sTmpFile;
  var sTmpDir;
  var sFiles;
  var sPass;
  var sHandle;
  var sRanges;
  var nMaxRange;
  var aRange;
  var nRange;
  var sCmd;
  var sCmdOut;
  var bFileExists;
  var aInList;
  var aTmp;
  var nChoice;
  var i, n;

  if (bCollateW && ! oFSO.FileExists(sWaterPDF))
  {
    nTab = 3;
    SendMessage(aDlg[IDTABTC].HWND, 4912 /*TCM_SETCURFOCUS*/, nTab, 0);
    SendMessage(aDlg[IDWATERPDFE].HWND, 177 /*EM_SETSEL*/, 0, -1);
    oSys.Call("User32::SetFocus", aDlg[IDWATERPDFE].HWND);
    MsgBox(sWaterPDF ? sWaterPDF + "\n\n" + sTxtNoFile : sTxtNoWaterFile);
    return;
  }

  if (! (sOutFile = GetOpenSaveFileName(1, "", "pdf", GetFileUniqueName(sLastDir, oFSO.GetFileName(aPDF[nPDF].F)))))
    return;

  if (! (sTmpDir = CreateTempDir()))
  {
    MsgBox(sTxtNoTempDir);
    return;
  }

  bCreating = 1;
  EnableControlsDlg();
  SetDefButton(IDCREATEB, IDCREATEB);

  sFiles      = '';
  sPass       = '';
  sRanges     = '';
  nMaxRange   = 10;
  bFileExists = oFSO.FileExists(sOutFile);
  aInList     = [];
  aTmp        = [];
  nExitCode   = 0

  if (nOutRanges > nMaxRange)
  {
    nRange = 0;
    i      = 0;

    for (n = 1; n <= nOutRanges; ++n)
    {
      if (nRange == 0)
      {
        aRange  = aPDF[i].R.split(" ");
        sHandle = GetInputPDFHandle(i);
        sFiles  += sHandle + '="' + aPDF[i].F + '" ';

        if (aPDF[i].P)
          sPass += sHandle + '="' + aPDF[i].P + '" ';

        if (bFileExists && (aPDF[i].F.toUpperCase() == sOutFile.toUpperCase()))
          aInList.push(i);
      }

      sRanges += sHandle + aRange[nRange] + ' ';

      if ((n % nMaxRange == 0) || (n == nOutRanges))
      {
        if (sPass)
          sPass = 'input_pw ' + sPass;

        aTmp.push(GetTempFile(sTmpDir));

        sCmdOut = RunCmd('"' + sPDFtkExe + '" ' + sFiles + sPass + 'cat ' + sRanges + 'output "' + aTmp[aTmp.length - 1] + '"');

        if (nExitCode > 0)
        {
          if (nExitCode < 258)
            MsgBox(sCmdOut, sTxtPDFtkError);
          break;
        }

        if (nRange == aRange.length - 1)
        {
          sFiles = '';
          sPass  = '';
        }

        sRanges = '';
      }

      if (nRange == aRange.length - 1)
      {
        ++i;
        nRange = 0;
      }
      else
        ++nRange;
    }

    while ((aTmp.length > 1) && (nExitCode == 0))
    {
      sFiles = '';
      n      = aTmp.length;

      for (i = 0; i < n; ++i)
      {
        sFiles += '"' + aTmp[i] + '" ';

        if (((i + 1) % nMaxRange == 0) || (i + 1 == n))
        {
          aTmp.push(GetTempFile(sTmpDir));

          sCmdOut = RunCmd('"' + sPDFtkExe + '" ' + sFiles + 'cat output "' + aTmp[aTmp.length - 1] + '"');

          if (nExitCode > 0)
          {
            if (nExitCode < 258)
              MsgBox(sCmdOut, sTxtPDFtkError);
            break;
          }

          sFiles  = '';
        }
      }

      aTmp.splice(0, n);
    }

    if (nExitCode == 0)
    {
      if (bCollateW && oFSO.FileExists(sWaterPDF))
        sCmd = '"' + sPDFtkExe + '" "' + aTmp[0] + '" ' + GetWaterString();
      else
        sCmd = '"' + sPDFtkExe + '" "' + aTmp[0] + '" ' + 'cat ';
    }
  }
  else
  {
    for (i = 0; i < aPDF.length; ++i)
    {
      sHandle  = GetInputPDFHandle(i);
      sFiles  += sHandle + '="' + aPDF[i].F + '" ';
      sRanges += sHandle + aPDF[i].R.replace(/ /g, ' ' + sHandle) + ' ';

      if (aPDF[i].P)
        sPass += sHandle + '="' + aPDF[i].P + '" ';

      if (bFileExists && (aPDF[i].F.toUpperCase() == sOutFile.toUpperCase()))
        aInList.push(i);
    }

    if (sPass)
      sPass = 'input_pw ' + sPass;

    if (bCollateW && oFSO.FileExists(sWaterPDF))
    {
      aTmp[0] = GetTempFile(sTmpDir);
      sCmdOut = RunCmd('"' + sPDFtkExe + '" ' + sFiles + sPass + 'cat ' + sRanges + 'output "' + aTmp[0] + '"');

      if (nExitCode == 0)
        sCmd = '"' + sPDFtkExe + '" "' + aTmp[0] + '" ' + GetWaterString();
      else if (nExitCode < 258)
        MsgBox(sCmdOut, sTxtPDFtkError);
    }
    else
      sCmd = '"' + sPDFtkExe + '" ' + sFiles + sPass + 'cat ' + sRanges;
  }

  if (nExitCode == 0)
  {
    sTmpFile = bFileExists ? GetTempFile(sTmpDir) : sOutFile;
    sCmdOut  = RunCmd(sCmd + 'output "' + sTmpFile + '"' + GetPermissString());

    if (nExitCode == 0)
    {
      if (bFileExists)
      {
        while (sOutFile)
        {
          if (DeleteFile(sOutFile))
          {
            CopyFile(sTmpFile, sOutFile, 1);
            break;
          }
          else
          {
            if (MsgBox(sOutFile + "\n\n" + sTxtWriteError + "\n" + sTxtSelOtherName, 0, 0, [sTxtOK, sTxtCancel]) == 0)
              sOutFile = GetOpenSaveFileName(1, "", "pdf", sOutFile);
            else
              sOutFile = "";
          }
        }
      }

      if (oFSO.FileExists(sOutFile))
      {
        if (aInList.length)
        {
          for (i = 0; i < aInList.length; ++i)
            aPDF[aInList[i]].TP = 0;
          Refresh();
        }

        if (nAfter == 0)
          nChoice = MsgBox(sTxtCreated + "\n" + sOutFile, 0, 0, [sTxtOK, sTxtOpenPDF, sTxtOpenDir]);

        if ((nAfter == 1) || (nChoice == 1))
        {
          if (IsReaderExists())
            AkelPad.Exec('"' + sPDFReader + '" "' + sOutFile + '"');
        }
        else if ((nAfter == 2) || (nChoice == 2))
          OpenFolder(sOutFile);
      }
    }
    else if (nExitCode < 258)
      MsgBox(sCmdOut, sTxtPDFtkError);
  }

  bCreating = 0;
  EnableControlsDlg();
  DeleteFolder(sTmpDir);
}

function Shuffle()
{
  var sOutFile;
  var sTmpFile;
  var sTmpDir;
  var sTmp;
  var sFiles;
  var sPass;
  var sRanges;
  var sHandle;
  var sCmd;
  var sCmdOut;
  var bFileExists;
  var aInList;
  var nChoice;
  var i;

  if (bShuffleW && ! oFSO.FileExists(sWaterPDF))
  {
    nTab = 3;
    SendMessage(aDlg[IDTABTC].HWND, 4912 /*TCM_SETCURFOCUS*/, nTab, 0);
    SendMessage(aDlg[IDWATERPDFE].HWND, 177 /*EM_SETSEL*/, 0, -1);
    oSys.Call("User32::SetFocus", aDlg[IDWATERPDFE].HWND);
    MsgBox(sWaterPDF ? sWaterPDF + "\n\n" + sTxtNoFile : sTxtNoWaterFile);
    return;
  }

  if (! (sOutFile = GetOpenSaveFileName(1, "", "pdf", GetFileUniqueName(sLastDir, oFSO.GetFileName(aPDF[nPDF].F)))))
    return;

  if (! (sTmpDir = CreateTempDir()))
  {
    MsgBox(sTxtNoTempDir);
    return;
  }

  if (bFileExists = oFSO.FileExists(sOutFile))
    sTmpFile = GetTempFile(sTmpDir);
  else
    sTmpFile = sOutFile;

  sFiles   = '';
  sPass    = '';
  sRanges  = '';
  aInList  = [];

  for (i = 0; i < aPDF.length; ++i)
  {
    sHandle  = GetInputPDFHandle(i);
    sFiles  += sHandle + '="' + aPDF[i].F + '" ';
    sRanges += sHandle + aPDF[i].R.replace(/ /g, ' ' + sHandle) + ' ';

    if (aPDF[i].P)
      sPass += sHandle + '="' + aPDF[i].P + '" ';

    if (bFileExists && (aPDF[i].F.toUpperCase() == sOutFile.toUpperCase()))
      aInList.push(i);
  }

  if (sPass)
    sPass = 'input_pw ' + sPass;

  if (bShuffleW && oFSO.FileExists(sWaterPDF))
  {
    sTmp = GetTempFile(sTmpDir);
    sCmd = '"' + sPDFtkExe + '" ' + sFiles + sPass + 'shuffle ' + sRanges + 'output "' + sTmp;
  }
  else
    sCmd = '"' + sPDFtkExe + '" ' + sFiles + sPass + 'shuffle ' + sRanges + 'output "' + sTmpFile + '"' + GetPermissString();

  if (sCmd.length > 32767)
  {
    DeleteFolder(sTmpDir);
    MsgBox(sTxtTooManyDocs);
    return;
  }

  bCreating = 1;
  EnableControlsDlg();
  SetDefButton(IDCREATEB, IDCREATEB);

  sCmdOut = RunCmd(sCmd);

  if ((nExitCode == 0) && bShuffleW && oFSO.FileExists(sWaterPDF))
    sCmdOut = RunCmd('"' + sPDFtkExe + '" "' + sTmp + '" ' + GetWaterString() + 'output "' + sTmpFile + '"' + GetPermissString());

  if (nExitCode == 0)
  {
    if (bFileExists)
    {
      while (sOutFile)
      {
        if (DeleteFile(sOutFile))
        {
          CopyFile(sTmpFile, sOutFile, 1);
          break;
        }
        else
        {
          if (MsgBox(sOutFile + "\n\n" + sTxtWriteError + "\n" + sTxtSelOtherName, 0, 0, [sTxtOK, sTxtCancel]) == 0)
            sOutFile = GetOpenSaveFileName(1, "", "pdf", sOutFile);
          else
            sOutFile = "";
        }
      }
    }

    if (oFSO.FileExists(sOutFile))
    {
      if (aInList.length)
      {
        for (i = 0; i < aInList.length; ++i)
          aPDF[aInList[i]].TP = 0;
        Refresh();
      }

      if (nAfter == 0)
        nChoice = MsgBox(sTxtCreated + "\n" + sOutFile, 0, 0, [sTxtOK, sTxtOpenPDF, sTxtOpenDir]);

      if ((nAfter == 1) || (nChoice == 1))
      {
        if (IsReaderExists())
          AkelPad.Exec('"' + sPDFReader + '" "' + sOutFile + '"');
      }
      else if ((nAfter == 2) || (nChoice == 2))
        OpenFolder(sOutFile);
    }
  }
  else if (nExitCode < 258)
    MsgBox(sCmdOut, sTxtPDFtkError);

  bCreating = 0;
  EnableControlsDlg();
  DeleteFolder(sTmpDir);
}

function Split()
{
  var sOutDir;
  var sOutFile;
  var sCmdOut;
  var nFrom;
  var nTo;
  var aInpFile;
  var nChoice;
  var sNumber;
  var i, n;

  if (! (sOutDir = BrowseForFolder(sLastDir, "\n" + sTxtSelOutDir)))
    return;

  sLastDir  = sOutDir;
  sOutDir  += (sOutDir.slice(-1) == "\\") ? "" : "\\";
  aInpFile  = [];

  if (bSplitAll)
  {
    nFrom = 0;
    nTo   = aPDF.length - 1;
  }
  else
  {
    nFrom = nPDF;
    nTo   = nPDF;
  }

  bCreating = 1;
  EnableControlsDlg();
  SetDefButton(IDCREATEB, IDCREATEB);

  for (i = nFrom; i <= nTo; ++i)
  {
    SetCurSelLV(aDlg[IDPDFLV].HWND, i);

    if (! aInpFile[aPDF[i].F.toUpperCase()])
    {
      sOutFile = sOutDir + AkelPad.GetFilePath(aPDF[i].F, 3 /*CPF_FILEBASENAME*/) + "_%0" + aPDF[i].TP.toString().length.toString() + "d.pdf";
      sCmdOut  = RunCmd('"' + sPDFtkExe + '" "' + aPDF[i].F + '" ' + (aPDF[i].P ? 'input_pw "' + aPDF[i].P + '" ': '') + 'burst output "' + sOutFile + '"' + GetPermissString());

      if (nExitCode == 0)
      {
        aInpFile[aPDF[i].F.toUpperCase()] = 1;
        aInpFile.push(i);
      }
      else
      {
        if (nExitCode < 259)
          aInpFile.push(i);
        if (nExitCode < 258)
          MsgBox(sCmdOut, sTxtPDFtkError);

        break;
      }
    }
  }

  DeleteFile(sOutDir + "doc_data.txt");

  if (nExitCode == 0)
  {
    nChoice = 0;
    if (nAfter == 0)
    {
      sOutFile = "";
      if (aInpFile.length > 20)
      {
        for (i = 0; i < 18; ++i)
          sOutFile += "\n" + aPDF[aInpFile[i]].F;
        sOutFile += "\n...\n" + aPDF[aInpFile[aInpFile.length - 1]].F;
      }
      else
      {
        for (i = 0; i < aInpFile.length; ++i)
          sOutFile += "\n" + aPDF[aInpFile[i]].F;
      }

      nChoice = MsgBox(sTxtSplitted + sOutFile, 0, 0, [sTxtOK, sTxtOpenPDF, sTxtOpenDir]);
    }

    sOutFile = sOutDir + AkelPad.GetFilePath(aPDF[aInpFile[aInpFile.length - 1]].F, 3 /*CPF_FILEBASENAME*/) + "_" + aPDF[aInpFile[aInpFile.length - 1]].TP.toString() + ".pdf";

    if ((nAfter == 1) || (nChoice == 1))
    {
      if (IsReaderExists())
        AkelPad.Exec('"' + sPDFReader + '" "' + sOutFile + '"');
    }
    else if ((nAfter == 2) || (nChoice == 2))
      OpenFolder(sOutFile);
  }
  else
  {
    for (i = 0; i < aInpFile.length; ++i)
    {
      sOutFile = sOutDir + AkelPad.GetFilePath(aPDF[aInpFile[i]].F, 3 /*CPF_FILEBASENAME*/) + "_";

      for (n = 1; n <= aPDF[aInpFile[i]].TP; ++n)
      {
        sNumber = n.toString();

        while (sNumber.length < aPDF[aInpFile[i]].TP.toString().length)
          sNumber = "0" + sNumber;

        DeleteFile(sOutFile + sNumber + ".pdf");
      }
    }
  }

  bCreating = 0;
  EnableControlsDlg();
}

function Watermark()
{
  var sOutFile;
  var sTmpFile;
  var sOutDir;
  var sTmpDir;
  var sCmdOut;
  var bFileExists;
  var nChoice;
  var nIndex;
  var aInpFile;
  var aOutFile;
  var i;

  if (! oFSO.FileExists(sWaterPDF))
  {
    SendMessage(aDlg[IDWATERPDFE].HWND, 177 /*EM_SETSEL*/, 0, -1);
    SetDefButton(0, IDWATERPDFE);
    MsgBox(sWaterPDF + "\n\n" + sTxtNoFile);
    return;
  }

  if (bWaterAll && (aPDF.length > 1))
  {
    nIndex = sWaterAdd.search(/[<>:"\/\\|?*]/);

    if (nIndex >= 0)
    {
      SendMessage(aDlg[IDWATERADDE].HWND, 177 /*EM_SETSEL*/, nIndex, nIndex + 1);
      SetDefButton(0, IDWATERADDE);
      MsgBox(sTxtInvalidChar);
      return;
    }

    if (! (sOutDir = BrowseForFolder(sLastDir, "\n" + sTxtSelOutDir)))
      return;

    if (! (sTmpDir = CreateTempDir()))
    {
      MsgBox(sTxtNoTempDir);
      return;
    }

    sLastDir  = sOutDir;
    sOutDir  += (sOutDir.slice(-1) == "\\") ? "" : "\\";
    aInpFile  = [];
    aOutFile  = [];
    nExitCode = 0;

    bCreating = 1;
    EnableControlsDlg();
    SetDefButton(IDCREATEB, IDCREATEB);

    for (i = 0; (i < aPDF.length) && (nExitCode == 0); ++i)
    {
      SetCurSelLV(aDlg[IDPDFLV].HWND, i);

      if (! aInpFile[aPDF[i].F.toUpperCase()])
      {
        sOutFile = sOutDir + AkelPad.GetFilePath(aPDF[i].F, 3 /*CPF_FILEBASENAME*/) + sWaterAdd + "." + AkelPad.GetFilePath(aPDF[i].F, 4 /*CPF_FILEEXT*/);

        if (bFileExists = oFSO.FileExists(sOutFile))
          sTmpFile = GetTempFile(sTmpDir);
        else
          sTmpFile = sOutFile;

        sCmdOut = RunCmd('"' + sPDFtkExe + '" "' + aPDF[i].F + '" ' + (aPDF[i].P ? 'input_pw "' + aPDF[i].P + '" ': '') + GetWaterString() + 'output "' + sTmpFile + '"' + GetPermissString());

        if (nExitCode == 0)
        {
          if (bFileExists)
          {
            if ((nChoice != 1) && (nChoice != 3))
              nChoice = MsgBox(sOutFile + "\n\n" + sTxtFileExists, 0, 0, [sTxtReplace, sTxtReplaceAll, sTxtSkip, sTxtSkipAll, sTxtCancel]);

            if ((nChoice == -1) || (nChoice == 4))
              nExitCode = 260;
            else if ((nChoice == 0) || (nChoice == 1))
            {
              for (;;)
              {
                if (DeleteFile(sOutFile))
                {
                  CopyFile(sTmpFile, sOutFile, 1);
                  aInpFile[aPDF[i].F.toUpperCase()] = 1;
                  aOutFile[sOutFile.toUpperCase()]  = 1;
                  aOutFile.push(sOutFile);
                  break;
                }
                else if (MsgBox(sOutFile + "\n\n" + sTxtWriteError + " " + sTxtUnlockFile, 0, 0, [sTxtRetry, sTxtSkip]) != 0)
                  break;
              }
            }
          }
          else
          {
            aInpFile[aPDF[i].F.toUpperCase()] = 1;
            aOutFile[sOutFile.toUpperCase()]  = 1;
            aOutFile.push(sOutFile);
          }
        }
        else if (nExitCode < 258)
          MsgBox(sCmdOut, sTxtPDFtkError);
      }
    }

    if (aOutFile.length)
    {
      for (i = 0; i < aPDF.length; ++i)
      {
        if (aOutFile[aPDF[i].F.toUpperCase()])
          aPDF[i].TP = 0;
      }
      Refresh();

      nChoice = 0;
      if (nAfter == 0)
      {
        sOutFile = "";
        if (aOutFile.length > 20)
        {
          for (i = 0; i < 18; ++i)
            sOutFile += "\n" + aOutFile[i];
          sOutFile += "\n...\n" + aOutFile[aOutFile.length - 1];
        }
        else
        {
          for (i = 0; i < aOutFile.length; ++i)
            sOutFile += "\n" + aOutFile[i];
        }

        nChoice = MsgBox(sTxtCreated + sOutFile, 0, 0, [sTxtOK, sTxtOpenPDF, sTxtOpenDir]);
      }

      if ((nAfter == 1) || (nChoice == 1))
      {
        if (IsReaderExists())
          AkelPad.Exec('"' + sPDFReader + '" "' + aOutFile[aOutFile.length - 1] + '"');
      }
      else if ((nAfter == 2) || (nChoice == 2))
        OpenFolder(aOutFile[aOutFile.length - 1]);
    }
  }
  else
  {
    if (! (sOutFile = GetOpenSaveFileName(1, "", "pdf", GetFileUniqueName(sLastDir, oFSO.GetFileName(aPDF[nPDF].F)))))
      return;

    if (! (sTmpDir = CreateTempDir()))
    {
      MsgBox(sTxtNoTempDir);
      return;
    }

    if (bFileExists = oFSO.FileExists(sOutFile))
      sTmpFile = GetTempFile(sTmpDir);
    else
      sTmpFile = sOutFile;

    bCreating = 1;
    EnableControlsDlg();
    SetDefButton(IDCREATEB, IDCREATEB);

    sCmdOut = RunCmd('"' + sPDFtkExe + '" "' + aPDF[nPDF].F + '" ' + (aPDF[nPDF].P ? 'input_pw "' + aPDF[nPDF].P + '" ': '') + GetWaterString() + 'output "' + sTmpFile + '"' + GetPermissString());

    if (nExitCode == 0)
    {
      if (bFileExists)
      {
        while (sOutFile)
        {
          if (DeleteFile(sOutFile))
          {
            CopyFile(sTmpFile, sOutFile, 1);
            break;
          }
          else
          {
            if (MsgBox(sOutFile + "\n\n" + sTxtWriteError + "\n" + sTxtSelOtherName, 0, 0, [sTxtOK, sTxtCancel]) == 0)
              sOutFile = GetOpenSaveFileName(1, "", "pdf", sOutFile);
            else
              sOutFile = "";
          }
        }
      }

      if (oFSO.FileExists(sOutFile))
      {
        if (bFileExists)
        {
          for (i = 0; i < aPDF.length; ++i)
          {
            if (aPDF[i].F.toUpperCase() == sOutFile.toUpperCase())
              aPDF[i].TP = 0;
          }
          Refresh();
        }

        if (nAfter == 0)
          nChoice = MsgBox(sTxtCreated + "\n" + sOutFile, 0, 0, [sTxtOK, sTxtOpenPDF, sTxtOpenDir]);

        if ((nAfter == 1) || (nChoice == 1))
        {
          if (IsReaderExists())
            AkelPad.Exec('"' + sPDFReader + '" "' + sOutFile + '"');
        }
        else if ((nAfter == 2) || (nChoice == 2))
          OpenFolder(sOutFile);
      }
    }
    else if (nExitCode < 258)
      MsgBox(sCmdOut, sTxtPDFtkError);
  }

  bCreating = 0;
  EnableControlsDlg();
  DeleteFolder(sTmpDir);
}

Last edited by KDJ on Wed Nov 04, 2015 8:01 pm, edited 5 times in total.

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

Post by KDJ »

GUI for PDFtk Server - manipulating PDF documents. Part 4.

Code: Select all

function Bookmarks()
{
  var sInfoFile;
  var sOutFile;
  var sTmpFile;
  var sTmpDir;
  var sCmdOut;
  var aBookmark;
  var sBookmark;
  var nLevel;
  var bFileExists;
  var nChoice;
  var i, n;

  if (nBook == 0)
  {
    bCreating = 1;
    EnableControlsDlg();
    SetDefButton(IDCREATEB, IDCREATEB);

    sCmdOut = RunCmd('"' + sPDFtkExe + '" "' + aPDF[nPDF].F + '" ' + (aPDF[nPDF].P ? 'input_pw "' + aPDF[nPDF].P + '" ': '') + 'dump_data' + (bUTF8 ? '_utf8' : ''));

    if (nExitCode == 0)
    {
      aBookmark = sCmdOut.match(/^BookmarkBegin\r\nBookmarkTitle: [\s\S]+?\r\nBookmarkLevel: \d+\r\nBookmarkPageNumber: \d+$/gm);

      if (aBookmark)
      {
        sCmdOut = "";

        for (i = 0; i < aBookmark.length; ++i)
        {
          nLevel = parseInt(aBookmark[i].match(/^BookmarkLevel: (\d+)$/m)[1]);

          for (n = 2; n <= nLevel; ++n)
            sCmdOut += "\t";

          sCmdOut += aBookmark[i].match(/^BookmarkTitle: ([\s\S]+?)\r\nBookmarkLevel: /m)[1].replace(/(\r\r\n)|(\r\n)|\r|\n/g, " ") + "/" + aBookmark[i].match(/^BookmarkPageNumber: (\d+)$/m)[1] + "\r\n";
        }

        if (sOutFile = GetOpenSaveFileName(1, "", "txt", GetFileUniqueName(sLastDir, oFSO.GetBaseName(aPDF[nPDF].F) + ".txt")))
        {
          if (bUTF8)
            sCmdOut = "" + sCmdOut;

          while (sOutFile && (! WriteFile(sOutFile, sCmdOut, 0)))
          {
            if (MsgBox(sOutFile + "\n\n" + sTxtWriteError + "\n" + sTxtSelOtherName, 0, 0, [sTxtOK, sTxtCancel]) == 0)
              sOutFile = GetOpenSaveFileName(1, "", "txt", sOutFile);
            else
              sOutFile = "";
          }

          if (oFSO.FileExists(sOutFile))
          {
            if (nAfter == 0)
              nChoice = MsgBox(sTxtCreated + "\n" + sOutFile, 0, 0, [sTxtOK, sTxtOpenTXT, sTxtOpenDir]);

            if ((nAfter == 1) || (nChoice == 1))
            {
              if (IsEditorExists())
                AkelPad.Exec('"' + sTXTEditor + '" "' + sOutFile + '"');
            }
            else if ((nAfter == 2) || (nChoice == 2))
              OpenFolder(sOutFile);
          }
        }
      }
      else
        MsgBox(aPDF[nPDF].F + "\n\n" + sTxtNoPDFBookmarks);
    }
    else if (nExitCode < 258)
      MsgBox(sCmdOut, sTxtPDFtkError);
  }
  else
  {
    if (! oFSO.FileExists(sBookTXT))
    {
      SendMessage(aDlg[IDBOOKTXTE].HWND, 177 /*EM_SETSEL*/, 0, -1);
      SetDefButton(0, IDBOOKTXTE);
      MsgBox(sBookTXT + "\n\n" + sTxtNoFile);
      return;
    }

    sBookmark = "";
    aBookmark = ReadFile(sBookTXT, 0).split(/(\r\r\n)|(\r\n)|\r|\n/);

    if (aBookmark[0].substr(0, 3) == "")
      aBookmark[0] = aBookmark[0].substr(3);

    for (i = 0; i < aBookmark.length; ++i)
    {
      if (/\S/.test(aBookmark[i]))
      {
        aBookmark[i] = aBookmark[i].match(/^(\t*)(.+?)(\/(\d+))*$/);
        sBookmark   += "BookmarkBegin" + "\r\n";
        sBookmark   += "BookmarkTitle: " + aBookmark[i][2] + "\r\n";
        sBookmark   += "BookmarkLevel: " + (aBookmark[i][1].length + 1) + "\r\n";
        sBookmark   += "BookmarkPageNumber: " + aBookmark[i][4] + "\r\n";
      }
    }

    if (! sBookmark)
    {
      SendMessage(aDlg[IDBOOKTXTE].HWND, 177 /*EM_SETSEL*/, 0, -1);
      SetDefButton(0, IDBOOKTXTE);
      MsgBox(sBookTXT + "\n\n" + sTxtNoTXTBookmarks);
      return;
    }

    if (! (sOutFile = GetOpenSaveFileName(1, "", "pdf", GetFileUniqueName(sLastDir, oFSO.GetFileName(aPDF[nPDF].F)))))
      return;

    if (! (sTmpDir = CreateTempDir()))
    {
      MsgBox(sTxtNoTempDir);
      return;
    }

    sInfoFile = GetTempFile(sTmpDir);
    if (! WriteFile(sInfoFile, sBookmark, 0))
    {
      MsgBox(sInfoFile + "\n\n" + sTxtWriteError);
      DeleteFolder(sTmpDir);
      return;
    }

    if (bFileExists = oFSO.FileExists(sOutFile))
      sTmpFile = GetTempFile(sTmpDir);
    else
      sTmpFile = sOutFile;

    bCreating = 1;
    EnableControlsDlg();
    SetDefButton(IDCREATEB, IDCREATEB);

    sCmdOut = RunCmd('"' + sPDFtkExe + '" "' + aPDF[nPDF].F + '" ' + (aPDF[nPDF].P ? 'input_pw "' + aPDF[nPDF].P + '" ': '') + 'update_info' + (bUTF8 ? '_utf8' : '') + ' "' + sInfoFile + '" ' + 'output "' + sTmpFile + '"' + GetPermissString());

    if (nExitCode == 0)
    {
      if (bFileExists)
      {
        while (sOutFile)
        {
          if (DeleteFile(sOutFile))
          {
            CopyFile(sTmpFile, sOutFile, 1);
            break;
          }
          else
          {
            if (MsgBox(sOutFile + "\n\n" + sTxtWriteError + "\n" + sTxtSelOtherName, 0, 0, [sTxtOK, sTxtCancel]) == 0)
              sOutFile = GetOpenSaveFileName(1, "", "pdf", sOutFile);
            else
              sOutFile = "";
          }
        }
      }

      if (oFSO.FileExists(sOutFile))
      {
        if (bFileExists)
        {
          for (i = 0; i < aPDF.length; ++i)
          {
            if (aPDF[i].F.toUpperCase() == sOutFile.toUpperCase())
              aPDF[i].TP = 0;
          }
          Refresh();
        }

        if (nAfter == 0)
          nChoice = MsgBox(sTxtCreated + "\n" + sOutFile, 0, 0, [sTxtOK, sTxtOpenPDF, sTxtOpenDir]);

        if ((nAfter == 1) || (nChoice == 1))
        {
          if (IsReaderExists())
            AkelPad.Exec('"' + sPDFReader + '" "' + sOutFile + '"');
        }
        else if ((nAfter == 2) || (nChoice == 2))
          OpenFolder(sOutFile);
      }
    }
    else if (nExitCode < 258)
      MsgBox(sCmdOut, sTxtPDFtkError);

    DeleteFolder(sTmpDir);
  }

  bCreating = 0;
  EnableControlsDlg();
}

function PDFInfo()
{
  var sInfoFile;
  var sOutFile;
  var sTmpFile;
  var sTmpDir;
  var sOperation;
  var sCmdOut;
  var bFileExists;
  var nChoice;
  var i;

  if (nData < 3)
  {
    bCreating = 1;
    EnableControlsDlg();
    SetDefButton(IDCREATEB, IDCREATEB);

    if (nData == 0)
      sOperation = "dump_data_annots";
    else if (nData == 1)
      sOperation = "dump_data_fields" + (bUTF8 ? "_utf8" : "");
    else if (nData == 2)
      sOperation = "dump_data" + (bUTF8 ? "_utf8" : "");

    sCmdOut = RunCmd('"' + sPDFtkExe + '" "' + aPDF[nPDF].F + '" ' + (aPDF[nPDF].P ? 'input_pw "' + aPDF[nPDF].P + '" ': '') + sOperation);

    if (nExitCode == 0)
    {
      if (sCmdOut)
      {
        if (sOutFile = GetOpenSaveFileName(1, "", "txt", GetFileUniqueName(sLastDir, oFSO.GetBaseName(aPDF[nPDF].F) + ".txt")))
        {
          if (bUTF8)
            sCmdOut = "" + sCmdOut;

          while (sOutFile && (! WriteFile(sOutFile, sCmdOut, 0)))
          {
            if (MsgBox(sOutFile + "\n\n" + sTxtWriteError + "\n" + sTxtSelOtherName, 0, 0, [sTxtOK, sTxtCancel]) == 0)
              sOutFile = GetOpenSaveFileName(1, "", "txt", sOutFile);
            else
              sOutFile = "";
          }

          if (oFSO.FileExists(sOutFile))
          {
            if (nAfter == 0)
              nChoice = MsgBox(sTxtCreated + "\n" + sOutFile, 0, 0, [sTxtOK, sTxtOpenTXT, sTxtOpenDir]);

            if ((nAfter == 1) || (nChoice == 1))
            {
              if (IsEditorExists())
                AkelPad.Exec('"' + sTXTEditor + '" "' + sOutFile + '"');
            }
            else if ((nAfter == 2) || (nChoice == 2))
              OpenFolder(sOutFile);
          }
        }
      }
      else
        MsgBox(aPDF[nPDF].F + "\n\n" + sTxtNoPDFData);
    }
    else if (nExitCode < 258)
      MsgBox(sCmdOut, sTxtPDFtkError);
  }
  else
  {
    if (! oFSO.FileExists(sDataTXT))
    {
      SendMessage(aDlg[IDDATATXTE].HWND, 177 /*EM_SETSEL*/, 0, -1);
      SetDefButton(0, IDDATATXTE);
      MsgBox(sDataTXT + "\n\n" + sTxtNoFile);
      return;
    }

    if (! (sOutFile = GetOpenSaveFileName(1, "", "pdf", GetFileUniqueName(sLastDir, oFSO.GetFileName(aPDF[nPDF].F)))))
      return;

    if (! (sTmpDir = CreateTempDir()))
    {
      MsgBox(sTxtNoTempDir);
      return;
    }

    bCreating = 1;
    EnableControlsDlg();
    SetDefButton(IDCREATEB, IDCREATEB);

    if (bFileExists = oFSO.FileExists(sOutFile))
      sTmpFile = GetTempFile(sTmpDir);
    else
      sTmpFile = sOutFile;

    sInfoFile = GetTempFile(sTmpDir);
    CopyFile(sDataTXT, sInfoFile);

    sCmdOut = RunCmd('"' + sPDFtkExe + '" "' + aPDF[nPDF].F + '" ' + (aPDF[nPDF].P ? 'input_pw "' + aPDF[nPDF].P + '" ': '') + 'update_info' + (bUTF8 ? '_utf8' : '') + ' "' + sInfoFile + '" ' + 'output "' + sTmpFile + '"' + GetPermissString());

    if (nExitCode == 0)
    {
      if (bFileExists)
      {
        while (sOutFile)
        {
          if (DeleteFile(sOutFile))
          {
            CopyFile(sTmpFile, sOutFile, 1);
            break;
          }
          else
          {
            if (MsgBox(sOutFile + "\n\n" + sTxtWriteError + "\n" + sTxtSelOtherName, 0, 0, [sTxtOK, sTxtCancel]) == 0)
              sOutFile = GetOpenSaveFileName(1, "", "pdf", sOutFile);
            else
              sOutFile = "";
          }
        }
      }

      if (oFSO.FileExists(sOutFile))
      {
        if (bFileExists)
        {
          for (i = 0; i < aPDF.length; ++i)
          {
            if (aPDF[i].F.toUpperCase() == sOutFile.toUpperCase())
              aPDF[i].TP = 0;
          }
          Refresh();
        }

        if (nAfter == 0)
          nChoice = MsgBox(sTxtCreated + "\n" + sOutFile, 0, 0, [sTxtOK, sTxtOpenPDF, sTxtOpenDir]);

        if ((nAfter == 1) || (nChoice == 1))
        {
          if (IsReaderExists())
            AkelPad.Exec('"' + sPDFReader + '" "' + sOutFile + '"');
        }
        else if ((nAfter == 2) || (nChoice == 2))
          OpenFolder(sOutFile);
      }
    }
    else if (nExitCode < 258)
      MsgBox(sCmdOut, sTxtPDFtkError);

    DeleteFolder(sTmpDir);
  }

  bCreating = 0;
  EnableControlsDlg();
}

function ReadFile(sFile, bUnicode)
{
  var sText = "";
  var oFile;

  try
  {
    oFile = oFSO.OpenTextFile(sFile, 1, false, bUnicode ? -1 : 0);
  }
  catch (oError)
  {
    return sText;
  }

  try
  {
    sText = oFile.ReadAll();
  }
  catch (oError)
  {}

  oFile.Close();
  return sText;
}

function WriteFile(sFile, sText, bUnicode)
{
  var bWrite = false;
  var oFile;

  try
  {
    oFile = oFSO.OpenTextFile(sFile, 2, true, bUnicode ? -1 : 0);
  }
  catch (oError)
  {
    return bWrite;
  }

  try
  {
    oFile.Write(sText);
    bWrite = true;
  }
  catch (oError)
  {}

  oFile.Close();
  return bWrite;
}

function CopyFile(sSource, sTarget, bMove)
{
  var bSuccess = true;

  try
  {
    if (bMove)
      oFSO.MoveFile(sSource, sTarget);
    else
      oFSO.CopyFile(sSource, sTarget);
  }
  catch (oError)
  {
    bSuccess = false;
  }

  return bSuccess;
}

function DeleteFile(sFile)
{
  try
  {
    oFSO.DeleteFile(sFile, 1);
  }
  catch (oError)
  {}

  return ! oFSO.FileExists(sFile);
}

function CreateFolder(sDir)
{
  try
  {
    oFSO.CreateFolder(sDir);
  }
  catch (oError)
  {}

  return oFSO.FolderExists(sDir);
}

function DeleteFolder(sDir)
{
  try
  {
    oFSO.DeleteFolder(sDir, 1);
  }
  catch (oError)
  {}

  return ! oFSO.FolderExists(sDir);
}

function CreateTempDir()
{
  var nBufSize = 260;
  var lpDir    = AkelPad.MemAlloc(nBufSize * 2);
  var lpName   = AkelPad.MemAlloc(nBufSize * 2);
  var sDir;

  oSys.Call("Kernel32::GetTempPathW", nBufSize, lpDir);
  sDir = AkelPad.MemRead(lpDir, 1 /*DT_UNICODE*/);

  if ((! oFSO.FolderExists(sDir)) && (! CreateFolder(sDir)))
    sDir = "";

  if (sDir)
  {
    oSys.Call("Shell32::PathMakeUniqueName", lpName, nBufSize, sDlgTitle, 0, sDir);
    sDir = AkelPad.MemRead(lpName, 1 /*DT_UNICODE*/);

    if (! CreateFolder(sDir))
      sDir = "";
  }

  AkelPad.MemFree(lpDir);
  AkelPad.MemFree(lpName);

  return sDir;
}

function GetTempFile(sDir)
{
  var lpFile = AkelPad.MemAlloc(260 * 2);
  var sFile;

  oSys.Call("Kernel32::GetTempFileNameW", sDir, "pdf", 0, lpFile);
  sFile = AkelPad.MemRead(lpFile, 1 /*DT_UNICODE*/);
  AkelPad.MemFree(lpFile);

  return sFile;
}

function GetFileUniqueName(sDir, sFile)
{
  var nBufSize;
  var lpDir;
  var lpName;

  sDir += (sDir.slice(-1) == "\\") ? "" : "\\";

  if (oFSO.FileExists(sDir + sFile) || oFSO.FolderExists(sDir + sFile))
  {
    nBufSize = 260;
    lpDir    = AkelPad.MemAlloc(nBufSize * 2);
    lpName   = AkelPad.MemAlloc(nBufSize * 2);

    oSys.Call("Shell32::PathMakeUniqueName", lpName, nBufSize, sFile, 0, sDir);
    sFile = AkelPad.MemRead(lpName, 1 /*DT_UNICODE*/);
    AkelPad.MemFree(lpName);
  }
  else
    sFile = sDir + sFile;

  return sFile;
}

function GetInputPDFHandle(n)
{
  var aN = [];
  var i;

  for (i = 3; i >= 0; --i)
  {
    aN[i] = Math.floor(n / Math.pow(26, i));
    n     = n % Math.pow(26, i);
  }

  return String.fromCharCode(aN[3] + 65, aN[2] + 65, aN[1] + 65, aN[0] + 65).replace(/^A{1,3}(.+)$/, "$1");
}

function GetWaterString()
{
  var sWater;

  if (nWater == 0)
    sWater = 'background';
  else if (nWater == 1)
    sWater = 'multibackground';
  else if (nWater == 2)
    sWater = 'stamp';
  else
    sWater = 'multistamp';

  return sWater + ' "' + sWaterPDF + '" ';
}

function GetPermissString()
{
  var sPermiss = '';

  if (bPassProt)
  {
    if (bTopPrint && bLowPrint && bModCont && bAssembly && bCopyCont && bScrRead && bModAnnot && bFillIn)
      sPermiss = ' AllFeatures';
    else
    {
      if (bTopPrint)
        sPermiss += ' Printing';
      if (bLowPrint)
        sPermiss += ' DegradedPrinting';
      if (bModCont)
        sPermiss += ' ModifyContents';
      if (bAssembly)
        sPermiss += ' Assembly';
      if (bCopyCont)
        sPermiss += ' CopyContents';
      if (bScrRead)
        sPermiss += ' ScreenReaders';
      if (bModAnnot)
        sPermiss += ' ModifyAnnotations';
      if (bFillIn)
        sPermiss += ' FillIn';
    }

    if (sPermiss)
      sPermiss = ' allow' + sPermiss;
    if (sOwnerPass)
      sPermiss += ' owner_pw "' + sOwnerPass + '"';
    if (sUserPass)
      sPermiss += ' user_pw "' + sUserPass + '"';
  }

  return sPermiss;
}

function OpenPDF()
{
  var sFile;

  if (IsReaderExists() && (sFile = GetOpenSaveFileName(0, sTxtOpenPDF.replace("&", ""), "pdf", "", 0)))
    AkelPad.Exec('"' + sPDFReader + '" "' + sFile + '"');
}

function OpenTXT()
{
  var sFile;

  if (IsEditorExists() && (sFile = GetOpenSaveFileName(0, sTxtOpenTXT.replace("&", ""), "txt", "", 0)))
    AkelPad.Exec('"' + sTXTEditor + '" "' + sFile + '"');
}

function OpenFolder(sFile)
{
  var nCount;
  var lpNull;
  var lpIDL;

  if (! oFSO.FileExists(sFile))
  {
    nCount = 1;
    lpNull = AkelPad.MemAlloc(1);

    if (oFSO.FolderExists(sLastDir))
      sFile = sLastDir;
    else
      sFile = sScriptDir;
  }

  lpIDL = oSys.Call("Shell32::ILCreateFromPathW", sFile);
  oSys.Call("Shell32::SHOpenFolderAndSelectItems", lpIDL, nCount, lpNull, 0);
  oSys.Call("Shell32::ILFree", lpIDL);
  AkelPad.MemFree(lpNull);
}

function PDFtkHelp()
{
  var sFile;

  if (IsPDFtkExists())
  {
    sFile = sPDFtkDir + ((sPDFtkDir.slice(-1) == "\\") ? "" : "\\") + "pdftk_help.txt";

    if (! oFSO.FileExists(sFile))
      RunCmd('cmd.exe /c ""' + sPDFtkExe + '" --help > "' + sFile + '""');

    if (IsEditorExists() && oFSO.FileExists(sFile))
      AkelPad.Exec('"' + sTXTEditor + '" "' + sFile + '"');
  }
}

function RunCmd(sCmd)
{
  var sOutput       = "";
  var hCurProcess   = oSys.Call("Kernel32::GetCurrentProcess");
  var nBufSize      = 65536;
  var lpBuffer      = AkelPad.MemAlloc(nBufSize);
  var lpBytesAvail  = AkelPad.MemAlloc(4);
  var lpBytesRead   = AkelPad.MemAlloc(4);
  var lpExitCode    = AkelPad.MemAlloc(4);
  var lpMsg         = AkelPad.MemAlloc(_X64 ? 48 : 28 /*sizeof(MSG)*/);
  var lpSA          = AkelPad.MemAlloc(_X64 ? 24 : 12 /*sizeof(SECURITY_ATTRIBUTES)*/);
  var lpSI          = AkelPad.MemAlloc(_X64 ? 104 : 68 /*sizeof(STARTUPINFO)*/);
  var lpPI          = AkelPad.MemAlloc(_X64 ? 24 : 16 /*sizeof(PROCESS_INFORMATION)*/);
  var lpInpRead     = AkelPad.MemAlloc(_X64 ? 8 : 4);
  var lpInpWriteTmp = AkelPad.MemAlloc(_X64 ? 8 : 4);
  var lpInpWrite    = AkelPad.MemAlloc(_X64 ? 8 : 4);
  var lpOutReadTmp  = AkelPad.MemAlloc(_X64 ? 8 : 4);
  var lpOutRead     = AkelPad.MemAlloc(_X64 ? 8 : 4);
  var lpOutWrite    = AkelPad.MemAlloc(_X64 ? 8 : 4);
  var lpErrWrite    = AkelPad.MemAlloc(_X64 ? 8 : 4);
  var hInpRead;
  var hInpWriteTmp;
  var hInpWrite;
  var hOutReadTmp;
  var hOutRead;
  var hOutWrite;
  var hErrWrite;
  var hThread;
  var nBytesAvail;

  AkelPad.MemCopy(_PtrAdd(lpSA, 0), _X64 ? 24 : 12, 3 /*DT_DWORD*/); //nLength
  AkelPad.MemCopy(_PtrAdd(lpSA, _X64 ? 16 : 8),  1, 3 /*DT_DWORD*/); //bInheritHandle

  oSys.Call("Kernel32::CreatePipe", lpInpRead,    lpInpWriteTmp, lpSA, nBufSize);
  oSys.Call("Kernel32::CreatePipe", lpOutReadTmp, lpOutWrite,    lpSA, nBufSize);
  hInpRead     = AkelPad.MemRead(lpInpRead,     2 /*DT_QWORD*/);
  hInpWriteTmp = AkelPad.MemRead(lpInpWriteTmp, 2 /*DT_QWORD*/);
  hOutReadTmp  = AkelPad.MemRead(lpOutReadTmp,  2 /*DT_QWORD*/);
  hOutWrite    = AkelPad.MemRead(lpOutWrite,    2 /*DT_QWORD*/);

  oSys.Call("Kernel32::DuplicateHandle", hCurProcess, hInpWriteTmp, hCurProcess, lpInpWrite, 0, 0 /*bInheritHandle*/, 2 /*DUPLICATE_SAME_ACCESS*/);
  oSys.Call("Kernel32::DuplicateHandle", hCurProcess, hOutReadTmp,  hCurProcess, lpOutRead,  0, 0 /*bInheritHandle*/, 2 /*DUPLICATE_SAME_ACCESS*/);
  oSys.Call("Kernel32::DuplicateHandle", hCurProcess, hOutWrite,    hCurProcess, lpErrWrite, 0, 1 /*bInheritHandle*/, 2 /*DUPLICATE_SAME_ACCESS*/);
  hInpWrite = AkelPad.MemRead(lpInpWrite, 2 /*DT_QWORD*/);
  hOutRead  = AkelPad.MemRead(lpOutRead,  2 /*DT_QWORD*/);
  hErrWrite = AkelPad.MemRead(lpErrWrite, 2 /*DT_QWORD*/);

  AkelPad.MemCopy(_PtrAdd(lpSI, 0),         _X64 ? 104 : 68, 3 /*DT_DWORD*/); //cb=sizeof(STARTUPINFO)
  AkelPad.MemCopy(_PtrAdd(lpSI, _X64 ? 60 : 44), 0x00000101, 3 /*DT_DWORD*/); //dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW
  AkelPad.MemCopy(_PtrAdd(lpSI, _X64 ? 80 : 56),   hInpRead, 2 /*DT_QWORD*/); //hStdInput
  AkelPad.MemCopy(_PtrAdd(lpSI, _X64 ? 88 : 60),  hOutWrite, 2 /*DT_QWORD*/); //hStdOutput
  AkelPad.MemCopy(_PtrAdd(lpSI, _X64 ? 96 : 64),  hErrWrite, 2 /*DT_QWORD*/); //hStdError

  if (oSys.Call("Kernel32::CreateProcessW", 0, sCmd, 0, 0, 1 /*bInheritHandles*/, 0x10 /*CREATE_NEW_CONSOLE*/, 0, 0, lpSI, lpPI))
  {
    hProcess = AkelPad.MemRead(_PtrAdd(lpPI, 0),             2 /*DT_QWORD*/);
    hThread  = AkelPad.MemRead(_PtrAdd(lpPI, _X64 ?  8 : 4), 2 /*DT_QWORD*/);

    oSys.Call("User32::ShowWindow", aDlg[IDPROGRESS].HWND, 1);
    oSys.Call("User32::UpdateWindow", hDlg);

    while (oSys.Call("Kernel32::PeekNamedPipe", hOutRead, 0, 0, 0, lpBytesAvail, 0) && oSys.Call("Kernel32::GetExitCodeProcess", hProcess, lpExitCode))
    {
      while (oSys.Call("User32::PeekMessageW", lpMsg, hDlg, 0, 0, 0x1 /*PM_REMOVE*/))
      {
        oSys.Call("User32::TranslateMessage", lpMsg);
        oSys.Call("User32::DispatchMessageW", lpMsg);
      }

      nExitCode = AkelPad.MemRead(lpExitCode, 3 /*DT_DWORD*/);

      if (nBytesAvail = AkelPad.MemRead(lpBytesAvail, 3 /*DT_DWORD*/))
      {
        if (nBytesAvail >= nBufSize)
          nBytesAvail = nBufSize - 1;

        oSys.Call("Kernel32::ReadFile", hOutRead, lpBuffer, nBytesAvail, lpBytesRead, 0);
        sOutput += AkelPad.MemRead(lpBuffer, 0 /*DT_ANSI*/, AkelPad.MemRead(lpBytesRead, 3 /*DT_DWORD*/));
      }
      else if (nExitCode == 259 /*STILL_ACTIVE*/)
        WScript.Sleep(10);
      else
        break;

      SendMessage(aDlg[IDPROGRESS].HWND, 1029 /*PBM_STEPIT*/, 0, 0);
    }

    oSys.Call("User32::ShowWindow", aDlg[IDPROGRESS].HWND, 0);
  }
  else
  {
    nExitCode = 260;
    MsgBox(sTxtCantExec + "\n" + sCmd);
  }

  AkelPad.MemFree(lpBuffer);
  AkelPad.MemFree(lpBytesAvail);
  AkelPad.MemFree(lpBytesRead);
  AkelPad.MemFree(lpExitCode);
  AkelPad.MemFree(lpMsg);
  AkelPad.MemFree(lpSA);
  AkelPad.MemFree(lpPI);
  AkelPad.MemFree(lpSI);
  AkelPad.MemFree(lpInpRead);
  AkelPad.MemFree(lpInpWriteTmp);
  AkelPad.MemFree(lpInpWrite);
  AkelPad.MemFree(lpOutReadTmp);
  AkelPad.MemFree(lpOutRead);
  AkelPad.MemFree(lpOutWrite);
  AkelPad.MemFree(lpErrWrite);

  oSys.Call("Kernel32::CloseHandle", hInpRead);
  oSys.Call("Kernel32::CloseHandle", hInpWriteTmp);
  oSys.Call("Kernel32::CloseHandle", hInpWrite);
  oSys.Call("Kernel32::CloseHandle", hOutReadTmp);
  oSys.Call("Kernel32::CloseHandle", hOutRead);
  oSys.Call("Kernel32::CloseHandle", hOutWrite);
  oSys.Call("Kernel32::CloseHandle", hErrWrite);
  oSys.Call("Kernel32::CloseHandle", hProcess);
  oSys.Call("Kernel32::CloseHandle", hThread);

  hProcess = 0;

  return sOutput;
}

function StopCmd()
{
  if (hProcess)
  {
    oSys.Call("Kernel32::TerminateProcess", hProcess, 258);
    oSys.Call("Kernel32::WaitForSingleObject", hProcess, 100);
  }
}

function GetOpenSaveFileName(bSave, sTitle, sExt, sFile, bMultiSelect, nX, nY)
{
  var sFunc    = bSave ? "GetSaveFileNameW" : "GetOpenFileNameW";
  var lpCurDir = AkelPad.MemAlloc(260 * 2);
  var oRect    = {};
  var sFilter  = "*." + sExt + "\0*." + sExt + "\0\0";
  var lpFilter = AkelPad.MemAlloc(sFilter.length * 2 + 2);
  var lpFile   = AkelPad.MemAlloc(0x80000 * 2);
  var lpDir    = AkelPad.MemAlloc(260 * 2);
  var lpTitle  = AkelPad.MemAlloc(sTitle.length * 2 + 2);
  var lpDefExt = AkelPad.MemAlloc(sFilter.length * 2 + 2);
  var nOFNSize = _X64 ? 152 : 88 /*sizeof(OPENFILENAME)*/;
  var lpOFN    = AkelPad.MemAlloc(nOFNSize);
  var nFlags   = 0x02081026 /*OFN_DONTADDTORECENT|OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_ENABLEHOOK|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT*/;
  var sCurDir;
  var hWndOwn;
  var vFile;
  var nOffset;
  var i;

  oSys.Call("Kernel32::GetCurrentDirectoryW", 260, lpCurDir);
  sCurDir = AkelPad.MemRead(lpCurDir, 1 /*DT_UNICODE*/);

  GetWindowPos(hDlg, oRect);
  if (typeof nX != "number")
    nX = oRect.X + (oRect.W - Scale.X(560)) / 2;
  if (typeof nY != "number")
    nY = oRect.Y + (oRect.H - Scale.Y(420)) / 2 + 15;

  hWndOwn = oSys.Call("User32::CreateWindowExW", 0, "STATIC", 0, 0x80000000 /*WS_POPUP*/, nX, nY, 0, 0, hDlg, 0, hInstDLL, 0);

  AkelPad.MemCopy(lpFilter, sFilter, 1 /*DT_UNICODE*/);
  AkelPad.MemCopy(lpTitle,  sTitle,  1 /*DT_UNICODE*/);
  AkelPad.MemCopy(lpDefExt, sExt,    1 /*DT_UNICODE*/);

  if (sFile)
  {
    if (oFSO.FileExists(sFile))
      AkelPad.MemCopy(lpFile, sFile, 1 /*DT_UNICODE*/);
    else if (oFSO.FolderExists(sFile))
      AkelPad.MemCopy(lpDir, sFile, 1 /*DT_UNICODE*/);
    else
    {
      AkelPad.MemCopy(lpFile, oFSO.GetFileName(sFile), 1 /*DT_UNICODE*/);
      AkelPad.MemCopy(lpDir, oFSO.GetParentFolderName(sFile), 1 /*DT_UNICODE*/);
    }
  }
  else
    AkelPad.MemCopy(lpDir, oFSO.FolderExists(sLastDir) ? sLastDir : sScriptDir, 1 /*DT_UNICODE*/);

  if (bMultiSelect)
    nFlags |= 0x00000200 /*OFN_ALLOWMULTISELECT*/;

  AkelPad.MemCopy(_PtrAdd(lpOFN,               0), nOFNSize, 3 /*DT_DWORD*/); //lStructSize
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ?   8 :  4),  hWndOwn, 2 /*DT_QWORD*/); //hwndOwner
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ?  24 : 12), lpFilter, 2 /*DT_QWORD*/); //lpstrFilter
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ?  44 : 24),        1, 3 /*DT_DWORD*/); //nFilterIndex
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ?  48 : 28),   lpFile, 2 /*DT_QWORD*/); //lpstrFile
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ?  56 : 32),  0x80000, 3 /*DT_DWORD*/); //nMaxFile
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ?  80 : 44),    lpDir, 2 /*DT_QWORD*/); //lpstrInitialDir
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ?  88 : 48),  lpTitle, 2 /*DT_QWORD*/); //lpstrTitle
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ?  96 : 52),   nFlags, 3 /*DT_DWORD*/); //Flags
  AkelPad.MemCopy(_PtrAdd(lpOFN, _X64 ? 104 : 60), lpDefExt, 2 /*DT_QWORD*/); //lpstrDefExt

  oSys.Call("User32::EnableWindow", hDlg, 0);

  if (oSys.Call("Comdlg32::" + sFunc, lpOFN))
  {
    if (bMultiSelect)
    {
      vFile   = [];
      nOffset = 0;

      while (sFile = AkelPad.MemRead(_PtrAdd(lpFile, nOffset), 1 /*DT_UNICODE*/))
      {
        vFile.push(sFile);
        nOffset += (sFile.length + 1) * 2;
      }

      if (vFile.length == 1)
        sLastDir = oFSO.GetParentFolderName(vFile[0]);
      else
      {
        sLastDir = vFile[0];

        if (vFile[0].slice(-1) != "\\") vFile[0] += "\\";

        for (i = 1; i < vFile.length; ++i)
          vFile[i] = vFile[0] + vFile[i];

        vFile.shift();
      }
    }
    else
    {
      vFile    = AkelPad.MemRead(lpFile, 1 /*DT_UNICODE*/);
      sLastDir = oFSO.GetParentFolderName(vFile);
    }
  }
  else
    vFile = bMultiSelect ? [] : "";

  oSys.Call("User32::EnableWindow", hDlg, 1);
  oSys.Call("User32::DestroyWindow", hWndOwn);
  oSys.Call("Kernel32::SetCurrentDirectoryW", sCurDir);

  AkelPad.MemFree(lpCurDir);
  AkelPad.MemFree(lpFilter);
  AkelPad.MemFree(lpFile);
  AkelPad.MemFree(lpDir);
  AkelPad.MemFree(lpTitle);
  AkelPad.MemFree(lpDefExt);
  AkelPad.MemFree(lpOFN);

  return vFile;
}

function BrowseForFolder(sDir, sTitle, nX, nY)
{
  try
  {
    oSys.RegisterCallback(BFFCallback);
  }
  catch (oError)
  {
    MsgBox(sTxtNoCallback);
    return;
  }

  var lpDir    = AkelPad.MemAlloc(260 * 2 /*sizeof(MAX_PATH)*/);
  var lpTitle  = AkelPad.MemAlloc((sTitle.length + 1) * 2);
  var lpBrowse = AkelPad.MemAlloc(_X64 ? 64 : 32 /*sizeof(BROWSEINFO)*/);
  var lpIDL;

  AkelPad.MemCopy(lpDir, oFSO.FolderExists(sDir) ? sDir : sScriptDir, 1 /*DT_UNICODE*/);
  AkelPad.MemCopy(lpTitle, sTitle, 1 /*DT_UNICODE*/);

  AkelPad.MemCopy(_PtrAdd(lpBrowse, 0),                     hDlg, 2 /*DT_QWORD*/); //hWndOwner
  AkelPad.MemCopy(_PtrAdd(lpBrowse, _X64 ? 16 :  8),       lpDir, 2 /*DT_QWORD*/); //pszDisplayName
  AkelPad.MemCopy(_PtrAdd(lpBrowse, _X64 ? 24 : 12),     lpTitle, 2 /*DT_QWORD*/); //lpszTitle
  AkelPad.MemCopy(_PtrAdd(lpBrowse, _X64 ? 32 : 16),  0x00000041, 3 /*DT_DWORD*/); //ulFlags=BIF_NEWDIALOGSTYLE|BIF_RETURNONLYFSDIRS
  AkelPad.MemCopy(_PtrAdd(lpBrowse, _X64 ? 40 : 20), BFFCallback, 2 /*DT_QWORD*/); //lpfn
  AkelPad.MemCopy(_PtrAdd(lpBrowse, _X64 ? 48 : 24),       lpDir, 2 /*DT_QWORD*/); //lParam

  if (lpIDL = oSys.Call("Shell32::SHBrowseForFolderW", lpBrowse))
  {
    oSys.Call("Shell32::SHGetPathFromIDListW", lpIDL, lpDir);
    oSys.Call("Ole32::CoTaskMemFree", lpIDL);
    sDir = AkelPad.MemRead(lpDir, 1 /*DT_UNICODE*/);
  }
  else
    sDir = "";

  oSys.UnregisterCallback(BFFCallback);
  AkelPad.MemFree(lpDir);
  AkelPad.MemFree(lpTitle);
  AkelPad.MemFree(lpBrowse);

  return sDir;

  function BFFCallback(hWnd, uMsg, lParam, lpData)
  {
    if (uMsg == 1 /*BFFM_INITIALIZED*/)
    {
      var hWndNS;
      var hWndTV;
      var oRect1;
      var oRect2;

      SendMessage(hWnd, 0x0080 /*WM_SETICON*/, 0 /*ICON_SMALL*/, hIconSmall);
      SendMessage(hWnd, 0x0467 /*BFFM_SETSELECTIONW*/, 1, lpData);

      //set focus to TreeView
      if (hWndNS = oSys.Call("User32::FindWindowExW", hWnd, 0, "SHBrowseForFolder ShellNameSpace Control", 0))
      {
        if (hWndTV = oSys.Call("User32::FindWindowExW", hWndNS, 0, "SysTreeView32", 0))
        {
          WScript.Sleep(50);
          PostMessage(hWnd, 40 /*WM_NEXTDLGCTL*/, hWndTV, 1);
          PostMessage(hWndTV, 4372 /*TVM_ENSUREVISIBLE*/, 0, SendMessage(hWndTV, 4362 /*TVM_GETNEXTITEM*/, 0x0009 /*TVGN_CARET*/, 0));
        }
      }

      if ((typeof nX != "number") || (typeof nY != "number"))
      {
        oRect1 = {};
        oRect2 = {};
        GetWindowPos(hDlg, oRect1);
        GetWindowPos(hWnd, oRect2);
        nX = oRect1.X + (oRect1.W - oRect2.W) / 2;
        nY = oRect1.Y + (oRect1.H - oRect2.H) / 2;
      }

      oSys.Call("User32::SetWindowPos", hWnd, 0, nX, nY, 0, 0, 0x15 /*SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOSIZE*/);
    }

    return 0;
  }
}

function EnterPassword(sFile, sPass)
{
  var lpSize = AkelPad.MemAlloc(8);
  var hDC    = oSys.Call("User32::GetDC", hDlg);
  var sText  = sFile + "\n\n" + sTxtEnterPass;
  var oRect  = {};
  var nEH = Scale.Y(21);
  var nBW = Scale.X(80);
  var nBH = Scale.Y(23);
  var nBX;
  var nTW, nTH;
  var nWX, nWY, nWW, nWH;
  var nWAY2;
  var hWndPass, hWndOK, hWndCancel, hFocus;

  oSys.Call("Gdi32::SetMapMode", hDC, 1 /*MM_TEXT*/);
  oSys.Call("Gdi32::SelectObject", hDC, hGuiFont);
  oSys.Call("Gdi32::GetTextExtentPoint32W", hDC, sFile, sFile.length, lpSize);
  nTW = AkelPad.MemRead(lpSize, 3 /*DT_DWORD*/);
  nTH = AkelPad.MemRead(_PtrAdd(lpSize, 4), 3 /*DT_DWORD*/) * 3;

  oSys.Call("Gdi32::GetTextExtentPoint32W", hDC, sTxtEnterPass, sTxtEnterPass.length, lpSize);
  nTW = Math.max(Scale.X(200), nTW, AkelPad.MemRead(lpSize, 3 /*DT_DWORD*/));

  oSys.Call("User32::ReleaseDC", hDlg, hDC); 
  AkelPad.MemFree(lpSize);

  nBX = nTW - nBW * 2;
  nWW = nTW + 20 + oSys.Call("User32::GetSystemMetrics", 7 /*SM_CXFIXEDFRAME*/) * 2;
  nWH = nTH + nEH + nBH + 35 + oSys.Call("User32::GetSystemMetrics", 8 /*SM_CYFIXEDFRAME*/) * 2 + oSys.Call("User32::GetSystemMetrics", 4 /*SM_CYCAPTION*/);

  GetWindowPos(0, oRect);
  nWAY2 = oRect.Y + oRect.H;
  GetWindowPos(aDlg[IDPDFLV].HWND, oRect);
  nWX = oRect.X + (oRect.W - nWW) / 2;
  GetItemRectLV(aDlg[IDPDFLV].HWND, nPDF, oRect);
  nWY = (oRect.Y2 + nWH < nWAY2) ? oRect.Y2 + 2 : oRect.Y1 - nWH - 2;

  oSys.Call("User32::CreateWindowExW",
    0,             //dwExStyle
    sClass,        //lpClassName
    sDlgTitle,     //lpWindowName
    0x90C80000,    //dwStyle=WS_POPUP|WS_VISIBLE|WS_CAPTION|WS_SYSMENU
    nWX,           //x
    nWY,           //y
    nWW,           //nWidth
    nWH,           //nHeight
    hDlg,          //hWndParent
    0,             //hMenu
    hInstDLL,      //hInstance
    PassCallback); //Script function callback. To use it class must be registered by WindowRegisterClass.

  oSys.Call("User32::EnableWindow", hDlg, 0);
  AkelPad.WindowGetMessage();

  return sPass;

  function PassCallback(hWnd, uMsg, wParam, lParam)
  {
    var nID, nCode, i;

    if (uMsg == 1 /*WM_CREATE*/)
    {
      if (! hMainWnd)
        SendMessage(hWnd, 0x0080 /*WM_SETICON*/, 0 /*ICON_SMALL*/, hIconSmall);

      SendMessage(oSys.Call("User32::CreateWindowExW",
        0,          //dwExStyle
        "STATIC",   //lpClassName
        sText,      //lpWindowName
        0x50000080, //dwStyle=WS_CHILD|WS_VISIBLE|SS_NOPREFIX
        10,         //x
        10,         //y
        nTW,        //nWidth
        nTH,        //nHeight
        hWnd,       //hWndParent
        -1,         //ID
        hInstDLL,   //hInstance
        0),         //lpParam
        48 /*WM_SETFONT*/, hGuiFont, 1);

      SendMessage(oSys.Call("User32::CreateWindowExW",
        0x00000200, //dwExStyle=WS_EX_CLIENTEDGE
        "EDIT",     //lpClassName
        sPass,      //lpWindowName
        0x50010080, //dwStyle=WS_CHILD|WS_VISIBLE|WS_TABSTOP|ES_AUTOHSCROLL
        10,         //x
        nTH + 15,   //y
        nTW,        //nWidth
        nEH,        //nHeight
        hWnd,       //hWndParent
        3000,       //ID
        hInstDLL,   //hInstance
        0),         //lpParam
        48 /*WM_SETFONT*/, hGuiFont, 1);

      for (i = 0; i < 2; ++i)
        SendMessage(oSys.Call("User32::CreateWindowExW",
          0,                            //dwExStyle
          "BUTTON",                     //lpClassName
          i == 0 ? sTxtOK : sTxtCancel, //lpWindowName
          0x50010000,                   //dwStyle=WS_CHILD|WS_VISIBLE|WS_TABSTOP
          nBX + (nBW + 10) * i,         //x
          nTH + nEH + 25,               //y
          nBW,                          //nWidth
          nBH,                          //nHeight
          hWnd,                         //hWndParent
          i + 3001,                     //ID
          hInstDLL,                     //hInstance
          0),                           //lpParam
          48 /*WM_SETFONT*/, hGuiFont, 1);

      hWndPass   = oSys.Call("User32::GetDlgItem", hWnd, 3000);
      hWndOK     = oSys.Call("User32::GetDlgItem", hWnd, 3001);
      hWndCancel = oSys.Call("User32::GetDlgItem", hWnd, 3002);
      hFocus     = hWndPass;

      SendMessage(hWndPass, 197 /*EM_SETLIMITTEXT*/, 32, 0);
      SendMessage(hWndPass, 177 /*EM_SETSEL*/, 0, -1);
      PostMessage(hWnd, 273 /*WM_COMMAND*/, MkLong(3000, 0x0300 /*EN_CHANGE*/), hWndPass);
    }

    else if (uMsg == 6 /*WM_ACTIVATE*/)
    {
      if (wParam == 0 /*WA_INACTIVE*/)
        hFocus = oSys.Call("User32::GetFocus");
    }

    else if (uMsg == 7 /*WM_SETFOCUS*/)
      oSys.Call("User32::SetFocus", hFocus);

    else if (uMsg == 256 /*WM_KEYDOWN*/)
    {
      if (wParam == 0x0D /*VK_RETURN*/)
      {
        if ((oSys.Call("User32::GetFocus") == hWndPass) && SendMessage(hWndPass, 14 /*WM_GETTEXTLENGTH*/, 0, 0))
          PostMessage(hWnd, 273 /*WM_COMMAND*/, 3001, hWndOK);
      }
    }

    else if (uMsg == 273 /*WM_COMMAND*/)
    {
      nID   = LoWord(wParam);
      nCode = HiWord(wParam);

      if (nID == 3000)
      {
        if (nCode == 0x0100 /*EN_SETFOCUS*/)
          PostMessage(hWndOK, 244 /*BM_SETSTYLE*/, SendMessage(hWndPass, 14 /*WM_GETTEXTLENGTH*/, 0, 0) ? 1 /*BS_DEFPUSHBUTTON*/ : 0 /*BS_PUSHBUTTON*/, 1);
        else if (nCode == 0x0200 /*EN_KILLFOCUS*/)
          SendMessage(hWndOK, 244 /*BM_SETSTYLE*/, 0 /*BS_PUSHBUTTON*/, 1);
        else if (nCode == 0x0300 /*EN_CHANGE*/)
        {
          oSys.Call("User32::EnableWindow", hWndOK, SendMessage(hWndPass, 14 /*WM_GETTEXTLENGTH*/, 0, 0));
          PostMessage(hWndOK, 244 /*BM_SETSTYLE*/, SendMessage(hWndPass, 14 /*WM_GETTEXTLENGTH*/, 0, 0) ? 1 /*BS_DEFPUSHBUTTON*/ : 0 /*BS_PUSHBUTTON*/, 1);
        }
      }
      else if ((nID == 3001) || (nID == 3002) || (nID == 2 /*IDCANCEL*/))
        PostMessage(hWnd, 16 /*WM_CLOSE*/, (nID == 3001), 0);
    }

    else if (uMsg == 16 /*WM_CLOSE*/)
    {
      if (wParam)
        sPass = GetWindowText(hWndPass);
      else
        sPass = undefined;

      oSys.Call("User32::EnableWindow", hDlg, 1);
      oSys.Call("User32::DestroyWindow", hWnd);
    }

    else if (uMsg == 2 /*WM_DESTROY*/)
      oSys.Call("User32::PostQuitMessage", 0);

    return 0;
  }
}

function MsgBox(sText, sTitle, hWndOwn, aBut, nDefBut)
{
  var lpSize = AkelPad.MemAlloc(8);
  var hDC    = oSys.Call("User32::GetDC", hDlg);
  var oRect  = {};
  var nTW    = 0;
  var nTH    = 0;
  var nBW    = Scale.X(70);
  var nTX;
  var nBX;
  var nCW;
  var nWX, nWY, nWW, nWH;
  var aLine;
  var hFocus;
  var nButton;
  var i;

  if (typeof sText != "string")
    sText = sText.toString();

  if (! sTitle)
    sTitle = sDlgTitle;

  if (! hWndOwn)
  {
    if (hDlg)
      hWndOwn = hDlg;
    else if (hMainWnd)
      hWndOwn = hMainWnd;
  }

  if ((typeof aBut != "object") || (! aBut.length))
    aBut = [sTxtOK];

  if ((typeof nDefBut != "number") || (nDefBut < 0) || (nDefBut >= aBut.length))
    nDefBut = 0;

  oSys.Call("Gdi32::SetMapMode", hDC, 1 /*MM_TEXT*/);
  oSys.Call("Gdi32::GetTextExtentPoint32W", hDC, sDlgTitle, sDlgTitle.length, lpSize);
  nCW = AkelPad.MemRead(lpSize, 3 /*DT_DWORD*/) + oSys.Call("User32::GetSystemMetrics", 49 /*SM_CXSMICON*/) + oSys.Call("User32::GetSystemMetrics", 30 /*SM_CXSIZE*/) + 10;

  oSys.Call("Gdi32::SelectObject", hDC, hGuiFont);

  aLine = sText.split("\n");
  for (i = 0; i < aLine.length; ++i)
  {
    oSys.Call("Gdi32::GetTextExtentPoint32W", hDC, aLine[i], aLine[i].length, lpSize);
    nTW = Math.max(nTW, AkelPad.MemRead(lpSize, 3 /*DT_DWORD*/));
    nTH = Math.max(nTH, AkelPad.MemRead(_PtrAdd(lpSize, 4), 3 /*DT_DWORD*/));
  }

  nTH = nTH * aLine.length;

  for (i = 0; i < aBut.length; ++i)
  {
    oSys.Call("Gdi32::GetTextExtentPoint32W", hDC, aBut[i], aBut[i].length, lpSize)
    nBW = Math.max(nBW, AkelPad.MemRead(lpSize, 3 /*DT_DWORD*/) + 8);
  }

  oSys.Call("User32::ReleaseDC", hDlg, hDC); 
  AkelPad.MemFree(lpSize);

  nCW = Math.max(Scale.X(120), nCW, nTW, nBW * aBut.length + 10 * (aBut.length - 1)) + 20;
  nWW = nCW + oSys.Call("User32::GetSystemMetrics", 7 /*SM_CXFIXEDFRAME*/) * 2;
  nWH = nTH + Scale.Y(23) + 35 + oSys.Call("User32::GetSystemMetrics", 8 /*SM_CYFIXEDFRAME*/) * 2 + oSys.Call("User32::GetSystemMetrics", 4 /*SM_CYCAPTION*/);
  nBX = (nCW - nBW * aBut.length - 10 * (aBut.length - 1)) / 2;
  nTX = (nCW - nTW) / 2;

  GetWindowPos(hWndOwn, oRect);
  nWX = oRect.X + (oRect.W - nWW) / 2;
  nWY = oRect.Y + (oRect.H - nWH) / 2;

  oSys.Call("User32::CreateWindowExW",
    0,            //dwExStyle
    sClass,       //lpClassName
    sTitle,       //lpWindowName
    0x90C80000,   //dwStyle=WS_POPUP|WS_VISIBLE|WS_CAPTION|WS_SYSMENU
    nWX,          //x
    nWY,          //y
    nWW,          //nWidth
    nWH,          //nHeight
    hWndOwn,      //hWndParent
    0,            //hMenu
    hInstDLL,     //hInstance
    MsgCallback); //Script function callback. To use it class must be registered by WindowRegisterClass.

  oSys.Call("User32::EnableWindow", hWndOwn, 0);
  AkelPad.WindowGetMessage();

  return nButton;

  function MsgCallback(hWnd, uMsg, wParam, lParam)
  {
    var i;

    if (uMsg == 1 /*WM_CREATE*/)
    {
      if (! hMainWnd)
        SendMessage(hWnd, 0x0080 /*WM_SETICON*/, 0 /*ICON_SMALL*/, hIconSmall);

      SendMessage(oSys.Call("User32::CreateWindowExW",
        0,          //dwExStyle
        "STATIC",   //lpClassName
        sText,      //lpWindowName
        0x50000080, //dwStyle=WS_CHILD|WS_VISIBLE|SS_NOPREFIX
        nTX,        //x
        10,         //y
        nTW,        //nWidth
        nTH,        //nHeight
        hWnd,       //hWndParent
        -1,         //ID
        hInstDLL,   //hInstance
        0),         //lpParam
        48 /*WM_SETFONT*/, hGuiFont, 1);

      for (i = 0; i < aBut.length; ++i)
        SendMessage(oSys.Call("User32::CreateWindowExW",
          0,                    //dwExStyle
          "BUTTON",             //lpClassName
          aBut[i],              //lpWindowName
          0x50010000,           //dwStyle=WS_CHILD|WS_VISIBLE|WS_TABSTOP
          nBX + (nBW + 10) * i, //x
          nTH + 25,             //y
          nBW,                  //nWidth
          Scale.Y(23),          //nHeight
          hWnd,                 //hWndParent
          i + 4000,             //ID
          hInstDLL,             //hInstance
          0),                   //lpParam
          48 /*WM_SETFONT*/, hGuiFont, 1);

      oSys.Call("User32::DefDlgProcW", hWnd, 1025 /*DM_SETDEFID*/, nDefBut + 4000, 0);
      hFocus = oSys.Call("User32::GetDlgItem", hWnd, nDefBut + 4000);
    }

    else if (uMsg == 6 /*WM_ACTIVATE*/)
    {
      if (wParam == 0 /*WA_INACTIVE*/)
        hFocus = oSys.Call("User32::GetFocus");
    }

    else if (uMsg == 7 /*WM_SETFOCUS*/)
      oSys.Call("User32::SetFocus", hFocus);

    else if (uMsg == 273 /*WM_COMMAND*/)
      PostMessage(hWnd, 16 /*WM_CLOSE*/, LoWord(wParam), 0);

    else if (uMsg == 16 /*WM_CLOSE*/)
    {
      if (wParam >= 4000)
        nButton = wParam - 4000;
      else
        nButton = -1;

      oSys.Call("User32::EnableWindow", hWndOwn, 1);
      oSys.Call("User32::DestroyWindow", hWnd);
    }

    else if (uMsg == 2 /*WM_DESTROY*/)
      oSys.Call("User32::PostQuitMessage", 0);

    return 0;
  }
}

function LoWord(nDwNum)
{
  return nDwNum & 0xFFFF;
}

function HiWord(nDwNum)
{
  return (nDwNum >> 16) & 0xFFFF;
}

function MkLong(nLoWord, nHiWord)
{
  return (nLoWord & 0xFFFF) | (nHiWord << 16);
}

function Ctrl()
{
  return oSys.Call("User32::GetKeyState", 0x11 /*VK_CONTROL*/) & 0x8000;
}

function Shift()
{
  return oSys.Call("User32::GetKeyState", 0x10 /*VK_SHIFT*/) & 0x8000;
}

function Alt()
{
  return oSys.Call("User32::GetKeyState", 0x12 /*VK_MENU*/) & 0x8000;
}

function SendMessage(hWnd, uMsg, wParam, lParam)
{
  return AkelPad.SendMessage(hWnd, uMsg, wParam, lParam);
}

function PostMessage(hWnd, uMsg, wParam, lParam)
{
  return oSys.Call("User32::PostMessageW", hWnd, uMsg, wParam, lParam);
}

Last edited by KDJ on Wed Nov 04, 2015 8:02 pm, edited 7 times in total.

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

Post by KDJ »

GUI for PDFtk Server - manipulating PDF documents. Part 5.

Code: Select all

function ReadIni()
{
  try
  {
    eval(ReadFile(WScript.ScriptFullName.replace(/js$/i, "ini"), 1));
  }
  catch (oError)
  {}

  aDlg.W = Math.max(Scale.X(aDlg.W), aDlg.MinW);
  aDlg.H = Math.max(Scale.Y(aDlg.H), aDlg.MinH);
}

function WriteIni()
{
  var sText;
  var i;

  if (! bSaveList)
  {
    nPDF = -1;
    aPDF = [];
  }

  if (! bSavePass)
  {
    sOwnerPass = "";
    sUserPass  = "";

    for (i = 0; i < aPDF.length; ++i)
      aPDF[i].P = "";
  }

  sText =
    'aDlg.X='      + aDlg.X + ';\r\n' +
    'aDlg.Y='      + aDlg.Y + ';\r\n' +
    'aDlg.W='      + Scale.UX(aDlg.W) + ';\r\n' +
    'aDlg.H='      + Scale.UY(aDlg.H) + ';\r\n' +
    'aDlg.Max='    + oSys.Call("User32::IsZoomed", hDlg) + ';\r\n' +
    'nTab='        + nTab + ';\r\n' +
    'bCollateW='   + bCollateW + ';\r\n' +
    'bShuffleW='   + bShuffleW + ';\r\n' +
    'bSplitAll='   + bSplitAll + ';\r\n' +
    'bWaterAll='   + bWaterAll + ';\r\n' +
    'nWater='      + nWater + ';\r\n' +
    'nBook='       + nBook + ';\r\n' +
    'bUTF8='       + bUTF8 + ';\r\n' +
    'nData='       + nData + ';\r\n' +
    'sWaterAdd="'  + EscapeStr(sWaterAdd) + '";\r\n' +
    'sWaterPDF="'  + EscapeStr(sWaterPDF) + '";\r\n' +
    'sBookTXT="'   + EscapeStr(sBookTXT) + '";\r\n' +
    'sDataTXT="'   + EscapeStr(sDataTXT) + '";\r\n' +
    'sPDFtkDir="'  + EscapeStr(sPDFtkDir) + '";\r\n' +
    'sPDFReader="' + EscapeStr(sPDFReader) + '";\r\n' +
    'sTXTEditor="' + EscapeStr(sTXTEditor) + '";\r\n' +
    'sLastDir="'   + EscapeStr(sLastDir) + '";\r\n' +
    'nAfter='      + nAfter + ';\r\n' +
    'bSaveList='   + bSaveList + ';\r\n' +
    'bSavePass='   + bSavePass + ';\r\n' +
    'bPassProt='   + bPassProt + ';\r\n' +
    'sOwnerPass="' + EscapeStr(sOwnerPass) + '";\r\n' +
    'sUserPass="'  + EscapeStr(sUserPass) + '";\r\n' +
    'bTopPrint='   + bTopPrint + ';\r\n' +
    'bLowPrint='   + bLowPrint + ';\r\n' +
    'bModCont='    + bModCont + ';\r\n' +
    'bAssembly='   + bAssembly + ';\r\n' +
    'bCopyCont='   + bCopyCont + ';\r\n' +
    'bScrRead='    + bScrRead + ';\r\n' +
    'bModAnnot='   + bModAnnot + ';\r\n' +
    'bFillIn='     + bFillIn + ';\r\n' +
    'nPDF='        + nPDF + ';\r\naPDF=[';

  for (i = 0; i < aPDF.length; ++i)
    sText +=
      '{' +
      'F:"' + EscapeStr(aPDF[i].F) + '",' +
      'R:"' + EscapeStr(aPDF[i].R) + '",' +
      'P:"' + EscapeStr(aPDF[i].P) + '"}' +
      ((i == aPDF.length - 1) ? '' : ',');

  sText += '];\r\n';

  WriteFile(WScript.ScriptFullName.replace(/js$/i, "ini"), sText, 1);
}

function EscapeStr(sStr)
{
  return sStr.replace(/[\\"]/g, '\\$&').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
}

function GetLangStrings()
{
  if ((hMainWnd && (AkelPad.GetLangId(0 /*LANGID_FULL*/) == 1045)) || ((! hMainWnd) && (oSys.Call("Kernel32::GetUserDefaultLangID") == 1045))) //Polish
  {
    //main dialog box
    sTxtCollate        = 'Zestaw';
    sTxtShuffle        = 'Potasuj';
    sTxtSplit          = 'Wydziel';
    sTxtWatermark      = 'Znak wodny';
    sTxtBookmarks      = 'Zakładki';
    sTxtPDFInfo        = 'PDF info';
    sTxtSettings       = 'Ustawienia';
    sTxtCollateDescr   = 'Zbiera strony ze wszystkich źródłowych dokumentów PDF i tworzy nowy plik PDF.\nMożesz użyć tej operacji w celu wydzielenia, obrotu i połączenia stron PDF.\nKolejność stron w nowym pliku PDF jest określona przez podane zakresy stron.';
    sTxtShuffleDescr   = 'Działa podobnie jak "Zestaw" z tą różnicą, że pobiera po jednej stronie z każdego zakresu aby dołączyć je do wyjściowego pliku PDF.\nJeśli w jednym zakresie zabraknie stron, operacja jet kontynuowana dla pozostałych zakresów.\nTa funkcja jest przeznaczona do zestawienia stron PDF po zeskanowaniu dokumentów papierowych.';
    sTxtSplitDescr     = 'Dzieli jeden lub wszystkie źródłowe dokumenty PDF na pojedyncze strony.\nKażda strona zostanie zapisana w odrębnym pliku nazwanym: NazwaŻródłowegoDokumentu_NumerStronyŹródłowej.pdf';
    sTxtWaterDescr     = 'Wstawia znak wodny jako tło lub stempel do jednego lub wszystkich dokumentów PDF.';
    sTxtInsertWater    = 'Wstaw znak wodny do dokumentu wyjściowego';
    sTxtAllDocs        = 'Wszystkie dokumenty';
    sTxtAddToName      = 'Dodaj do nazwy:';
    sTxtBackgr         = 'Obraz tła';
    sTxtMultiBackgr    = 'Wiele obrazów tła';
    sTxtStamp          = 'Stempel';
    sTxtMultiStamp     = 'Wiele stempli';
    sTxtWaterPDF       = 'Plik PDF ze znakiem wodnym (nie może być zabezpieczony hasłem):';
    sTxtExportFrom     = 'Eksport z pojedynczego dokumentu źródłowego PDF do pliku TXT';
    sTxtImportTo       = 'Import do dokumentu PDF z poniższego pliku TXT:';
    sTxtDumpAnnots     = 'Dump data annotations to TXT file';
    sTxtDumpFields     = 'Dump data fields to TXT file';
    sTxtDumpInfo       = 'Dump data info to TXT file';
    sTxtUpdateInfo     = 'Update data info in PDF document from following TXT file:';
    sTxtPDFtkDir       = 'Katalog PDFtk:';
    sTxtPDFReader      = 'Czytnik PDF:';
    sTxtTXTEditor      = 'Edytor TXT:';
    sTxtAfterCreate    = 'Po utworzeniu plików wyjściowych:';
    sTxtShowMessage    = 'Pokaż komunikat';
    sTxtOpenNewFile    = 'Otwórz nowy plik';
    sTxtOpenOutDir     = 'Otwórz katalog docelowy';
    sTxtKeepList       = 'Zachowaj listę PDF przy wyjściu';
    sTxtKeepPass       = 'Zachowaj hasła';
    sTxtSourcePDFs     = 'Źródłowe dokumenty PDF';
    sTxtPageCount      = 'Liczba stron';
    sTxtPagesToCopy    = 'Zakresy stron do skopiowania';
    sTxtRotation       = 'Obrót';
    sTxtOutPages       = 'Stron wyjściowych';
    sTxtAdd            = '&Dodaj';
    sTxtDuplicate      = 'Powiel';
    sTxtRemove         = 'Usuń';
    sTxtClear          = 'Wyczyść';
    sTxtMoveUp         = 'W górę';
    sTxtMoveDown       = 'W dół';
    sTxtRanges         = 'Zakresy';
    sTxtOpen           = 'Otwórz';
    sTxtRefresh        = 'Odśwież';
    sTxtTotalPages     = 'Suma stron: ';
    sTxtTotalOutPages  = 'Suma stron wyjściowych: ';
    sTxtReading        = 'czyta';
    sTxtOutputPermiss  = 'Wyjściowy dokument PDF - uprawnienia';
    sTxtPassProt       = 'Zabezpiecz hasłami';
    sTxtOwner          = 'Właściciel:';
    sTxtUser           = 'Użytkownik:';
    sTxtTopPrint       = 'Druk wysokiej jakości';
    sTxtLowPrint       = 'Druk niskiej jakości';
    sTxtModCont        = 'Modyfikacja zawartości';
    sTxtAssembly       = 'Składanie dokumentów';
    sTxtCopyCont       = 'Kopiowanie zawartości';
    sTxtScrRead        = 'Czytanie z ekranu';
    sTxtModAnnot       = 'Modyfikacja przypisów';
    sTxtFillIn         = 'Wypełnianie pól formularza';
    sTxtAllPerm        = 'Wszystkie uprawnienia';
    sTxtCreateFiles    = '&Utwórz plik(i)';
    sTxtOpenPDF        = 'Otwórz &PDF';
    sTxtOpenTXT        = 'Otwórz &TXT';
    sTxtOpenDir        = 'Otwórz &katalog';
    sTxtPDFtkHelp      = 'Pomoc PDFtk';
    sTxtPDFtkSite      = 'Strona PDFtk';
    sTxtExit           = 'Zakończ';
    //edit ranges
    sTxtPages          = 'Strony';
    sTxtFrom           = 'Od:';
    sTxtTo             = 'Do:';
    sTxtFromEnd        = 'Od końca';
    sTxtNumLastPage    = 'numer ostatniej strony';
    sTxtAll            = 'Wszystkie';
    sTxtEven           = 'Parzyste';
    sTxtOdd            = 'Nieparzyste';
    sTxtNone           = 'Brak';
    sTxtNorth          = 'Północ';
    sTxtEast           = 'Wschód';
    sTxtSouth          = 'Południe';
    sTxtWest           = 'Zachód';
    sTxtLeft           = 'W lewo';
    sTxtRight          = 'W prawo';
    sTxtDown           = 'Do dołu';
    sTxtNew            = 'Nowy';
    //EnterPassword()
    sTxtEnterPass      = 'Podaj hasło właściciela dla dokumentu PDF:';
    //MsgBox()
    sTxtNoFile         = 'Ten plik nie istnieje.';
    sTxtNoWaterFile    = 'Brak pliku PDF ze znakiem wodnym.';
    sTxtNoPDFReader    = 'Nie ma czytnika plików PDF.';
    sTxtNoTXTEditor    = 'Nie ma edytora plików TXT.';
    sTxtCantExec       = 'Nie można wykonać tego polecenia:';
    sTxtNoCallback     = 'Nie można zarejestrować funkcji zwrotnej.';
    sTxtPDFtkError     = 'Błąd PDFtk';
    sTxtNoTempDir      = 'Nie można utworzyć katalogu tymczasowego.';
    sTxtWriteError     = 'Błąd zapisu do tego pliku.';
    sTxtSelOtherName   = 'Wybierz inną nazwę lub odblokuj plik.';
    sTxtUnlockFile     = 'Odblokuj plik i wciśnij "Ponów"';
    sTxtTooManyDocs    = 'Za dużo dokumentów lub zakresów jest do przetworzenia.\nNie można utworzyć dokumentu wyjściowego.'
    sTxtCreated        = 'Utworzono:';
    sTxtSplitted       = 'Podzielono:';
    sTxtFileExists     = 'Ten plik już istnieje. Czy chcesz go zastąpić?';
    sTxtReplace        = 'Zastąp';
    sTxtReplaceAll     = 'Zastąp wszystkie';
    sTxtSkip           = 'Pomiń';
    sTxtSkipAll        = 'Pomiń wszystkie';
    sTxtRetry          = 'Ponów';
    sTxtInvalidChar    = 'Nieprawidłowy znak w nazwie pliku.';
    sTxtNoPDFBookmarks = 'Ten dokument PDF nie zawiera zakładek.';
    sTxtNoTXTBookmarks = 'Ten plik TXT nie zawiera zakładek.';
    sTxtBookmarksHelp  = 'Każdy wiersz pliku z zakładkami powinien zawierać opis jednej zakładki w formacie:\n[TAB...]Tekst zakładki/Numer strony w dokumencie PDF\n\nPrzykład:\nZakładka - poziom 0 (bez TAB na początku wiersza)/2\n\tZakładka - poziom 1 (jeden znak TAB na początku wiersza)/14\n\t\tZakładka - poziom 2 (dwa znaki TAB na początku wiersza)/29\n\tZakładka - poziom 1 (jeden znak TAB na początku wiersza)/35\nZakładka - poziom 0 (bez TAB na początku wiersza)/47';
    sTxtNoPDFData      = 'Ten dokument PDF nie zawiera wymaganych danych.';
    //GetOpenSaveFileName()
    sTxtSelWaterPDF    = 'Wybierz plik PDF zawierający znaki wodne';
    sTxtSelBookTXT     = 'Wybierz plik TXT zawierający zakładki';
    sTxtSelDataTXT     = 'Wybierz plik TXT zawierający dane';
    sTxtSelPDFReader   = 'Wybierz czytnik PDF';
    sTxtSelTXTEditor   = 'Wybierz edytor TXT';
    sTxtSelSourcePDFs  = 'Wybierz źródłowe dokumenty PDF';
    //BrowseForFolder()
    sTxtSelOutDir      = 'Wybierz katalog docelowy:';
    sTxtSelPDFtkDir    = 'Wybierz katalog zawierający PDFtk.exe:';
    sTxtSelAkelDir     = 'Wybierz katalog zawierający AkelPad.exe:';
    //common
    sTxtOK             = 'OK';
    sTxtCancel         = 'Anuluj';
  }
//  else if ((hMainWnd && (AkelPad.GetLangId(0 /*LANGID_FULL*/) == 1049)) || ((! hMainWnd) && (oSys.Call("Kernel32::GetUserDefaultLangID") == 1049))) //Russian
//  {
//  }
  else
  {
    //main dialog box
    sTxtCollate        = 'Collate';
    sTxtShuffle        = 'Shuffle';
    sTxtSplit          = 'Split';
    sTxtWatermark      = 'Watermark';
    sTxtBookmarks      = 'Bookmarks';
    sTxtPDFInfo        = 'PDF info';
    sTxtSettings       = 'Settings';
    sTxtCollateDescr   = 'Assembles pages from all source PDF documents to create new PDF file.\nYou can use this operation to split, rotate and merge PDF pages.\nPage order in new PDF file is specified by the order of the given page ranges.';
    sTxtShuffleDescr   = 'Works like "Collate" operation except that it takes one page at a time from each page range to assemble the output PDF.\nIf one range runs out of pages, it continues with the remaining ranges.\nThis feature is designed to collate PDF pages after scanning paper documents.';
    sTxtSplitDescr     = 'Splits one or all source PDF documents into individual pages.\nEach page will be saved in a separate file named: SourceDocumentName_SourcePageNumber.pdf';
    sTxtWaterDescr     = 'Inserts a watermark as the background or stamp into one or all PDF documents.';
    sTxtInsertWater    = 'Insert watermark into output PDF document';
    sTxtAllDocs        = 'All documents';
    sTxtAddToName      = 'Add to name:';
    sTxtBackgr         = 'Background';
    sTxtMultiBackgr    = 'MultiBackground';
    sTxtStamp          = 'Stamp';
    sTxtMultiStamp     = 'MultiStamp';
    sTxtWaterPDF       = 'Watermark PDF file (cannot be password-protected):';
    sTxtExportFrom     = 'Export from single source PDF document to TXT file';
    sTxtImportTo       = 'Import to PDF document from following TXT file:';
    sTxtDumpAnnots     = 'Dump data annotations to TXT file';
    sTxtDumpFields     = 'Dump data fields to TXT file';
    sTxtDumpInfo       = 'Dump data info to TXT file';
    sTxtUpdateInfo     = 'Update data info in PDF document from following TXT file:';
    sTxtPDFtkDir       = 'PDFtk directory:';
    sTxtPDFReader      = 'PDF reader:';
    sTxtTXTEditor      = 'TXT editor:';
    sTxtAfterCreate    = 'After creating output file(s):';
    sTxtShowMessage    = 'Show message';
    sTxtOpenNewFile    = 'Open new file';
    sTxtOpenOutDir     = 'Open output directory';
    sTxtKeepList       = 'Kepp PDF list on exit';
    sTxtKeepPass       = 'Keep passwords';
    sTxtSourcePDFs     = 'Source PDF documents';
    sTxtPageCount      = 'Page count';
    sTxtPagesToCopy    = 'Page ranges to copy';
    sTxtRotation       = 'Rotation';
    sTxtOutPages       = 'Output pages';
    sTxtAdd            = '&Add';
    sTxtDuplicate      = 'Duplicate';
    sTxtRemove         = 'Remove';
    sTxtClear          = 'Clear';
    sTxtMoveUp         = 'Move up';
    sTxtMoveDown       = 'Move down';
    sTxtRanges         = 'Ranges';
    sTxtOpen           = 'Open';
    sTxtRefresh        = 'Refresh';
    sTxtTotalPages     = 'Total pages: ';
    sTxtTotalOutPages  = 'Total output pages: ';
    sTxtReading        = 'reading';
    sTxtOutputPermiss  = 'Output PDF document - permissions';
    sTxtPassProt       = 'Passwords protection';
    sTxtOwner          = 'Owner:';
    sTxtUser           = 'User:';
    sTxtTopPrint       = 'Top quality printing';
    sTxtLowPrint       = 'Lower quality printing';
    sTxtModCont        = 'Modify contents';
    sTxtAssembly       = 'Assembly';
    sTxtCopyCont       = 'Copy contents';
    sTxtScrRead        = 'Screen readers';
    sTxtModAnnot       = 'Modify annotations';
    sTxtFillIn         = 'Fill in form fields';
    sTxtAllPerm        = 'All permissions';
    sTxtCreateFiles    = '&Create file(s)';
    sTxtOpenPDF        = 'Open &PDF';
    sTxtOpenTXT        = 'Open &TXT';
    sTxtOpenDir        = 'Open &directory';
    sTxtPDFtkHelp      = 'PDFtk help';
    sTxtPDFtkSite      = 'PDFtk site';
    sTxtExit           = 'Exit';
    //edit ranges
    sTxtPages          = 'Pages';
    sTxtFrom           = 'From:';
    sTxtTo             = 'To:';
    sTxtFromEnd        = 'From end';
    sTxtNumLastPage    = 'number of last page';
    sTxtAll            = 'All';
    sTxtEven           = 'Even';
    sTxtOdd            = 'Odd';
    sTxtNone           = 'None';
    sTxtNorth          = 'North';
    sTxtEast           = 'East';
    sTxtSouth          = 'South';
    sTxtWest           = 'West';
    sTxtLeft           = 'Left';
    sTxtRight          = 'Right';
    sTxtDown           = 'Down';
    sTxtNew            = 'New';
    //EnterPassword()
    sTxtEnterPass      = 'Enter owner password for PDF document:';
    //MsgBox()
    sTxtNoFile         = 'This file does not exists.';
    sTxtNoWaterFile    = 'There is no PDF watermark file.';
    sTxtNoPDFReader    = 'There is no PDF reader.';
    sTxtNoTXTEditor    = 'There is no TXT editor.';
    sTxtCantExec       = 'Can not execute this command:';
    sTxtNoCallback     = 'Unable to register callback function.';
    sTxtPDFtkError     = 'PDFtk Error';
    sTxtNoTempDir      = 'Unable to create temporary directory.';
    sTxtWriteError     = 'Write error to this file.';
    sTxtSelOtherName   = 'Select another name or unlock the file.';
    sTxtUnlockFile     = 'Unlock the file and press "Retry"';
    sTxtTooManyDocs    = 'Too many documents or ranges are to be processed.\nUnable to create the output document.'
    sTxtCreated        = 'Created:';
    sTxtSplitted       = 'Splitted:';
    sTxtFileExists     = 'This file already exists. Do you want to replace it?';
    sTxtReplace        = 'Replace';
    sTxtReplaceAll     = 'Replace all';
    sTxtSkip           = 'Skip';
    sTxtSkipAll        = 'Skip all';
    sTxtRetry          = 'Retry';
    sTxtInvalidChar    = 'Invalid character in file name.';
    sTxtNoPDFBookmarks = 'This PDF document does not contain any bookmarks.';
    sTxtNoTXTBookmarks = 'This TXT file does not contain any bookmarks.';
    sTxtBookmarksHelp  = 'Each line of bookmarks file should contain a description of one bookmark in the following format:\n[TAB...]Bookmark text/Page number in PDF document\n\nExample:\nBookmark - level 0 (without TAB at beginning of line)/2\n\tBookmark - level 1 (one TAB char at beginning of line)/14\n\t\tBookmark - level 2 (two TAB chars at beginning of line)/29\n\tBookmark - level 1 (one TAB char at beginning of line)/35\nBookmark - level 0 (without TAB at beginning of line)/47';
    sTxtNoPDFData      = 'This PDF document does not contain the required data.';
    //GetOpenSaveFileName()
    sTxtSelWaterPDF    = 'Select PDF file containing watermarks';
    sTxtSelBookTXT     = 'Select TXT file containing bookmarks';
    sTxtSelDataTXT     = 'Select TXT file containing data info';
    sTxtSelPDFReader   = 'Select PDF reader';
    sTxtSelTXTEditor   = 'Select TXT editor';
    sTxtSelSourcePDFs  = 'Select source PDF documents';
    //BrowseForFolder()
    sTxtSelOutDir      = 'Select output directory:';
    sTxtSelPDFtkDir    = 'Select directory containing PDFtk.exe:';
    sTxtSelAkelDir     = 'Select directory containing AkelPad.exe:';
    //common
    sTxtOK             = 'OK';
    sTxtCancel         = 'Cancel';
  }
}

Last edited by KDJ on Wed Nov 04, 2015 8:03 pm, edited 3 times in total.

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

Post by VladSh »

Works with HTML Tidy.

The last version HTML Tidy for HTML5 (Win).

Tools file tidy.exe put in ...\AkelPad\AkelFiles\Tools\HTMLTidy\

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=27896#p27896
// Description(1033): Works with HTML Tidy: validate / formatting
// Description(1049): Работа с HTML Tidy: валидация / форматирование
// Version: 1.3 (2015.04.10)
// Author: VladSh
// Initial code: Instructor
// 
// Dependencies:
// 	...\Include\ShowMenuEx.js
// 
// Default tooldir and configdir is ...\AkelPad\AkelFiles\Tools\HTMLTidy\.
// If your tooldir and/or configdir differ from those of the default, then set them in tidy.ini.
// 
// Arguments:
// 	action: [0] - validate, 1 - formatting
// 	xml: [0] or without this argument - html, 1 - xml
// 	config - config filename's, -config="?" will show the list for a config choise (from param-file)
// 		if the config setted as filename only then the config-files must be placed in tooldir;
// 		if the config has been set, the options below will be ignored
// 	spaces - number of spaces in Tab; by default takes from program settings
// 
// Usage:
// Если в tidy.ini параметр pExt=ini:
// 	-"Tidy валидация XML" Call("Scripts::Main", 1, "tidy.js", `-xml=1`)
// 	-"Tidy валидация HTML" Call("Scripts::Main", 1, "tidy.js")
// 	-"Tidy форматирование XML" Call("Scripts::Main", 1, "tidy.js", `-xml=1 -action=1`)
// 	-"Tidy форматирование HTML" Call("Scripts::Main", 1, "tidy.js", `-action=1`)
// 	-"Tidy форматирование с выбором конфига" Call("Scripts::Main", 1, "tidy.js", `-action=1 -config="?"`)
// Если в tidy.ini параметр pExt=json (в json-файле можно задать все аргументы каждой строки меню):
// 	"Tidy валидация XML" Call("Scripts::Main", 1, "tidy.js", `-pID="vXML"`) - задействование определённого шаблона настроек из json-файла по ID

if (! AkelPad.Include("ShowMenuEx.js")) WScript.Quit();
var fLogOutput = "Log::Output";
var repattern = "^line (\\d+) column (\\d+)";
var retags = "/GOTOLINE=\\1:\\2";

initIniOptions(['tooldir', 'configdir', 'configlist', 'config', 'spaces']);

var tooldir = expandPath(opts['tooldir'] || (AkelPad.GetAkelDir() + '\\AkelFiles\\Tools\\HTMLTidy\\'));
var toolpath = tooldir + 'tidy.exe';
checkFilePath("Tidy", toolpath);

var cmdline = toolpath + ' --input-xml ' + AkelPad.GetArgValue("xml", 0 /* html */) + ' --quiet 1 -errors';
AkelPad.Call(fLogOutput, 1, cmdline, "", repattern, retags, 65001, 65001, 4160 /*64+4096*/);
while (getExecState())
	WScript.Sleep(100);

if (getExitCode() == 0) {
	AkelPad.Call(fLogOutput, 6);
	if (AkelPad.GetArgValue("action", 0) == 0) {
		AkelPad.MessageBox(hWndMain, "Document is valid.", WScript.ScriptName, 0 /*MB_OK*/);
	}
	else {
		switch (opts['pExt']) {
			case "json":
				if (!initMenuParams(POS_CURSOR)) WScript.Quit();
				break;
			case "ini":
				initArgs(['config', 'spaces']);
				break;
			default:
				AkelPad.Call(fLogOutput, 4, WScript.ScriptName + ": pExt='" + opts['pExt'] + "' is not supported.");
				WScript.Quit();
		}
		config = opts['config'];
		if (config) {
			if (config == "?") {
				if (opts['configlist']) {
					opts['pExt'] = "";
					opts['pFile'] = opts['configlist'];
				}
				config = getSelectedMenuItem(POS_CURSOR, false);
				if (!config) WScript.Quit();
			}
			if (config.indexOf('\\') == -1) {
				config = (opts['configdir'] || tooldir) + config;
			}
			config = expandPath(config);
			checkFilePath("Config", config);
			
			cmdline = toolpath + ' -config "' + config + '"';
		}
		else {
			var nTabStop = opts['spaces'] || AkelPad.SendMessage(AkelPad.GetEditWnd(), 3239 /*AEM_GETTABSTOP*/, 0, 0);
			
			cmdline = toolpath + ' --indent auto --indent-spaces ' + nTabStop + ' --wrap 0 --quiet 1';
		}
		
		AkelPad.Call(fLogOutput, 1, cmdline, "", repattern, retags, 65001, 65001, 1052673);
	}
}
else
	AkelPad.SendMessage(hWndMain, 1278 /*AKD_DOCK*/, 0x200 /*DK_SHOW*/, getOutputDock());


function getExecState() {
	var lpState;
	var nState = 0;
	if (lpState = AkelPad.MemAlloc(4 /*sizeof(DWORD)*/)) {
		AkelPad.Call(fLogOutput, 3, lpState);
		nState = AkelPad.MemRead(lpState, 3 /*DT_DWORD*/);
		AkelPad.MemFree(lpState);
	}
	return nState;
}

function getExitCode() {
	var lpCode;
	var nCode = 0;
	if (lpCode = AkelPad.MemAlloc(4 /*sizeof(DWORD)*/)) {
		AkelPad.Call(fLogOutput, 3, 0, 0, 0, 0, lpCode);
		nCode = AkelPad.MemRead(lpCode, 3 /*DT_DWORD*/);
		AkelPad.MemFree(lpCode);
	}
	return nCode;
}

function getOutputDock() {
	var lpDock;
	var hDock = 0;
	if (lpDock = AkelPad.MemAlloc(_X64?8:4 /*sizeof(DOCK *)*/)) {
		AkelPad.Call(fLogOutput, 2, 0, lpDock);
		hDock = AkelPad.MemRead(lpDock, 2 /*DT_QWORD*/);
		AkelPad.MemFree(lpDock);
	}
	return hDock;
}



Если ваши пути отличаются от дефолтных, используйте tidy.ini:

Code: Select all

[Options]
tooldir=c:\Program Files (x86)\AkelPad\AkelFiles\Tools\HTMLTidy\
configdir=c:\Program Files (x86)\AkelPad\AkelFiles\Tools\HTMLTidy\
Файл д.б. в кодировке 1200 (UTF-16 LE)


Example

Code: Select all

// default config file with XHTML options
indent-attributes: 1
indent: auto
indent-spaces: 2
markup: 1
output-xhtml: 1
wrap: 0
wrap-asp: 1
wrap-attributes: 1
wrap-jste: 1
wrap-php: 1
numeric-entities: 1
tab-size: 4
quiet: 1
Last edited by VladSh on Fri Jun 19, 2015 8:19 pm, edited 6 times in total.

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

Post by KDJ »

Open next/previous/first/last file in directory of current file.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=27932#p27932
// Version: 2015-03-29
// Author: KDJ
//
// *** Open next/previous/first/last file in directory of current file ***
//
// Usage:
//   Call("Scripts::Main", 1, "OpenNextFile.js", '-direction=1 -cycle=0 -ext=0 -tab=0')
//
// Arguments:
//   -direction=1  - open next file - default
//   -direction=-1 - open previous file
//   -direction=0  - open first file
//   -direction=2  - open last file
//   -cycle=0      - cycle search turn off - default
//   -cycle=1      - cycle search turn on
//   -ext=0        - open file any type (extension) - default
//   -ext=1        - open file, same type as current file
//   -tab=0        - open in current tab - default
//   -tab=1        - open in new tab
//
// Remark:
//   Files are sorted in alphabetical order.

var sEditFile = AkelPad.GetEditFile(0);

if (! sEditFile)
  WScript.Quit();

var oSys        = AkelPad.SystemFunction();
var nDirecton   = AkelPad.GetArgValue("direction", 1);
var bCycle      = AkelPad.GetArgValue("cycle", 0);
var bExt        = AkelPad.GetArgValue("ext", 0);
var bTab        = AkelPad.GetArgValue("tab", 0);
var hMainWnd    = AkelPad.GetMainWnd();
var bSingleOpen = AkelPad.SendMessage(hMainWnd, 1222 /*AKD_GETMAININFO*/, 152 /*MI_SINGLEOPENFILE*/, 0);
var sDir        = AkelPad.GetFilePath(sEditFile, 1 /*CPF_DIR*/) + "\\";
var sExt        = bExt ? AkelPad.GetFilePath(sEditFile, 4 /*CPF_FILEEXT*/) : "*";
var lpFindData  = AkelPad.MemAlloc(44 + (260 + 14) * 2); //sizeof(WIN32_FIND_DATA)
var hFindFile   = oSys.Call("Kernel32::FindFirstFileW", sDir + "*." + sExt, lpFindData);
var aFile;
var sNewFile;
var i, n;

if (hFindFile != -1 /*INVALID_HANDLE_VALUE*/);
{
  sEditFile = AkelPad.GetFilePath(sEditFile, 2 /*CPF_FILENAME*/).toUpperCase();
  aFile     = [];

  do
  {
    if (! (AkelPad.MemRead(lpFindData, 3 /*DT_DWORD*/) & 16 /*FILE_ATTRIBUTE_DIRECTORY*/))
      aFile.push(AkelPad.MemRead(_PtrAdd(lpFindData, 44 /*offsetof(WIN32_FIND_DATAW, cFileName)*/), 1 /*DT_UNICODE*/));
  }
  while (oSys.Call("Kernel32::FindNextFileW", hFindFile, lpFindData));

  oSys.Call("Kernel32::FindClose", hFindFile);

  if (aFile.length > 1)
  {
    aFile.sort(function(sA, sB)
      {
        return oSys.Call("Kernel32::lstrcmpiW", sA, sB);
      });

    n = -1;

    if (nDirecton == 0)
    {
      if (aFile[0].toUpperCase() != sEditFile)
        n = 0;
    }
    else if (nDirecton == 2)
    {
      if (aFile[aFile.length - 1].toUpperCase() != sEditFile)
        n = aFile.length - 1;
    }
    else
    {
      for (i = 0; i < aFile.length; ++i)
      {
        if (aFile[i].toUpperCase() == sEditFile)
          break;
      }

      if (nDirecton == 1)
      {
        if (i < aFile.length - 1)
          n = i + 1;
        else if (bCycle)
          n = 0;
      }
      else
      {
        if (i > 0)
          n = i - 1;
        else if (bCycle)
          n = aFile.length - 1;
      }
    }

    if (n >= 0)
    {
      sNewFile = sDir + aFile[n];

      if (AkelPad.IsMDI() && bTab)
        AkelPad.OpenFile(sNewFile);
      else if (AkelPad.Command(4324 /*IDM_WINDOW_FILECLOSE*/))
      {
        AkelPad.SendMessage(hMainWnd, 1219 /*AKD_SETMAININFO*/, 152 /*MIS_SINGLEOPENFILE*/, 0);
        AkelPad.OpenFile(sNewFile);
        AkelPad.SendMessage(hMainWnd, 1219 /*AKD_SETMAININFO*/, 152 /*MIS_SINGLEOPENFILE*/, bSingleOpen);
      }
    }
  }
}

AkelPad.MemFree(lpFindData);


Offline
Posts: 202
Joined: Sat Mar 28, 2015 2:36 pm
Location: Russia

Post by Kley »

Делал когда-то надстройку, еще для Visual Basic 6.0
Попробовал воспроизвести для AkelPad.
Может пригодится, особенно для начинающих программеров?

"Генерация строки кода для MessageBox и InputBox (JS, VBS)"

Code: Select all

//  ============================================================================
//  Version: 2015-03-14
//  Author: Kley
//
//  *** Генерация строки кода для MessageBox и InputBox ***
//
//  Usage:
//  Generation of a line of code for MessageBox and InputBox
//  Call("Scripts::Main", 1, "MsgBoxBuild.js")
//
//  ============================================================================
//  Include: CreateDialog_functions.js
//  http://akelpad.sourceforge.net/forum/viewtopic.php?p=24766#p24766
//  ============================================================================
var oSys   = AkelPad.SystemFunction();
var sClass = "AkelPad::Scripts::" + WScript.ScriptName + "::" + AkelPad.GetInstanceDll();
var hDlg   = oSys.Call("User32::FindWindowW", sClass, 0);
var nTab   = 0;
var nChoiceButtons = 0;
var nChoiceIcon    = 0;
var nChoiceDefBtn  = 0;

GetLangStrings();

if (hDlg) {

  if (! oSys.Call("User32::IsWindowVisible", hDlg))
    oSys.Call("User32::ShowWindow", hDlg, 8 /*SW_SHOWNA*/);

  if (oSys.Call("User32::IsIconic", hDlg))
    oSys.Call("User32::ShowWindow", hDlg, 9 /*SW_RESTORE*/);

  oSys.Call("User32::SetForegroundWindow", hDlg);
}

else if (AkelPad.Include("CreateDialog_functions.js")) {

  var hIcon = oSys.Call("User32::LoadImageW",
                    AkelPad.GetInstanceDll(), //hints
                    101, //lpszName
                      1, //uType=IMAGE_ICON
                     16, //cxDesired (0)
                     16, //cyDesired (0)
                     0); //fuLoad    (0x40 /*LR_DEFAULTSIZE*/)

  var ID_GRP_PROP   = 2000;
  var ID_LBL_TITLE  = 2001;
  var ID_EDT_TITLE  = 2002;
  var ID_LBL_MESS   = 2003;
  var ID_EDT_MESS   = 2004;
  var ID_LBL_TXTDEF = 2005;
  var ID_EDT_TXTDEF = 2006;
  var ID_LBL_BTN    = 2007;
  var ID_CBO_BTN    = 2008;
  var ID_LBL_BDEF   = 2009;
  var ID_OPT_DEF1   = 2010;
  var ID_OPT_DEF2   = 2011;
  var ID_OPT_DEF3   = 2012;
  var ID_LBL_ICON   = 2013;
  var ID_CBO_ICON   = 2014;
  var ID_CMD_TEST   = 2015;
  var ID_CHK_MODAL  = 2016;
  var ID_CHK_VBS    = 2017;
  var ID_CMD_INSERT = 2018;
  var ID_CMD_CANCEL = 2019;
  var ID_TAB        = 2020;
  var aDlg          = [];

  if (AkelPad.WindowRegisterClass(sClass)) {

    AkelPad.ScriptNoMutex();

    CreateDialog(AkelPad.GetMainWnd());
    AkelPad.WindowUnregisterClass(sClass);
  }
  oSys.Call("user32::DestroyIcon", hIcon);
}

function CreateDialog(hParent) {

  var hFocus;

  aDlg.Modeless = true;
  aDlg.Title    = WScript.ScriptBaseName;
  aDlg.Style    = WS_VISIBLE|WS_POPUP|WS_CAPTION|WS_SYSMENU;
  aDlg.Parent   = hParent;
  aDlg.Callback = DialogCallback;
  aDlg.Icon     = hIcon;
  aDlg.W        = 490;
  aDlg.H        = 215;
  aDlg.PosPar   = 3;
  aDlg.PosEdge  = "CC";
  aDlg.CtlStyle = WS_VISIBLE;
  aDlg.Class    = sClass;
  aDlg.SizeClt  = true;
  aDlg.CtlFont  = oSys.Call("Gdi32::GetStockObject", 17 /*DEFAULT_GUI_FONT*/);

  //0x00107 - BS_GROUPBOX|BS_LEFT
  //0x10003 - WS_TABSTOP|CBS_DROPDOWNLIST (BS_AUTOCHECKBOX)
  //0x10009 - WS_TABSTOP|BS_AUTORADIOBUTTON
  //0x10080 - WS_TABSTOP|ES_AUTOHSCROLL
  //0x11044 - WS_TABSTOP|ES_MULTILINE|ES_WANTRETURN|ES_AUTOVSCROLL
  //0x10000 - WS_TABSTOP|BS_PUSHBUTTON
  //0x11400 - WS_TABSTOP|TCS_FIXEDWIDTH|TCS_FOCUSONBUTTONDOWN

  aDlg[ID_GRP_PROP  ] = {X:10,  Y:35,  W:140, H:168, Title: GRP_PROP,          Style: 0x00107};
  aDlg[ID_LBL_BTN   ] = {X:25,  Y:58,  W:115, H:13,  Title: LBL_BTN,           Class: "STATIC"};
  aDlg[ID_CBO_BTN   ] = {X:25,  Y:76,  W:115, H:120, Class: "COMBOBOX",        Style: 0x10003};
  aDlg[ID_LBL_BDEF  ] = {X:25,  Y:104, W:115, H:13,  Title: LBL_BDEF,          Class: "STATIC"};
  aDlg[ID_OPT_DEF1  ] = {X:25,  Y:123, W:25,  H:16,  Title: "1",               Style: 0x10009};
  aDlg[ID_OPT_DEF2  ] = {X:67,  Y:123, W:25,  H:16,  Title: "2",               Style: 0x10009};
  aDlg[ID_OPT_DEF3  ] = {X:110, Y:123, W:25,  H:16,  Title: "3",               Style: 0x10009};
  aDlg[ID_LBL_ICON  ] = {X:25,  Y:152, W:115, H:13,  Title: LBL_ICON,          Class: "STATIC"};
  aDlg[ID_CBO_ICON  ] = {X:25,  Y:170, W:115, H:120, Class: "COMBOBOX",        Style: 0x10003};

  aDlg[ID_LBL_TITLE ] = {X:160, Y:35,  W:230, H:13,  Title: LBL_TITLE,         Class: "STATIC"};
  aDlg[ID_EDT_TITLE ] = {X:160, Y:55,  W:230, H:22,  Class: "EDIT",            Style: 0x10080, ExStyle: 0x200};
  aDlg[ID_LBL_MESS  ] = {X:160, Y:80,  W:230, H:13,  Title: LBL_MESS1,         Class: "STATIC"};
  aDlg[ID_EDT_MESS  ] = {X:160, Y:106, W:230, H:96,  Class: "EDIT",            Style: 0x11044, ExStyle: 0x200};

  aDlg[ID_CMD_TEST  ] = {X:405, Y:54,  W:70,  H:23,  Title: CMD_TEST,          Style: 0x10000};
  aDlg[ID_CHK_MODAL ] = {X:405, Y:104, W:70,  H:16,  Title: "Sys Modal",       Style: 0x10003};
  aDlg[ID_CHK_VBS   ] = {X:405, Y:128, W:70,  H:16,  Title: "VBScript",        Style: 0x10003};
  aDlg[ID_CMD_INSERT] = {X:405, Y:152, W:70,  H:23,  Title: CMD_INSERT,        Style: 0x10000};
  aDlg[ID_CMD_CANCEL] = {X:405, Y:179, W:70,  H:23,  Title: CMD_CANCEL,        Style: 0x10000};

  aDlg[ID_LBL_TXTDEF] = {X:20,  Y:160, W:230, H:13,  Title: LBL_TXTDEF,        Class: "STATIC"};
  aDlg[ID_EDT_TXTDEF] = {X:20,  Y:181, W:370, H:22,  Class: "EDIT",            Style: 0x10080, ExStyle: 0x200};

  aDlg[ID_TAB       ] = {X:0,   Y:0,   W:510, H:24,  Class: "SysTabControl32", Style: 0x11400};

  if (CreateDialogWindow(aDlg, 1))
    AkelPad.WindowGetMessage(0x2 /*WGM_NOKEYSEND*/);

  function DialogCallback(hWnd, uMsg, wParam, lParam) {

    if (uMsg == 1 /*WM_CREATE*/) {

      aDlg.HWND = hWnd;
      CreateDialogWindow(aDlg, 2, hWnd);
      InitDialog();
      hFocus = aDlg[ID_EDT_TITLE].HWND;
    }

    else if ((uMsg == 6 /*WM_ACTIVATE*/) && (wParam == 0 /*WA_INACTIVE*/))
      hFocus = oSys.Call("User32::GetFocus");

    else if ((uMsg == 7 /*WM_SETFOCUS*/))
      oSys.Call("User32::SetFocus", hFocus);

    else if (uMsg == 0x004E /*WM_NOTIFY*/) {

      if (wParam == ID_TAB) {

        if (AkelPad.MemRead(_PtrAdd(lParam, _X64?16:8), 3 /*DT_DWORD*/) == -551 /*TCN_SELCHANGE*/) {

          nTab = AkelPad.SendMessage(aDlg[ID_TAB].HWND, 4875 /*TCM_GETCURSEL*/, 0, 0);
          oSys.Call("User32::SetFocus", aDlg[ID_EDT_TITLE].HWND);
          EnableWindows();
        }
      }
    }

    else if (uMsg == 273 /*WM_COMMAND*/) {

      var nLowParam = LoWord(wParam);
      var nHiwParam = HiWord(wParam);

      if (nLowParam == ID_CMD_TEST)
        TestMessage(true);

      else if (nLowParam == ID_CMD_INSERT)
        TestMessage();

      else if (nLowParam == ID_CBO_BTN) {

        if (nHiwParam == 1 /*CBN_SELCHANGE*/) {

          var nCBSel = AkelPad.SendMessage(lParam /*CB_hWnd*/, 327 /*CB_GETCURSEL*/, 0, 0);
          if (nChoiceButtons != nCBSel) {
            nChoiceButtons = nCBSel;
            EnableRadioButton();
          }
        }
      }

      else if (nLowParam == ID_CBO_ICON) {

        if (nHiwParam == 1 /*CBN_SELCHANGE*/)
          nChoiceIcon = (AkelPad.SendMessage(lParam /*CB_hWnd*/, 327 /*CB_GETCURSEL*/, 0, 0)) * 16;
      }

      else if (nLowParam == ID_OPT_DEF1)
        nChoiceDefBtn = 0;

      else if (nLowParam == ID_OPT_DEF2)
        nChoiceDefBtn = 256;

      else if (nLowParam == ID_OPT_DEF3)
        nChoiceDefBtn = 512;

      else if ((nLowParam == ID_CMD_CANCEL) || (nLowParam == 2 /*IDCANCEL*/))
        oSys.Call("User32::PostMessageW", hWnd, 16 /*WM_CLOSE*/, nLowParam, 0);
    }

    else if (uMsg == 16 /*WM_CLOSE*/) {

        AkelPad.WindowUnsubClass(aDlg[ID_EDT_MESS].HWND);
        oSys.Call("User32::DestroyWindow", hWnd);
    }

    else if (uMsg == 2 /*WM_DESTROY*/)
      oSys.Call("User32::PostQuitMessage", 0);

    return 0;
  }

  function InitDialog() {

    var aButtons = ["OK",
                    "OK Cancel",
                    "Abort Retry Ignore",
                    "Yes No Cancel",
                    "Yes No",
                    "Retry Cancel"];

    var aIcon = ["No","Critical","Question","Exclamation","Information"];
    var i;

    //ComboBox
    for (i = 0; i < aButtons.length; ++i)
      AkelPad.SendMessage(aDlg[ID_CBO_BTN].HWND, 323 /*CB_ADDSTRING*/, 0, aButtons[i]);
    AkelPad.SendMessage(aDlg[ID_CBO_BTN].HWND, 334 /*CB_SETCURSEL*/, 0, 0); //0 - индекс строки, 0);

    for (i = 0; i < aIcon.length; ++i)
      AkelPad.SendMessage(aDlg[ID_CBO_ICON].HWND, 323 /*CB_ADDSTRING*/, 0, aIcon[i]);
    AkelPad.SendMessage(aDlg[ID_CBO_ICON].HWND, 334 /*CB_SETCURSEL*/, 0, 0); //0 - индекс строки, 0);

    //Edit
    AkelPad.WindowSubClass(aDlg[ID_EDT_MESS].HWND, EditCallback, 258 /*WM_CHAR*/);

    //Tab
    FillTC();

    EnableWindows();
    EnableRadioButton();
  }

  function EditCallback(hWnd, uMsg, wParam, lParam) {

    if (uMsg == 258 /*WM_CHAR*/) {
      if (wParam == 0x09 /*VK_TAB*/)
        oSys.Call("User32::SetFocus", oSys.Call("User32::GetNextDlgTabItem", aDlg.HWND, hWnd, Shift()));
    }
    return 0;
  }

  function FillTC() {

    var lpText   = AkelPad.MemAlloc(64);
    var lpTCITEM = AkelPad.MemAlloc(_X64?40:28 /*sizeof(TCITEM)*/);
    var aTabText = ["MessageBox","InputBox"];
    var i;

    AkelPad.MemCopy(lpTCITEM, 1 /*TCIF_TEXT*/, 3 /*DT_DWORD*/); //mask
    AkelPad.MemCopy(lpTCITEM + (_X64?16:12), lpText, 2 /*DT_QWORD*/); //pszText

    for (i = 0; i < aTabText.length; ++i) {

      AkelPad.MemCopy(lpText, aTabText[i], 1 /*DT_UNICODE*/);
      AkelPad.SendMessage(aDlg[ID_TAB].HWND, 4926 /*TCM_INSERTITEMW*/, i, lpTCITEM);
    }

    AkelPad.SendMessage(aDlg[ID_TAB].HWND, 4905 /*TCM_SETITEMSIZE*/, 0, MkLong(80, 20));
    AkelPad.SendMessage(aDlg[ID_TAB].HWND, 4876 /*TCM_SETCURSEL*/, nTab, 0); //1 - номер вкладки, 0);

    AkelPad.MemFree(lpText);
    AkelPad.MemFree(lpTCITEM);
  }
}

function LoWord(nDwNum) {

  return nDwNum & 0xFFFF;
}

function HiWord(nParam)
{
  return ((nParam >> 16) & 0xffff);
}

function MkLong(nLoWord, nHiWord) {

  return (nLoWord & 0xFFFF) | (nHiWord << 16);
}

function Shift() {

  return Boolean(oSys.Call("User32::GetKeyState", 0x10 /*VK_SHIFT*/) & 0x8000);
}

function EnableWindows() {

  oSys.Call("User32::ShowWindow", aDlg[ID_GRP_PROP  ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_LBL_BTN   ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_CBO_BTN   ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_LBL_BDEF  ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_OPT_DEF1  ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_OPT_DEF2  ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_OPT_DEF3  ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_LBL_ICON  ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_CBO_ICON  ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_CHK_MODAL ].HWND, (nTab == 0));
  oSys.Call("User32::ShowWindow", aDlg[ID_LBL_TXTDEF].HWND, (nTab == 1));
  oSys.Call("User32::ShowWindow", aDlg[ID_EDT_TXTDEF].HWND, (nTab == 1));

  if (nTab == 1) {
    oSys.Call("User32::MoveWindow",     aDlg[ID_LBL_TITLE].HWND, 20,  35, 230, 13, 1);
    oSys.Call("User32::MoveWindow",     aDlg[ID_EDT_TITLE].HWND, 20,  55, 370, 22, 1);
    oSys.Call("User32::MoveWindow",     aDlg[ID_LBL_MESS ].HWND, 20,  85, 230, 13, 1);
    oSys.Call("User32::MoveWindow",     aDlg[ID_EDT_MESS ].HWND, 20, 106, 370, 47, 1);
    oSys.Call("user32::SetWindowTextW", aDlg[ID_LBL_MESS ].HWND, LBL_MESS2);
  }
  else {
    oSys.Call("User32::MoveWindow",     aDlg[ID_LBL_TITLE].HWND, 160,  35, 230, 13, 1);
    oSys.Call("User32::MoveWindow",     aDlg[ID_EDT_TITLE].HWND, 160,  55, 230, 22, 1);
    oSys.Call("User32::MoveWindow",     aDlg[ID_LBL_MESS ].HWND, 160,  85, 230, 13, 1);
    oSys.Call("User32::MoveWindow",     aDlg[ID_EDT_MESS ].HWND, 160, 106, 230, 96, 1);
    oSys.Call("user32::SetWindowTextW", aDlg[ID_LBL_MESS ].HWND, LBL_MESS1);
  }
}

function EnableRadioButton() {

  AkelPad.SendMessage(aDlg[ID_OPT_DEF1].HWND, 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
  AkelPad.SendMessage(aDlg[ID_OPT_DEF2].HWND, 241 /*BM_SETCHECK*/, 0 /*BST_UNCHECKED*/, 0);
  AkelPad.SendMessage(aDlg[ID_OPT_DEF3].HWND, 241 /*BM_SETCHECK*/, 0 /*BST_UNCHECKED*/, 0);

  switch (nChoiceButtons)
  {
    case 0:
      oSys.Call("User32::EnableWindow", aDlg[ID_OPT_DEF2].HWND, false);
      oSys.Call("User32::EnableWindow", aDlg[ID_OPT_DEF3].HWND, false);
      break;
    case 1:
    case 4:
    case 5:
      oSys.Call("User32::EnableWindow", aDlg[ID_OPT_DEF2].HWND, true);
      oSys.Call("User32::EnableWindow", aDlg[ID_OPT_DEF3].HWND, false);
      break;
    default:
      oSys.Call("User32::EnableWindow", aDlg[ID_OPT_DEF2].HWND, true);
      oSys.Call("User32::EnableWindow", aDlg[ID_OPT_DEF3].HWND, true);
      break;
  }
}

function TestMessage(bTest) {

  var pTitle = GetTextFromDialog(aDlg[ID_EDT_TITLE].HWND) || LBL_TITLE;
  var pMessage = GetTextFromDialog(aDlg[ID_EDT_MESS].HWND);
  var nType;
  var nModal;
  var aConst = [];

  if (! pMessage)
    pMessage = (nTab == 0) ? LBL_MESS1
                           : LBL_MESS2;
  if (nTab == 0) {

    switch (nChoiceButtons) {
      case 0: aConst.push("MB_OK");               break;
      case 1: aConst.push("MB_OKCANCEL");         break;
      case 2: aConst.push("MB_ABORTRETRYIGNORE"); break;
      case 3: aConst.push("MB_YESNOCANCEL");      break;
      case 4: aConst.push("MB_YESNO");            break;
      case 5: aConst.push("MB_RETRYCANCEL");      break;
    }

    switch (nChoiceIcon) {
      case 16: aConst.push("MB_ICONSTOP");        break;
      case 32: aConst.push("MB_ICONQUESTION");    break;
      case 48: aConst.push("MB_ICONEXCLAMATION"); break;
      case 64: aConst.push("MB_ICONINFORMATION"); break;
    }

    switch (nChoiceDefBtn) {
      case 256: aConst.push("MB_DEFBUTTON2"); break;
      case 512: aConst.push("MB_DEFBUTTON3"); break;
    }

    if (nModal = AkelPad.SendMessage(aDlg[ID_CHK_MODAL].HWND, 240 /*BM_GETCHECK*/, 0, 0) ? 4096 /*MB_SYSTEMMODAL*/ : 0)
      aConst.push("MB_SYSTEMMODAL");

    nType = nChoiceButtons + nChoiceIcon + nChoiceDefBtn + nModal;

    if (bTest) {
      AkelPad.MessageBox(aDlg.HWND, pMessage, pTitle, nType);
      return;
    }
  }
  else {

    nType = GetTextFromDialog(aDlg[ID_EDT_TXTDEF].HWND);

    if (bTest) {
      AkelPad.InputBox(aDlg.HWND, pTitle, pMessage, nType);
      return;
    }
  }
  InsertTextToEditFile(pTitle, pMessage, nType, aConst);
}

function InsertTextToEditFile(pTitle, pMessage, nType, aConst) {

  var nVBcheck = AkelPad.SendMessage(aDlg[ID_CHK_VBS].HWND, 240 /*BM_GETCHECK*/, 0, 0);
  var pOutput;

  pMessage  = pMessage.replace(/(\r\n|\r|\n)/g, "\\n");

  if (nTab == 0) {

    if (nVBcheck) {

      pMessage = pMessage.replace(/\\n/g, '" & vbNewLine & "');
      pMessage = pMessage.replace(/& "" &/g, "&");

      pOutput  = (nChoiceButtons ? 'lngButton = MsgBox("' : 'MsgBox "') +
                 pMessage        + '", ' +
                 nType           + ', "' +
                 pTitle          + '"'   +
                 (nChoiceButtons ? ") '" : " '") + aConst.join("|");
    }
    else {

      pOutput  = (nChoiceButtons ? "var nButton = " : "")     +
                 'AkelPad.MessageBox(AkelPad.GetMainWnd(), "' +
                 pMessage + '", "' +
                 pTitle   + '", '  +
                 nType    + ' /*'  + aConst.join("|") + '*/);';
    }
  }
  else {

    nType = (nType) ? nType + '"' : '"';

    if (nVBcheck) {

      pMessage = pMessage.replace(/\\n/g, '" & vbNewLine & "');
      pMessage = pMessage.replace(/& "" &/g, "&");
      pOutput  = 'strOutput = InputBox("' +
                 pMessage + '", "' +
                 pTitle   + '", "' +
                 nType    + ')'    ;
    }
    else {

      pOutput  = 'var nButton = AkelPad.InputBox(AkelPad.GetMainWnd(), "' +
                 pTitle   + '", "' +
                 pMessage + '", "' +
                 nType    + ');'   ;
    }
  }
  AkelPad.ReplaceSel(pOutput + "\n");
}

function GetTextFromDialog(hWndEditControl) {

  var nTextLen = AkelPad.SendMessage(hWndEditControl, 14 /*WM_GETTEXTLENGTH*/, 0, 0) + 1;
  var lpText = AkelPad.MemAlloc(nTextLen * 2);

  AkelPad.SendMessage(hWndEditControl, 13 /*WM_GETTEXT*/, nTextLen, lpText);

  var pText = AkelPad.MemRead(lpText, 1 /*DT_UNICODE*/);

  AkelPad.MemFree(lpText);

  return pText;
}

function GetLangStrings() {

  if (AkelPad.GetLangId(0 /*LANGID_FULL*/) == 1049 /*Russian*/) {

    LBL_MESS1  = "Текст сообщения";
    LBL_MESS2  = "Заголовок поля ввода";
    GRP_PROP   = "Параметры"
    LBL_BTN    = "Кнопки"
    LBL_BDEF   = "Кнопка по умолчанию"
    LBL_ICON   = "Значок"
    LBL_TITLE  = "Заголовок"
    CMD_TEST   = "Тест"
    CMD_INSERT = "Добавить"
    CMD_CANCEL = "Закрыть"
    LBL_TXTDEF = "Начальный текст"
  }
  else {

    LBL_MESS1  = "Message text";
    LBL_MESS2  = "Edit box label";
    GRP_PROP   = "Settings";
    LBL_BTN    = "Buttons";
    LBL_BDEF   = "Default button";
    LBL_ICON   = "Icon";
    LBL_TITLE  = "Title";
    CMD_TEST   = "Test";
    CMD_INSERT = "Add";
    CMD_CANCEL = "Close";
    LBL_TXTDEF = "Edit box text";
  }
}


Требуется CreateDialog_functions.js

Спасибо всем, чей код попал в этот скрипт!

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

Post by KDJ »

Extended version of "Find/Replace" dialog FindReplaceEx.js - part 3.
Language files are in the next post.

Code: Select all

function SetTextLV(nID, nItem, nSubItem, sText)
{
  AkelPad.MemCopy(_PtrAdd(lpLVITEM, 8), nSubItem, DT_DWORD);
  AkelPad.MemCopy(lpBuffer, sText, DT_UNICODE);
  SendMessage(aWnd[nID].HWND, 4212 /*LVM_SETITEMTEXTW*/, nItem, lpLVITEM);
}

function FindItemLV(nID, sText, nItem)
{
  var lpLVFINDINFO = AkelPad.MemAlloc(_X64 ? 40 : 24); //sizeof(LVFINDINFO)

  AkelPad.MemCopy(lpLVFINDINFO, 0x02 /*LVFI_STRING*/, DT_DWORD);
  AkelPad.MemCopy(_PtrAdd(lpLVFINDINFO, _X64 ? 8 : 4), lpBuffer, DT_QWORD);
  AkelPad.MemCopy(lpBuffer, sText, DT_UNICODE);

  nItem = SendMessage(aWnd[nID].HWND, 4179 /*LVM_FINDITEMW*/, nItem, lpLVFINDINFO);
  AkelPad.MemFree(lpLVFINDINFO);

  return nItem;
}

function InsertItemLV(nID, aField, nItem)
{
  var i;

  AkelPad.MemCopy(_PtrAdd(lpLVITEM, 4), nItem, DT_DWORD);
  AkelPad.MemCopy(_PtrAdd(lpLVITEM, 8),     0, DT_DWORD);

  AkelPad.MemCopy(lpBuffer, aField[0], DT_UNICODE);
  nItem = SendMessage(aWnd[nID].HWND, 4173 /*LVM_INSERTITEMW*/, 0, lpLVITEM);

  for (i = 1; i < aField.length; ++i)
  {
    AkelPad.MemCopy(_PtrAdd(lpLVITEM, 8), i, DT_DWORD);
    AkelPad.MemCopy(lpBuffer, aField[i], DT_UNICODE);
    SendMessage(aWnd[nID].HWND, 4212 /*LVM_SETITEMTEXTW*/, nItem, lpLVITEM);
  }

  return nItem;
}

function DeleteItemLV(nID, nItem)
{
  SendMessage(aWnd[nID].HWND, 4104 /*LVM_DELETEITEM*/, nItem, 0);
}

function InsertColumnsLV(nID)
{
  var lpLVCOLUMN = AkelPad.MemAlloc(_X64 ? 56 : 44); //sizeof(LVCOLUMN)
  var aText      = [sTxtTemplateName, sTxtWhatFind, sTxtReplaceWith, sTxtConditions];
  var i;

  AkelPad.MemCopy(lpLVCOLUMN,                               0x4, DT_DWORD); //mask=LVCF_TEXT
  AkelPad.MemCopy(_PtrAdd(lpLVCOLUMN, _X64 ? 16 : 12), lpBuffer, DT_QWORD); //pszText

  for (i = 0; i < aText.length; ++i)
  {
    AkelPad.MemCopy(lpBuffer, aText[i], DT_UNICODE);
    SendMessage(aWnd[nID].HWND, 4193 /*LVM_INSERTCOLUMNW*/, i, lpLVCOLUMN);
  }

  SetColumnsWidthLV(nID);
  AkelPad.MemFree(lpLVCOLUMN);
}

function GetColumnsWidthLV(nID)
{
  var aCol = (nID == IDFRTLV) ? aFRTCol : aBRCol;
  var nColW;
  var i;

  for (i = 0; i < aCol.length; ++i)
  {
    if ((nColW = SendMessage(aWnd[nID].HWND, 4125 /*LVM_GETCOLUMNWIDTH*/, i, 0)) > 0)
    {
      aCol[i][0] = 1;
      aCol[i][1] = nColW;
    }
    else
      aCol[i][0] = 0;
  }
}

function SetColumnsWidthLV(nID)
{
  var aCol = (nID == IDFRTLV) ? aFRTCol : aBRCol;
  var i;

  for (i = 0; i < aCol.length; ++i)
    SendMessage(aWnd[nID].HWND, 4126 /*LVM_SETCOLUMNWIDTH*/, i, aCol[i][0] ? aCol[i][1] : 0);
}

function SetSortFRTLV()
{
  var lpHDITEM = AkelPad.MemAlloc(_X64 ? 72 : 48); //sizeof(HDITEM)
  var nFmt     = 0x4000 /*HDF_STRING*/ | (bFRTSort ? 0x0400 /*HDF_SORTUP*/ : 0);
  var hHeader  = SendMessage(aWnd[IDFRTLV].HWND, 4127 /*LVM_GETHEADER*/, 0, 0);

  AkelPad.MemCopy(lpBuffer, sTxtTemplateName, DT_UNICODE);
  AkelPad.MemCopy(lpHDITEM, 0x06, DT_DWORD); //mask=HDI_FORMAT|HDI_TEXT
  AkelPad.MemCopy(_PtrAdd(lpHDITEM, 8),lpBuffer, DT_QWORD); //pszText
  AkelPad.MemCopy(_PtrAdd(lpHDITEM, _X64 ? 28 : 20), nFmt, DT_DWORD); //fmt

  SendMessage(hHeader, 4620 /*HDM_SETITEMW*/, 0, lpHDITEM);
  AkelPad.MemFree(lpHDITEM);

  if (bFRTSort)
    aWnd[IDFRTLV].S |= 0x10 /*LVS_SORTASCENDING*/;
  else
    aWnd[IDFRTLV].S &= ~0x10/*LVS_SORTASCENDING*/;

  oSys.Call("User32::SetWindowLongW", aWnd[IDFRTLV].HWND, -16 /*GWL_STYLE*/, aWnd[IDFRTLV].S);
}

function FillFRTLV()
{
  var aRecord = AkelPad.ReadFile(WScript.ScriptFullName.replace(/\.js$/i, "_templates.tsv"), 0x1D /*OD_ADT_BINARY_ERROR|OD_ADT_DETECT_CODEPAGE|OD_ADT_DETECT_BOM|OD_ADT_NOMESSAGES*/);
  var aField;
  var i, n;

  if (aRecord)
    aRecord = aRecord.split("\r\n");
  else
    aRecord = ["Empty lines\t^[ \\t]*$\\n*\t\t0010"];

  for (i = 0; i < aRecord.length; ++i)
  {
    aField = aRecord[i].split("\t");

    if (aField[0])
    {
      while (aField.length < 4)
        aField[aField.length] = "";

      if (aField[3].length == 4)
        aField[3] = aField[3].substr(0, 3) + "1" + aField[3].charAt(3);
      else if (aField[3].length > 4)
        aField[3] = aField[3].substr(0, 5);
      else
      {
        while (aField[3].length < 5)
          aField[3] += (aField[3].length == 3) ? "1" : "0";
      }

      aField[3] = aField[3].replace(/[^1]/g, "0");

      if ((aField[3].charAt(2) == "1") && (aField[3].charAt(4) == "1"))
        aField[3] = aField[3].substr(0, 4) + "0";

      InsertItemLV(IDFRTLV, aField, i);
    }
  }

  for (i = 0; i < aBR.length; ++i)
  {
    for (n = aBR[i].length - 1; n > -1; --n)
    {
      if (FindItemLV(IDFRTLV, aBR[i][n], -1) == -1)
      {
        aBR[i].splice(n, 1);
        aBRCB[i].splice(n, 1);
      }
    }
  }

  if (nFRTSel > GetItemCountLV(IDFRTLV) - 1)
    nFRTSel = GetItemCountLV(IDFRTLV) - 1;
  if (nFRTSel < 0)
    nFRTSel = 0;

  SetCurSelLV(IDFRTLV, nFRTSel);
}

function FillBRLV()
{
  var i, n;

  bCheckBRLV = 0;

  SendMessage(aWnd[IDBRLV].HWND, 4105 /*LVM_DELETEALLITEMS*/, 0, 0);

  if (aBR[nBR].length)
  {
    for (i = 0; i < aBR[nBR].length; ++i)
    {
      n = FindItemLV(IDFRTLV, aBR[nBR][i], -1);
      InsertItemLV(IDBRLV, [aBR[nBR][i], GetTextLV(IDFRTLV, n, 1), GetTextLV(IDFRTLV, n, 2), GetTextLV(IDFRTLV, n, 3)], i);
      SetCheckBRLV(i, aBRCB[nBR][i]);
    }

    SetCurSelLV(IDBRLV, FindItemLV(IDBRLV, GetTextLV(IDFRTLV, GetCurSelLV(IDFRTLV), 0), -1));
  }

  bCheckBRLV = 1;
}

function GetCheckBRLV(nItem)
{
  aBRCB[nBR][nItem] = (SendMessage(aWnd[IDBRLV].HWND, 4140 /*LVM_GETITEMSTATE*/, nItem, 0xF000 /*LVIS_STATEIMAGEMASK*/) >> 12) - 1;
}

function SetCheckBRLV(nItem, bCheck)
{
  AkelPad.MemCopy(_PtrAdd(lpLVITEM, 12), (bCheck + 1) << 12, DT_DWORD); //state
  AkelPad.MemCopy(_PtrAdd(lpLVITEM, 16), 0xF000 /*LVIS_STATEIMAGEMASK*/, DT_DWORD); //stateMask
  SendMessage(aWnd[IDBRLV].HWND, 4139 /*LVM_SETITEMSTATE*/, nItem, lpLVITEM);
}

function NewAddRenameFRT(nID)
{
  var nItem = GetCurSelLV(IDFRTLV);
  var aField;
  var sOldName;
  var i, n;

  if (nID == IDFRTADDB)
  {
    GetWhatWithFR();
    nFRF = SendMessage(hMainWnd, 1222 /*AKD_GETMAININFO*/, 228 /*MI_SEARCHOPTIONS*/, 0);
    aField = [
      (nItem > -1) ? GetTextLV(IDFRTLV, nItem, 0) : "",
      sWhatText.replace(/[\r\n\t]/g, ""),
      hWithE ? sWithText.replace(/[\r\n\t]/g, "") : "",
      ((nFRF & FRF_MATCHCASE) ? "1" : "0") +
      ((nFRF & FRF_WHOLEWORD) ? "1" : "0") +
      ((nFRF & FRF_REGEXP) ? "1" : "0") +
      ((nFRF & FRF_REGEXPNONEWLINEDOT) ? "0" : "1") +
      ((nFRF & FRF_ESCAPESEQ) ? "1" : "0")];
  }
  else
  {
    if (nItem > -1)
    {
      aField = [];
      for (i = 0; i < 4; ++i)
        aField[i] = GetTextLV(IDFRTLV, nItem, i);
    }
    else
      aField = ["", "", "", "00010"];

    sOldName = aField[0];
  }

  aField[0] = InputBox(aWnd[IDFRTLV].HWND, sTxtTemplates + " - " + aWnd[nID].T, sTxtTemplateName, aField[0], 0, CheckNameFRT, nID, 0, 0, 0, 0, 128 /*vEditLength*/);

  if (aField[0])
  {
    if (nID == IDFRTRENB)
    {
      DeleteItemLV(IDFRTLV, nItem)

      for (i = 0; i < aBR.length; ++i)
      {
        for (n = 0; n < aBR[i].length; ++n)
        {
          if (aBR[i][n].toUpperCase() == sOldName.toUpperCase())
            aBR[i][n] = aField[0];
        }
      }

      n = -1;
      while ((n = FindItemLV(IDBRLV, sOldName, n)) > -1)
        SetTextLV(IDBRLV, n, 0, aField[0]);
    }
    else
      ++nItem;

    SetCurSelLV(IDFRTLV, InsertItemLV(IDFRTLV, aField, nItem));
  }
}

function CheckNameFRT(hWnd, aField, nID)
{
  var nSelItem;
  var nFindItem;

  if (aField[0])
  {
    if (/[\r\n\t]/.test(aField[0]))
    {
      AkelPad.MessageBox(hWnd, sTxtNameInvalid, aWnd[nID].T, 0x30 /*MB_ICONWARNING*/);
      return 0;
    }
    else
    {
      nSelItem  = GetCurSelLV(IDFRTLV);
      nFindItem = FindItemLV(IDFRTLV, aField[0], -1);

      if (nFindItem > -1)
      {
        if ((nID != IDFRTRENB) || (nFindItem != nSelItem))
        {
          AkelPad.MessageBox(hWnd, '"' + aField[0] + '"\n\n' + sTxtNameExists, aWnd[nID].T, 0x30 /*MB_ICONWARNING*/);
          return 0;
        }
      }
    }
  }

  return -1;
}

function UpDownFRT(nID)
{
  var nItemCur = GetCurSelLV(IDFRTLV);
  var nItemNew = (nID == IDFRTUPB) ? nItemCur - 1 : nItemCur + 1;
  var aField   = [];
  var i;

  for (i = 0; i < aFRTCol.length; ++i)
    aField[i] = GetTextLV(IDFRTLV, nItemCur, i);
  for (i = 0; i < aFRTCol.length; ++i)
    SetTextLV(IDFRTLV, nItemCur, i, GetTextLV(IDFRTLV, nItemNew, i));
  for (i = 0; i < aFRTCol.length; ++i)
    SetTextLV(IDFRTLV, nItemNew, i, aField[i]);

  SetCurSelLV(IDFRTLV, nItemNew);
}

function RemoveFRT()
{
  var nItem = GetCurSelLV(IDFRTLV);
  var sName = GetTextLV(IDFRTLV, nItem, 0);
  var i, n;

  if (AkelPad.MessageBox(hWndFRT, '"' + sName + '"\n\n' + sTxtWantRemove, sTxtTemplates + ' - ' + sTxtRemove, 0x21 /*MB_ICONQUESTION|MB_OKCANCEL*/) == 1 /*IDOK*/)
  {
    DeleteItemLV(IDFRTLV, nItem);

    for (i = 0; i < aBR.length; ++i)
    {
      for (n = aBR[i].length - 1; n > -1; --n)
      {
        if (aBR[i][n].toUpperCase() == sName.toUpperCase())
        {
          aBR[i].splice(n, 1);
          aBRCB[i].splice(n, 1);
        }
      }
    }

    n = -1;
    while ((n = FindItemLV(IDBRLV, sName, n)) > -1)
      DeleteItemLV(IDBRLV, n--);

    if (nItem == GetItemCountLV(IDFRTLV))
      --nItem;

    SetCurSelLV(IDFRTLV, nItem);
    RefreshViewFRT();
  }
}

function CheckExpressionFRT(nItem, bMsgOK)
{
  var nEditID = IDWHATE;
  var nErrOffset;

  if (GetTextLV(IDFRTLV, nItem, 3).charAt(2) == "1")
    nErrOffset = CheckRegExp(GetTextLV(IDFRTLV, nItem, 1));
  else
  {
    nErrOffset = CheckEscSeq(GetTextLV(IDFRTLV, nItem, 1));

    if (! nErrOffset)
    {
      nErrOffset = CheckEscSeq(GetTextLV(IDFRTLV, nItem, 2));
      nEditID    = IDWITHE;
    }
  }

  if (nErrOffset)
  {
    SetCurSelLV(IDFRTLV, nItem);
    AkelPad.MessageBox(hWndFRT, sTxtExprError + ' "' + ((nEditID == IDWHATE) ? sTxtWhatFind : sTxtReplaceWith) + '" (' + nErrOffset + ').', sTxtTemplates, 0x10 /*MB_ICONERROR*/);
    SendMessage(aWnd[nEditID].HWND, 177 /*EM_SETSEL*/, nErrOffset - 1, -1);
    PostMessage(hWndFRT, 0x8001 /*WM_APP+1*/, 0, nEditID);
  }
  else if (bMsgOK)
  {
    AkelPad.MessageBox(hWndFRT, sTxtExprOK, sTxtTemplates, 0x40 /*MB_ICONINFORMATION*/);

    if (oSys.Call("User32::GetFocus") == aWnd[IDCHECKEXPB].HWND)
      PostMessage(hWndFRT, 0x8001 /*WM_APP+1*/, 0, IDFRTLV);
  }

  return nErrOffset;
}

function AddToBatch()
{
  var n     = GetCurSelLV(IDFRTLV);
  var sName = GetTextLV(IDFRTLV, n, 0);
  var nItem = InsertItemLV(IDBRLV, [sName, GetTextLV(IDFRTLV, n, 1), GetTextLV(IDFRTLV, n, 2), GetTextLV(IDFRTLV, n, 3)], GetItemCountLV(IDBRLV));

  aBR[nBR][nItem] = sName;
  SetCurSelLV(IDBRLV, nItem);
  SetCheckBRLV(nItem, 1);

  if (oSys.Call("User32::GetFocus") == aWnd[IDTOBATCH].HWND)
    PostMessage(hWndFRT, 0x8001 /*WM_APP+1*/, 0, IDFRTLV);
}

function SetFRTtoFR()
{
  var nItem  = GetCurSelLV(IDFRTLV);
  var sConds = GetTextLV(IDFRTLV, nItem, 3);

  nWhatSel1 = 0;
  nWhatSel2 = -1;
  SendMessage(hWhatE, 177 /*EM_SETSEL*/, nWhatSel1, nWhatSel2);
  SendMessage(hWhatE, 194 /*EM_REPLACESEL*/, 1, GetTextLV(IDFRTLV, nItem, 1));
  SendMessage(hWhatE, 177 /*EM_SETSEL*/, nWhatSel1, nWhatSel2);

  if (hWithE)
  {
    nWithSel1 = 0;
    nWithSel2 = -1;
    SendMessage(hWithE, 177 /*EM_SETSEL*/, nWithSel1, nWithSel2);
    SendMessage(hWithE, 194 /*EM_REPLACESEL*/, 1, GetTextLV(IDFRTLV, nItem, 2));
    SendMessage(hWithE, 177 /*EM_SETSEL*/, nWithSel1, nWithSel2);
  }

  nFRF = SendMessage(hMainWnd, 1222 /*AKD_GETMAININFO*/, 228 /*MI_SEARCHOPTIONS*/, 0) & ~FRF_REGEXPNONEWLINEDOT;

  if (sConds.charAt(3) == "0")
    nFRF |= FRF_REGEXPNONEWLINEDOT;

  SendMessage(hMainWnd, 1219 /*AKD_SETMAININFO*/, 228 /*MIS_SEARCHOPTIONS*/, nFRF);

  SendDlgItemMessage(hDlg, IDC_SEARCH_MATCHCASE, 241 /*BM_SETCHECK*/, parseInt(sConds.charAt(0)), 0);
  SendMessage(hDlg, 273 /*WM_COMMAND*/, IDC_SEARCH_MATCHCASE, GetDlgItem(hDlg, IDC_SEARCH_MATCHCASE));

  SendDlgItemMessage(hDlg, IDC_SEARCH_WHOLEWORD, 241 /*BM_SETCHECK*/, parseInt(sConds.charAt(1)), 0);
  SendMessage(hDlg, 273 /*WM_COMMAND*/, IDC_SEARCH_WHOLEWORD, GetDlgItem(hDlg, IDC_SEARCH_WHOLEWORD));

  SendDlgItemMessage(hDlg, IDC_SEARCH_REGEXP, 241 /*BM_SETCHECK*/, parseInt(sConds.charAt(2)), 0);
  SendMessage(hDlg, 273 /*WM_COMMAND*/, IDC_SEARCH_REGEXP, GetDlgItem(hDlg, IDC_SEARCH_REGEXP));

  SendDlgItemMessage(hDlg, IDC_SEARCH_ESCAPESEQ, 241 /*BM_SETCHECK*/, parseInt(sConds.charAt(4)), 0);
  SendMessage(hDlg, 273 /*WM_COMMAND*/, IDC_SEARCH_ESCAPESEQ, GetDlgItem(hDlg, IDC_SEARCH_ESCAPESEQ));
}

function RenameBR()
{
  var sName = InputBox(aWnd[IDBRLV].HWND, sTxtBatches + " - " + sTxtRename, sTxtBatchNumber + (nBR + 1) + ":", aBRName[nBR], 0, 0, 0, 0, 0, 0, 0, 128 /*vEditLength*/);

  if (typeof sName == "string")
  {
    aBRName[nBR] = sName.replace(/[\r\n\t]/g, "");
    SetNameBR();
  }
}

function SetNameBR()
{
  oSys.Call("User32::SetWindowTextW", aWnd[IDBRNAMES].HWND, " " + (aBRName[nBR] ? aBRName[nBR] : sTxtBatchNumber + (nBR + 1)));
}

function UpDownBR(nID)
{
  var nItemCur  = GetCurSelLV(IDBRLV);
  var nItemNew  = (nID == IDBRUPB) ? nItemCur - 1 : nItemCur + 1;
  var bCheckCur = aBRCB[nBR][nItemCur];
  var bCheckNew = aBRCB[nBR][nItemNew];
  var i;

  aBR[nBR][nItemCur] = aBR[nBR][nItemNew];
  for (i = 0; i < aBRCol.length; ++i)
    SetTextLV(IDBRLV, nItemCur, i, GetTextLV(IDBRLV, nItemNew, i));

  nFRTSel = GetCurSelLV(IDFRTLV);
  aBR[nBR][nItemNew] = GetTextLV(IDFRTLV, nFRTSel, 0);
  for (i = 0; i < aBRCol.length; ++i)
    SetTextLV(IDBRLV, nItemNew, i, GetTextLV(IDFRTLV, nFRTSel, i));

  SetCheckBRLV(nItemCur, bCheckNew);
  SetCheckBRLV(nItemNew, bCheckCur);

  SetCurSelLV(IDBRLV, nItemNew);
}

function RemoveBR()
{
  var nItem = GetCurSelLV(IDBRLV);

  aBR[nBR].splice(nItem, 1);
  aBRCB[nBR].splice(nItem, 1);
  DeleteItemLV(IDBRLV, nItem);

  if (nItem == aBR[nBR].length)
    --nItem;

  SetCurSelLV(IDBRLV, nItem);
  EnableButtonsFRT();
}

function BatchReplaceAll()
{
  var nChanges = 0;
  var bCloseDlg;
  var bNoMsg;
  var sConds;
  var i;

  if ((nBatchNum >= 0) && (AkelPad.MessageBox(hWndFRT, sTxtBatchNumber + (nBR + 1) + ".\n" + aBRName[nBR] + "\n\n" + sTxtWantBatchRepl, sTxtBatchReplace, 0x21 /*MB_ICONQUESTION|MB_OKCANCEL*/) != 1 /*IDOK*/))
  {
    if (oSys.Call("User32::GetFocus") == aWnd[IDBRALLB].HWND)
      PostMessage(hWndFRT, 0x8001 /*WM_APP+1*/, 0, IDBRLV);
    return;
  }

  for (i = 0; i < aBR[nBR].length; ++i)
  {
    if (aBRCB[nBR][i])
    {
      if (! GetTextLV(IDBRLV, i, 1))
      {
        SetCurSelLV(IDBRLV, i);
        AkelPad.MessageBox(hWndFRT, aBR[nBR][i] + "\n\n" + sTxtNoFindText, sTxtTemplates, 0x10 /*MB_ICONERROR*/);
        PostMessage(hWndFRT, 0x8001 /*WM_APP+1*/, 0, IDWHATE);
        return;
      }

      if (((GetTextLV(IDBRLV, i, 3).charAt(2) == "1") || (GetTextLV(IDBRLV, i, 3).charAt(4) == "1")) && CheckExpressionFRT(FindItemLV(IDFRTLV, aBR[nBR][i], -1), 0))
        return;
    }
  }

  nFRF = SendMessage(hMainWnd, 1222 /*AKD_GETMAININFO*/, 228 /*MI_SEARCHOPTIONS*/, 0);
  bCloseDlg  = nFRF & FRF_REPLACEALLANDCLOSE;
  bNoMsg     = nFRF & FRF_REPLACEALLNOMSG;
  nFRF &= ~(FRF_REPLACEALLANDCLOSE | FRF_REPLACEALLNOMSG | FRF_CHECKINSELIFSEL | FRF_CYCLESEARCH | FRF_CYCLESEARCHPROMPT);

  for (i = 0; i < aBR[nBR].length; ++i)
  {
    if (aBRCB[nBR][i])
    {
      SetCurSelLV(IDBRLV, i);
      oSys.Call("User32::UpdateWindow", hWndFRT);

      sConds = GetTextLV(IDBRLV, i, 3);
      nFRF &= ~(FRF_MATCHCASE | FRF_WHOLEWORD | FRF_REGEXP | FRF_REGEXPNONEWLINEDOT | FRF_ESCAPESEQ);

      if (sConds.charAt(0) == "1")
        nFRF |= FRF_MATCHCASE;

      if (sConds.charAt(1) == "1")
        nFRF |= FRF_WHOLEWORD;

      if (sConds.charAt(2) == "1")
      {
        nFRF |= FRF_REGEXP;
        if (sConds.charAt(3) == "0")
          nFRF |= FRF_REGEXPNONEWLINEDOT;
      }
      else if (sConds.charAt(4) == "1")
        nFRF |= FRF_ESCAPESEQ;

      nChanges += AkelPad.TextReplace(0, GetTextLV(IDBRLV, i, 1), GetTextLV(IDBRLV, i, 2), nFRF, 1);
    }
  }

  if (! bNoMsg)
    AkelPad.MessageBox(hWndFRT, sTxtCountChanges + nChanges, sTxtBatchReplace, 0x40 /*MB_ICONINFORMATION*/);

  if (bCloseDlg)
  {
    PostMessage(hWndFRT, 16 /*WM_CLOSE*/, 0, 0);

    if (hDlg)
      PostMessage(hDlg, 16 /*WM_CLOSE*/, 0, 0);
  }
  else if (oSys.Call("User32::GetFocus") == aWnd[IDBRALLB].HWND)
    PostMessage(hWndFRT, 0x8001 /*WM_APP+1*/, 0, IDBRLV);
}

function FindAllMenu(hWnd, nID)
{
  var nFocusID = GetDlgCtrlID(oSys.Call("User32::GetFocus"));
  var hButton  = GetDlgItem(hDlg, nID);
  var hMenu    = oSys.Call("User32::CreatePopupMenu");
  var nX, nY;
  var nCmd;

  if (nID != nFocusID)
  {
    if ((nFocusID == IDCANCEL) || (nFocusID >= IDC_SEARCH_FIND_BUTTON) && (nFocusID <= IDC_SEARCH_ALL_BUTTON) || (nFocusID == IDMOREB) || (nFocusID >= IDCOUNTB) && (nFocusID <= IDFRTB))
      SendDlgItemMessage(hDlg, nFocusID, 244 /*BM_SETSTYLE*/, 0 /*BS_PUSHBUTTON*/, 1);

    SendDlgItemMessage(hDlg, nDefButID, 244 /*BM_SETSTYLE*/, 0 /*BS_PUSHBUTTON*/, 1);
    SendDlgItemMessage(hDlg, nID, 244 /*BM_SETSTYLE*/, 1 /*BS_DEFPUSHBUTTON*/, 1);
    oSys.Call("User32::SetFocus", hButton);
  }

  oSys.Call("User32::GetWindowRect", hButton, lpBuffer);
  nX = AkelPad.MemRead(_PtrAdd(lpBuffer,  8), DT_DWORD);
  nY = AkelPad.MemRead(_PtrAdd(lpBuffer, 12), DT_DWORD);

  oSys.Call("User32::AppendMenuW", hMenu, 0 /*MF_STRING*/, 1, sTxtShowInLog + " - " + sTxtOnlyMatched);
  oSys.Call("User32::AppendMenuW", hMenu, 0 /*MF_STRING*/, 2, sTxtShowInLog + " - " + sTxtEntireLines);
  oSys.Call("User32::AppendMenuW", hMenu, 0 /*MF_STRING*/, 3, sTxtCopyToCB);

  if (AkelPad.IsMDI())
    oSys.Call("User32::AppendMenuW", hMenu, 0 /*MF_STRING*/, 4, sTxtOpenInTab);

  oSys.Call("User32::AppendMenuW", hMenu, 0x0800 /*MF_SEPARATOR*/, 0);
  oSys.Call("User32::AppendMenuW", hMenu, 0 /*MF_STRING*/, 5, sTxtBookmarkLines);
  oSys.Call("User32::AppendMenuW", hMenu, 0 /*MF_STRING*/, 6, sTxtUnmarkLines);


  nCmd = oSys.Call("User32::TrackPopupMenu", hMenu, 0x188 /*TPM_NONOTIFY|TPM_RETURNCMD|TPM_RIGHTALIGN*/, nX, nY, 0, hWnd, 0);

  oSys.Call("User32::DestroyMenu", hMenu);

  if (nCmd)
    FindAll(hButton, nID, nCmd);
}

function HeaderLVMenu(hWnd, nX, nY)
{
  var MF_STRING    = 0x0000;
  var MF_GRAYED    = 0x0001;
  var MF_CHECKED   = 0x0008;
  var MF_SEPARATOR = 0x0800;
  var nID;
  var aCol;
  var hMenu;
  var nCmd;
  var nCount;
  var sName;
  var aField;
  var i;

  if (nX < 0)
  {
    //LVN_COLUMNCLICK
    oSys.Call("User32::GetCursorPos", lpBuffer);
    nX = AkelPad.MemRead(_PtrAdd(lpBuffer, 0), DT_DWORD);
    nY = AkelPad.MemRead(_PtrAdd(lpBuffer, 4), DT_DWORD);
  }
  else
  {
    //WM_CONTEXTMENU
    oSys.Call("User32::GetWindowRect", SendMessage(hWnd, 4127 /*LVM_GETHEADER*/, 0, 0), lpBuffer);
    if ((nX < AkelPad.MemRead(_PtrAdd(lpBuffer, 0), DT_DWORD)) || (nX > AkelPad.MemRead(_PtrAdd(lpBuffer, 8), DT_DWORD)) || (nY < AkelPad.MemRead(_PtrAdd(lpBuffer, 4), DT_DWORD)) || (nY > AkelPad.MemRead(_PtrAdd(lpBuffer, 12), DT_DWORD)))
      return;
  }

  oSys.Call("User32::SetFocus", hWnd);

  nID  = GetDlgCtrlID(hWnd);
  aCol = (nID == IDFRTLV) ? aFRTCol : aBRCol;
  GetColumnsWidthLV(nID);

  hMenu = oSys.Call("User32::CreatePopupMenu");
  oSys.Call("User32::AppendMenuW", hMenu, aCol[0][0] ? MF_CHECKED|MF_GRAYED : MF_STRING, 1, sTxtTemplateName);
  oSys.Call("User32::AppendMenuW", hMenu, aCol[1][0] ? MF_CHECKED : MF_STRING, 2, sTxtWhatFind);
  oSys.Call("User32::AppendMenuW", hMenu, aCol[2][0] ? MF_CHECKED : MF_STRING, 3, sTxtReplaceWith);
  oSys.Call("User32::AppendMenuW", hMenu, aCol[3][0] ? MF_CHECKED : MF_STRING, 4, sTxtConditions);
  oSys.Call("User32::AppendMenuW", hMenu, MF_SEPARATOR, 0);
  oSys.Call("User32::AppendMenuW", hMenu, (aCol[0][0] && aCol[1][0] && aCol[2][0] && aCol[3][0]) ? MF_GRAYED : MF_STRING, 5, sTxtAllColumns);
  oSys.Call("User32::AppendMenuW", hMenu, ((! aCol[0][0]) || aCol[1][0] || aCol[2][0] || aCol[3][0]) ? MF_STRING : MF_GRAYED, 6, sTxtNameOnly);

  if (nID == IDFRTLV)
  {
    oSys.Call("User32::AppendMenuW", hMenu, MF_SEPARATOR, 0);
    oSys.Call("User32::AppendMenuW", hMenu, bFRTSort ? MF_CHECKED : MF_STRING, 7, sTxtSortByName);
  }

  nCmd = oSys.Call("User32::TrackPopupMenu", hMenu, 0x180 /*TPM_NONOTIFY|TPM_RETURNCMD*/, nX, nY, 0, hWnd, 0);

  oSys.Call("User32::DestroyMenu", hMenu);

  if ((nCmd >= 1) && (nCmd <= 6))
  {
    if (nCmd == 5)
    {
      for (i = 0; i < aCol.length; ++i)
        aCol[i][0] = 1;
    }
    else if (nCmd == 6)
    {
      aCol[0][0] = 1;
      for (i = 1; i < aCol.length; ++i)
        aCol[i][0] = 0;
    }
    else
      aCol[nCmd - 1][0] = aCol[nCmd - 1][0] ? 0 : 1;

    SetColumnsWidthLV(nID);
  }
  else if (nCmd == 7)
  {
    bFRTSort = ! bFRTSort;
    SetSortFRTLV();

    if (bFRTSort && (nCount = GetItemCountLV(IDFRTLV)))
    {
      sName  = GetTextLV(IDFRTLV, GetCurSelLV(IDFRTLV), 0);
      aField = [];

      for (i = 0; i < nCount; ++i)
        aField[i] = [GetTextLV(IDFRTLV, i, 0), GetTextLV(IDFRTLV, i, 1), GetTextLV(IDFRTLV, i, 2), GetTextLV(IDFRTLV, i, 3)];

      SendMessage(aWnd[IDFRTLV].HWND, 4105 /*LVM_DELETEALLITEMS*/, 0, 0);

      for (i = 0; i < nCount; ++i)
        InsertItemLV(IDFRTLV, aField[i], 0);

      SetCurSelLV(IDFRTLV, FindItemLV(IDFRTLV, sName, -1));
    }

    EnableButtonsFRT();
  }
}

function TabMenu()
{
  var MF_STRING          = 0x0000;
  var MF_CHECKED         = 0x0008;
  var MF_USECHECKBITMAPS = 0x0200;
  var MF_SEPARATOR       = 0x0800;
  var hMenu = oSys.Call("User32::CreatePopupMenu");
  var nX, nY, nX1, nX2;
  var nCmd;
  var i;

  oSys.Call("User32::SetFocus", aWnd[IDBRLV].HWND);
  oSys.Call("User32::GetCursorPos", lpBuffer);
  nX = AkelPad.MemRead(_PtrAdd(lpBuffer, 0), DT_DWORD);
  nY = AkelPad.MemRead(_PtrAdd(lpBuffer, 4), DT_DWORD);

  for (i = 0; i < aBR.length; ++i)
  {
    SendMessage(aWnd[IDBRTC].HWND, 4874 /*TCM_GETITEMRECT*/, i, lpBuffer);
    oSys.Call("User32::ClientToScreen", aWnd[IDBRTC].HWND, lpBuffer);
    oSys.Call("User32::ClientToScreen", aWnd[IDBRTC].HWND, _PtrAdd(lpBuffer, 8));
    nX1 = AkelPad.MemRead(_PtrAdd(lpBuffer, 0), DT_DWORD);
    nX2 = AkelPad.MemRead(_PtrAdd(lpBuffer, 8), DT_DWORD);

    if ((nX >= nX1) && (nX < nX2))
    {
      SendMessage(aWnd[IDBRTC].HWND, 4912 /*TCM_SETCURFOCUS*/, i, 0);
      break;
    }
  }

  for (i = 0; i < aBR.length; ++i)
    oSys.Call("User32::AppendMenuW", hMenu, (nBR == i) ? MF_USECHECKBITMAPS | MF_CHECKED : MF_STRING, i + 1, (i + 1) + " - " + (aBRName[i] ? aBRName[i] : sTxtBatchNumber + (i + 1)));

  oSys.Call("User32::AppendMenuW", hMenu, MF_SEPARATOR, 0, 0);
  oSys.Call("User32::AppendMenuW", hMenu, MF_STRING, aBR.length + 1, sTxtRename + "\tF2");

  nCmd = oSys.Call("User32::TrackPopupMenu", hMenu, 0x180 /*TPM_NONOTIFY|TPM_RETURNCMD*/, nX, nY, 0, aWnd[IDBRTC].HWND, 0);

  oSys.Call("User32::DestroyMenu", hMenu);

  if (nCmd > 0)
  {
    if (--nCmd < aBR.length)
      SendMessage(aWnd[IDBRTC].HWND, 4912 /*TCM_SETCURFOCUS*/, nCmd, 0);
    else
      RenameBR();
  }
}

function EditMenu(hWnd, nX, nY)
{
  var MF_STRING    = 0x0000;
  var MF_GRAYED    = 0x0001;
  var MF_CHECKED   = 0x0008;
  var MF_SEPARATOR = 0x0800;
  var hMenu    = oSys.Call("User32::CreatePopupMenu");
  var nCmd;

  oSys.Call("User32::SetFocus", hWnd);
  nFRTSel = GetCurSelLV(IDFRTLV);

  if (nX == 0xFFFF) //menu from keyboard
  {
    oSys.Call("User32::GetCaretPos", lpBuffer);
    oSys.Call("User32::ClientToScreen", hWnd, lpBuffer);
    nX = AkelPad.MemRead(_PtrAdd(lpBuffer, 0), DT_DWORD);
    nY = AkelPad.MemRead(_PtrAdd(lpBuffer, 4), DT_DWORD) + SendMessage(hWnd, 3188 /*AEM_GETCHARSIZE*/, 0 /*AECS_HEIGHT*/, 0);
  }

  oSys.Call("User32::AppendMenuW", hMenu, SendMessage(hWnd,  198 /*EM_CANUNDO*/, 0, 0) ? MF_STRING : MF_GRAYED, 1, sMnuUndo + "\tCtrl+Z");
  oSys.Call("User32::AppendMenuW", hMenu, SendMessage(hWnd, 1109 /*EM_CANREDO*/, 0, 0) ? MF_STRING : MF_GRAYED, 2, sMnuRedo + "\tCtrl+Shift+Z");
  oSys.Call("User32::AppendMenuW", hMenu, MF_SEPARATOR, 0, 0);
  oSys.Call("User32::AppendMenuW", hMenu, SendMessage(hWnd, 3125 /*AEM_GETSEL*/, 0, 0)  ? MF_STRING : MF_GRAYED, 3, sMnuCut + "\tCtrl+X");
  oSys.Call("User32::AppendMenuW", hMenu, SendMessage(hWnd, 3125 /*AEM_GETSEL*/, 0, 0)  ? MF_STRING : MF_GRAYED, 4, sMnuCopy + "\tCtrl+C");
  oSys.Call("User32::AppendMenuW", hMenu, SendMessage(hWnd, 1074 /*EM_CANPASTE*/, 0, 0) ? MF_STRING : MF_GRAYED, 5, sMnuPaste + "\tCtrl+V");
  oSys.Call("User32::AppendMenuW", hMenu, SendMessage(hWnd, 3125 /*AEM_GETSEL*/, 0, 0)  ? MF_STRING : MF_GRAYED, 6, sMnuDelete + "\tDel");
  oSys.Call("User32::AppendMenuW", hMenu, MF_SEPARATOR, 0, 0);
  oSys.Call("User32::AppendMenuW", hMenu, oSys.Call("User32::GetWindowTextLengthW", hWnd) ? MF_STRING : MF_GRAYED, 7, sMnuSelectAll + "\tCtrl+A");
  oSys.Call("User32::AppendMenuW", hMenu, MF_SEPARATOR, 0, 0);
  oSys.Call("User32::AppendMenuW", hMenu, bAEFont ? MF_CHECKED : MF_STRING, 8, sMnuAPFont + "\tCtrl+F");
  oSys.Call("User32::AppendMenuW", hMenu, MF_SEPARATOR, 0, 0);
  oSys.Call("User32::AppendMenuW", hMenu, (nFRTSel < GetItemCountLV(IDFRTLV) - 1) ? MF_STRING : MF_GRAYED,  9, sMnuNextTempl + "\tF3");
  oSys.Call("User32::AppendMenuW", hMenu, (nFRTSel > 0)                           ? MF_STRING : MF_GRAYED, 10, sMnuPrevTempl + "\tShift+F3");

  nCmd = oSys.Call("User32::TrackPopupMenu", hMenu, 0x180 /*TPM_NONOTIFY|TPM_RETURNCMD*/, nX, nY, 0, hWnd, 0);

  oSys.Call("User32::DestroyMenu", hMenu);

  if (nCmd == 1)
    SendMessage(hWnd, 199 /*EM_UNDO*/, 0, 0);
  else if (nCmd == 2)
    SendMessage(hWnd, 1108 /*EM_REDO*/, 0, 0);
  else if (nCmd == 3)
    SendMessage(hWnd, 768 /*WM_CUT*/, 0, 0);
  else if (nCmd == 4)
    SendMessage(hWnd, 769 /*WM_COPY*/, 0, 0);
  else if (nCmd == 5)
    SendMessage(hWnd, 770 /*WM_PASTE*/, 0, 0);
  else if (nCmd == 6)
    SendMessage(hWnd, 771 /*WM_CLEAR*/, 0, 0);
  else if (nCmd == 7)
    SendMessage(hWnd, 177 /*EM_SETSEL*/, 0, -1);
  else if (nCmd == 8)
  {
    bAEFont = ! bAEFont;
    SetEditFontFRT();
  }
  else if (nCmd == 9)
    SetCurSelLV(IDFRTLV, nFRTSel + 1);
  else if (nCmd == 10)
    SetCurSelLV(IDFRTLV, nFRTSel - 1);
}

function HelpMenu(hWnd, nID, bRegExp)
{
  var sHelpFile = GetAkelHelpFile();
  var hMenu     = oSys.Call("User32::CreatePopupMenu");
  var nString   = 0x0000; //MF_STRING
  var nGrayed   = 0x0001; //MF_GRAYED
  var nBreak    = 0x0060; //MF_MENUBREAK|MF_MENUBARBREAK
  var nSepar    = 0x0800; //MF_SEPARATOR
  var hFromPos;
  var hEdit;
  var aMenu;
  var nX;
  var nY;
  var nCmd;
  var i;

  if (nID == IDHELP1L)
  {
    if (hWnd)
    {
      hFromPos = GetDlgItem(hDlg, IDC_SEARCH_FIND);
      hEdit    = hWhatE;
    }
    else
    {
      hFromPos = aWnd[IDWHATE].HWND;
      hEdit    = aWnd[IDWHATE].HWND;
    }

    if (bRegExp)
      aMenu = [
        [nString, ".",         sHlpAnyChar],
        [nString, "\\(",       sHlpSpecChars],
        [nString, "\\f",       sHlpFF + " \\x0C"],
        [nString, "\\n",       sHlpAnyNL],
        [nString, "\\r",       sHlpAnyNL],
        [nString, "\\t",       sHlpTab + " \\x09"],
        [nString, "\\v",       sHlpVTab + " \\x0B"],
        [nString, "\\d",       sHlpDigit + " [0-9]"],
        [nString, "\\D",       sHlpNonDigit + " [^0-9]"],
        [nString, "\\s",       sHlpWhiteSp + " [ \\f\\n\\t\\v]"],
        [nString, "\\S",       sHlpNonWhiteSp],
        [nString, "\\w",       sHlpWordChar],
        [nString, "\\W",       sHlpNonWordChar],
        [nString, "\\x{F}",    sHlpCharHex],
        [nString, "\\xFF",     sHlpCharHex2],
        [nString, "\\uFFFF",   sHlpCharHex4],
        [nSepar],
        [nString, "ab|xy",     sHlpAlternative],
        [nString, "[abc]",     sHlpCharSet],
        [nString, "[^abc]",    sHlpNegCharSet],
        [nString, "[a-z]",     sHlpRange],
        [nString, "[^a-z]",    sHlpNegRange],
        [nSepar],
        [nString, "^",         sHlpBeginLine],
        [nString, "$",         sHlpEndLine],
        [nString, "\\A",       sHlpBeginText],
        [nString, "\\Z",       sHlpEndText],
        [nString, "\\a",       sHlpBeginRange],
        [nString, "\\z",       sHlpEndRange],
        [nString, "\\b",       sHlpWordBoun],
        [nString, "\\B",       sHlpNonWordBoun],
        [nString, "\\K",       sHlpExcludePrev],
  
        [nBreak,  "?",         sHlpZeroOrOne],
        [nString, "*",         sHlpZeroOrMore],
        [nString, "+",         sHlpOneOrMore],
        [nString, "{3}",       sHlpExactly],
        [nString, "{3,}",      sHlpAtLeast],
        [nString, "{3,7}",     sHlpFromTo],
        [nGrayed, "\xA0",      sHlpGreedy],
        [nString, "?",         sHlpLazy],
        [nString, "+",         sHlpPossesive],
        [nSepar],
        [nString, "(ab)",      sHlpCapture1],
        [nString, "(?^ab)",    sHlpCapture2],
        [nString, "(?:ab)",    sHlpNotCapture],
        [nString, "(?>bc|b)",  sHlpAtomicGrouping],
        [nString, "(?<=ab)",   sHlpPreceded],
        [nString, "(?<!ab)",   sHlpNotPreceded],
        [nString, "(?=ab)",    sHlpFollowed],
        [nString, "(?!ab)",    sHlpNotFollowed],
        [nString, "(?(1)x|y)", sHlpCondition],
        [nString, "\\9",       sHlpBackrefer9],
        [nString, "\\99",      sHlpBackrefer99],
        [nSepar],
        [nString, "(?i)",      sHlpIgnoreCase],
        [nString, "(?m)",      sHlpMultiline],
        [nString, "(?s)",      sHlpDotDefault],
        [nString, "(?U)",      sHlpInvertGreed],
        [nString, "(?-i)",     sHlpMatchCase],
        [nString, "(?-m)",     sHlpMultilineOff],
        [nString, "(?-s)",     sHlpDotDefaultOff],
        [nString, "(?-U)",     sHlpInvertGreedOff]];
  }
  else
  {
    if (hWnd)
    {
      hFromPos = GetDlgItem(hDlg, IDC_SEARCH_REPLACE);
      hEdit    = hWithE;
    }
    else
    {
      hFromPos = aWnd[IDWITHE].HWND;
      hEdit    = aWnd[IDWITHE].HWND;
    }

    if (bRegExp)
      aMenu = [
        [nString, "\\\\",    sHlpBackslash],
        [nString, "\\f",     sHlpFF + " \\x0C"],
        [nString, "\\n",     sHlpNL],
        [nString, "\\r",     sHlpNL],
        [nString, "\\t",     sHlpTab + " \\x09"],
        [nString, "\\v",     sHlpVTab + " \\x0B"],
        [nString, "\\x{F}",  sHlpCharHex],
        [nString, "\\xFF",   sHlpCharHex2],
        [nString, "\\uFFFF", sHlpCharHex4],
        [nSepar],
        [nString, "\\0",     sHlpEntireStr],
        [nString, "\\9",     sHlpSubmatch9],
        [nString, "\\99",    sHlpSubmatch99]];
  }

  if (bRegExp)
  {
    if (sHelpFile)
    {
      aMenu.push([nSepar]);
      aMenu.push([nString, "\xA0", sHelpFile]);
    }
  }
  else
    aMenu = [
      [nString, "\\\\",     sHlpBackslash],
      [nString, "\\0",      sHlpNull],
      [nString, "\\n",      sHlpNL],
      [nString, "\\t",      sHlpTab],
      [nString, "\\[FFFF]", sHlpCharHex4]];

  oSys.Call("User32::GetWindowRect", hFromPos, lpBuffer);
  nX = AkelPad.MemRead(_PtrAdd(lpBuffer,  0), DT_DWORD);
  nY = AkelPad.MemRead(_PtrAdd(lpBuffer, 12), DT_DWORD);

  if (hWnd)
    oSys.Call("User32::SetFocus", GetDlgItem(hDlg, nID));
  else
  {
    hWnd = hWndFRT;
    oSys.Call("User32::SetFocus", hEdit);
  }

  for (i = 0; i < aMenu.length; ++i)
    oSys.Call("User32::AppendMenuW", hMenu, aMenu[i][0], i + 1, aMenu[i][1] + "\t" + aMenu[i][2]);

  nCmd = oSys.Call("User32::TrackPopupMenu", hMenu, 0x0180 /*TPM_RETURNCMD|TPM_NONOTIFY*/, nX, nY, 0, hWnd, 0);

  oSys.Call("User32::DestroyMenu", hMenu);
  oSys.Call("User32::SetFocus", hEdit);

  if (nCmd--)
  {
    if (aMenu[nCmd][1] != "\xA0")
      SendMessage(hEdit, 194 /*EM_REPLACESEL*/, 1, aMenu[nCmd][1]);
    else if (aMenu[nCmd][2] == sHelpFile)
      AkelHelp(sHelpFile);
  }
}

function SaveFRT()
{
  var nItems = GetItemCountLV(IDFRTLV);
  var sText  = "";
  var i;

  for (i = 0; i < nItems; ++i)
    sText += GetTextLV(IDFRTLV, i, 0) + "\t" + GetTextLV(IDFRTLV, i, 1) + "\t" + GetTextLV(IDFRTLV, i, 2) + "\t" + GetTextLV(IDFRTLV, i, 3) + "\r\n";

  AkelPad.WriteFile(WScript.ScriptFullName.replace(/\.js$/i, "_templates.tsv"), sText, sText.length, 1200 /*UTF-16LE*/, true);

  oSys.Call("User32::GetWindowRect", hWndFRT, lpBuffer);

  if (hDlg)
  {
    oSys.Call("User32::GetWindowRect", GetDlgItem(hDlg, IDC_SEARCH_MATCHCASE), _PtrAdd(lpBuffer, 16));
    nFRTX = AkelPad.MemRead(_PtrAdd(lpBuffer,  0), DT_DWORD) - AkelPad.MemRead(_PtrAdd(lpBuffer, 16), DT_DWORD);
    nFRTY = AkelPad.MemRead(_PtrAdd(lpBuffer,  4), DT_DWORD) - AkelPad.MemRead(_PtrAdd(lpBuffer, 20), DT_DWORD);
  }
  else
  {
    nBRX = AkelPad.MemRead(_PtrAdd(lpBuffer,  0), DT_DWORD);
    nBRY = AkelPad.MemRead(_PtrAdd(lpBuffer,  4), DT_DWORD);
  }

  nFRTW   = AkelPad.MemRead(_PtrAdd(lpBuffer,  8), DT_DWORD) - AkelPad.MemRead(_PtrAdd(lpBuffer,  0), DT_DWORD);
  nFRTH   = AkelPad.MemRead(_PtrAdd(lpBuffer, 12), DT_DWORD) - AkelPad.MemRead(_PtrAdd(lpBuffer,  4), DT_DWORD);
  nFRTSel = GetCurSelLV(IDFRTLV);

  GetColumnsWidthLV(IDFRTLV);
  GetColumnsWidthLV(IDBRLV);
}

function CheckRegExp(sPat)
{
  //based on Instructor's code CheckPat.js: http://akelpad.sourceforge.net/forum/viewtopic.php?p=25621#p25621
  var lpPat     = AkelPad.MemAlloc((sPat.length + 1) * 2 /*sizeof(wchar_t)*/);
  var lpPatExec = AkelPad.MemAlloc(_X64? 216 : 108 /*sizeof(PATEXEC)*/);
  var lpStr     = AkelPad.MemAlloc(2 /*sizeof(wchar_t)*/);
  var nErrOffset;

  AkelPad.MemCopy(lpPat, sPat, DT_UNICODE);
  AkelPad.MemCopy(_PtrAdd(lpPatExec, _X64 ?  24 : 12) /*PATEXEC.wpText*/,      lpStr, DT_QWORD);
  AkelPad.MemCopy(_PtrAdd(lpPatExec, _X64 ?  32 : 16) /*PATEXEC.wpMaxText*/,   lpStr, DT_QWORD);
  AkelPad.MemCopy(_PtrAdd(lpPatExec, _X64 ?  40 : 20) /*PATEXEC.wpRange*/,     lpStr, DT_QWORD);
  AkelPad.MemCopy(_PtrAdd(lpPatExec, _X64 ?  48 : 24) /*PATEXEC.wwpMaxRange*/, lpStr, DT_QWORD);
  AkelPad.MemCopy(_PtrAdd(lpPatExec, _X64 ? 112 : 56) /*PATEXEC.wpPat*/,       lpPat, DT_QWORD);
  AkelPad.MemCopy(_PtrAdd(lpPatExec, _X64 ? 120 : 60) /*PATEXEC.wpMaxPat*/,    _PtrAdd(lpPat, sPat.length * 2 /*sizeof(wchar_t)*/), DT_QWORD);
  AkelPad.MemCopy(_PtrAdd(lpPatExec, _X64 ? 128 : 64) /*PATEXEC.wpStr*/,       lpStr, DT_QWORD);
  AkelPad.MemCopy(_PtrAdd(lpPatExec, _X64 ? 136 : 68) /*PATEXEC.wpMaxStr*/,    lpStr, DT_QWORD);

  SendMessage(hMainWnd, 1415 /*AKD_PATEXEC*/, 0, lpPatExec);
  nErrOffset = AkelPad.MemRead(_PtrAdd(lpPatExec, _X64 ? 192 : 96) /*PATEXEC.nErrorOffset*/, DT_QWORD);

  AkelPad.MemFree(lpPat);
  AkelPad.MemFree(lpPatExec);
  AkelPad.MemFree(lpStr);

  return nErrOffset;
}

function CheckEscSeq(sPat)
{
  var nErrOffset = 0;
  var i, n;

  for (i = 0; i < sPat.length; ++i)
  {
    if (sPat.charAt(i) == "\\")
    {
      if (sPat.charAt(++i) == "[")
      {
        while (sPat.charAt(++i) == " ");

        for (n = 0; n < 4; (++n < 4) && ++i)
        {
          if (! ((sPat.charCodeAt(i) >= 48) && (sPat.charCodeAt(i) <= 57) || (sPat.charCodeAt(i) >= 65) && (sPat.charCodeAt(i) <= 70) || (sPat.charCodeAt(i) >= 97) && (sPat.charCodeAt(i) <= 102)))
          {
            nErrOffset = i + 1;
            break;
          }
        }

        if (nErrOffset)
          break;

        while (sPat.charAt(++i) == " ");

        if (sPat.charAt(i) != "]")
        {
          nErrOffset = i + 1;
          break;
        }
      }
      else if ((sPat.charAt(i) != "\\") && (sPat.charAt(i) != "0") && (sPat.charAt(i) != "n") && (sPat.charAt(i) != "t"))
      {
        nErrOffset = i + 1;
        break;
      }
    }
  }

  return nErrOffset;
}

function EscSeqToRegExp(sText)
{
  return sText.replace(/\\([^\[])|\\\[(\d{4})\]|([\/.^$+*?|()\[\]{}])/g,
    function(sArg0, sArg1, sArg2, sArg3)
    {
      if (sArg3)
        return "\\" + sArg3;
      else if (sArg2)
        return "\\u" + sArg2;
      else if (sArg1 == "0")
        return "\\x00";
      else
        return "\\" + sArg1;
    });
}

function ReadIni()
{
  var sLangTxt = AkelPad.ReadFile(WScript.ScriptFullName.replace(/\.js$/i, "_" + AkelPad.GetLangId() + ".lng"), 0x1D /*OD_ADT_BINARY_ERROR|OD_ADT_DETECT_CODEPAGE|OD_ADT_DETECT_BOM|OD_ADT_NOMESSAGES*/);
  var i, n;

  if (sLangTxt)
  {
    try
    {
      eval(sLangTxt);
    }
    catch (oError)
    {
      sLangTxt = "";
    }
  }

  if (! sLangTxt)
  {
    sTxtMore          = '&More';
    sTxtCount         = 'C&ount';
    sTxtFindAll       = 'Find al&l';
    sTxtShowInLog     = 'Show in Log panel';
    sTxtOnlyMatched   = 'only matched';
    sTxtEntireLines   = 'entire lines';
    sTxtCopyToCB      = 'Copy to clipboard';
    sTxtOpenInTab     = "Open in new tab";
    sTxtBookmarkLines = 'Bookmark lines';
    sTxtUnmarkLines   = 'Unmark lines';
    sTxtTemplates     = 'Templates';
    sTxtBatches       = 'Batches';
    sTxtTransparentNA = 'Transparency - only when inactive';
    sTxtWait          = 'Wait...';
    sTxtStop          = 'Stop';
    sTxtNoName        = 'no name';
    sTxtTotalFound    = 'Total found: ';
    sTxtReplAllCD     = '"Replace all" closes dialo&g';
    sTxtReplAllWM     = '"Replace all" withou&t message';
    sTxtCheckInSel    = 'Check "in selection" if selection &not empty';
    sTxtCycleSearch   = 'C&ycle search';
    sTxtPrompt        = '&Prompt';
    sTxtWhatFind      = 'What find';
    sTxtReplaceWith   = 'Replace with';
    sTxtMatchCase     = 'Match &case';
    sTxtWholeWord     = '&Whole word';
    sTxtRegExp        = 'Regular e&xpressions';
    sTxtDotMatchesNL  = '&. matches \\n';
    sTxtEscSeq        = '&Esc sequences';
    sTxtDirection     = 'Direction';
    sTxtDirDown       = '&Down';
    sTxtDirUp         = '&Up';
    sTxtDirBeginning  = '&Beginning';
    sTxtDirInSel      = '&In selection';
    sTxtDirAllFiles   = 'All file&s';
    sTxtNew           = 'New';
    sTxtAdd           = 'Add';
    sTxtRename        = 'Rename';
    sTxtMoveUp        = 'Move up';
    sTxtMoveDown      = 'Move down';
    sTxtRemove        = 'Remove';
    sTxtCheckExpr     = 'Check expression';
    sTxtAddToBatch    = 'Add to batch';
    sTxtOK            = 'OK';
    sTxtClose         = 'Close';
    sTxtBatchReplace  = 'Batch replace';
    sTxtBatchReplAll  = 'Batch replace &all';
    sTxtEnableAll     = 'Enable&/disable all';
    sTxtClosesDialog  = 'Closes dialo&g';
    sTxtWithoutMsg    = 'Withou&t message';
    sTxtTemplateName  = 'Template name';
    sTxtConditions    = 'Conditions';
    sTxtAllColumns    = 'All columns';
    sTxtNameOnly      = 'Name only';
    sTxtSortByName    = 'Sort by name';
    sTxtNameInvalid   = 'Invalid name.';
    sTxtNameExists    = 'This name already exists.';
    sTxtWantRemove    = 'Do you want to remove this template?';
    sTxtBatchNumber   = 'Batch #';
    sTxtWantBatchRepl = 'Do you want to batch replace all?';
    sTxtNoFindText    = 'No text in field "What find".';
    sTxtExprOK        = 'Expression is OK.';
    sTxtExprError     = 'Error in expression';
    sTxtCountChanges  = 'Count of changes: ';
    //context menu edit
    sMnuUndo      = '&Undo';
    sMnuRedo      = '&Redo';
    sMnuCut       = 'C&ut';
    sMnuCopy      = '&Copy';
    sMnuPaste     = '&Paste';
    sMnuDelete    = '&Delete';
    sMnuSelectAll = 'Select &all';
    sMnuAPFont    = 'AkelPad font';
    sMnuNextTempl = 'Next template';
    sMnuPrevTempl = 'Previous template';
    //RegExp help
    sHlpAnyChar        = 'any character (dot)';
    sHlpSpecChars      = '()[]{}^$.?+*|\\ special chars';
    sHlpBackslash      = 'backslash';
    sHlpNull           = 'null character';
    sHlpFF             = 'form feed';
    sHlpNL             = 'new line';
    sHlpAnyNL          = 'any new line';
    sHlpTab            = 'tab';
    sHlpVTab           = 'vertical tab';
    sHlpDigit          = 'digit';
    sHlpNonDigit       = 'non-digit';
    sHlpWhiteSp        = 'whitespace';
    sHlpNonWhiteSp     = 'non-whitespace';
    sHlpWordChar       = 'word character (non-delimiter)';
    sHlpNonWordChar    = 'non-word character (delimiter)';
    sHlpCharHex        = 'char - hex code, range 0-10FFFF';
    sHlpCharHex2       = 'char - 2-digit hex code';
    sHlpCharHex4       = 'char - 4-digit hex code';
    sHlpAlternative    = 'alternative ab or xy';
    sHlpCharSet        = 'character set, any specified';
    sHlpNegCharSet     = 'negative character set';
    sHlpRange          = 'range of chars from a to z';
    sHlpNegRange       = 'negative range of chars';
    sHlpBeginLine      = 'beginning of line';
    sHlpEndLine        = 'end of line';
    sHlpBeginText      = 'beginning of text';
    sHlpEndText        = 'end of text';
    sHlpBeginRange     = 'beginning of search range';
    sHlpEndRange       = 'end of search range';
    sHlpWordBoun       = 'word boundary';
    sHlpNonWordBoun    = 'non-word boundary';
    sHlpExcludePrev    = 'excludes previous chars from result';
    sHlpZeroOrOne      = 'zero or one time';
    sHlpZeroOrMore     = 'zero or more times';
    sHlpOneOrMore      = 'one or more times';
    sHlpExactly        = 'exactly 3 times';
    sHlpAtLeast        = 'at least 3 times';
    sHlpFromTo         = 'from 3 to 7 times';
    sHlpEntireStr      = 'entire string matched';
    sHlpSubmatch9      = '9th captured submatch, range 1-9';
    sHlpSubmatch99     = '99th captured submatch, range 01-99';
    sHlpGreedy         = '- above quantifiers are greedy';
    sHlpLazy           = 'add at end for lazy quantifier';
    sHlpPossesive      = 'add at end for possesive quantifier';
    sHlpCapture1       = 'matches ab, captures';
    sHlpCapture2       = 'matches negative ab, captures';
    sHlpNotCapture     = 'matches ab, not captures';
    sHlpAtomicGrouping = 'atomic grouping, not captures';
    sHlpPreceded       = 'preceded by ab';
    sHlpNotPreceded    = 'not preceded by ab';
    sHlpFollowed       = 'followed by ab';
    sHlpNotFollowed    = 'not followed by ab';
    sHlpCondition      = 'if (1) then x, else y';
    sHlpBackrefer9     = 'backreference, range 1-9';
    sHlpBackrefer99    = 'backreference, range 01-99';
    sHlpIgnoreCase     = 'case insensitive';
    sHlpMultiline      = 'multiline search (default)';
    sHlpDotDefault     = 'dot matches any char (default)';
    sHlpInvertGreed    = 'invert greediness';
    sHlpMatchCase      = 'match case';
    sHlpMultilineOff   = 'turn off multiline search';
    sHlpDotDefaultOff  = 'dot matches any char, except \\n';
    sHlpInvertGreedOff = 'turn off greediness inversion';
  }

  try
  {
    eval(ReadIni.Text = AkelPad.ReadFile(WScript.ScriptFullName.replace(/\.js$/i, ".ini"), 0x1D /*OD_ADT_BINARY_ERROR|OD_ADT_DETECT_CODEPAGE|OD_ADT_DETECT_BOM|OD_ADT_NOMESSAGES*/));
  }
  catch (oError)
  {}

  if (nOpacity > 255) nOpacity = 255;
  else if (nOpacity < 15) nOpacity = 15;

  nFRTW = Math.max(Scale.X(nFRTW), nFRTMinW);
  nFRTH = Math.max(Scale.Y(nFRTH), nFRTMinH);

  if (! aBR)
  {
    nBR = 0;
    aBR = [[], [], [], [], [], [], [], [], []];
  }

  if (! aBRCB)
  {
    aBRCB = [[], [], [], [], [], [], [], [], []];
    for (i = 0; i < aBR.length; ++i)
    {
      for (n = 0; n < aBR[i].length; ++n)
        aBRCB[i][n] = 1;
    }
  }

  if ((nBR < 0) || (nBR >= aBR.length))
    nBR = 0;

  if (! aBRName)
    aBRName = ["", "", "", "", "", "", "", "", ""];

  if (! aFRTCol)
    aFRTCol = [[1, 120], [0, 90], [0, 90], [0, 65]];

  if (! aBRCol)
    aBRCol = [aFRTCol[0].slice(0), aFRTCol[1].slice(0), aFRTCol[2].slice(0), aFRTCol[3].slice(0)];

  for (i = 0; i < aFRTCol.length; ++i)
  {
    aFRTCol[i][1] = Scale.X(aFRTCol[i][1]);
    aBRCol[i][1]  = Scale.X(aBRCol[i][1]);
  }
}

function WriteIni()
{
  var i, n;

  var sText =
    'bGoToDlg='    + bGoToDlg + ';\r\n' +
    'bFastCount='  + bFastCount + ';\r\n' +
    'bTranspNA='   + bTranspNA + ';\r\n' +
    'nOpacity='    + nOpacity + ';\r\n' +
    'bMore='       + bMore + ';\r\n' +
    'nDlgX='       + nDlgX + ';\r\n' +
    'nDlgY='       + nDlgY + ';\r\n' +
    'nFRTX='       + nFRTX + ';\r\n' +
    'nFRTY='       + nFRTY + ';\r\n' +
    'nFRTW='       + Scale.UX(nFRTW) + ';\r\n' +
    'nFRTH='       + Scale.UY(nFRTH) + ';\r\n' +
    'nBRX='        + nBRX + ';\r\n' +
    'nBRY='        + nBRY + ';\r\n' +
    'bAEFont='     + bAEFont + ';\r\n' +
    'nFRTSel='     + nFRTSel + ';\r\n' +
    'bFRTSort='    + bFRTSort + ';\r\n' +
    'nBR='         + nBR + ';\r\naBR=[';

  for (i = 0; i < aBR.length; ++i)
  {
    sText += '[';

    for (n = 0; n < aBR[i].length; ++n)
      sText += '"' + aBR[i][n].replace(/[\\"]/g, '\\$&') + ((n == aBR[i].length - 1) ? '"' : '",');

    sText += ']' + ((i == aBR.length - 1) ? '' : ',');
  }
  sText += '];\r\naBRCB=[';

  for (i = 0; i < aBRCB.length; ++i)
  {
    sText += '[';

    for (n = 0; n < aBRCB[i].length; ++n)
      sText += aBRCB[i][n] + ((n == aBR[i].length - 1) ? '' : ',');

    sText += ']' + ((i == aBRCB.length - 1) ? '' : ',');
  }
  sText += '];\r\naBRName=[';

  for (i = 0; i < aBRName.length; ++i)
    sText += '"' + aBRName[i].replace(/[\\"]/g, '\\$&') + ((i == aBRName.length - 1) ? '"' : '",');

  sText += '];\r\naFRTCol=[';

  for (i = 0; i < aFRTCol.length; ++i)
    sText += '[' + aFRTCol[i][0] + ',' + Scale.UX(aFRTCol[i][1]) + ']' + ((i == aFRTCol.length - 1) ? '' : ',');

  sText += '];\r\naBRCol=[';

  for (i = 0; i < aBRCol.length; ++i)
    sText += '[' + aBRCol[i][0] + ',' + Scale.UX(aBRCol[i][1]) + ']' + ((i == aBRCol.length - 1) ? '' : ',');

  sText += '];\r\n';

  if (sText != ReadIni.Text) 
    AkelPad.WriteFile(WScript.ScriptFullName.replace(/\.js$/i, ".ini"), sText, sText.length, 1200 /*UTF-16LE*/, true);
}

Last edited by KDJ on Tue Nov 01, 2016 9:37 pm, edited 28 times in total.

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

Post by KDJ »

Interface language files for FindReplaceEx.js.

Code: Select all

/**************************************
FindReplaceEx.js - ver. 2018-11-06
Interface language
Language:      English (1033)
Translated by: KDJ
**************************************/
sTxtMore          = '&More';
sTxtCount         = 'C&ount';
sTxtFindAll       = 'Find al&l';
sTxtShowInLog     = 'Show in Log panel';
sTxtOnlyMatched   = 'only matched';
sTxtEntireLines   = 'entire lines';
sTxtCopyToCB      = 'Copy to clipboard';
sTxtOpenInTab     = 'Open in new tab';
sTxtBookmarkLines = 'Bookmark lines';
sTxtUnmarkLines   = 'Unmark lines';
sTxtTemplates     = 'Templates';
sTxtBatches       = 'Batches';
sTxtTransparentNA = 'Transparency - only when inactive';
sTxtWait          = 'Wait...';
sTxtStop          = 'Stop';
sTxtNoName        = 'no name';
sTxtTotalFound    = 'Total found: ';
sTxtReplAllCD     = '"Replace all" closes dialo&g';
sTxtReplAllWM     = '"Replace all" withou&t message';
sTxtCheckInSel    = 'Check "in selection" if selection &not empty';
sTxtCycleSearch   = 'C&ycle search';
sTxtPrompt        = '&Prompt';
sTxtWhatFind      = 'What find';
sTxtReplaceWith   = 'Replace with';
sTxtMatchCase     = 'Match &case';
sTxtWholeWord     = '&Whole word';
sTxtRegExp        = 'Regular e&xpressions';
sTxtDotMatchesNL  = '&. matches \\n';
sTxtEscSeq        = '&Esc sequences';
sTxtDirection     = 'Direction';
sTxtDirDown       = '&Down';
sTxtDirUp         = '&Up';
sTxtDirBeginning  = '&Beginning';
sTxtDirInSel      = '&In selection';
sTxtDirAllFiles   = 'All file&s';
sTxtNew           = 'New';
sTxtAdd           = 'Add';
sTxtRename        = 'Rename';
sTxtMoveUp        = 'Move up';
sTxtMoveDown      = 'Move down';
sTxtRemove        = 'Remove';
sTxtCheckExpr     = 'Check expression';
sTxtAddToBatch    = 'Add to batch';
sTxtOK            = 'OK';
sTxtClose         = 'Close';
sTxtBatchReplace  = 'Batch replace';
sTxtBatchReplAll  = 'Batch replace &all';
sTxtEnableAll     = 'Enable&/disable all';
sTxtClosesDialog  = 'Closes dialo&g';
sTxtWithoutMsg    = 'Withou&t message';
sTxtTemplateName  = 'Template name';
sTxtConditions    = 'Conditions';
sTxtAllColumns    = 'All columns';
sTxtNameOnly      = 'Name only';
sTxtSortByName    = 'Sort by name';
sTxtNameInvalid   = 'Invalid name.';
sTxtNameExists    = 'This name already exists.';
sTxtWantRemove    = 'Do you want to remove this template?';
sTxtBatchNumber   = 'Batch #';
sTxtWantBatchRepl = 'Do you want to batch replace all?';
sTxtNoFindText    = 'No text in field "What find".';
sTxtExprOK        = 'Expression is OK.';
sTxtExprError     = 'Error in expression';
sTxtCountChanges  = 'Count of changes: ';
//context menu edit
sMnuUndo      = '&Undo';
sMnuRedo      = '&Redo';
sMnuCut       = 'C&ut';
sMnuCopy      = '&Copy';
sMnuPaste     = '&Paste';
sMnuDelete    = '&Delete';
sMnuSelectAll = 'Select &all';
sMnuAPFont    = 'AkelPad font';
sMnuNextTempl = 'Next template';
sMnuPrevTempl = 'Previous template';
//RegExp help
sHlpAnyChar        = 'any character (dot)';
sHlpSpecChars      = '()[]{}^$.?+*|\\ special chars';
sHlpBackslash      = 'backslash';
sHlpNull           = 'null character';
sHlpFF             = 'form feed';
sHlpNL             = 'new line';
sHlpAnyNL          = 'any new line';
sHlpTab            = 'tab';
sHlpVTab           = 'vertical tab';
sHlpDigit          = 'digit';
sHlpNonDigit       = 'non-digit';
sHlpWhiteSp        = 'whitespace';
sHlpNonWhiteSp     = 'non-whitespace';
sHlpWordChar       = 'word character (non-delimiter)';
sHlpNonWordChar    = 'non-word character (delimiter)';
sHlpCharHex        = 'char - hex code, range 0-10FFFF';
sHlpCharHex2       = 'char - 2-digit hex code';
sHlpCharHex4       = 'char - 4-digit hex code';
sHlpAlternative    = 'alternative ab or xy';
sHlpCharSet        = 'character set, any specified';
sHlpNegCharSet     = 'negative character set';
sHlpRange          = 'range of chars from a to z';
sHlpNegRange       = 'negative range of chars';
sHlpBeginLine      = 'beginning of line';
sHlpEndLine        = 'end of line';
sHlpBeginText      = 'beginning of text';
sHlpEndText        = 'end of text';
sHlpBeginRange     = 'beginning of search range';
sHlpEndRange       = 'end of search range';
sHlpWordBoun       = 'word boundary';
sHlpNonWordBoun    = 'non-word boundary';
sHlpExcludePrev    = 'excludes previous chars from result';
sHlpZeroOrOne      = 'zero or one time';
sHlpZeroOrMore     = 'zero or more times';
sHlpOneOrMore      = 'one or more times';
sHlpExactly        = 'exactly 3 times';
sHlpAtLeast        = 'at least 3 times';
sHlpFromTo         = 'from 3 to 7 times';
sHlpEntireStr      = 'entire string matched';
sHlpSubmatch9      = '9th captured submatch, range 1-9';
sHlpSubmatch99     = '99th captured submatch, range 01-99';
sHlpGreedy         = '- above quantifiers are greedy';
sHlpLazy           = 'add at end for lazy quantifier';
sHlpPossesive      = 'add at end for possesive quantifier';
sHlpCapture1       = 'matches ab, captures';
sHlpCapture2       = 'matches negative ab, captures';
sHlpNotCapture     = 'matches ab, not captures';
sHlpAtomicGrouping = 'atomic grouping, not captures';
sHlpPreceded       = 'preceded by ab';
sHlpNotPreceded    = 'not preceded by ab';
sHlpFollowed       = 'followed by ab';
sHlpNotFollowed    = 'not followed by ab';
sHlpCondition      = 'if (1) then x, else y';
sHlpBackrefer9     = 'backreference, range 1-9';
sHlpBackrefer99    = 'backreference, range 01-99';
sHlpIgnoreCase     = 'case insensitive';
sHlpMultiline      = 'multiline search (default)';
sHlpDotDefault     = 'dot matches any char (default)';
sHlpInvertGreed    = 'invert greediness';
sHlpMatchCase      = 'match case';
sHlpMultilineOff   = 'turn off multiline search';
sHlpDotDefaultOff  = 'dot matches any char, except \\n';
sHlpInvertGreedOff = 'turn off greediness inversion';
- English template for translation

Code: Select all

/**************************************
FindReplaceEx.js - ver. 2018-11-06
Interface language
Language:      Polish (1045)
Translated by: KDJ
**************************************/
sTxtMore          = 'Wię&cej';
sTxtCount         = 'P&olicz';
sTxtFindAll       = 'Zna&jdź wszystkie';
sTxtShowInLog     = 'Pokaż w panelu Log';
sTxtOnlyMatched   = 'tylko dopasowane';
sTxtEntireLines   = 'całe wiersze';
sTxtCopyToCB      = 'Kopiuj do schowka';
sTxtOpenInTab     = 'Otwórz na nowej karcie';
sTxtBookmarkLines = 'Oznacz wiersze zakładkami';
sTxtUnmarkLines   = 'Usuń zakładki z wierszy';
sTxtTemplates     = 'Szablony';
sTxtBatches       = 'Pakiety';
sTxtTransparentNA = 'Przezroczystość - gdy nieaktywne';
sTxtWait          = 'Czekaj...';
sTxtStop          = 'Zatrzymaj';
sTxtNoName        = 'bez nazwy';
sTxtTotalFound    = 'Łącznie znaleziono: ';
sTxtReplAllCD     = '"Zamień wszystko" za&myka okno dialogowe';
sTxtReplAllWM     = '"Zamień wszystko" &bez komunikatu';
sTxtCheckInSel    = 'U&staw "W zaznaczeniu" jeśli jest zaznaczenie';
sTxtCycleSearch   = 'Szu&kaj wkoło';
sTxtPrompt        = 'Zapy&tanie';
sTxtWhatFind      = 'Co znaleźć';
sTxtReplaceWith   = 'Czym zamienić';
sTxtMatchCase     = 'Uwzględnij wielkość &liter';
sTxtWholeWord     = 'Całe &wyrazy';
sTxtRegExp        = 'Wyrażenia &regularne';
sTxtDotMatchesNL  = '&. dopasowuje \\n';
sTxtEscSeq        = 'Sekwencje &Esc';
sTxtDirection     = 'Kierunek';
sTxtDirDown       = 'W &dół';
sTxtDirUp         = 'W &górę';
sTxtDirBeginning  = 'Od &początku';
sTxtDirInSel      = 'W zaznaczeni&u';
sTxtDirAllFiles   = 'Wsz&ystkie pliki';
sTxtNew           = 'Nowy';
sTxtAdd           = 'Dodaj';
sTxtRename        = 'Zmień nazwę';
sTxtMoveUp        = 'W górę';
sTxtMoveDown      = 'W dół';
sTxtRemove        = 'Usuń';
sTxtCheckExpr     = '&Sprawdź wyrażenie';
sTxtAddToBatch    = 'Do pakietu';
sTxtOK            = 'OK';
sTxtClose         = 'Zamknij';
sTxtBatchReplace  = 'Zamiana pakietowa';
sTxtBatchReplAll  = 'Z&amień pakietowo wszystko';
sTxtEnableAll     = 'Włącz&/wyłącz wszystkie';
sTxtClosesDialog  = 'Za&myka dialog';
sTxtWithoutMsg    = '&Bez komunikatu';
sTxtTemplateName  = 'Nazwa szablonu';
sTxtConditions    = 'Warunki';
sTxtAllColumns    = 'Wszystkie kolumny';
sTxtNameOnly      = 'Tylko nazwa';
sTxtSortByName    = 'Sortuj wg nazwy';
sTxtNameInvalid   = 'Nieprawidłowa nazwa.';
sTxtNameExists    = 'Ta nazwa już istnieje.';
sTxtWantRemove    = 'Czy chcesz usunąć ten szablon?';
sTxtBatchNumber   = 'Pakiet nr ';
sTxtWantBatchRepl = 'Czy chcesz zamienić pakietowo wszystko?';
sTxtNoFindText    = 'Brak tekstu w polu "Co znaleźć".';
sTxtExprOK        = 'Wyrażenie jest prawidłowe.';
sTxtExprError     = 'Błąd w wyrażeniu';
sTxtCountChanges  = 'Liczba zmian: ';
//context menu edit
sMnuUndo      = '&Cofnij';
sMnuRedo      = '&Powtórz';
sMnuCut       = '&Wytnij';
sMnuCopy      = '&Kopiuj';
sMnuPaste     = 'Wkl&ej';
sMnuDelete    = '&Usuń';
sMnuSelectAll = 'Zaznacz w&szystko';
sMnuAPFont    = 'Czcionka AkelPad\'a';
sMnuNextTempl = 'Następny szablon';
sMnuPrevTempl = 'Poprzedni szablon';
//RegExp help
sHlpAnyChar        = 'dowolny znak (kropka)';
sHlpSpecChars      = '()[]{}^$.?+*|\\ znaki specjalne';
sHlpBackslash      = 'backslash';
sHlpNull           = 'znak null';
sHlpFF             = 'wysuw strony';
sHlpNL             = 'nowy wiersz';
sHlpAnyNL          = 'nowy wiersz dowolnego formatu';
sHlpTab            = 'tab';
sHlpVTab           = 'pionowy tab';
sHlpDigit          = 'cyfra';
sHlpNonDigit       = 'inny niż cyfra';
sHlpWhiteSp        = 'biały znak';
sHlpNonWhiteSp     = 'inny niż biały znak';
sHlpWordChar       = 'znak słowa (nie separator)';
sHlpNonWordChar    = 'inny niż znak słowa (separator)';
sHlpCharHex        = 'znak - kod hex, zakres 0-10FFFF';
sHlpCharHex2       = 'znak - 2-cyfrowy kod hex';
sHlpCharHex4       = 'znak - 4-cyfrowy kod hex';
sHlpAlternative    = 'alternatywa ab lub xy';
sHlpCharSet        = 'zestaw znaków, dowolny z abc';
sHlpNegCharSet     = 'zaprzeczenie zestawu znaków';
sHlpRange          = 'zakres znaków od a do z';
sHlpNegRange       = 'zaprzeczenie zakresu znaków';
sHlpBeginLine      = 'początek wiersza';
sHlpEndLine        = 'koniec wiersza';
sHlpBeginText      = 'początek tekstu';
sHlpEndText        = 'koniec tekstu';
sHlpBeginRange     = 'początek zakresu wyszukiwania';
sHlpEndRange       = 'koniec zakresu wyszukiwania';
sHlpWordBoun       = 'granica słowa';
sHlpNonWordBoun    = 'brak granicy słowa';
sHlpExcludePrev    = 'wyłącza poprzedzające znaki z wyniku';
sHlpZeroOrOne      = 'zero lub jeden raz';
sHlpZeroOrMore     = 'zero lub więcej razy';
sHlpOneOrMore      = 'jeden lub więcej razy';
sHlpExactly        = 'dokładnie 3 razy';
sHlpAtLeast        = 'co najmniej 3 razy';
sHlpFromTo         = 'od 3 do 7 razy';
sHlpEntireStr      = 'cały dopasowany ciąg';
sHlpSubmatch9      = '9-ty dopasowany podciąg, zakres 1-9';
sHlpSubmatch99     = '99-ty dopasowany podciąg, zakres 01-99';
sHlpGreedy         = '- powyższe kwantyfikatory są zachłanne';
sHlpLazy           = 'dodaj na końcu dla kw. leniwego';
sHlpPossesive      = 'dodaj na końcu dla kw. zaborczego';
sHlpCapture1       = 'dopasowuje ab, przechwytuje';
sHlpCapture2       = 'zaprzeczenie ab, przechwytuje';
sHlpNotCapture     = 'dopasowuje ab, nie przechwytuje';
sHlpAtomicGrouping = 'atomowe grupowanie, nie przechwytuje';
sHlpPreceded       = 'przed ciągiem jest ab';
sHlpNotPreceded    = 'przed ciągiem nie ma ab';
sHlpFollowed       = 'za ciągiem jest ab';
sHlpNotFollowed    = 'za ciągiem nie ma ab';
sHlpCondition      = 'jeśli (1) to x, w przeciwnym razie y';
sHlpBackrefer9     = 'odwołanie wsteczne, zakres 1-9';
sHlpBackrefer99    = 'odwołanie wsteczne, zakres 01-99';
sHlpIgnoreCase     = 'ignoruje wielkość liter';
sHlpMultiline      = 'szukanie wielowierszowe (domyślne)';
sHlpDotDefault     = 'kropka = dowlony znak (domyślne)';
sHlpInvertGreed    = 'wyłącza zachłanność kwanyfikatorów';
sHlpMatchCase      = 'uwzględnia wielkość liter';
sHlpMultilineOff   = 'wyłącza szukanie wielowierszowe';
sHlpDotDefaultOff  = 'kropka = dowlony znak, oprócz \\n';
sHlpInvertGreedOff = 'włącza zachłanność kwanyfikatorów';
- Polish

Code: Select all

/**************************************************
FindReplaceEx.js - ver. 2018-11-06
Interface language
Language:      Russian (1049)
Translated by: F. Phoenix, Andrey_A_A, VladSh, YuS
**************************************************/
sTxtMore          = 'Ещё';
sTxtCount         = 'Подсчитать';
sTxtFindAll       = 'Найти все';
sTxtShowInLog     = 'Показать в Log-панели';
sTxtOnlyMatched   = 'только найденное';
sTxtEntireLines   = 'целые строки';
sTxtCopyToCB      = 'Копировать в буфер';
sTxtOpenInTab     = 'Открыть в новой вкладке';
sTxtBookmarkLines = 'Пометить строки';
sTxtUnmarkLines   = 'Снять пометки строк';
sTxtTemplates     = 'Шаблоны';
sTxtBatches       = 'Пакеты';
sTxtTransparentNA = 'Прозрачный неактивный диалог';
sTxtWait          = 'Подождите...';
sTxtStop          = 'Стоп';
sTxtNoName        = 'без имени';
sTxtTotalFound    = 'Всего вхождений: ';
sTxtReplAllCD     = '"Заменить всё" закрывает диалог';
sTxtReplAllWM     = '"Заменить всё" без сообщения';
sTxtCheckInSel    = 'Отметить "В выделении" если есть выделение';
sTxtCycleSearch   = 'Поиск по кругу';
sTxtPrompt        = 'Запрос';
sTxtWhatFind      = 'Что найти';
sTxtReplaceWith   = 'Чем заменить';
sTxtMatchCase     = '&Учитывать регистр';
sTxtWholeWord     = 'Слово &целиком';
sTxtRegExp        = '&Регулярные выражения';
sTxtDotMatchesNL  = '&. захватывает \\n';
sTxtEscSeq        = 'Esc-&последовательности';
sTxtDirection     = 'Направление';
sTxtDirDown       = 'Вни&з';
sTxtDirUp         = 'Ввер&х';
sTxtDirBeginning  = '&С начала';
sTxtDirInSel      = 'В в&ыделении';
sTxtDirAllFiles   = 'Все &файлы';
sTxtNew           = 'Создать';
sTxtAdd           = 'Добавить';
sTxtRename        = 'Изменить';
sTxtMoveUp        = 'Вверх';
sTxtMoveDown      = 'Вниз';
sTxtRemove        = 'Удалить';
sTxtCheckExpr     = 'Проверить выражение';
sTxtAddToBatch    = 'В пакет';
sTxtOK            = 'OK';
sTxtClose         = 'Закрыть';
sTxtBatchReplace  = 'Пакетная замена';
sTxtBatchReplAll  = 'Заменить всё (пакетом)';
sTxtEnableAll     = 'Включить&/выключить всё';
sTxtClosesDialog  = 'Закрывает диалог';
sTxtWithoutMsg    = 'Без сообщения';
sTxtTemplateName  = 'Имя шаблона';
sTxtConditions    = 'Условия';
sTxtAllColumns    = 'Все колонки';
sTxtNameOnly      = 'Только имя';
sTxtSortByName    = 'Сортировка по имени';
sTxtNameInvalid   = 'Неверное имя.';
sTxtNameExists    = 'Такое наименование шаблона уже используется.';
sTxtWantRemove    = 'Вы действительно хотите удалить этот шаблон?';
sTxtBatchNumber   = 'Пакет №';
sTxtWantBatchRepl = 'Заменить всё этим пакетом?';
sTxtNoFindText    = 'Нет текста в поле "Что найти".';
sTxtExprOK        = 'Выражение правильное.';
sTxtExprError     = 'Ошибка в выражении';
sTxtCountChanges  = 'Количество замен: ';
//context menu edit
sMnuUndo      = '&Отменить';
sMnuRedo      = '&Повторить';
sMnuCut       = 'Вырезать';
sMnuCopy      = '&Копировать';
sMnuPaste     = '&Вставить';
sMnuDelete    = '&Удалить';
sMnuSelectAll = 'Выделить всё';
sMnuAPFont    = 'Шрифт (Вид->Шрифт)';
sMnuNextTempl = 'Следующий шаблон';
sMnuPrevTempl = 'Предыдущий шаблон';
//RegExp help
sHlpAnyChar        = 'любой символ (точка)';
sHlpSpecChars      = '()[]{}^$.?+*|\\ специальные символы';
sHlpBackslash      = 'обратный слеш';
sHlpNull           = 'пустой символ';
sHlpFF             = 'перевод страницы';
sHlpNL             = 'перевод строки';
sHlpAnyNL          = 'перевод строки';
sHlpTab            = 'табуляция';
sHlpVTab           = 'вертикальная табуляция';
sHlpDigit          = 'цифра';
sHlpNonDigit       = 'не цифра';
sHlpWhiteSp        = 'пробельный символ';
sHlpNonWhiteSp     = 'непробельный символ';
sHlpWordChar       = 'словесный символ  (non-delimiter)';
sHlpNonWordChar    = 'несловесный символ (delimiter)';
sHlpCharHex        = 'символ - код в диапазоне 0-10FFFF';
sHlpCharHex2       = 'символ - 2-значный код';
sHlpCharHex4       = 'символ - 4-значный код';
sHlpAlternative    = 'одна из альтернатив: ab либо xy';
sHlpCharSet        = 'набор символов, нужен любой из них';
sHlpNegCharSet     = 'исключающий набор символов';
sHlpRange          = 'диапазон символов от a до z';
sHlpNegRange       = 'исключающий диапазон';
sHlpBeginLine      = 'начало строки';
sHlpEndLine        = 'конец строки';
sHlpBeginText      = 'начало документа';
sHlpEndText        = 'конец документа';
sHlpBeginRange     = 'начало диапазона поиска';
sHlpEndRange       = 'конец диапазона поиска';
sHlpWordBoun       = 'граница слова';
sHlpNonWordBoun    = 'не граница слова';
sHlpExcludePrev    = 'исключить предыдущее из результата';
sHlpZeroOrOne      = '0 или 1 раз';
sHlpZeroOrMore     = '0 или более раз';
sHlpOneOrMore      = '1 или более раз';
sHlpExactly        = 'ровно 3 раза';
sHlpAtLeast        = 'не менее 3 раз';
sHlpFromTo         = 'от 3 до 7 раз';
sHlpEntireStr      = 'вся захваченная строка';
sHlpSubmatch9      = '9я подстрока (диапазон 1-9)';
sHlpSubmatch99     = '99я подстрока (диапазон 01-99)';
sHlpGreedy         = '- выше жадные квантификаторы ';
sHlpLazy           = 'добавить для ленивого квантификатора';
sHlpPossesive      = 'добавить для сверхжадного квантификатора';
sHlpCapture1       = 'запоминающая скобка';
sHlpCapture2       = 'соответствует негативному ab, захвату';
sHlpNotCapture     = 'незапоминающая скобка';
sHlpAtomicGrouping = 'атомарная группа (незапоминающая)';
sHlpPreceded       = 'строка следует за ab';
sHlpNotPreceded    = 'строка не следует за ab';
sHlpFollowed       = 'строка предшествует ab';
sHlpNotFollowed    = 'строка не предшествует ab';
sHlpCondition      = 'если (1) то x, иначе y';
sHlpBackrefer9     = 'обратная ссылка, диапазон 1-9';
sHlpBackrefer99    = 'обратная ссылка, диапазон 01-99';
sHlpIgnoreCase     = 'не учитывать регистр символов';
sHlpMultiline      = 'многострочный поиск (по умолчанию)';
sHlpDotDefault     = 'точке соответствует любой символ (по умолчанию)';
sHlpInvertGreed    = 'инвертировать жадность квантификаторов';
sHlpMatchCase      = 'учитывать регистр символов';
sHlpMultilineOff   = 'выключить многострочный поиск';
sHlpDotDefaultOff  = 'точке соответствует любой символ, кроме \\n';
sHlpInvertGreedOff = 'отменить инвертирование жадности';
- Russian by F. Phoenix, Andrey_A_A, VladSh, YuS

Code: Select all

/**************************************
FindReplaceEx.js - ver. 2018-11-06
Interface language
Language:      ChineseSimplified (2052)
Translated by: cnnnc
**************************************/
sTxtMore          = '更多(&M)';
sTxtCount         = '计数(&O)';
sTxtFindAll       = '查找全部(&L)';
sTxtOnlyMatched   = '仅匹配';
sTxtEntireLines   = '整行';
sTxtShowInLog     = '显示到输出面板';
sTxtCopyToCB      = '复制到剪贴板';
sTxtOpenInTab     = '在新标签页打开';
sTxtBookmarkLines = '添加书签行';
sTxtUnmarkLines   = '取消书签行';
sTxtTemplates     = '方案';
sTxtBatches       = '批量';
sTxtTransparentNA = '透明 - 仅当非活动时';
sTxtWait          = '请稍候...';
sTxtStop          = '停止';
sTxtNoName        = '未命名';
sTxtTotalFound    = '找到总数: ';
sTxtReplAllCD     = '"全部替换" 后关闭对话框(&G)';
sTxtReplAllWM     = '"全部替换" 无提示(&T)';
sTxtCheckInSel    = '如果选定区域不为空就选上 "选定区域"(&N)';
sTxtCycleSearch   = '循环搜索(&Y)';
sTxtPrompt        = '提示(&P)';
sTxtWhatFind      = '查找';
sTxtReplaceWith   = '替换';
sTxtMatchCase     = '区分大小写';
sTxtWholeWord     = '整字匹配';
sTxtRegExp        = '正则表达式';
sTxtDotMatchesNL  = '&. 匹配 \\n';
sTxtEscSeq        = '转义符序列';
sTxtDirection     = '方向';
sTxtDirDown       = '向下(&D)';
sTxtDirUp         = '向上(&U)';
sTxtDirBeginning  = '开始(&B)';
sTxtDirInSel      = '选定区域(&I)';
sTxtDirAllFiles   = '所有文件(&S)';
sTxtNew           = '新建';
sTxtAdd           = '添加';
sTxtRename        = '重命名';
sTxtMoveUp        = '向上';
sTxtMoveDown      = '向下';
sTxtRemove        = '删除';
sTxtCheckExpr     = '检验表达式';
sTxtAddToBatch    = '到批量';
sTxtOK            = '确定';
sTxtClose         = '关闭';
sTxtBatchReplace  = '批量替换';
sTxtBatchReplAll  = '批量替换全部(&A)';
sTxtEnableAll     = '允许/禁用全部(&/)';
sTxtClosesDialog  = '后关闭对话框(&G)';
sTxtWithoutMsg    = '无提示(&T)';
sTxtTemplateName  = '方案名称';
sTxtConditions    = '条件';
sTxtAllColumns    = '所有列';
sTxtNameOnly      = '仅名称';
sTxtSortByName    = '按名称排序';
sTxtNameInvalid   = '无效的名称。';
sTxtNameExists    = '名称已经存在。';
sTxtWantRemove    = '是否想要删除?';
sTxtBatchNumber   = '批量 #';
sTxtWantBatchRepl = '是否要批量替换全部?';
sTxtNoFindText    = '“查找内容”文本框中无文本。';
sTxtExprOK        = '表达式正常。';
sTxtExprError     = '表达式中有错误';
sTxtCountChanges  = '替换数量: ';
//context menu edit
sMnuUndo      = '撤消(&U)';
sMnuRedo      = '恢复(&R)';
sMnuCut       = '剪切(&U)';
sMnuCopy      = '复制(&C)';
sMnuPaste     = '粘贴(&P)';
sMnuDelete    = '删除(&D)';
sMnuSelectAll = '全选(&A)';
sMnuAPFont    = 'AkelPad 字体';
sMnuNextTempl = '下一方案';
sMnuPrevTempl = '上一方案';
//RegExp help
sHlpAnyChar        = '任意单一字符';
sHlpSpecChars      = '()[]{}^$.?+*|\\ 特殊符号';
sHlpBackslash      = '反斜线';
sHlpNull           = 'null 字符';
sHlpFF             = '换页符';
sHlpNL             = '换行符';
sHlpAnyNL          = '任何换行符';
sHlpTab            = '制表符';
sHlpVTab           = '垂直制表符';
sHlpDigit          = '数字';
sHlpNonDigit       = '非数字';
sHlpWhiteSp        = '空白字符';
sHlpNonWhiteSp     = '非空白字符';
sHlpWordChar       = '单词字符 (非分隔符)';
sHlpNonWordChar    = '非单词字符 (分隔符)';
sHlpCharHex        = '字符 - 16 进制编码, 范围 0-10FFFF';
sHlpCharHex2       = '字符 - 2 位 16 进制编码';
sHlpCharHex4       = '字符 - 4 位 16 进制编码';
sHlpAlternative    = '匹配 ab 或 xy';
sHlpCharSet        = '字符集合, 匹配所包含的任意一个字符';
sHlpNegCharSet     = '负值字符集合,匹配未包含的任意字符';
sHlpRange          = '匹配 a 到 z 范围内的任意小写字母字符';
sHlpNegRange       = '匹配任何不在 a 到 z 范围内的任意字符';
sHlpBeginLine      = '行开头';
sHlpEndLine        = '行末尾';
sHlpBeginText      = '文本开头';
sHlpEndText        = '文本末尾';
sHlpBeginRange     = '搜索范围的开头';
sHlpEndRange       = '搜索范围的末尾';
sHlpWordBoun       = '单词边界';
sHlpNonWordBoun    = '非单词边界';
sHlpExcludePrev    = '从结果中排除之前的字符';
sHlpZeroOrOne      = '匹配前面的子表达式零次或一次';
sHlpZeroOrMore     = '匹配前面的子表达式零次或多次';
sHlpOneOrMore      = '匹配前面的子表达式一次或多次';
sHlpExactly        = '精确匹配 3 次';
sHlpAtLeast        = '最少匹配 3 次';
sHlpFromTo         = '匹配 3 到 7 次的';
sHlpEntireStr      = '匹配整个字符串';
sHlpSubmatch9      = '第 9 个捕捉子匹配, 范围 1-9';
sHlpSubmatch99     = '第 99 个捕捉子匹配, 范围 01-99';
sHlpGreedy         = '- 以上量词都是贪婪的';
sHlpLazy           = '添加在末尾变成懒惰量词';
sHlpPossesive      = '添加在末尾变成占有优先量词';
sHlpCapture1       = '匹配并获取 ab';
sHlpCapture2       = '匹配非 ab 并获取';
sHlpNotCapture     = '匹配 ab 但不获取匹配';
sHlpAtomicGrouping = '原子分组, 不获取匹配';
sHlpPreceded       = '前面带有 ab';
sHlpNotPreceded    = '前面不带有 ab';
sHlpFollowed       = '在任何匹配 ab 的字符串开始处匹配查找字符串';
sHlpNotFollowed    = '在任何不匹配 ab 的字符串开始处匹配查找字符串';
sHlpCondition      = '如果 (1) 就 x, 否则 y';
sHlpBackrefer9     = '向后引用, 范围 1-9';
sHlpBackrefer99    = '向后引用, 范围 01-99';
sHlpIgnoreCase     = '不区分大小写';
sHlpMultiline      = '多行搜索 (默认值)';
sHlpDotDefault     = '点 "." 匹配任意字符 (默认值)';
sHlpInvertGreed    = '反转贪婪';
sHlpMatchCase      = '区分大小写';
sHlpMultilineOff   = '取消多行搜索';
sHlpDotDefaultOff  = '点 "." 匹配除 "\\n" 外的任意字符';
sHlpInvertGreedOff = '取消反转贪婪';
- Chinese-Simplified by cnnnc
Last edited by KDJ on Tue Nov 06, 2018 7:30 pm, edited 34 times in total.

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

Post by Instructor »

Multiple clipboard.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=28437#p28437
// Version: 1.1
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Multiple clipboard.
// Description(1049): Множественный буфер обмена.
//
// Arguments:
// -SaveID=1             -Save current clipboard in specified ID.
// -PasteID=1            -Paste text from saved ID.
// -SendKeys="^v"        -SendKeys to paste text. Most common combinations:
//                         "^v"     - Ctrl+V.
//                         "+{INS}" - Shift+Insert.
//                        Special values:
//                         "1"      - Ctrl+V via keybd_event (default).
//                         "2"      - Shift+Insert via keybd_event.
// -RestoreTimeout=100   -Sleep before restore clipboard after paste. Default is 100. If zero, don't restore clipboard.
// -DeleteID=0           -Delete saved IDs. If zero, delete all IDs.
//
// Usage (save clipboard):
// Call("Scripts::Main", 1, "MultiClipboard.js", `-SaveID=1`)
//
// Usage (paste clipboard):
// Call("Scripts::Main", 1, "MultiClipboard.js", `-PasteID=1`)

//Arguments
var nSaveID=AkelPad.GetArgValue("SaveID", -1);
var nPasteID=AkelPad.GetArgValue("PasteID", -1);
var pSendKeys=AkelPad.GetArgValue("SendKeys", "1");
var nRestoreTimeout=AkelPad.GetArgValue("RestoreTimeout", 100);
var nDeleteID=AkelPad.GetArgValue("DeleteID", -1);

//Variables
var oSys=AkelPad.SystemFunction();
var oSet=AkelPad.ScriptSettings();
var pPasteText;
var pClipboardText=AkelPad.GetClipboardText();

if (nSaveID != -1)
{
  if (oSet.Begin("", 0x2 /*POB_SAVE*/))
  {
    oSet.Write("ID" + nSaveID, 2 /*PO_BINARY*/, pClipboardText);
    oSet.End();
  }
}
if (nPasteID != -1)
{
  if (oSet.Begin("", 0x1 /*POB_READ*/))
  {
    pPasteText=oSet.Read("ID" + nPasteID, 20 /*PO_BINARYSTRING*/);
    AkelPad.SetClipboardText(pPasteText);

    if (pSendKeys == "1") //Ctrl+V
    {
      oSys.Call("user32::keybd_event", 0x11 /*VK_CONTROL*/, 0, 0x1 /*KEYEVENTF_EXTENDEDKEY*/, 0);
      oSys.Call("user32::keybd_event", 0x56 /*V*/, 0, 0x0, 0);
      oSys.Call("user32::keybd_event", 0x56 /*V*/, 0, 0x2 /*KEYEVENTF_KEYUP*/, 0);
      oSys.Call("user32::keybd_event", 0x11 /*VK_CONTROL*/, 0, 0x3 /*KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP*/, 0);
    }
    else if (pSendKeys == "2") //Shift+Insert
    {
      oSys.Call("user32::keybd_event", 0x10 /*VK_SHIFT*/, 0, 0x1 /*KEYEVENTF_EXTENDEDKEY*/, 0);
      oSys.Call("user32::keybd_event", 0x2D /*VK_INSERT*/, 0, 0x1 /*KEYEVENTF_EXTENDEDKEY*/, 0);
      oSys.Call("user32::keybd_event", 0x2D /*VK_INSERT*/, 0, 0x3 /*KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP*/, 0);
      oSys.Call("user32::keybd_event", 0x10 /*VK_SHIFT*/, 0, 0x3 /*KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP*/, 0);
    }
    else
    {
      var WshShell=new ActiveXObject("WScript.shell");

      WshShell.SendKeys(pSendKeys);
    }

    if (nRestoreTimeout)
    {
      WScript.Sleep(nRestoreTimeout);
      AkelPad.SetClipboardText(pClipboardText);
    }
    oSet.End();
  }
}
if (nDeleteID != -1)
{
  if (nDeleteID)
  {
    if (oSet.Begin("", 0x2 /*POB_SAVE*/))
    {
      oSet.Delete("ID" + nDeleteID);
      oSet.End();
    }
  }
  else
  {
    if (oSet.Begin("", 0x6 /*POB_SAVE|POB_CLEAR*/))
    {
      oSet.End();
    }
  }
}
Last edited by Instructor on Sat May 16, 2015 8:09 am, edited 1 time in total.

Offline
Posts: 202
Joined: Sat Mar 28, 2015 2:36 pm
Location: Russia

Post by Kley »

GUI for HexSel plugin.

Code: Select all

//  ============================================================================
//  Version: 2015-05-13
//  Author: Kley
//
//  *** GUI for HexSel plugin. ***
//
//  Note:
//  "Упрощенная имитация" диалога настроек HexSel.
//
//  Usage:
//  Call("Scripts::Main", 1, "HexSelAs.js")
//  ============================================================================
//Options
var nDirection =     0;
var nRadix     =     0;
var nUnicode   =  1200;
var nAnsi      =     8;
var nSelect    =     0;
var aPrefix    = ["<"];
var aSuffix    = [">"];
var aCurfix    =    [];

//Variables
var hMainWnd = AkelPad.GetMainWnd();
var oSys = AkelPad.SystemFunction();
var hInstanceDLL = AkelPad.GetInstanceDll();
var pClassName = "AkelPad::Scripts::" + WScript.ScriptName + "::" + oSys.Call("kernel32::GetCurrentProcessId");
var hWndDialog;
var hWndControl;
var hWndDrctAuto;
var hWndHex2Text;
var hWndText2Hex;
var hWndCboPrefix;
var hWndCboSuffix;
var hWndRadixHex;
var hWndRadixDec;
var hWndRadixOct;
var hWndUtf16LE;
var hWndUtf16BE;
var hWndChkSelect;
var hWndChkAnsi;
var hWndReplace;
var hWndCansel;
var ptScale = [];
var hGuiFont;
var hFocus;

//Control IDs
var ID_OPT_AUTO    = 1001;
var ID_OPT_STR2HEX = 1002;
var ID_OPT_HEX2STR = 1003;
var ID_CBO_PREFIX  = 1004;
var ID_CBO_SUFFIX  = 1005;
var ID_OPT_HEX     = 1006;
var ID_OPT_DEC     = 1007;
var ID_OPT_OCT     = 1008;
var ID_OPT_LE      = 1009;
var ID_OPT_BE      = 1010;
var ID_CHK_SELECT  = 1011;
var ID_CHK_ANSI    = 1012;
var ID_REPLACE     = 1013;
var ID_CANCEL      = 1014;
var ID_LABEL       =   -1;

GetLangStrings();
ReadIni();

if (AkelPad.GetEditWnd()) {

  if (AkelPad.WindowRegisterClass(pClassName)) {

    var sizeNonClient = [];

    sizeNonClient.cx = oSys.Call("user32::GetSystemMetrics", 7 /*SM_CXFIXEDFRAME*/) * 2;
    sizeNonClient.cy = oSys.Call("user32::GetSystemMetrics", 8 /*SM_CYFIXEDFRAME*/) * 2 +
                       oSys.Call("user32::GetSystemMetrics", 4 /*SM_CYCAPTION*/);

    //Get scale factor for ScaleX and ScaleY
    ScaleInit(0, hMainWnd);

    //Create dialog
    hWndDialog = oSys.Call("user32::CreateWindowEx" + _TCHAR,
                           0,                              //dwExStyle
                           pClassName,                     //lpClassName
                           0,                              //lpWindowName
                           0x90CA0000,                     //WS_VISIBLE|WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX
                           ScaleX(0),                      //x
                           ScaleY(0),                      //y
                           ScaleX(450) + sizeNonClient.cx, //nWidth
                           ScaleY(240) + sizeNonClient.cy, //nHeight
                           hMainWnd,                       //hWndParent
                           0,                              //ID
                           hInstanceDLL,                   //hInstance
                           DialogCallback);                //Script function callback.
                                                           //To use it class must be registered by WindowRegisterClass.
    if (hWndDialog) {

      //Allow other scripts running
      AkelPad.ScriptNoMutex();
      //Message loop
      AkelPad.WindowGetMessage();
    }
    AkelPad.WindowUnregisterClass(pClassName);
  }
  else if (hWndDialog = oSys.Call("user32::FindWindowEx" + _TCHAR, 0, 0, pClassName, 0)) {

    if (oSys.Call("user32::IsIconic", hWndDialog))
      oSys.Call("user32::ShowWindow", hWndDialog, 9 /*SW_RESTORE*/);

    AkelPad.SendMessage(hWndDialog, 7 /*WM_SETFOCUS*/, 0, 0);
  }
}

function DialogCallback(hWnd, uMsg, wParam, lParam) {

  if (uMsg == 1) {  //WM_CREATE

    hGuiFont = oSys.Call("gdi32::GetStockObject", 17 /*DEFAULT_GUI_FONT*/);

    //Dialog caption
    SetWindowText(hWnd, WScript.ScriptBaseName);


    ////GroupBox DIRECTION

    //Create window
    hWndControl=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000007,     //WS_VISIBLE|WS_CHILD|BS_GROUPBOX
                            ScaleX(10),     //x
                            ScaleY(14),     //y
                            ScaleX(155),    //nWidth
                            ScaleY(90),     //nHeight
                            hWnd,           //hWndParent
                            ID_LABEL,       //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndControl, hGuiFont, STR_DIRECT);


    ////RadioButton AUTO

    //Create window
    hWndDrctAuto=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000009,     //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            ScaleX(20),     //x
                            ScaleY(35),     //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_OPT_AUTO,    //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndDrctAuto, hGuiFont, STR_AUTO);


    ////RadioButton TEXT2HEX

    //Create window
    hWndText2Hex=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000009,     //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            ScaleX(20),     //x
                            ScaleY(55),     //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_OPT_STR2HEX, //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndText2Hex, hGuiFont, STR_STR2HEX);


    ////RadioButton HEX2TEXT

    //Create window
    hWndHex2Text=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000009,     //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            ScaleX(20),     //x
                            ScaleY(75),     //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_OPT_HEX2STR, //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndHex2Text, hGuiFont, STR_HEX2STR);


    ////GroupBox SEPARATOR

    //Create window
    hWndControl=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000007,     //WS_VISIBLE|WS_CHILD|BS_GROUPBOX
                            ScaleX(10),     //x
                            ScaleY(108),    //y
                            ScaleX(155),    //nWidth
                            ScaleY(90),     //nHeight
                            hWnd,           //hWndParent
                            ID_LABEL,       //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndControl, hGuiFont, STR_SEP);


    ////Static PREFIX

    //Create window
    hWndControl = oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "STATIC",       //lpClassName
                            0,              //lpWindowName
                            0x50000000,     //0x50000000|0x0002,   //WS_VISIBLE|WS_CHILD
                            ScaleX(20),     //x
                            ScaleY(132),    //y
                            ScaleX(58),     //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_LABEL,       //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndControl, hGuiFont, STR_PREFIX);


    ////Static SUFFIX

    //Create window
    hWndControl = oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "STATIC",       //lpClassName
                            0,              //lpWindowName
                            0x50000000,     //0x50000000|0x0002,   //WS_VISIBLE|WS_CHILD
                            ScaleX(20),     //x
                            ScaleY(159),    //y
                            ScaleX(58),     //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_LABEL,       //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndControl, hGuiFont, STR_SUFFIX);


    ////ComboBox PREFIX

    //Create window
    hWndCboPrefix=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "COMBOBOX",     //lpClassName
                            0,              //lpWindowName
                            0x50210042,     //WS_VISIBLE|WS_CHILD|WS_TABSTOP|WS_VSCROLL|CBS_DROPDOWN|CBS_AUTOHSCROLL
                            ScaleX(82),     //x
                            ScaleY(132),    //y
                            ScaleX(70),     //nWidth
                            ScaleY(160),    //nHeight
                            hWnd,           //hWndParent
                            ID_CBO_PREFIX,  //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Fill combobox
    FillCBPrefix();

    //Set font and text
    SetWindowFontAndText(hWndCboPrefix, hGuiFont, aCurfix[0]);


    ////ComboBox SUFFIX

    //Create window
    hWndCboSuffix=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "COMBOBOX",     //lpClassName
                            0,              //lpWindowName
                            0x50210042,     //WS_VISIBLE|WS_CHILD|WS_TABSTOP|WS_VSCROLL|CBS_DROPDOWN|CBS_AUTOHSCROLL
                            ScaleX(82),     //x
                            ScaleY(159),    //y
                            ScaleX(70),     //nWidth
                            ScaleY(160),    //nHeight
                            hWnd,           //hWndParent
                            ID_CBO_SUFFIX,  //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Fill combobox
    FillCBSuffix();

    //Set font and text
    SetWindowFontAndText(hWndCboSuffix, hGuiFont, aCurfix[1]);


    ////GroupBox RADIX

    //Create window
    hWndControl=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000007,     //WS_VISIBLE|WS_CHILD|BS_GROUPBOX
                            ScaleX(185),    //x
                            ScaleY(14),     //y
                            ScaleX(155),    //nWidth
                            ScaleY(90),     //nHeight
                            hWnd,           //hWndParent
                            ID_LABEL,       //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndControl, hGuiFont, STR_RADIX);


    ////RadioButton HEX

    //Create window
    hWndRadixHex=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000009,     //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            ScaleX(195),    //x
                            ScaleY(35),     //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_OPT_HEX,     //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndRadixHex, hGuiFont, STR_HEX);


    ////RadioButton DEC

    //Create window
    hWndRadixDec=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000009,     //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            ScaleX(195),    //x
                            ScaleY(55),     //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_OPT_DEC,     //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndRadixDec, hGuiFont, STR_DEC);


    ////RadioButton OCT

    //Create window
    hWndRadixOct=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000009,     //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            ScaleX(195),    //x
                            ScaleY(75),     //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_OPT_OCT,     //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndRadixOct, hGuiFont, STR_OCT);


    ////GroupBox UTF 16

    //Create window
    hWndControl=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000007,     //WS_VISIBLE|WS_CHILD|BS_GROUPBOX
                            ScaleX(185),    //x
                            ScaleY(108),    //y
                            ScaleX(155),    //nWidth
                            ScaleY(90),     //nHeight
                            hWnd,           //hWndParent
                            ID_LABEL,       //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndControl, hGuiFont, STR_UTF16);


    ////RadioButton 1200 LE

    //Create window
    hWndUtf16LE=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000009,     //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            ScaleX(195),    //x
                            ScaleY(134),    //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_OPT_LE,      //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndUtf16LE, hGuiFont, "1200 (UTF-16 LE)");


    ////RadioButton 1201 BE

    //Create window
    hWndUtf16BE=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50000009,     //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            ScaleX(195),    //x
                            ScaleY(161),    //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_OPT_BE,      //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndUtf16BE, hGuiFont, "1201 (UTF-16 BE)");


    ////CheckBox SELECT

    //Create window
    hWndChkSelect=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50010003,     //WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_AUTOCHECKBOX
                            ScaleX(10),     //x
                            ScaleY(206),    //y
                            ScaleX(160),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_CHK_SELECT,  //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndChkSelect, hGuiFont, STR_SELECT);


    ////CheckBox ANSI

    //Create window
    hWndChkAnsi=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50010003,     //WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_AUTOCHECKBOX
                            ScaleX(195),    //x
                            ScaleY(206),    //y
                            ScaleX(130),    //nWidth
                            ScaleY(16),     //nHeight
                            hWnd,           //hWndParent
                            ID_CHK_ANSI,    //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndChkAnsi, hGuiFont, STR_ANSI);


    ////Button REPLACE

    //Create window
    hWndReplace = oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50010000,     //0x50010001: WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_DEFPUSHBUTTON(0x0001)
                            ScaleX(360),    //x
                            ScaleY(175),    //y
                            ScaleX(75),     //nWidth
                            ScaleY(23),     //nHeight
                            hWnd,           //hWndParent
                            ID_REPLACE,     //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndReplace, hGuiFont, STR_CHANGE);


    ////Button CANCEL

    //Create window
    hWndCansel = oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,              //dwExStyle
                            "BUTTON",       //lpClassName
                            0,              //lpWindowName
                            0x50010000,     //0x50010001: WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_DEFPUSHBUTTON(0x0001)
                            ScaleX(360),    //x
                            ScaleY(204),    //y
                            ScaleX(75),     //nWidth
                            ScaleY(23),     //nHeight
                            hWnd,           //hWndParent
                            ID_CANCEL,      //ID
                            hInstanceDLL,   //hInstance
                            0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndCansel, hGuiFont, STR_CANCEL);

    //Center dialog
    CenterWindow(hMainWnd, hWnd);

    SetButtonState();
  }

  else if ((uMsg == 6 /*WM_ACTIVATE*/) && (! wParam))
    hFocus = oSys.Call("User32::GetFocus");

  else if (uMsg == 7) { //WM_SETFOCUS

    if (! hFocus)
      oSys.Call("User32::SetFocus", hWndCboPrefix);
    else oSys.Call("User32::SetFocus", hFocus);
  }

  else if (uMsg == 256) { //WM_KEYDOWN

    if (wParam == 13 /*VK_RETURN*/)
      oSys.Call("user32::PostMessage" + _TCHAR, hWndDialog, 273 /*WM_COMMAND*/, ID_REPLACE, 0);

    if (wParam == 27 /*VK_ESCAPE*/)
      oSys.Call("user32::PostMessage" + _TCHAR, hWndDialog, 273 /*WM_COMMAND*/, ID_CANCEL, 0);
  }

  else if (uMsg == 273) { //WM_COMMAND

    var nID = wParam & 0xffff;

    if ( nID == ID_OPT_AUTO || nID == ID_OPT_HEX2STR || nID == ID_OPT_STR2HEX ||
         nID == ID_OPT_HEX  || nID == ID_OPT_DEC     || nID == ID_OPT_OCT     ||
         nID == ID_OPT_LE   || nID == ID_OPT_BE      || nID == ID_CHK_ANSI    ||
         nID == ID_CHK_SELECT ) {

      SetButtonState(nID);
    }

    else if (nID == ID_REPLACE)
      APTextChange();

    else if (nID == ID_CANCEL)
      oSys.Call("user32::PostMessage" + _TCHAR, hWndDialog, 16 /*WM_CLOSE*/, 0, 0);
  }

  else if (uMsg == 16) { //WM_CLOSE

    WriteIni();

    //Destroy dialog
    oSys.Call("user32::DestroyWindow", hWnd);
  }

  else if (uMsg == 2)  //WM_DESTROY
    //Exit message loop
    oSys.Call("user32::PostQuitMessage", 0);

  return 0;
}

function ScaleInit(hDC, hWnd) {

  if (!ptScale.x && !ptScale.y) {

    var hNewDC = hDC;

    if (!hDC)
      hNewDC = oSys.Call("user32::GetDC", hWnd);

    if (hNewDC) {

      ptScale.x = oSys.Call("gdi32::GetDeviceCaps", hNewDC, 88 /*LOGPIXELSX*/);
      ptScale.y = oSys.Call("gdi32::GetDeviceCaps", hNewDC, 90 /*LOGPIXELSY*/);

      //Align to 16 pixel
      if (ptScale.x % 16) ptScale.x+=16 - ptScale.x % 16;
      if (ptScale.y % 16) ptScale.y+=16 - ptScale.y % 16;
    }
    else return false;

    if (!hDC)
      oSys.Call("user32::ReleaseDC", hWnd, hNewDC);
  }
  return true;
}

function ScaleX(x) {

  if (ptScale.x)
    return oSys.Call("kernel32::MulDiv", x, ptScale.x, 96);
  return x;
}

function ScaleY(y) {

  if (ptScale.y)
    return oSys.Call("kernel32::MulDiv", y, ptScale.y, 96);
  return y;
}

function SetWindowFontAndText(hWnd, hFont, pText) {

  AkelPad.SendMessage(hWnd, 48 /*WM_SETFONT*/, hFont, 1);
  SetWindowText(hWnd, pText);
}

function SetWindowText(hWnd, sText) {

  oSys.Call("User32::SetWindowText" + _TCHAR, hWnd, sText);
}

function CenterWindow(hWndParent, hWnd) {

  var lpRect;
  var rcWndParent = [];
  var rcWnd = [];
  var X;
  var Y;

  if (lpRect = AkelPad.MemAlloc(16)) {  //sizeof(RECT)

    if (!hWndParent)
      hWndParent = oSys.Call("user32::GetDesktopWindow");

    oSys.Call("user32::GetWindowRect", hWndParent, lpRect);
    RectToArray(lpRect, rcWndParent);

    oSys.Call("user32::GetWindowRect", hWnd, lpRect);
    RectToArray(lpRect, rcWnd);

    //Center window
    X = rcWndParent.left + ((rcWndParent.right - rcWndParent.left) / 2 - (rcWnd.right - rcWnd.left) / 2);
    Y = rcWndParent.top + ((rcWndParent.bottom - rcWndParent.top) / 2 - (rcWnd.bottom - rcWnd.top) / 2);

    oSys.Call("user32::SetWindowPos", hWnd, 0, X, Y, 0, 0, 0x15 /*SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOSIZE*/);

    AkelPad.MemFree(lpRect);
  }
}

function RectToArray(lpRect, rcRect) {

  rcRect.left   = AkelPad.MemRead(_PtrAdd(lpRect,  0) /*offsetof(RECT, left)*/  , 3 /*DT_DWORD*/);
  rcRect.top    = AkelPad.MemRead(_PtrAdd(lpRect,  4) /*offsetof(RECT, top)*/   , 3 /*DT_DWORD*/);
  rcRect.right  = AkelPad.MemRead(_PtrAdd(lpRect,  8) /*offsetof(RECT, right)*/ , 3 /*DT_DWORD*/);
  rcRect.bottom = AkelPad.MemRead(_PtrAdd(lpRect, 12) /*offsetof(RECT, bottom)*/, 3 /*DT_DWORD*/);
  return rcRect;
}

function FillCBPrefix() {

  for (var i = 0; i < aPrefix.length; ++i)
    AkelPad.SendMessage(hWndCboPrefix, 323 /*CB_ADDSTRING*/, 0, aPrefix[i]);

  AkelPad.SendMessage(hWndCboPrefix, 334 /*CB_SETCURSEL*/, 0, 0);
}

function FillCBSuffix() {

  for (var i = 0; i < aSuffix.length; ++i)
    AkelPad.SendMessage(hWndCboSuffix, 323 /*CB_ADDSTRING*/, 0, aSuffix[i]);

  AkelPad.SendMessage(hWndCboSuffix, 334 /*CB_SETCURSEL*/, 0, 0);
}

function SetButtonState(nIDC) {

  switch (nIDC) {

    case ID_OPT_AUTO:    nDirection =    0; break;
    case ID_OPT_STR2HEX: nDirection =    1; break;
    case ID_OPT_HEX2STR: nDirection =    2; break;
    case ID_OPT_HEX:     nRadix     =    0; break;
    case ID_OPT_DEC:     nRadix     =  256; break;
    case ID_OPT_OCT:     nRadix     =  512; break;
    case ID_OPT_LE:      nUnicode   = 1200; break;
    case ID_OPT_BE:      nUnicode   = 1201; break;
    case ID_CHK_ANSI:
      nAnsi = (AkelPad.SendMessage(hWndChkAnsi, 240 /*BM_GETCHECK*/, 0, 0)) ? 4 : 8;
      break;
    case ID_CHK_SELECT:
      nSelect = (AkelPad.SendMessage(hWndChkSelect, 240 /*BM_GETCHECK*/, 0, 0)) ? 16 : 0;
      break;
  }

  AkelPad.SendMessage(hWndDrctAuto, 241 /*BM_SETCHECK*/, (nDirection == 0), 0);
  AkelPad.SendMessage(hWndHex2Text, 241 /*BM_SETCHECK*/, (nDirection == 2), 0);
  AkelPad.SendMessage(hWndText2Hex, 241 /*BM_SETCHECK*/, (nDirection == 1), 0);

  AkelPad.SendMessage(hWndRadixHex, 241 /*BM_SETCHECK*/, (nRadix ==   0), 0);
  AkelPad.SendMessage(hWndRadixDec, 241 /*BM_SETCHECK*/, (nRadix == 256), 0);
  AkelPad.SendMessage(hWndRadixOct, 241 /*BM_SETCHECK*/, (nRadix == 512), 0);

  AkelPad.SendMessage(hWndUtf16LE, 241 /*BM_SETCHECK*/, (nUnicode == 1200), 0);
  AkelPad.SendMessage(hWndUtf16BE, 241 /*BM_SETCHECK*/, (nUnicode == 1201), 0);

  oSys.Call("user32::EnableWindow", hWndUtf16LE, nAnsi == 8); 
  oSys.Call("user32::EnableWindow", hWndUtf16BE, nAnsi == 8); 

  AkelPad.SendMessage(hWndChkAnsi,   241 /*BM_SETCHECK*/, (nAnsi   ==  4), 0);
  AkelPad.SendMessage(hWndChkSelect, 241 /*BM_SETCHECK*/, (nSelect == 16), 0);
}

function ReadIni() {

  var oSet = AkelPad.ScriptSettings();

  if (oSet.Begin(WScript.ScriptBaseName, 0x01 /*POB_READ*/)) {

    //Read settings
    nDirection = oSet.Read("Direction", 1 /*PO_DWORD*/,      0);
    nRadix     = oSet.Read("Radix",     1 /*PO_DWORD*/,      0);
    nUnicode   = oSet.Read("Unicode",   1 /*PO_DWORD*/,   1200);
    nAnsi      = oSet.Read("Ansi",      1 /*PO_DWORD*/,      8);
    nSelect    = oSet.Read("Select",    1 /*PO_DWORD*/,      0);
    aPrefix    = oSet.Read("Prefix",    3 /*PO_STRING*/,   "<").split(",");
    aSuffix    = oSet.Read("Suffix",    3 /*PO_STRING*/,   ">").split(",");
    aCurfix    = oSet.Read("Curfix",    3 /*PO_STRING*/, "<,>").split(",");

    oSet.End();
  }
}

function WriteIni() {

  var bExist = false;
  var i;

  aCurfix[0] = GetWindowText(hWndCboPrefix).replace(/\\/g, "\\");
  aCurfix[1] = GetWindowText(hWndCboSuffix).replace(/\\/g, "\\");

  for (i = 0; i < aPrefix.length; i++) {

    if (aPrefix[i] == aCurfix[0]) {
      bExist = true;
      break;
    }
  }

  if (!bExist && aCurfix[0])
    aPrefix.push(aCurfix[0]);

  bExist = false;

  for (i = 0; i < aSuffix.length; i++) {

    if (aSuffix[i] == aCurfix[1]) {
      bExist = true;
      break;
    }
  }

  if (!bExist && aCurfix[1])
    aSuffix.push(aCurfix[1]);

  var oSet = AkelPad.ScriptSettings();

  if (oSet.Begin(WScript.ScriptBaseName, 0x2 /*POB_SAVE*/)) {

    //Save settings
    oSet.Write("Direction", 1 /*PO_DWORD*/,  nDirection);
    oSet.Write("Radix",     1 /*PO_DWORD*/,  nRadix);
    oSet.Write("Unicode",   1 /*PO_DWORD*/,  nUnicode);
    oSet.Write("Ansi",      1 /*PO_DWORD*/,  nAnsi);
    oSet.Write("Select",    1 /*PO_DWORD*/,  nSelect);
    oSet.Write("Prefix",    3 /*PO_STRING*/, aPrefix.join(","));
    oSet.Write("Suffix",    3 /*PO_STRING*/, aSuffix.join(","));
    oSet.Write("Curfix",    3 /*PO_STRING*/, aCurfix.join(","));

    oSet.End();
  }
}

function GetWindowText(hWnd) {

  var lpBuffer = AkelPad.MemAlloc(256 * _TSIZE);
  var sText;

  oSys.Call("User32::GetWindowText" + _TCHAR, hWnd, lpBuffer, 256);
  sText = AkelPad.MemRead(lpBuffer, _TSTR);
  AkelPad.MemFree(lpBuffer);
  return sText;
}

function APTextChange() {

  if (AkelPad.GetEditWnd()) {

    if (AkelPad.GetSelStart() != AkelPad.GetSelEnd())

      AkelPad.Call("HexSel::Main", 2, nDirection + nRadix + nAnsi + nSelect,
                                      GetWindowText(hWndCboPrefix),
                                      GetWindowText(hWndCboSuffix),
                                      -1,              //ANSICODEPAGE (Auto)
                                      nUnicode,        //UNICODECODEPAGE
                                      AkelPad.GetSelText());
  }
}

function GetLangStrings() {

  if (AkelPad.GetLangId(0 /*LANGID_FULL*/) == 1049 /*Russian*/) {

    STR_DIRECT  = "Направление";
    STR_AUTO    = "Авто";
    STR_STR2HEX = "Текст -> Hex";
    STR_HEX2STR = "Hex -> Текст";
    STR_PREFIX  = "Префикс:";
    STR_SUFFIX  = "Суффикс:";
    STR_SEP     = "Разделитель";
    STR_RADIX   = "Система счисления";
    STR_HEX     = "Шестнадцатеричная";
    STR_DEC     = "Десятеричная";
    STR_OCT     = "Восьмеричная";
    STR_SELECT  = " Выделить после замены";
    STR_UTF16   = "Два байта";
    STR_ANSI    = " Один байт (авто)";
    STR_CHANGE  = "Заменить";
    STR_CANCEL  = "Выход";
  }
  else {

    STR_DIRECT  = "Direction";
    STR_AUTO    = "Auto";
    STR_STR2HEX = "Text -> Hex";
    STR_HEX2STR = "Hex -> Text";
    STR_PREFIX  = "Prefix:";
    STR_SUFFIX  = "Suffix:";
    STR_SEP     = "Enclose";
    STR_RADIX   = "Radix";
    STR_HEX     = "Hexadecimal";
    STR_DEC     = "Decimal";
    STR_OCT     = "Octal";
    STR_SELECT  = " Select after replace";
    STR_UTF16   = "Double bytes";
    STR_ANSI    = " Single byte (auto)";
    STR_CHANGE  = "Replace";
    STR_CANCEL  = "Exit";
  }
}

Offline
Posts: 202
Joined: Sat Mar 28, 2015 2:36 pm
Location: Russia

Post by Kley »

Translation of digital code "hot keys" to the string.

Code: Select all

//  ============================================================================
//  Version: 2015-11-21
//  Author: Kley
//
//  *** Перевод цифрового кода "Горячих клавиш" в строку. ***
//
//  Usage:
//  Translation of digital code "hot keys" to the string.
//  Call("Scripts::Main", 1, "HotKeyCode2String.js")
//
//  Note:
//   -выделенный текст;
//   -слово под кареткой;
//   -диалог.
//  ... Hotkey(2854) --> Hotkey(Ctrl + Shift + Up)
//
//  Код функций GetHotkeyString и GetKeyNameText из Hotkeys плагина, v6.2.
//  ============================================================================
var oSys = AkelPad.SystemFunction();
var hMainWnd = AkelPad.GetMainWnd();
var pSelText = AkelPad.GetSelText();
var pTytle = WScript.ScriptName;
var aWordPos;

if (!pSelText)
{
  if (aWordPos = GetWordUnderCaret())
  {
    AkelPad.SetSel(aWordPos.min, aWordPos.max);
    pSelText = AkelPad.GetSelText();
  }
}

if (isNaN(parseInt(pSelText)))
  pSelText = AkelPad.InputBox(hMainWnd, pTytle, "Code:", "0");

if (!isNaN(parseInt(pSelText)))
{
  if (pSelText = GetHotkeyString(parseInt(pSelText)))
  {
    var nResult = AkelPad.MessageBox(hMainWnd, GetLangString(0) + ":\n\n" + pSelText, pTytle,
                  32 /*MB_ICONQUESTION*/, 0,
                  6 /*IDYES*/, GetLangString(1), 0x1 /*BMB_DEFAULT*/,
                  7 /*IDNO*/, GetLangString(2), 0,
                  2 /*IDCANCEL*/, GetLangString(3), 0);

    if (nResult == 6) AkelPad.ReplaceSel(pSelText);
    else if (nResult == 7) AkelPad.SetClipboardText(pSelText);
  }
}

function GetHotkeyString(wHotkey)
{
  var lScan;
  var pKeyText = "";
  var nResult = "";

  if (wHotkey)
  {
    lScan = oSys.Call("User32::MapVirtualKey" + _TCHAR, LOBYTE(wHotkey), 0) << 16;

    if (HIBYTE(wHotkey) & 0x08 /*HOTKEYF_EXT*/)
      lScan |= 0x01000000;

    pKeyText = GetKeyNameText(lScan);

    nResult = (HIBYTE(wHotkey) & 0x02 /*HOTKEYF_CONTROL*/) ? "Ctrl + " : "";
    nResult += (HIBYTE(wHotkey) & 0x01 /*HOTKEYF_SHIFT*/) ? "Shift + " : "";
    nResult += (HIBYTE(wHotkey) & 0x04 /*HOTKEYF_ALT*/) ? "Alt + " : "";
    nResult += pKeyText;
  }
  return nResult;
}

function GetKeyNameText(lScan)
{
  var lpKeyText = AkelPad.MemAlloc(100 * _TSIZE);
  lScan = oSys.Call("User32::GetKeyNameText" + _TCHAR, lScan, lpKeyText, 100);
  lScan = AkelPad.MemRead(lpKeyText, _TSTR);
  AkelPad.MemFree(lpKeyText);
  return lScan;
}

function LOBYTE(wParam)
{
  return wParam & 0xFF;
}

function HIBYTE(wParam)
{
  return wParam >> 8;
}

function GetWordUnderCaret()
{
  var hWndEdit = AkelPad.GetEditWnd();
  var nCaretPos = AkelPad.GetSelStart();
  var crInfo = [];

  crInfo.min = SendMessage(hWndEdit, 1100 /*EM_FINDWORDBREAK */, 0 /*WB_LEFT*/, nCaretPos);
  crInfo.max = SendMessage(hWndEdit, 1100 /*EM_FINDWORDBREAK */, 7 /*WB_RIGHTBREAK*/, crInfo.min);

  if (crInfo.max < nCaretPos)
  {
    crInfo.min = SendMessage(hWndEdit, 1100 /*EM_FINDWORDBREAK*/, 0 /*WB_LEFT*/, nCaretPos + 1);
    crInfo.max = SendMessage(hWndEdit, 1100 /*EM_FINDWORDBREAK*/, 7 /*WB_RIGHTBREAK*/, crInfo.min);
  }
  
  if (crInfo.max >= nCaretPos)
    return crInfo;
}

function SendMessage(hWnd, uMsg, wParam, lParam)
{
  return oSys.Call("User32::SendMessage" + _TCHAR, hWnd, uMsg, wParam, lParam);
}

function GetLangString(nStringID)
{
  var nLangID = AkelPad.GetLangId(1 /*LANGID_PRIMARY*/);

  if (nLangID == 0x19) //LANG_RUSSIAN
  {
    if (nStringID == 0)
      return "Результат";
    if (nStringID == 1)
      return "Вставить";
    if (nStringID == 2)
      return "Копировать";
    if (nStringID == 3)
      return "Отмена";
  }
  else
  {
    if (nStringID == 0)
      return "Result";
    if (nStringID == 1)
      return "Insert";
    if (nStringID == 2)
      return "Copy";
    if (nStringID == 3)
      return "Cancel";
  }
  return "";
}
Last edited by Kley on Sat Nov 21, 2015 5:28 am, edited 1 time in total.

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

Post by Instructor »

Go to nearest undo.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=28612#p28612
// Version: 1.0
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Go to nearest undo.
// Description(1049): Перейти к ближайшему месту отмены.
//
// Arguments:
// -Up=true     -Go up. Default is false.
//
// Usage (go down):
// Call("Scripts::Main", 1, "UndoPos.js")
//
// Usage (go up):
// Call("Scripts::Main", 1, "UndoPos.js", `-Up=true`)

//Arguments
var bUp=AkelPad.GetArgValue("Up", false);

//Variables
var hWndEdit=AkelPad.GetEditWnd();
var lpUndoItem;
var aOffset=[];
var nCount=0;
var nCaret;
var nGoto=-1;
var i;

if (lpUndoItem=AkelPad.MemAlloc(_X64?8:4 /*sizeof(HANDLE)*/))
{
  for (;;)
  {
    aOffset[nCount]=AkelPad.SendMessage(hWndEdit, 3092 /*AEM_GETUNDOPOS*/, 0x02 /*AEGUP_PREV*/, lpUndoItem);
    if (aOffset[nCount] == -1)
      break;
    ++nCount;
  }
  aOffset.sort(function(a, b)
  {
    return a - b;
  });
  AkelPad.MemFree(lpUndoItem);
}
if (aOffset.length)
{
  nCaret=AkelPad.SendMessage(hWndEdit, 3138 /*AEM_GETRICHOFFSET*/, 5 /*AEGI_CARETCHAR*/, 0);

  if (bUp)
  {
    for (i=0; i < aOffset.length; ++i)
    {
      if (aOffset[i] > nCaret)
      {
        nGoto=aOffset[i];
        break;
      }
    }
  }
  else
  {
    for (i=aOffset.length - 1; i >= 0; --i)
    {
      if (aOffset[i] < nCaret)
      {
        nGoto=aOffset[i];
        break;
      }
    }
  }
  if (nGoto != -1)
    AkelPad.SetSel(nGoto, nGoto);
}

Offline
Posts: 202
Joined: Sat Mar 28, 2015 2:36 pm
Location: Russia

Post by Kley »

Rename/Save As... file.

Code: Select all

//  ============================================================================
//  http://akelpad.sourceforge.net/forum/viewtopic.php?p=28705#p28705
//  Version: 2016-05-25
//  Author: Kley
//
//  Description(1033): Rename/Save As... file.
//  Description(1049): Переименовать/Сохранить Как... файл.
//
//  Arguments:
//  -action=0        - Необходимое действие.
//                       0  Переименовать файл (по умолчанию).
//                       1  Копировать    файл (backup).
//                       2  Сохранить     файл (current state).
//  -open=1          - Открыть после сохранения/копирования.
//                       0  запрос (по умолчанию);
//                       1  открыть;
//  -dir="%a\MyDir"  - Путь к папке для сохранения/копирования (по умолчанию папка редактируемого файла).
//                       "%%f"  сохранять/копировать в папку с именем файла
//  -file="NewDoc"   - Имя (без расширения) для нового файла (по умолчанию "").
//  -post="_backup"  - Приставка добавляемая после имени файла (по умолчанию "").
//                       "%%d"  вставить дату и время в заданном формате
//                       "%%n"  вставить счетчик (по умолчанию вставляется в конец файла)
//  -pref="backup_"  - Приставка добавляемая перед именем файла (по умолчанию "").
//                       "%%d"  вставить дату и время в заданном формате
//                       "%%n"  вставить счетчик (по умолчанию вставляется в конец файла)
//  -dataformat=""   - Описание формата смотри в InsertDate.js Shengalts Aleksander aka Instructor
//                       (http://akelpad.sourceforge.net/en/plugins.php#Scripts).
//
//  Usage:
//  Call("Scripts::Main", 1, "RenameFileAs.js")                                                             -Rename..."
//  Call("Scripts::Main", 1, "RenameFileAs.js", `-action=1 -post="_backup-%%n"`)                            -Backup
//  Call("Scripts::Main", 1, "RenameFileAs.js", `-action=1 -post="_[%%d]" -dir="%%f"`)                      -Backup to folder with file name
//  Call("Scripts::Main", 1, "RenameFileAs.js", `-action=2 -post="_curstate(%%n)"`)                         -Save
//  Call("Scripts::Main", 1, "RenameFileAs.js", `-action=2 -post="_[%%d]" -dir="c:\MyText"`)                -Save to folder (file/new file as...)
//  Call("Scripts::Main", 1, "RenameFileAs.js", `-action=2 -post="_[%%d]" -dir="c:\MyText" -file="NewDoc"`) -Save to folder as NewDoc (file/new file)
//  ============================================================================
//Arguments
var nAction = AkelPad.GetArgValue("action", 0);
var nOpen   = AkelPad.GetArgValue("open", 0);
var pDir    = AkelPad.GetArgValue("dir", "");
var pFile   = AkelPad.GetArgValue("file", "");
var pPost   = AkelPad.GetArgValue("post", "");
var pPref   = AkelPad.GetArgValue("pref", "");
var pData   = AkelPad.GetArgValue("dataformat", "yyyy.MM.dd-H.mm.ss");

//Variables
var hWndEdit = AkelPad.GetEditWnd();
if (!hWndEdit) WScript.Quit();

var oSys = AkelPad.SystemFunction();
var hMainWnd = AkelPad.GetMainWnd();
var pScriptName = WScript.ScriptName;
var pFileFullName = AkelPad.GetEditFile(0);
var pFileDir = AkelPad.GetFilePath(pFileFullName, 1 /*CPF_DIR*/);
var pExt = AkelPad.GetFilePath(pFileFullName, 4 /*CPF_FILEEXT*/);
var pNewFileFullName = "";
var nUpdate = 0;

var nBOM;
var nCodePage;
var aCurMarks;
var pBookmarks;
var pAlias;
var lpPoint64;
var lpSelect;
var lpCaret;

GetLangStrings();

if (/[\/\*\?"<>\|]/.test(pDir) || /[\\\/\*\?"<>:\|]/.test(pFile + pPost + pPref + pData))
{
  AkelPad.MessageBox(hMainWnd, sParamError, pScriptName, 48 /*MB_OK|MB_ICONEXCLAMATION*/);
  WScript.Quit();
}

//Tab contains name of a nonexistent file.
if (pFileFullName && (GetFileAttributes(pFileFullName) == -1 /*INVALID_FILE_ATTRIBUTES*/))
{
  if (AkelPad.MessageBox(
        hMainWnd,
        sCreateFile.replace(/%s/, pFileFullName),
        pScriptName, 33 /*MB_OKCANCEL|MB_ICONQUESTION*/)
      == 1 /*IDOK*/)
  {
    if (CreateDirectory(pFileDir))
      AkelPad.Command(4105); // Save
    else
      AkelPad.MessageBox(hMainWnd, sPathNotFound.replace(/%s/, pFileDir), pScriptName, 48 /*MB_OK|MB_ICONEXCLAMATION*/);
  }
  WScript.Quit();
}

switch (nAction)
{
  case 0: // Rename
    if (pFileFullName)
    {
      nOpen = 0;
      InputDialog();

      if (pNewFileFullName)
      {
        GetDocumentState();

        //Close editing file
        if (SendMessage(hMainWnd, 273 /*WM_COMMAND*/, 4324 /*IDM_WINDOW_FILECLOSE*/, 0))
        {
          //Rename file
          if (!oSys.Call("kernel32::MoveFile" + _TCHAR, pFileFullName, pNewFileFullName))
          {
            AkelPad.MessageBox(
              hMainWnd,
              sErrorOccurred.replace(/%s/, "" + oSys.GetLastError()),
              pScriptName, 48 /*MB_ICONEXCLAMATION*/);

            pNewFileFullName = pFileFullName;
          }
          nOpen = 1;
        }
      }
    }
    else
    {
      AkelPad.Command(4106); // SaveAs...
      WScript.Quit();
    }
    break;

  case 1: // Copy
    if (pFileFullName)
    {
      if (pDir == "%f")
        pDir = pFileDir + "\\" + AkelPad.GetFilePath(pFileFullName, 3 /*CPF_FILEBASENAME*/);

      if (!pDir || !CreateDirectory(pDir))
        pDir = pFileDir;

      if (pFile)
      {
        if (pExt) pExt = "." + pExt;
        pNewFileFullName = NextFileName(pDir + "\\" + pFile + pExt);
      }
      else
        pNewFileFullName = NextFileName(pDir + "\\" + AkelPad.GetFilePath(pFileFullName, 2 /*CPF_FILENAME*/));

      if (IsTooLongPath(pNewFileFullName))
        WScript.Quit();

      //Copy File
      if (oSys.Call("kernel32::CopyFile" + _TCHAR, pFileFullName, pNewFileFullName, true))
      {
        if (!nOpen)
        {
          if (AkelPad.MessageBox(
                hMainWnd,
                sCreateBack.replace(/%s/, pNewFileFullName),
                pScriptName, 324 /*MB_YESNO|MB_ICONINFORMATION|MB_DEFBUTTON2*/)
              == 6 /*IDYES*/)
            nOpen = 1;
        }
      }
      else
      {
        AkelPad.MessageBox(
          hMainWnd,
          sErrorOccurred.replace(/%s/, "" + oSys.GetLastError()),
          pScriptName, 48 /*MB_ICONEXCLAMATION*/);
        nOpen = 0;
      }

      if (nOpen)
        GetDocumentState();
    }
    else
    {
      AkelPad.Command(4106); // SaveAs...
      WScript.Quit();
    }
    break;

  case 2: // Save
    if (pFileFullName)
    {
      if (pDir == "%f")
        pDir = pFileDir + "\\" + AkelPad.GetFilePath(pFileFullName, 3 /*CPF_FILEBASENAME*/);

      if (!pDir || !CreateDirectory(pDir))
        pDir = pFileDir;

      if (pFile)
      {
        if (pExt) pExt = "." + pExt;
        pNewFileFullName = NextFileName(pDir + "\\" + pFile + pExt);
      }
      else
        pNewFileFullName = NextFileName(pDir + "\\" + AkelPad.GetFilePath(pFileFullName, 2 /*CPF_FILENAME*/));
    }
    else // New tab
    {
      if (pDir && (pDir != "%f"))
      {
        if (!CreateDirectory(pDir))
        {
          AkelPad.Command(4106); // SaveAs...
          WScript.Quit();
        }

        pExt = GetAliasExt(hWndEdit, 0) || GetDefaultExt(hMainWnd);

        if (pFile)
        {
          if (pExt) pExt = "." + pExt;
          pNewFileFullName = NextFileName(pDir + "\\" + pFile + pExt);
        }
        else
        {
          pFileDir = pDir;
          nUpdate = 1;
          nOpen = 0;

          InputDialog();

          if (!pNewFileFullName)
            WScript.Quit();
        }
      }
      else
      {
        AkelPad.Command(4106); // SaveAs...
        WScript.Quit();
      }
    }

    if (IsTooLongPath(pNewFileFullName))
      WScript.Quit();

    GetDocumentState();

    //Save File
    if (AkelPad.SaveFile(hWndEdit, pNewFileFullName, nCodePage, nBOM, nUpdate) == 0 /*ESD_SUCCESS*/)
    {
      if (!nOpen && !nUpdate)
      {
        if (AkelPad.MessageBox(
              hMainWnd,
              sCreateBack.replace(/%s/, pNewFileFullName),
              pScriptName, 324 /*MB_YESNO|MB_ICONINFORMATION|MB_DEFBUTTON2*/)
            == 6 /*IDYES*/)
          nOpen = 1;
      }
    }
    else nOpen = 0;
    break;
}

// Open file
if (nOpen)
{
  if (AkelPad.OpenFile(pNewFileFullName, 0, nCodePage, nBOM) == 0 /*EOD_SUCCESS*/)
    RestoreDocumentState();
}

AkelPad.MemFree(lpCaret);
AkelPad.MemFree(lpSelect);
AkelPad.MemFree(lpPoint64);

function GetDocumentState()
{
  if (lpPoint64 = AkelPad.MemAlloc(_X64?16:8 /*sizeof(POINT64)*/))
    SendMessage(hWndEdit, 3179 /*AEM_GETSCROLLPOS*/, 0, lpPoint64);

  if (lpSelect = AkelPad.MemAlloc(_X64?56:32 /*sizeof(AESELECTION)*/))
  {
    if (lpCaret = AkelPad.MemAlloc(_X64?24:12 /*sizeof(AECHARINDEX)*/))
      SendMessage(hWndEdit, 3125 /*AEM_GETSEL*/, lpCaret, lpSelect);
  }

  nCodePage = AkelPad.GetEditCodePage(hWndEdit);
  nBOM = AkelPad.GetEditBOM(hWndEdit);

  if (AkelPad.IsPluginRunning("LineBoard::Main"))
    pBookmarks = GetBookmarksString(hWndEdit, 0);
  if (AkelPad.IsPluginRunning("Coder::HighLight"))
  {
    aCurMarks = GetMarks();
    pAlias = GetAlias(hWndEdit, 0);
  }
}

function RestoreDocumentState()
{
  var hWndEdit = AkelPad.GetEditWnd();
  var dwFlags;

  if (lpSelect)
  {
    dwFlags = AkelPad.MemRead(_PtrAdd(lpSelect, _X64 ? 48 : 24) /*offsetof(AESELECTION, dwFlags)*/, 3 /*DT_DWORD*/);
    AkelPad.MemCopy(_PtrAdd(lpSelect, _X64 ? 48 : 24) /*offsetof(AESELECTION, dwFlags)*/,
                    dwFlags|0x808 /*AESELT_LOCKSCROLL|AESELT_INDEXUPDATE*/,
                    3 /*DT_DWORD*/);
    if (lpCaret)
      SendMessage(hWndEdit, 3126 /*AEM_SETSEL*/, lpCaret, lpSelect);
  }

  if (lpPoint64)
    SendMessage(hWndEdit, 3180 /*AEM_SETSCROLLPOS*/, 0, lpPoint64);

  WScript.Sleep(50);

  if (AkelPad.IsPluginRunning("LineBoard::Main"))
    AkelPad.Call("LineBoard::Main", 13, hWndEdit, 0, pBookmarks);
  if (AkelPad.IsPluginRunning("Coder::HighLight"))
  {
    SetMarks(aCurMarks);
    AkelPad.Call("Coder::Settings", 6, pAlias);
  }
  if (AkelPad.IsPluginRunning("Explorer::Main"))
     AkelPad.Call("Explorer::Main", 2);
}

function InputDialog()
{
  var pClassName = "AkelPad::Scripts::" + pScriptName + "::" + oSys.Call("kernel32::GetCurrentProcessId");
  var hSubClass;
  var hWndName = 0;
  var hWndExt  = 0;
  var hWndOk   = 0;

  //Control IDs
  var ID_EDT_NAME   = 1001;
  var ID_EDT_EXT    = 1002;
  var ID_BTN_MENU   = 1003;
  var ID_BTN_OK     = 1004;
  var ID_BTN_CANCEL = 1005;
  var ID_STATIC     =   -1;

  if (AkelPad.WindowRegisterClass(pClassName))
  {
    //0x50000000=WS_VISIBLE|WS_CHILD
    //0x50010000=WS_VISIBLE|WS_CHILD|WS_TABSTOP
    //0x50010001=WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_DEFPUSHBUTTON
    //0x50810080=WS_VISIBLE|WS_CHILD|WS_TABSTOP|WS_BORDER|ES_AUTOHSCROLL
    //0x90C80840=DS_SETFONT|WS_VISIBLE|WS_POPUP|WS_CAPTION|WS_SYSMENU|DS_CENTER
    AkelPad.CreateDialog(
      0,
      pClassName,
      (!nAction ? sRename : sSaveAs),
      0x90C80840,
      10,
      10,
      270,
      63,
      hMainWnd,
      DialogCallback,
      0x1, //CDF_MODAL
      "|",
    //ExSt, Class,    Title,        Style,        X,  Y,   W,  H, ID,            lParam
      0x00, "STATIC", sNewFileName, 0x50000000,   8,  8, 195, 10, ID_STATIC,     0, "|",
      0x00, "STATIC", sExtension,   0x50000000, 212,  8,  50, 10, ID_STATIC,     0, "|",
      0x00, "STATIC", "\u2022",     0x50000000, 206, 25,   5, 10, ID_STATIC,     0, "|",
      0x00, "EDIT",   "",           0x50810080,   8, 20, 195, 14, ID_EDT_NAME,   0, "|",
      0x00, "EDIT",   "",           0x50810080, 212, 20,  50, 14, ID_EDT_EXT,    0, "|",
      0x00, "BUTTON", "...",        0x50010000,   8, 40,  15, 15, ID_BTN_MENU,   0, "|",
      0x00, "BUTTON", "OK",         0x50010001, 154, 40,  50, 15, ID_BTN_OK,     0, "|",
      0x00, "BUTTON", sCancel,      0x50010000, 212, 40,  50, 15, ID_BTN_CANCEL, 0
    );

    AkelPad.WindowUnregisterClass(pClassName);
  }

  function DialogCallback(hWnd, uMsg, wParam, lParam)
  {
    switch (uMsg)
    {
      case 272: // WM_INITDIALOG
          hWndName = oSys.Call("User32::GetDlgItem", hWnd, ID_EDT_NAME);
          hWndExt  = oSys.Call("User32::GetDlgItem", hWnd, ID_EDT_EXT);
          hWndOk   = oSys.Call("User32::GetDlgItem", hWnd, ID_BTN_OK);

          SetWindowFont(hWndName);
          SetWindowFont(hWndExt);

          SendMessage(hWndName, 197 /*EM_LIMITTEXT*/ , 260 /*MAX_PATH*/, 0);
          SendMessage(hWndName, 194 /*EM_REPLACESEL*/,   0,
            AkelPad.GetFilePath(pFileFullName, 3 /*CPF_FILEBASENAME*/));
          SendMessage(hWndExt,  197 /*EM_LIMITTEXT*/ , 260 /*MAX_PATH*/, 0);
          SendMessage(hWndExt,  194 /*EM_REPLACESEL*/,   0, pExt);

          //Устанавливаем раскладку клавиатуры, как в AkelPad
          SetKeyboardLayout(hMainWnd);
          break;

      case 273: // WM_COMMAND
          var nID   = wParam & 0xffff;
          var nCode = wParam >> 16;

          if (nID == ID_BTN_MENU)
          {
            ContextMenu(hWnd, lParam);
            oSys.Call("User32::SetFocus", hWndName);
          }
          else if ( (nID == ID_EDT_NAME) || (nID == ID_EDT_EXT) )
          {
            if (nCode == 0x0100 /*EN_SETFOCUS*/)
            {
              oSys.Call("User32::PostMessageW", lParam, 177 /*EM_SETSEL*/, 0, -1);
              hSubClass = AkelPad.WindowSubClass(lParam, EditCallback, 258 /*WM_CHAR*/);
            }
            else if (nCode == 0x0200 /*EN_KILLFOCUS*/)
              AkelPad.WindowUnsubClass(lParam);

            if (nID == ID_EDT_NAME)
              oSys.Call("user32::EnableWindow", hWndOk, GetEditTextLength(hWndName));
          }
          else if (nID == ID_BTN_OK)
          {
            if (pNewFileFullName = GetNewFileFullName())
              oSys.Call("User32::EndDialog", hWnd, 0);
            else
              oSys.Call("user32::SetFocus", hWndName);
          }
          else if ((nID == ID_BTN_CANCEL) || (nID == 2 /*IDCANCEL*/))
          {
            pNewFileFullName = "";
            oSys.Call("User32::EndDialog", hWnd, 0);
          }
          break;
    }
    return 0;
  }

  function EditCallback(hWnd, uMsg, wParam, lParam)
  {
    var nID = oSys.Call("User32::GetDlgCtrlID", hWnd);

    if (uMsg == 258 /*WM_CHAR*/)
    {
      if ((nID == ID_EDT_NAME) || (nID == ID_EDT_EXT))
      {
        if ( (wParam == 34 /*"*/) || (wParam == 42 /***/) || (wParam == 47 /*/*/) ||
             (wParam == 58 /*:*/) || (wParam == 60 /*<*/) || (wParam == 62 /*>*/) ||
             (wParam == 63 /*?*/) || (wParam == 92 /*\*/) || (wParam == 124 /*|*/) )

          AkelPad.WindowNoNextProc(hSubClass);
      }
    }
    return 0;
  }

  function GetEditText(hWndEdit)
  {
    var nTextLen = GetEditTextLength(hWndEdit) + 1;
    var lpText = AkelPad.MemAlloc(nTextLen * 2);
    var pText = "";

    SendMessage(hWndEdit, 13 /*WM_GETTEXT*/, nTextLen, lpText);
    pText = AkelPad.MemRead(lpText, 1 /*DT_UNICODE*/);
    AkelPad.MemFree(lpText);

    return pText;
  }

  function GetEditTextLength(hWnd)
  {
    return SendMessage(hWnd, 14 /*WM_GETTEXTLENGTH*/, 0, 0);
  }

  function SetKeyboardLayout(hWnd)
  {
    var nEditThreadId = oSys.Call("user32::GetWindowThreadProcessId", hWnd, 0);
    var nLang = oSys.Call("user32::GetKeyboardLayout", nEditThreadId);
    oSys.Call("user32::ActivateKeyboardLayout", nLang, 0);
  }

  function SetWindowFont(hWnd)
  {
    var nLFSize = 28 + 32 * 2; //sizeof(LOGFONTW)
    var lpLF    = AkelPad.MemAlloc(nLFSize);
    var nHeight = 10;
    var hFont;
    var hDC =  oSys.Call("User32::GetDC", hMainWnd);
    nHeight = -oSys.Call("Kernel32::MulDiv", nHeight,
               oSys.Call("Gdi32::GetDeviceCaps", hDC, 90 /*LOGPIXELSY*/), 72);
    oSys.Call("User32::ReleaseDC", hMainWnd, hDC);

    AkelPad.MemCopy(_PtrAdd(lpLF,  0), nHeight,           3 /*DT_DWORD*/);   //lfHeight
    AkelPad.MemCopy(_PtrAdd(lpLF, 16), 400 /*FW_NORMAL*/, 3 /*DT_DWORD*/);   //lfWeight
    AkelPad.MemCopy(_PtrAdd(lpLF, 20), false,             5 /*DT_BYTE*/);    //lfItalic
    AkelPad.MemCopy(_PtrAdd(lpLF, 28), "MS Shell Dlg",    1 /*DT_UNICODE*/); //lfFaceName

    hFont = oSys.Call("Gdi32::CreateFontIndirectW", lpLF);
    AkelPad.MemFree(lpLF);

    SendMessage(hWnd, 48 /*WM_SETFONT*/, hFont, true);
  }

  function ContextMenu(hWndDlg, hWndCtrl)
  {
    var hMenu = oSys.Call("User32::CreatePopupMenu");
    var rcRect = GetWindowRect(hWndCtrl);
    var nFlags;
    var nCmd;
    var pText;

    nFlags = SendMessage(hWndEdit, 3125 /*AEM_GETSEL*/, 0, 0) ? 0x0 /*MF_STRING*/ : 0x1 /*MF_GRAYED*/;
    oSys.Call("User32::AppendMenuW", hMenu, nFlags, 1, sSelTextName);

    nFlags = SendMessage(hWndEdit, 193 /*EM_LINELENGTH*/, 0, 0) ? 0x0 /*MF_STRING*/ : 0x1 /*MF_GRAYED*/;
    oSys.Call("User32::AppendMenuW", hMenu, nFlags, 2, sFirstStrName);

    nFlags = GetEditTextLength(hWndName) ? 0x0 /*MF_STRING*/ : 0x1 /*MF_GRAYED*/;
    oSys.Call("User32::AppendMenuW", hMenu, 0x0800 /*MF_SEPARATOR*/, 0, 0);
    oSys.Call("User32::AppendMenuW", hMenu, nFlags, 3, sSpaceUnderscore);
    oSys.Call("User32::AppendMenuW", hMenu, nFlags, 4, sUnderscoreSpace);
    oSys.Call("User32::AppendMenuW", hMenu, nFlags, 5, sDeleteSpace);
    oSys.Call("User32::AppendMenuW", hMenu, 0x0800 /*MF_SEPARATOR*/, 0, 0);
    oSys.Call("User32::AppendMenuW", hMenu, nFlags, 6, sDividedInWords);

    nCmd = oSys.Call("User32::TrackPopupMenu",
      hMenu, 0x180 /*TPM_NONOTIFY|TPM_RETURNCMD*/, rcRect.left, rcRect.bottom, 0, hWndDlg, 0);

    oSys.Call("User32::DestroyMenu", hMenu);

    if (nCmd == 1)
      pText = CorrectFileName(AkelPad.GetSelText(3 /*"\r\n"*/));
    else if (nCmd == 2)
    {
      pText = AkelPad.GetTextRange(0, SendMessage(hWndEdit, 193 /*EM_LINELENGTH*/, 0, 0));
      pText = CorrectFileName(pText);
    }
    else if (nCmd == 3)
      pText = GetEditText(hWndName).replace(/ /g, "_");
    else if (nCmd == 4)
      pText = GetEditText(hWndName).replace(/_/g, " ");
    else if (nCmd == 5)
      pText = GetEditText(hWndName).replace(/ /g, "");
    else if (nCmd == 6)
      pText = String2Words(GetEditText(hWndName)); // ReadMe -> Read Me

    if (pText)
    {
      SendMessage(hWndName, 177 /*EM_SETSEL*/, 0, -1);
      SendMessage(hWndName, 194 /*EM_REPLACESEL*/, true, pText);
    }
  }

  function GetWindowRect(hWnd)
  {
    var lpRect = AkelPad.MemAlloc(16); //sizeof(RECT)
    var rcRect = [];

    oSys.Call("User32::GetWindowRect", hWnd, lpRect);

    rcRect.left   = AkelPad.MemRead(_PtrAdd(lpRect, 0) /*offsetof(RECT, left)*/, 3 /*DT_DWORD*/);
    rcRect.bottom = AkelPad.MemRead(_PtrAdd(lpRect, 12) /*offsetof(RECT, bottom)*/, 3 /*DT_DWORD*/);

    AkelPad.MemFree(lpRect);
    return rcRect;
  }

  function String2Words(pStr)
  {
    var aWord = pStr.split('');
    var pUCase;

    for (var i = 0; i < aWord.length; ++i)
    {
      pUCase = aWord[i].toUpperCase();

      if (pUCase != aWord[i].toLowerCase()) //symbol
      {
        if (pUCase == aWord[i])
          aWord[i] = " " + aWord[i];
      }
    }

    aWord = aWord.join('');
    aWord = aWord.replace(/ +/g, " ");
    aWord = aWord.replace(/^ +| +$/gm, "");

    return aWord;
  }

  function GetNewFileFullName()
  {
    var pNewFile = CorrectFileName(GetEditText(hWndName));
    var pExt     = CorrectFileName(GetEditText(hWndExt));

    if (pExt) pExt = "." + pExt;
    pNewFile = pFileDir + "\\" + pNewFile + pExt;

    if (IsTooLongPath(pNewFile))
      return "";

    if (GetFileAttributes(pNewFile) != -1 /*INVALID_FILE_ATTRIBUTES*/)
    {
      AkelPad.MessageBox(hMainWnd, sFileExists.replace(/%s/, pNewFile), pScriptName, 48 /*MB_ICONEXCLAMATION*/);
      return "";
    }
    return pNewFile;
  }
}

function GetFileAttributes(pPath)
{
  return oSys.Call("kernel32::GetFileAttributes" + _TCHAR, pPath);
}

function NextFileName(pPath)
{
  var pDir  = AkelPad.GetFilePath(pPath, 1 /*CPF_DIR*/);
  var pName = AkelPad.GetFilePath(pPath, 3 /*CPF_FILEBASENAME*/);
  var pExt  = AkelPad.GetFilePath(pPath, 4 /*CPF_FILEEXT*/);
  var sB;
  var sA;
  var bB = false;
  var i  = 0;

  pPost = pPost.replace(/%d/, "" + TimeFormat(pData));
  pPref = pPref.replace(/%d/, "" + TimeFormat(pData));

  sA = pPost.replace(/%n/, i);
  sB = pPref.replace(/%n/, i);

  if (sA != pPost || sB != pPref)
    bB = true;

  if (pExt) pExt = "." + pExt;
  pPath = pDir + "\\" + CorrectFileName(sB + pName + sA) + pExt;

  while (GetFileAttributes(pPath) != -1 /*INVALID_FILE_ATTRIBUTES*/)
  {
    ++i;

    if (bB)
    {
      sB = pPref.replace(/%n/, i);
      sA = pPost.replace(/%n/, i);
      pPath = pDir + "\\" + sB + pName + sA + pExt;
    }
    else
      pPath = pDir + "\\" + sB + pName + sA + i + pExt;
  }

  return pPath;
}

function CorrectFileName(pFileName)
{
  pFileName = pFileName.replace(/[\r\n|\n|\r]/gm, " ");
  pFileName = pFileName.replace(/\t+/g, " ");
  pFileName = pFileName.replace(/[\\\/:\*\?"<>\|]/g, "");
  pFileName = pFileName.replace(/ {2,}/g, " ");
  pFileName = pFileName.replace(/(^ +)|( +$)/g, "");
  return pFileName;
}

function CreateDirectory(pDirPath)
{
  oSys.Call("Shell32::SHCreateDirectory", 0, pDirPath);
  if (GetFileAttributes(pDirPath) & 16 /*FILE_ATTRIBUTE_DIRECTORY*/)
    return true;
  return false;
}

function IsTooLongPath(pPath)
{
  if (pPath.length >= 260 /*MAX_PATH*/)
  {
    AkelPad.MessageBox(
      hMainWnd,
      sTooLongPath.replace(/%s/, pPath.length),
      pScriptName, 48 /*MB_ICONEXCLAMATION*/);
    return true;
  }
  return false;
}

function GetAlias(hWndEdit, hDocEdit)
{
  var pAlias = "";
  var lpAlias;

  if (lpAlias = AkelPad.MemAlloc(256 * 2 /*sizeof(wchar_t)*/))
  {
    AkelPad.CallW("Coder::Settings", 18, hWndEdit, hDocEdit, lpAlias, 0);
    pAlias = AkelPad.MemRead(lpAlias, 1 /*DT_UNICODE*/);
    AkelPad.MemFree(lpAlias);
  }
  return pAlias;
}

function GetAliasExt(hWndEdit, hDocEdit)
{
  return AkelPad.GetFilePath(GetAlias(hWndEdit, hDocEdit), 4 /*CPF_FILEEXT*/);
}

function GetDefaultExt(hWnd)
{
  var pDefExt = "txt";
  var lParam;

  if (lParam = AkelPad.MemAlloc(256))
  {
    SendMessage(hWnd, 1222 /*AKD_GETMAININFO*/, 224 /*MI_DEFAULTSAVEEXT*/, lParam);
    pDefExt = AkelPad.MemRead(lParam, 1 /*DT_UNICODE*/);
    AkelPad.MemFree(lParam);

    if (!pDefExt)
      pDefExt = "txt";
  }
  return pDefExt;
}

function GetBookmarksString(hWndEdit, hDocEdit)
{
  var pBookmarksStr = "";
  var lpBookmarksStr;
  var nBookmarksLen;
  var lpBookmarksLen;

  if (lpBookmarksLen = AkelPad.MemAlloc(4 /*sizeof(int)*/))
  {
    AkelPad.CallW("LineBoard::Main", 12, hWndEdit, hDocEdit, 0, lpBookmarksLen);

    if ((nBookmarksLen = AkelPad.MemRead(lpBookmarksLen, 3 /*DT_DWORD*/)) > 1)
    {
      if (lpBookmarksStr = AkelPad.MemAlloc(nBookmarksLen * 2 /*sizeof(wchar_t)*/))
      {
        AkelPad.CallW("LineBoard::Main", 12, hWndEdit, hDocEdit, lpBookmarksStr, 0);
        pBookmarksStr = AkelPad.MemRead(lpBookmarksStr, 1 /*DT_UNICODE*/);
        AkelPad.MemFree(lpBookmarksStr);
      }
    }
    AkelPad.MemFree(lpBookmarksLen);
  }
  return pBookmarksStr;
}

function GetMarks()
{
  var lpStack;
  var lpMarkText;
  var dwMarkID;
  var lpMarkItem;
  var lpText;
  var pText;
  var nFlags;
  var nMatchCase;
  var nWholeWord;
  var nRegExp;
  var nFontStyle;
  var sTextColor;
  var sBkColor;
  var aMarks = [];

  if (lpStack = AkelPad.MemAlloc(_X64?16:8 /*sizeof(STACKMARKTEXT)*/))
  {
    AkelPad.Call("Coder::HighLight", 12 /*DLLA_HIGHLIGHT_GETMARKSTACK*/, hWndEdit, AkelPad.GetEditDoc(), lpStack);
    lpMarkText = AkelPad.MemRead(_PtrAdd(lpStack, 0) /*offsetof(STACKMARKTEXT,first)*/, 2 /*DT_QWORD*/);

    while (lpMarkText)
    {
      dwMarkID = AkelPad.MemRead(_PtrAdd(lpMarkText, _X64?24:12) /*offsetof(MARKTEXT,dwMarkID)*/, 3 /*DT_DWORD*/);

      if (dwMarkID != -2 /*MARKID_SELECTION*/)
      {
        lpMarkItem = AkelPad.MemRead(_PtrAdd(lpMarkText, _X64?16:8) /*offsetof(MARKTEXT,hMarkTextHandle)*/, 2 /*DT_QWORD*/);
        lpText = AkelPad.MemRead(_PtrAdd(lpMarkItem, _X64?24:12) /*offsetof(AEMARKTEXTITEMW,pMarkText)*/, 2 /*DT_QWORD*/);
        pText = AkelPad.MemRead(lpText, 1 /*DT_UNICODE*/);
        nFlags = AkelPad.MemRead(_PtrAdd(lpMarkItem, _X64?36:20) /*offsetof(AEMARKTEXTITEMW,dwFlags)*/, 3 /*DT_DWORD*/);
        nMatchCase = (nFlags & 0x00000001/*AEHLF_MATCHCASE*/) ? 1:0;
        nWholeWord = (nFlags & 0x00000002/*AEHLF_WHOLEWORD*/) ? 1:0;
        nRegExp    = (nFlags & 0x10000000/*AEHLF_REGEXP*/)    ? 1:0;
        nFontStyle = AkelPad.MemRead(_PtrAdd(lpMarkItem, _X64?40:24) /*offsetof(AEMARKTEXTITEMW,dwFontStyle)*/, 3 /*DT_DWORD*/);
        sTextColor = RGBToHex(_PtrAdd(lpMarkItem, _X64?44:28) /*offsetof(AEMARKTEXTITEMW,crText)*/);
        sBkColor   = RGBToHex(_PtrAdd(lpMarkItem, _X64?48:32) /*offsetof(AEMARKTEXTITEMW,crBk)*/);

        aMarks.push([sTextColor, sBkColor, nMatchCase|4*nWholeWord|2*nRegExp, nFontStyle, dwMarkID, pText]);
      }
      lpMarkText = AkelPad.MemRead(_PtrAdd(lpMarkText, 0) /*offsetof(MARKTEXT,next)*/, 2 /*DT_QWORD*/);
    }
    AkelPad.MemFree(lpStack);

    return aMarks;
  }
}

function RGBToHex(lpRGB)
{
  var sHex = "0";
  var sByte;

  if (AkelPad.MemRead(lpRGB, 3 /*DT_DWORD*/) != -1)
  {
    sHex = "#";

    for (var i = 0; i < 3; ++i)
    {
      sByte = AkelPad.MemRead(_PtrAdd(lpRGB, i), 5 /*DT_BYTE*/).toString(16).toUpperCase();

      if (sByte.length == 1)
        sByte = "0" + sByte;

      sHex += sByte;
    }
  }
  return sHex;
}

function SetMarks(aMarks)
{
  for (var i = 0; i < aMarks.length; ++i)
    AkelPad.Call(
      "Coder::HighLight",
      2,
      aMarks[i][0],
      aMarks[i][1],
      aMarks[i][2],
      aMarks[i][3],
      aMarks[i][4],
      aMarks[i][5]
    );
}

//Функция из скрипта InsertDate.js (v.1.0) Shengalts Aleksander aka Instructor
//http://akelpad.sourceforge.net/en/plugins.php#Scripts
function TimeFormat(pFormat)
{
  var lpFormatBuffer;
  var lpTimeBuffer;
  var pTime="";

  if (lpFormatBuffer=AkelPad.MemAlloc(256 * _TSIZE))
  {
    AkelPad.MemCopy(lpFormatBuffer, pFormat.substr(0, 255), _TSTR);

    if (lpTimeBuffer=AkelPad.MemAlloc(256 * _TSIZE))
    {
      oSys.Call("kernel32::GetTimeFormat" + _TCHAR, 1024 /*LOCALE_USER_DEFAULT*/, 0, 0, lpFormatBuffer, lpTimeBuffer);
      oSys.Call("kernel32::GetDateFormat" + _TCHAR, 1024 /*LOCALE_USER_DEFAULT*/, 0, 0, lpTimeBuffer, lpFormatBuffer, 256);
      pTime=AkelPad.MemRead(lpFormatBuffer, _TSTR);

      AkelPad.MemFree(lpTimeBuffer);
    }
    AkelPad.MemFree(lpFormatBuffer);
  }
  return pTime;
}

function SendMessage(hWnd, uMsg, wParam, lParam)
{
  return oSys.Call("User32::SendMessageW", hWnd, uMsg, wParam, lParam);
}

function GetLangStrings()
{
  if (AkelPad.GetLangId(1 /*LANGID_PRIMARY*/) == 0x19 /*LANG_RUSSIAN*/)
  {
      sNewFileName     = "Новое имя файла";
      sExtension       = "Расширение";
      sSelTextName     = "Заменить выделенным текстом";
      sFirstStrName    = "Заменить текстом первой строки";
      sSpaceUnderscore = "Заменить пробелы на знак ''_''";
      sUnderscoreSpace = "Заменить пробелами знак ''_''";
      sDeleteSpace     = "Удалить пробелы";
      sDividedInWords  = "FileName -> File Name";
      sRename          = "Переименовать";
      sSaveAs          = "Сохранить как...";
      sCancel          = "Отмена";
      sErrorOccurred   = "Произошла ошибка: код %s.";
      sPathNotFound    = "Путь не найден\n\"%s\".";
      sTooLongPath     = "Слишком длинное имя файла: %s.";
      sFileExists      = "Файл \"%s\" уже существует.";
      sCreateFile      = "Создать новый файл \"%s\"?";
      sParamError      = "Параметры содержат запрещенные символы.";
      sCreateBack      = "Резервная копия создана.\n\nОткрыть файл \"%s\"?";
  }
  else
  {
      sNewFileName     = "New file name";
      sExtension       = "Extension";
      sSelTextName     = "Selected text -> file name";
      sFirstStrName    = "First line text -> file name";
      sSpaceUnderscore = "Spaces -> ''_''";
      sUnderscoreSpace = "''_'' -> Spaces";
      sDeleteSpace     = "Delete spaces";
      sDividedInWords  = "FileName -> File Name";
      sRename          = "Rename";
      sSaveAs          = "Save As...";
      sCancel          = "Cancel";
      sErrorOccurred   = "An error has occurred: code %s.";
      sPathNotFound    = "Path Not Found\n\"%s\".";
      sTooLongPath     = "Too long filename: %s.";
      sFileExists      = "File \"%s\" already exists.";
      sCreateFile      = "Create a new file \"%s\"?";
      sParamError      = "Parameters contain forbidden characters.";
      sCreateBack      = "A backup copy created.\n\nOpen file \"%s\"?";
  }
  return "";
}
Last edited by Kley on Wed May 25, 2016 4:46 pm, edited 4 times in total.

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

Post by VladSh »

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=28716#p28716
// Description(1033): Pack/unpack of archives with 7-zip
// Description(1049): Запаковка/распаковка архивов с помощью 7-zip
// Version: 1.0 (2015.04.24)
// Author: VladSh 

// Arguments:
//    -action: [0] - pack, 1 - unpack
//    the descriptions of the other arguments see in \Include\ShowMenuEx.js
// 
// Parameters pack7zip.ini:
//    toolreg - the paths to 7-zip tool dir in Windows registry; separator: ';'
//    tooldir - the dir with 7-zip tool
//    archtype: -tzip - for zip-archives, "" or without parameter - it will created 7z-archive; it is default value which will be rewrited in a config of json-file
//    pExt    - can be used instead -pExt-argument (see ShowMenuEx.js)
// 
// Example of pack7zip.ini:
//  [Options]
//  toolreg=HKEY_CURRENT_USER\Software\7-Zip\Path;HKEY_LOCAL_MACHINE\SOFTWARE\7-Zip\Path
//  tooldir=c:\Program Files\7-Zip\
//  archtype=-tzip
//  pExt=json
// 
// Parameters *.json, or they can be set in arguments:
//    archtype - has more priority then corresponding ini parameter
//    archOptions - additional 7z-options
//    workdir  - the folder which will archived or where the archive will extracted
//    inclist  - the files list, which will be included to the archiving
//    exclist  - the files list, which will be excluded from the archiving
//    outfile  - the result file for pack or the source file for unpack
// 
// Example of one config in *.json-file for this script
//  {
//     "id": {   // id - for -pID argument
//        "name": "name (label) of this config which will showed in menu",
//        "options": {
//           "archOptions": "-spf -y",
//           "workdir":     "%a",
//           "inclist":     "%o\\pack7zip\\AkelPadSettings\\IncludeList.txt",
//           "outfile":     "d:\\Downloads\\INSTALL\\Text\\AkelPad\\AkelPadSettings.zip"
//        }
//     }
//  }
// 
// Usage:
//    -"Pack with configs dialog" Call("Scripts::Main", 1, "pack7zip.js", `-pExt="json"`)
//    -"Pack with configs dialog" Call("Scripts::Main", 1, "pack7zip.js") - same, bacause pExt=json was set in pack7zip.ini
//    -"Backup AkelPad folder" Call("Scripts::Main", 1, "pack7zip.js", `-pFile="packAkelPad.json" -pID="AkelPadFolder"`)
//    -"Unpack with configs dialog" Call("Scripts::Main", 1, "pack7zip.js", `-pExt="json" -action=1`)

var action = AkelPad.GetArgValue('action', 0);

if (! AkelPad.Include("ShowMenuEx.js")) WScript.Quit();

initIniOptions(['toolreg', 'tooldir', 'archtype']);

var toolexe = '7z.exe';
var toolpath;
if (opts['toolreg']) {
	toolpath = getToolPathReg(toolexe);
}
if (!toolpath) {
	toolpath = expandPath(opts['tooldir']) + toolexe;
	checkFilePath("7-zip", toolpath);
}

if (!initMenuParams(POS_CURSOR)) WScript.Quit();

var workdir = expandPath(opts['workdir']);
var outfile = expandPath(opts['outfile']);
var archOptions = opts['archOptions'];
var cmdline;

if (action) {
	checkFilePath("Output file", outfile);
	
	cmdline = toolpath + ' e "' + outfile + '" -o"' + workdir + '" ' + archOptions;
	
	AkelPad.Call("Log::Output", 1, cmdline, "", "", "", -1, -1);
}
else {
	checkDirPath(workdir);
	
	cmdline = toolpath + ' u ' + archOptions + ' ' + opts['archtype'] + ' "' + outfile + '"';
	
	var inclist = expandPath(opts['inclist']);
	var exclist = expandPath(opts['exclist']);
	if (inclist)
		cmdline += ' @"' + inclist + '"';
	if (exclist)
		cmdline += ' -x@"' + exclist + '"';
	
	AkelPad.Call("Log::Output", 1, cmdline, workdir, "", "", -1, -1);
}

function getToolPathReg(toolexe) {
	var result;
	var regpath = opts['toolreg'].split(';');
	for (var p in regpath) {
		try {
			result = expandPath(WshShell.RegRead(regpath[p])) + toolexe;
			if (fso.FileExists(result)) break;
		}
		catch (e) {
			if (bDebug) AkelPad.Call("Log::Output", 4, WScript.ScriptName + ": " + (e.message || e));
		}
	}
	return result;
}

Code: Select all

{
	"AkelPadSettings": {
		"name": "AkelPad Settings",
		"options": {
			"archOptions": "-spf -y",
			"workdir":     "%a",
			"inclist":     "%o\\pack7zip\\AkelPadSettings\\IncludeList.txt",
			"outfile":     "d:\\Downloads\\AkelPadSettings.zip"
		}
	},
	"ScriptsArchive": {
		"name": "Scripts archive",
		"options": {
			"archOptions": "-spf -y",
			"workdir":     "%s",
			"inclist":     "%o\\pack7zip\\ScriptsArchive.txt",
			"outfile":     "d:\\Downloads\\INSTALL\\Text\\AkelPad\\VladSh.zip"
		}
	}
}

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

Post by Instructor »

Fast macro execution and/or test how fast macro executed.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=29052#p29052
// Version: 1.1
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Fast macro execution and/or test how fast macro executed.
// Description(1049): Быстрое выполнение скрипта и/или тест скорости выполнения скрипта.
//
// Arguments:
// -Macro="MyMacro"     -Saved macro name. If "", then execute last recorded macro. Default is "".
// -Repeat=10           -Repeat count (default is 1).
// -NoRedraw=2          -Lock redraw for fast execution (one of the following):
//                         0  don't lock redraw.
//                         1  edit window (default).
//                         2  main window.
// -Test=true           -Show message with execution time and last error value (default is false).
//
// Usage:
// Call("Scripts::Main", 1, "MacroSpeed.js", `-Macro="MyMacro" -Repeat=0`)

//Arguments
var pMacro=AkelPad.GetArgValue("Macro", "");
var nRepeat=AkelPad.GetArgValue("Repeat", 1);
var nNoRedraw=AkelPad.GetArgValue("NoRedraw", 1);
var bTest=AkelPad.GetArgValue("Test", false);

//Variables
var hMainWnd=AkelPad.GetMainWnd();
var hWndEdit=AkelPad.GetEditWnd();
var oSys=AkelPad.SystemFunction();
var hWndLock=0;
var nTimeStart;
var nTimeEnd;
var lpdwLastError;
var dwLastError=0;

if (nNoRedraw == 1)
  hWndLock=hWndEdit;
else if (nNoRedraw == 2)
  hWndLock=hMainWnd;

if (lpdwLastError=AkelPad.MemAlloc(4 /*sizeof(DWORD)*/))
{
  if (bTest) nStartTime=oSys.Call("kernel32::GetTickCount");
  if (hWndLock) SetRedraw(hWndLock, false);

  //Execute macro
  AkelPad.Call("Macros::Main", 1, pMacro, nRepeat, 1 /*EMF_SCRIPTSNOSYNC*/);

  //Wait macro
  for (;;)
  {
    WScript.Sleep(100);
    AkelPad.Call("Macros::Main", 4, lpdwLastError);
    dwLastError=AkelPad.MemRead(lpdwLastError, 3 /*DT_DWORD*/);
    if (!(dwLastError & 0x0001 /*MS_PLAYING*/) && !(dwLastError & 0x1000 /*MS_INITIALIZING*/)) break;
  }

  if (hWndLock) SetRedraw(hWndLock, true);
  if (bTest)
  {
    nTimeEnd=oSys.Call("kernel32::GetTickCount");
    WScript.Echo("Time (ms)=" + (nTimeEnd - nStartTime) + "; Last error=" + dwLastError);
  }
  AkelPad.MemFree(lpdwLastError);
}

function SetRedraw(hWnd, nNoRedraw)
{
  AkelPad.SendMessage(hWnd, 11 /*WM_SETREDRAW*/, nNoRedraw, 0);
  if (nNoRedraw) oSys.Call("user32::InvalidateRect", hWnd, 0, true);
}
Post Reply