Macro_file menus;

#include windows.sh
#include metools.sh
#include menus.sh
#include mew.sh
#include db.sh
#include dialog.sh
#include mew_dlgs.sh


#define MAXMENUDEPTH  16
#define MAINMENU_HELPLINK "MENUS, CHANGING"
#define MOUSEMENU_HELPLINK "MENUS, RIGHT MOUSE BUTTON"
#define MDIMENU_HELPLINK ""

global
{
  str menuitems;
  str menusetname;
  str menuglo "!MENUGLO";
  int wcmdglo "!WCMDGLO";
  int menucount;
  str mainlist;
  str contextlist;
  str mdilist;
}

struct Menu
{
  int menus[16];
}

void LoadMenus (str name[40] = parse_str ("/N=", mparm_str))
{
  int oMenu  = GetMenu (frame_handle);

  MainMenuHandle = CreateMenuFromDB( wcmdmapname, name, MENU_Main );

  if ( MainMenuHandle != 0 )
  {
    SendMessage ( client_handle, WM_MDISETMENU , 0 , MainMenuHandle + (WindowMenu * 0x10000) );
    DrawMenuBar ( frame_handle );
    DestroyMenu ( oMenu );
  }
  else
    MainMenuHandle = oMenu;
}

int CreateMenuFromDb( str db[128], str name[40], int flags )
{
  return( CreateMenuFromDbEx( db, name, flags,0 ) );
}

int CreateMenuFromDBEx( str &db, str &name, int flags, int origmenuhandle  )
{
  int result = 0;
  struct Menu   nMenu;
  int first = 1;
  str xstr;
  str tstr[1024], lstr[2048];
  str mtext;
  int sep;
  int cmd;
  int k1, k2;
  int jx;
  int nlevel;
  int level   = 1;

  if ( name == "" )
  {
    name = "MAIN";
  }


  int oWin = cur_window;
  int tRefresh = refresh;
  refresh = False;

  if ( LocateDBPage (db, name + ".MNU", FALSE) )
  {

    nMenu.menus[0] = origmenuhandle;
    if(flags & MENU_Popup)
    {
      if(origmenuhandle == 0)
        nMenu.menus[0] = CreatePopupMenu;
    }
    else
    {
      if(origmenuhandle == 0)
        nMenu.menus[0] = CreateMenu;
      if ( flags & Menu_Main )
      {
        WindowMenu = 0;
        FileMenu   = 0;
      }
    }
    down;
    while( !at_eof && (cur_char != '|12'))
    {

      lstr = get_line;
      tstr = parse_str ("MENU=", lstr);
      nlevel = parse_int ("/IN=", tstr);

      if ( !first )
      {
        Call CheckItem;
      }
      else
      {
        first = 0;
      }

      mtext = parse_str ("/TX=", tstr);
      sep   = parse_int ("/SP=", tstr);
      cmd   = parse_int ("WCMD=", lstr);
      level = nlevel;
      down;
    }
    if ( !first )
    {
      Call CheckItem;
    }
    result = nMenu.menus[0];

  }

  switch_window (owin);
  refresh = tRefresh;
  return( result );

CheckItem:
  if(level < 1)
  {
    RM("messagebox /T=LOADMENUS ERROR/M=" + str(level) + " is not a valid menu level. Occurred at line " + str(c_line) +
      " of " + file_name );
    ret;
  }
  if (( level < nlevel ) || (((level == nlevel) && (level == 1)) && !(flags & MENU_PopUp)))
  {
    nMenu.menus[level] = CreatePopupMenu;

    AppendMenu( nMenu.menus[level-1], MF_STRING | MF_POPUP, nMenu.menus[level], mtext);

    // Check for the window menu
    if ( (mtext == "&Window") && (level == 1) && ((flags & Menu_Main) != 0))
    {
      WindowMenu = nMenu.menus[level];
    }
    if ( (mtext == "&File") && (level == 1) && ((flags & Menu_Main) != 0))
    {
      FileMenu = nMenu.menus[level];
    }
    if ( level < nlevel )
    {
      nlevel = level+1;
    }
  }
  else
  {
    if ( sep )
    {
      AppendMenu (nMenu.menus[level-1], MF_SEPARATOR, cmd, "");
    }
    else
    {
      if( Wcmd_Find( 0, cmd, jx, k1, k2, xstr, xstr))
      {
        if( k1 == 0)
          k1 = k2;

        if( k1 != 0 )
          mtext += "\t" + Make_Key_Name(k1 );
      }
      AppendMenu( nMenu.menus[level-1], MF_STRING, cmd, mtext);
    }
  }
  ret;
}

