// http://akelpad.sourceforge.net/forum/viewtopic.php?p=25685#25685
// Version: 1.1
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Change printing paper orientation.
// Description(1049): Изменить ориентацию бумаги для печати.
//
// Arguments:
// -Orientation=1  -Paper orientation (one of the following):
//                    1  portrait.
//                    2  landscape.
// -Print=1        -Print current document (one of the following):
//                    0  don't print (default).
//                    1  print with dialog.
//                    2  silent print.
// Usage:
// Call("Scripts::Main", 1, "PrintOrientation.js", `-Orientation=2 -Print=2`)

//Arguments
var nOrientation=AkelPad.GetArgValue("Orientation", 0);
var nPrint=AkelPad.GetArgValue("Print", 0);

if (SetPaperOrientation(nOrientation))
{
  //Print with dialog
  if (nPrint == 1)
    AkelPad.Command(4108 /*IDM_FILE_PRINT*/);
  //Silent print
  else if (nPrint == 2)
    AkelPad.Command(4113 /*IDM_FILE_SILENTPRINT*/);
}

function SetPaperOrientation(nOrientation)
{
  var hMainWnd=AkelPad.GetMainWnd();
  var oSys=AkelPad.SystemFunction();
  var lpPrintInfo;
  var lpDevMode;
  var hDevMode;
  var hDC;
  var bResult=false;

  if (nOrientation == 1 /*DMORIENT_PORTRAIT*/ ||
      nOrientation == 2 /*DMORIENT_LANDSCAPE*/)
  {
    if (lpPrintInfo=AkelPad.MemAlloc(_X64?56:44 /*sizeof(PRINTINFO)*/))
    {
      if (AkelPad.SendMessage(hMainWnd, 1215 /*AKD_GETPRINTINFO*/, lpPrintInfo, true))
      {
        if (hDevMode=AkelPad.MemRead(_PtrAdd(lpPrintInfo, 0) /*offsetof(PRINTINFO, hDevMode)*/, 2 /*DT_QWORD*/))
        {
          //Set orientation
          if (lpDevMode=oSys.Call("kernel32::GlobalLock", hDevMode))
          {
            AkelPad.MemCopy(_PtrAdd(lpDevMode, _TSTR?76:44) /*offsetof(DEVMODE, dmOrientation)*/, nOrientation, 4 /*DT_WORD*/);
            bResult=true;
            oSys.Call("kernel32::GlobalUnlock", hDevMode);
          }

          //Free printer DC
          if (hDC=AkelPad.MemRead(_PtrAdd(lpPrintInfo, _X64?16:8) /*offsetof(PRINTINFO, hDC)*/, 2 /*DT_QWORD*/))
          {
            oSys.Call("gdi32::DeleteDC", hDC);
            AkelPad.MemCopy(_PtrAdd(lpPrintInfo, _X64?16:8) /*offsetof(PRINTINFO, hDC)*/, 0, 2 /*DT_QWORD*/);
          }

          //Copy information
          AkelPad.SendMessage(hMainWnd, 1216 /*AKD_SETPRINTINFO*/, lpPrintInfo, 0);
        }
      }
      AkelPad.MemFree(lpPrintInfo);
    }
  }
  return bResult;
}