macro MenuDBIn()
{
	str gls = parse_str('/GLO=',mparm_str);
  str record[2048] = global_str(gls);
  str menuid = parse_str('MENUID=', record);
  int post = parse_int('/P=',mparm_str);
  int d = parse_int('/D=',mparm_str);
  int creat = parse_int('/CREATE=',mparm_str);
  int cancl = parse_int('/C=',mparm_str);
  int copying = parse_int('/COPY=',mparm_str);
  int moving = parse_int('/MOVE=', mparm_str);

  if(post | cancl)
  {
    var_remove_str("MENU=",record);
    var_remove_str("WCMD=",record);
    record = record + "MENU=/TX=" + parse_str("NAME=",record) +
                "/IN=" + parse_str("IN=", record ) +
                "/SP=" + str(wcmdglo == 6969) +
                "WCMD=" +  str(wcmdglo);
    var_remove_str("NAME=",record);
    var_remove_str("IN=",record);
    var_remove_str("CMD=",record);
    set_global_str(gls, record );
  }
  else
  {
    if( moving )
    {
      int t_level = parse_int("/IN=", parse_str("MENU=", get_line));

      goto_col(1);
      do
      {
        down;
      } while((!at_eof) && (cur_char != "\f") &&
              ( t_level < parse_int("/IN=", parse_str("MENU=", get_line))));
      block_line2 = c_line - 1;
      if( moving == 1)
      {
        goto_line( block_line1 );
        if((c_line > 1 ) && (cur_char != "\f"))
        {
          up;
          while((c_line > 1) && (cur_char != "\f") &&
                ( t_level < parse_int("/IN=", parse_str("MENU=", get_line))))
          {
            up;
          }
        }
      }
      else
      {
        if(!at_eof && (cur_char != "\f"))
        {
          down;
          while((!at_eof) && (cur_char != "\f") &&
                ( t_level < parse_int("/IN=", parse_str("MENU=", get_line))))
          {
            down;
          }
        }
      }
    }
    else
    {
      str tstr[128],tstr2;
      int flags, k1,k2, tint;

      if(creat)
      {
        int level = 1;
        goto_col(1);
        if(!at_eof)
        {
          down;
          if( cur_char != "\f" )
          {
            level = parse_int("/IN=", parse_str("MENU=", get_line ));
          }
          up;
        }
        record =  "IN=" + str( level );
      }
      //else if ( copying )
      //{
      //  int level = 1, jx;
      //  str name;
      //  level = parse_int("/IN=", get_line );
      //  jx = xpos('NAME=', get_line, 1);
      //  if ( jx )
      //  {
      //    goto_col(jx + 6);
      //    name = get_word('/');
      //  }

      //  record =  "IN=" + str( level ) + "NAME=" + name;
      //}
      else if ( d )
      {
        int thiswinid = window_id;
        mark_pos;

        if ( LocateDBPage(wcmdmapname, MENUID + ".MNU",FALSE) )
        {
          DEL_LINE;
          while ( !at_eof & (cur_char != '|12')  )
          {
            del_line;
          }
        }

        goto_mark;
        switch_win_id(thiswinid);
  //***********  Try to update the fargin choice boxes ***********************
        int tint = parse_int('MENUSTYLE=', record);
        int dlg = parse_int('/DLGHANDLE=', mparm_str);
        if ( (tint == 1) || (tint == 2) || (tint == 3) )
        {
          int newint = SendDlgItemMessageStr(dlg, 3000 + tint, CB_FINDSTRINGEXACT, -1, menuid);
          if ( newint != CB_ERR ) {
            struct trect tr;
            int lh, fh, fw, df, count;
            SendDlgItemMessage(dlg, 3000 + tint, CB_DELETESTRING, newint, 0);
            count = SendDlgItemMessage(dlg, 3000 + tint, CB_GETCOUNT, 0, 0);
            GetWindowRect(getdlgitem(dlg, 3000 + tint), &tr);
            Get_MEW_Dlg_Metrics ( dlg, lh, fh, fw, df )
            SetWindowPos(getdlgitem(dlg, 3000 + tint), 0, 0, 0, (tr.right - tr.left),
                        (tr.bottom - tr.top) + (count * fh), SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
          }
          if ( tint == 1 )
            mainlist = str_del(mainlist, xpos(menuid, mainlist, 1), length(menuid) + 2);
          else if ( tint == 2 )
            contextlist = str_del(contextlist, xpos(menuid, contextlist, 1), length(menuid) + 2);
          else if ( tint == 3 )
            mdilist = str_del(mdilist, xpos(menuid, mdilist, 1), length(menuid) + 2);
        }
  //*************  End of fargin choice boxes ********************************

      }
      else if ( copying )
      {
        str sourcercd = global_str(parse_str('/COPYREC=',mparm_str));
        int thiswinid = window_id;
        str boxidline;
        mark_pos;
        // locate original record.
        if ( LocateDBPage(wcmdmapname,sourcercd + ".MNU",FALSE) )
        {
          int tpb = persistent_blocks;
          int insmode = insert_mode;

          insert_mode = TRUE;
          persistent_blocks = TRUE;

          down;               // move to first record
          if ( (copy(get_line,1,1) != char(12)) &&
                !at_eof ) // are there items defined?
          {
            // mark all items, copy to buffer
            block_begin;  // line marking!
            while ( (copy(get_line,1,1) != char(12)) &&
                    !at_eof )
            {
              down;
            }
            up; // dont want the page break line
            block_end;

            // move to new position (create new db page)
            LocateDBPage(wcmdmapname,menuid + ".MNU",TRUE);
            down; // insert after title line
            // copy block
            copy_block;
          }

          persistent_blocks = tpb;
          insert_mode = insmode;
          block_off;
        }

        switch_win_id(thiswinid);
        goto_mark;

      }
      else
      {
        var_remove_str("CMD",record);
        wcmdglo=parse_int("WCMD=",record);

        if( Wcmd_Find( 0, wcmdglo, flags, k1,
                        k2, tstr, tstr2 ))
        {
          record += "CMD=" + parse_str("NAME=", tstr2);
        }


        tstr = parse_str("MENU=", record );


        var_remove_str("NAME",record);
        var_remove_str("IN",record);
        record = record + "NAME=" + parse_str("/TX=",tstr) +
                    "IN=" + parse_str("/IN=", tstr );
      }
      set_global_str(gls, record );
    }
  }

  return_int = 1;
}

void MenuSelectCmd()
{
  rm("CommandMapEdit /LO=1/FFLD=WCMD/FV=" + str(WcmdGlo));
  if(return_int)
  {
    WcmdGlo = parse_int('WCMD=',global_str( WCMDGloName ));
    Return_Str = parse_str('NAME=',global_str( WCMDGloName ));
  }
  set_global_str(WCMDGloName , '');
}

void MenuEditor()
{
  int startid = window_id, dlg, j=1, tint, maincnt=0, contextcnt=0, mdicnt=0,
      initmain = 0, initcontext = 0, initmdi = 0;
  str menuname,tstr;

  if ( global_str('ACTIVE_MAIN')  == '')         // set to defaults if necessary
    Set_Global_Str('ACTIVE_MAIN', 'MAIN');
  if ( global_str('ACTIVE_CONTEXT')  == '')
    Set_Global_Str('ACTIVE_CONTEXT', 'CONTEXT');
  if ( global_str('ACTIVE_MDI')  == '')
    Set_Global_Str('ACTIVE_MDI', 'MDI');


again:
  rm('get_db_record /F='+wcmdmapname+'/NDF=1/#=' + str(j) +'/GLO=MENUITEMS/DPT=MENULIST.DB/AGLO=MENUCOUNT');
    if ( parse_int('MENUSTYLE=',menuitems) == 1)
    {
      ++maincnt;
      mainlist = mainlist + parse_str('MENUID=', menuitems) + '()';
      if ( global_str('ACTIVE_MAIN') == parse_str('MENUID=', menuitems) )
        initmain = maincnt;
    }
    else if ( parse_int('MENUSTYLE=',menuitems) == 2)
    {
      ++contextcnt;
      contextlist = contextlist + parse_str('MENUID=', menuitems) + '()';
      if ( global_str('ACTIVE_CONTEXT') == parse_str('MENUID=', menuitems) )
        initcontext = contextcnt;
    }
    else if ( parse_int('MENUSTYLE=',menuitems) == 3)
    {
      ++mdicnt;
      mdilist = mdilist + parse_str('MENUID=', menuitems) + '()';
      if ( global_str('ACTIVE_MDI') == parse_str('MENUID=', menuitems) )
        initmdi = mdicnt;
    }
    if ( j< menucount ) {
      ++ j;
      goto again;
    }

  switch_win_id (startid);

  DlgCreate ( dlg );
  DlgAddCtrl( dlg, DLG_Static, "&Main",12,1,0,0, 3101,0, "");
  DlgAddCtrl( dlg, DLG_Choice, mainlist,
              DLG_PosOffset + 9,DLG_PosOffset,22,0, 3001,0, "");
  DlgSetInt ( dlg, 3001, initmain);
  DlgAddCtrl( dlg, DLG_Static, "&Context",12,Dlg_PosOffset + 1,0,0, 3102,0, "");
  DlgAddCtrl( dlg, DLG_Choice, contextlist,
              DLG_PosOffset + 9,DLG_PosOffset,22,0, 3002,0, "");
  DlgSetInt ( dlg, 3002, initcontext);
  DlgAddCtrl( dlg, DLG_Static, "M&DI",12,Dlg_PosOffset + 1,0,0, 3103,0, "");
  DlgAddCtrl( dlg, DLG_Choice, mdilist,
              DLG_PosOffset + 9,DLG_PosOffset,22,0, 3003,0, "");
  DlgSetInt ( dlg, 3003, initmdi);

  // edit the list of defined menus
  db(wcmdmapname,"MENULIST.DB",
      "MEWHDRS.DB","MENULIST.HDR",
      "Menus", "","MENUSETNAME",
      0,
      '/PRE=MNU'+
      '/NOALPHA=1'+
      '/NDF=1/NDH=1'+
      '/CANMAC=1/DELMAC=1/MOVE=1/EMAC=MenuEdit'+
      '/BMP=BT_GN_111/FFLD=MENUID'+
      "/H=" + MAINMENU_HELPLINK +
      '/ADH=' + str(dlg) +'/ADF=1' +
      '/MACRO=MENUDBIN'
      );

  tint = 3001;
  while ( tint < 3004 )
  {
    if ( tint == 3001 )
      tstr = mainlist;
    else if ( tint == 3002 )
      tstr = contextlist;
    else if ( tint == 3003 )
      tstr = mdilist;
    j=1;
    if ( DlgGetInt( dlg, tint ))
    {
      while ( j != DlgGetInt( dlg, tint) )
      {
        tstr = str_del(tstr, 1, xpos('()', tstr, 1) + 1);
       ++j;
      }
    }

    if ( tint == 3001 )
      set_global_Str('ACTIVE_MAIN',    copy(tstr, 1, xpos('()', tstr,1) - 1));
    if ( tint == 3002 )
      set_global_Str('ACTIVE_CONTEXT', copy(tstr, 1, xpos('()', tstr,1) - 1));
    if ( tint == 3003 )
      set_global_Str('ACTIVE_MDI',     copy(tstr, 1, xpos('()', tstr,1) - 1));
    ++tint;
  }
  LoadMenus(global_str('ACTIVE_MAIN'));   //Activate the main menu
  rm('window^winop /T=15');                //Activate the MDI Menu

  Set_Global_Int('SETUP_CHANGED',Global_Int('SETUP_CHANGED') | $01);
  return_int = 0;
// CLEANUP
  DlgKill(dlg);
  mainlist = '';
  contextlist = '';
  mdilist = '';
}

void MenuEdit( str name[40] = parse_str("/N=",mparm_str),
               str bmp[40] = parse_str("/B=",mparm_str),
               str helplink[40] = parse_str("/H=",mparm_str))
{
  int create = parse_int('/CREATE=', mparm_str);
  int copying = parse_int('/COPY=', mparm_str);
  //return_str = name;
  if ( bmp == "" )
  {
    bmp = "BT_SETUP_107";
  }
  if ( name == "" )
  {
    name = parse_str('MENUID=',global_str('MENUSETNAME'));
  }
  //if ( create || copying)
  //{
  //  rm('QUERYBOX /W=20/ML=20/T=Enter a Menu Name');
  //  name = return_str;
  //}
  //if ( return_int )
  //{
    int menudlg;
    DlgCreate ( menudlg );
    DlgAddCtrl( menudlg, Dlg_Static, "&Name:", 2, 1, 0, 0, 3200, 0, "");
    DlgAddCtrl( menudlg, Dlg_Text, name, Dlg_PosOffset + 8, 1, 10, 0, 3100, 0, "");
    DlgAddCtrl( menudlg, DLG_Static, "&Menu Type",26,1,0,0, 3101,0, "");
    DlgAddCtrl( menudlg, DLG_Choice, "Main()Context()MDI()Other()",
                DLG_PosOffset + 12,DLG_PosOffset,20,0, 3001,0, "");
    DlgSetInt ( menudlg, 3001, parse_int('MENUSTYLE=', global_str('MENUSETNAME')));

    db( wcmdmapname, caps(name) + ".MNU", "MEWHDRS.DB", "MENU.HDR",
            "Edit Menu Set \"" + name + "\"",
            "Edit Menu Item",
            "!MENUGLO", 0,
            "/BMP=" + bmp + "/H=" + MAINMENU_HELPLINK +
            "/NOALPHA=1/NDF=1/NDH=1/MOVE=1/MOVEMAC=1/CANMAC=1/DELMAC=1" +
            '/ADH=' + str(menudlg) +'/ADF=1' +
            "/MACRO=MenuDBIn"
             );
    menuglo = "";
    wcmdglo = 0;

    if( NeedLoadWcmds )
    {
      RebuildWcmds();
    }
    int chgname = 0;
    str oldname;

    // if we change the name of the menu...
    if ( name != DlgGetStr( menudlg, 3100) )
    {
      oldname = name;
      if (LocateDBPage(wcmdmapname, name + ".MNU",True) )
      {
        name = DlgGetStr( menudlg, 3100);
        str newrec = '|12' + name + '.MNU';
        put_line(newrec);
        chgname = 1;
      }
    // ------------------------------------------------------------------------

    }

    Set_Global_Str('MENUSETNAME', 'MENUID=' + DlgGetStr( menudlg, 3100) +
                                  'MENUSTYLE=' + str(DlgGetInt( menudlg, 3001)));

//***********  Try to update the fargin choice boxes ***********************
    if ( create || copying || chgname)
    {
      int tint = parse_int('MENUSTYLE=', global_str('MENUSETNAME'));
      int dlg = parse_int('/DLGHANDLE=', mparm_str);
      if ( (tint == 1) || (tint == 2) || (tint == 3) )
      {
        struct trect tr;
        int lh, fh, fw, df, count;
        SendDlgItemMessageStr(dlg, 3000 + tint, CB_ADDSTRING, 0, name);
        if ( chgname )
        {
          int index = SendDlgItemMessageStr(dlg, 3000 + tint, CB_FINDSTRING, -1, oldname);
          if ( index == SendDlgItemMessage(dlg, 3000 + tint, CB_GETCURSEL, 0, 0) ) {
            SendDlgItemMessage(dlg, 3000 + tint, CB_DELETESTRING, index, 0)
            int newindex = SendDlgItemMessageStr(dlg, 3000 + tint, CB_FINDSTRING, -1, name);
            SendDlgItemMessage(dlg, 3000 + tint, CB_SETCURSEL, newindex, 0);
          }
          else {
            str curname;
            int cursel = SendDlgItemMessage(dlg, 3000 + tint, CB_GETCURSEL, 0, 0);
            SendDlgItemMessageStr(dlg, 3000 + tint, CB_GETLBTEXT, cursel, curname);
            SendDlgItemMessage(dlg, 3000 + tint, CB_DELETESTRING, index, 0);
            int newindex = SendDlgItemMessageStr(dlg, 3000 + tint, CB_FINDSTRING, -1, curname);
            SendDlgItemMessage(dlg, 3000 + tint, CB_SETCURSEL, newindex, 0);
          }
        }
        count = SendDlgItemMessage(dlg, 3000 + tint, CB_GETCOUNT, 0, 0);
        GetWindowRect(getdlgitem(dlg, 3000 + tint), &tr);
        Get_MEW_Dlg_Metrics ( dlg, lh, fh, fw, df )
        SetWindowPos(getdlgitem(dlg, 3000 + tint), 0, 0, 0, (tr.right - tr.left),
                    (tr.bottom - tr.top) + (count * fh), SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
        if ( tint == 1 ) {
          if ( chgname )
            mainlist = str_del(oldname, xpos(oldname, mainlist, 1), length(oldname) + 2);
          mainlist = mainlist + name + '()';
        }
        else if ( tint == 2 ) {
          if ( chgname )
            contextlist = str_del(oldname, xpos(oldname, contextlist, 1), length(oldname) + 2);
          contextlist = contextlist + name + '()';
        }
        else if ( tint == 3 ) {
          if ( chgname )
            mdilist = str_del(oldname, xpos(oldname, mdilist, 1), length(oldname) + 2);
          mdilist = mdilist + name + '()';
        }
      }
    }
//*************  End of fargin choice boxes ********************************
    DlgKill( menudlg );
    return_int = 1;
  //}
}


// Edit the Main Menu Bar
void SetupDefMenu ()
{
  return_int = 1;  //added for compatibility until menu mgr is done
  DefaultMenu = "MAIN";
  set_global_str('MENUSETNAME','MENUID=MAINMENUSTYLE=1'); //added for compatibility until menu mgr is done
  MenuEdit(DefaultMenu, "BT_SETUP_107", MAINMENU_HELPLINK);
  LoadMenus(DefaultMenu);

  Set_Global_Int('SETUP_CHANGED',Global_Int('SETUP_CHANGED') | $01);
  return_int = 0;
}

// Edit the Right Mouse Context Sensitive Menu
void SetupContextMenu()
{
  return_int = 1; //added for compatibility until menu mgr is done
  set_global_str('MENUSETNAME','MENUID=CONTEXTMENUSTYLE=2');  //added for compatibility until menu mgr is done
  MenuEdit("CONTEXT", "BT_SETUP_114", MOUSEMENU_HELPLINK);
  Set_Global_Int('SETUP_CHANGED',Global_Int('SETUP_CHANGED') | $01);
  return_int = 0;
}

// Edit the Mdi System Menu
void SetupMDIMenu ()
{
  set_global_str('MENUSETNAME','MENUID=MDIMENUSTYLE=3'); //added for compatibility until menu mgr is done
  MenuEdit ("MDI", "BT_SETUP_114", MDIMENU_HELPLINK);
  Set_Global_Int('SETUP_CHANGED',Global_Int('SETUP_CHANGED') | $01);
  return_int = 0;
}