macro_file mew;
#include winsmall.sh
#include mewlib.sh
#include metools.sh
#include colors.sh
#include fonts.sh
#include print.sh
#include menus.sh
#include mew.sh
#include exit.sh
#include mew_btn.sh
#include mewlogo.sh
#include window.sh
#include dialog.sh
#include DB.SH

#define KEYSCMNDS_HELPLINK "KEYS // COMMANDS"



void ProcessMEWInit( )
{
  if( !LocateDBPage( "MECONFIG", "INIT.CFG", false ) )
  {
    load_macro_file(  user_id + "INIT" );
    if(error_level != 0)
    {
      error_level = 0;
      load_macro_file( "INIT" );
      RM( "INIT" );
    }
    else
    {
      Rm( user_id + "INIT" );
    }
    return();
  }

  str gn[80], gv[2048];
  int gi;

  down;
  goto_col(1);

  int loop_done = false;
  while((!loop_done) && (!at_eof) && (cur_char != "\f"))
  {
    if(cur_char == "/")
    {
      right;
      gn = get_word("=");
      right;
      switch ( gn )
      {
        case  "CL_FOCUS_RECT" :
              call get_int;
              cl_focus_rect = gi;
              break;

        case  "MEMORY_PERCENTAGE" :
              call get_int;
              memory_percentage = gi;
              break;

        case "PAGE_STR" :
              page_str = Reconvert_String(get_word(""));
              break;

        case "TRUNCATE_SPACES" :
              call get_int;
              truncate_spaces = gi;
              break;

        case "PERSISTENT_BLOCKS" :
              call get_int;
              persistent_blocks = gi;
              break;

        case "SAVE_RESETS_CHANGED" :
              call get_int;
              save_resets_changed = gi;
              break;

        case "TYPING_OVERWRITES_BLOCK" :
              call get_int;
              typing_overwrites_block = gi;
              break;

        case "STREAM_BLOCK_MODE" :
              call get_int;
              stream_block_mode = gi;
              break;

        case "CTRL_Z" :
              call get_int;
              ctrl_z = gi;
              break;

        case "EOF_CR" :
              call get_int;
              eof_cr = gi;
              break;

        case "FILE_LOCKING" :
              call get_int;
              file_locking = gi;
              break;

        case "DISPLAY_TABS" :
              call get_int;
              display_tabs = gi;
              break;

        case "TAB_EXPAND" :
              call get_int;
              tab_expand = gi;
              break;

        case "WORD_DELIMITS" :
              word_delimits = Reconvert_String(get_word(""));
              break;

        case "MAX_UNDO" :
              call get_int;
              max_undo = gi;
              break;

        case "COLUMN_MOVE_STYLE" :
              call get_int;
              column_move_style = gi;
              break;

        case "KEYWORD_HIGHLIGHTING" :
              call get_int;
              keyword_highlighting = gi;
              break;

        case "KEYWORD_CLINE_OVERRIDE" :
              call get_int;
              keyword_cline_override = gi;
              break;

        case "INSERT_MODE" :
              call get_int;
              insert_mode = gi;
              break;

        case "BACKUPS" :
              call get_int;
              backups = gi;
              break;

        case "INS_CURSOR" :
              call get_int;
              ins_cursor = gi;
              break;

        case "OVR_CURSOR" :
              call get_int;
              ovr_cursor = gi;
              break;


        case "GLOBAL_VARIABLES" :
              loop_done = TRUE;
              break;
      }
    }
    down;
    goto_col(1);
  }

  loop_done = false;
  while((!loop_done) && (!at_eof) && (cur_char != "\f"))
  {
    if(cur_char == "/")
    {
      right;
      gn = get_word("=");
      right;
      switch ( gn )
      {
        case  "GS" :
          gn = get_word("=");
          right;
          Set_Global_Str( gn, ReConvert_String( get_word("") ) );
          break;

        case  "GI" :
          gn = get_word("=");
          right;
          val(gi,get_word(""));
          Set_Global_int( gn, gi );
          break;
      }
    }
    down;
    goto_col(1);
  }

  RM("MewProcStart");

  return();

get_int:
  val(gi,get_word(" "));
  ret;


}


#DEFINE wflags_mindisable    0x00010000

void Load_Wcmds ()
{
  str mstr, mcmd, keystr[80], keyname[80], wcmd_idname[32];
  int id,jx, key,k2, twin = window_id, trefresh = refresh, wcmd, type;
  int mindisable;
  refresh = false;

  rm("SETCONFIG /DB=" + wcmdmapname + "/T=WCMDMAP.DB");
  Wcmd_Clear_List( 0 );

  // search_fwd("%@*@*@*@*START@*@*@*@*", 0);
	down;
	goto_col(1);
	while( !at_eof && (cur_char != ""))
	{
		mstr = get_line;

    if( copy(mstr, 1, 4) != "@þ=")
    {
      var_parse_str("CMD=", mstr, mcmd );
      var_parse_int("WCMD=", mstr, wcmd );
      var_parse_int("TYPE=", mstr, type );
      var_parse_int("XMIN=", mstr, mindisable);
      var_parse_str("WCMDID=", mstr, wcmd_idname );


      var_parse_str("KEY=", mstr, keystr );
      key = make_word( parse_int("/K1=", keystr), parse_int("/K2=", keystr));

      var_parse_str("KEY2=", mstr, keystr );
      k2 = make_word( parse_int("/K1=", keystr), parse_int("/K2=", keystr));

      switch( type )
      {
        case 2 :
          type = 0;
          mcmd = "EXECPROG /PROG=" + mcmd;
              // let it fall through here

        case 0 :
        case 1 :
          type = 0;
          break;

        case 5 :
          type = 1;
          var_parse_int("CMD=", mstr, jx );
          if( jx != 0 )
          {
            mcmd = char( jx );
          }
          break;
      }

			if(wcmd != 0)
			{

        if ( mindisable )
        {
          type |= wflags_mindisable;
        }

        var_remove_str( "CMD=", mstr  );
        Wcmd_Add( 0, wcmd, type, key, k2, mcmd, mstr  );

          // Handle wcmd identifier globals
        if(svl(wcmd_idname))
        {
          Set_Global_Int( wcmd_idname, wcmd );
        }
			}

    }
		down;
	}
  switch_win_id( twin );
	refresh = trefresh;
}

void ProcessMsgQueue( int mcount )
{
  struct tmsg tm;
  while( mcount-- > 0 )
  {
    if(peekmessage( &tm, 0, 0, 0,pm_remove))
    {
      TranslateMessage( &tm );
      DispatchMessage( &tm );

    }
    else
    {
      mcount = 0;
    }
  }
  return();
}

void RegisterDLLList()
{
  int tr = refresh,
      tw = window_id;

  refresh = false;

  str tstr;
  int r;

  if(LocateDbPage( "MECONFIG", "RESOURCES.DB", false ) )
  {
    down;
    goto_col(1);
    while(!at_eof && (cur_char != "\f"))
    {
      tstr = parse_str("DLL=", get_line);
      if( svl(tstr) != 0)
      {
        r = MEW_RegisterDLL( tstr );
        if(r)
        {
          RegisterMEWResource( r );
        }
      }
      down;
    }
  }
  switch_win_id( tw );
  refresh = tr;
}



void Mew_Begin  ()
{
  int jx;

  wcmdmapname = "WCMDMAP";

  RegisterMEWResource( GetModuleHandle("MEWLIB") );
  int r = MEW_RegisterDLL( "MEWBMP" );
  if(r)
  {
    RegisterMEWResource( r );
  }

  RegisterDLLList();

  load_macro_file("LANGUAGE");
  load_macro_file("MEWSETUP");

  Error_Level = 0;

  ProcessMEWInit();
  mewlogo(3);

  SetWindowFonts( 0, parse_str("/NAME=", DefaultFont),
                      parse_int("/SIZE=", DefaultFont),
                      parse_int("/SET=", DefaultFont));

  SetTemplateAttrs (0,DefaultColor);
  SetPrintCfg ();

  Rm("MEWSYS^PARMS1");

  Rm("SETCONFIG /DB=MECONFIG");
  Load_Wcmds ();
  LoadMenus  (DefaultMenu);

  create_window;
  jx = window_id;
  if( nofile_hidden )
  {
    window_attr = $81;
  }
  else
  {
    make_window_visible (1);
  }

  jx = window_id;

  RestoreResult = 0;
  Rm("MEWSYS^PARMLOAD");
  if(!restoreresult)
  {
      rm('tbmgr^build_toolboxes');  // forced build accordingly to db file
      if ( !Global_Int ("@MAXIMIZE_WINDOWS")  )
      {
        rm('WOrganize /M=0');
      }
      else
      {
        switch_win_id (jx);
        if( !nofile_hidden)
          Maximize ();
      }
  }
  if (( global_str("!session_name") != "" ) && (restoreresult))
  {
    make_message( "Session \"" + global_str("!session_name") + "\" restored.");
  }
}


void CommandMacro (str r_str   = parse_str ('/GLO=',MParm_Str),
                   int bCreate = parse_int ('/CREATE=',MParm_Str),
                   int bAfter  = parse_int ('/P=', MParm_Str)) Trans2
{
  str record[1024], kstr;
  int wCmd, useWcmd;
  int tRegExp = reg_exp_stat;
  int tInsert = Insert_Mode;
  int tWin    = cur_window;
  int sortwin;
  int numSort = 0;

  reg_exp_stat = TRUE;
  Insert_Mode  = TRUE;
  Mark_pos;

  if ( bAfter )
  {
    record = get_line;
    kstr =  parse_str ("KEY=", global_str (r_str));
    if ( kstr != '' )
    {
      if (CheckDupFields ("WCMDMAP.DB", record, kstr, "KEY=", "KEY2="))
      {
        RM ("Meerror^MessageBox /T=Warning/B=1/M=" +
              "Primary Key: " + parse_str ("/KL=", kstr) +
              "\r\nAlready assigned to: " + Parse_Str('NAME=',Get_Line));
      }
    }
    kstr =  parse_str ("KEY2=", global_str (r_str));
    if ( kstr != '' )
    {
      if (CheckDupFields ("WCMDMAP.DB", record, kstr, "KEY=", "KEY2="))
      {
        RM ("Meerror^MessageBox /T=Warning/B=1/M=" +
              "Secondary Key: " + parse_str ("/KL=", kstr) +
              "\r\nAlready assigned to: " + Parse_Str('NAME=',Get_Line));
      }
    }

		if ( parse_str("WCMD=", global_str( r_str )) == "" )
		{
	    create_window;
	    sortWin = cur_window;

	    switch_window (tWin);
	    tof;
      if (  search_fwd('%|12WCMDMAP.DB||$',0)  ) {  // find start of header
        down;
        while( !at_eof && (cur_char != ""))
        {
          record = get_line;
          wcmd   = parse_int ('WCMD=', record);
          down;
          if ( wcmd >= 10000 ) // if greater than reserved numbers
          {
            put_line_to_win (str (wcmd), numsort+1, sortwin, 0);
            ++numSort;
          }
        }
	    }
	    useWcmd = 10000;
	    if ( numSort )
	    {
	      switch_window (sortWin);
	      qsort_lines (1, numSort, 1, 1, 5, 0);
	      tof;
	      useWcmd = 10000;
	      while ( !at_eof )
	      {
	        val (wcmd, get_line);
	        if ( wcmd > useWcmd )
	        {
	          break;
	        }
	        else
	          useWcmd = wcmd + 1;
	        down;
	      }
	      delete_window;
	    }
	setwcmd:
	    switch_window (tWin);

	    record = global_str (r_str);
	    record = record + 'WCMD=' + str(useWcmd);
	    set_global_str (r_str, record);
		}
  }
  else
  {
    if ( parse_int("/COPY=", mparm_str) )
    {
	    record = global_str (r_str);
      var_remove_str( 'WCMD=', record );
	    set_global_str (r_str, record);
    }
  }
  goto_mark;
  Insert_Mode  = tInsert;
  reg_exp_stat = tRegExp;
}

void RebuildWcmds()
{
  Load_Wcmds ();
  LoadMenus (DefaultMenu);
  rm('Tbmgr^build_toolboxes');
  NeedLoadWcmds = FALSE;
}


void CommandMapEdit () Trans2
{
 /*
  rm("DB " + mparm_str + "/F=" + wcmdmapname + "/NDF=1/NDH=1/HF=MEWHDRS.DB/HPT=WCMDMAP.HDR/H="
	str(hKEYS_COMMANDS)
    + "/LT=Command Mapping/DPT=WCMDMAP.DB/MOVE=1/NOALPHA=1/GLO="
    + WCMDGloName +
    "/MACRO=CommandMacro"
	);
*/

  DB(  wcmdmapname,
         "WCMDMAP.DB",
         "MEWHDRS.DB",
         "WCMDMAP.HDR",
         "Command Mapping",
         "",
         WCMDGloName,
         Parse_Int ("/LO=", mparm_str),
         mparm_str + "/H=" + KEYSCMNDS_HELPLINK
          + "/BMP=BT_SETUP_106/NDF=1/NDH=1/MOVE=1/NOALPHA=1/MACRO=CommandMacro"
         );

  if( Global_Int( '@DB_FILE_CHANGED' ))
  {
    if(parse_int("/LO=", mparm_str))
    {
      NeedLoadWcmds = TRUE;
    }
    else
    {
      RebuildWcmds();
    }
  }
}



/* GetAvailableWcmd

  Gets a temporary wcmd.

  is passed an existing wcmd (supposedly parsed from a global variable string
  (a container you could say)
  if the existing wcmd is non-zero, then use it, otherwise find a new one.

*/
int GetAvailableWcmd(int wcmdToUse, int startNum)
// int wcmdToUse    desired wcmd to use (previous value)
// int startNum     where to start looking in wcmdmap (for a series of cmds)
{
  str t[1];
  int k, s;

  int i = wcmdtouse;

  if ( !wcmdToUse )
  {
    if ( startNum == 0 )
    {
      s = 9999;
    }
    else
    {
      s = startNum-1;
    }
    for ( i = s; i > 0; i-- )
    {
      if(!global_int("~WCMD-" + str(i)))
      {
        if ( !Wcmd_Find(0,i,k,k,k,t,t) )
        {
          wcmdToUse = i;
          break;
        }
      }
    }
  }
  wcmdtouse = i;
  set_global_int("~WCMD-" + str(i), i );
  return (wcmdToUse);
}


/*
  ReleaseWcmd

    Removes a temporary wcmd from the list

*/
void ReleaseWcmd( int wcmd )
{
  set_global_int("~WCMD-" + str(wcmd), 0 );
  wcmd_del(0, wcmd );
}

/*********************************************************************
 *
 *	NAME: NOT_YET_SUPP
 *
 *	DESC: This macro was written for use in the Beta release of MEW. It's
 * 				only purpose is to inform the user of features that are not
 *				available to the product just yet.
 ********************************************************************/
void Not_Yet_Supp ()
{
	rm('messagebox /M=This feature is not completed yet.');
}


void EditDLLRegistry()
{
  DB(  "MECONFIG",
         "RESOURCES.DB",
         "MEWHDRS.DB",
         "RESOURCES.HDR",
         "DLL Resource Registry",
         "",
         "",
         0,
         "/BMP=/NDF=1/NDH=1/MOVE=1/NOALPHA=1"
         );
  if( Global_Int( '@DB_FILE_CHANGED' ) )
  {
    RegisterDLLList();
  }
}


str FileDateTimeStr( int ftime )
{
  int  j1, j2, j3, jx ;
  str sTime[2],tstr;

  jx = ftime & $FFFF;
  j1 = jx >> 11;
  j2 = (jx >> 5) & $3F;
// this code supports all time formats
  tstr = Make_Time_Str( j1, j2, 0 );
  j3 = 6;
  GetProfileString("intl","sTime", ":",sTime,2);
  if (xpos(sTime,tstr,1) == 2) {
    j3 = 5;
  }
  tstr = Str_Del(tstr,j3,3);

  jx = ftime >> 16;
  j1 = (jx >> 9) + 1980;
  j2 = (jx >> 5) & $0F;
  j3 = (jx & 31);
  tstr = Make_Date_Str( j1, j2, j3 ) + ' ' + tstr;

  return(tstr);
}

void MewActivate()
{
  int tr = refresh;
  int tw = cur_window;
  int jx;
  int dlg;

  str t_search_rec[64] = file_search_rec, tstr;
  int T_File_Search_Attr = File_Search_Attr;
  int res, yesall = 0;
  int cfa;
  int find_result;

	File_Search_Attr = $27;

  refresh = false;

  for ( jx = 1; jx <= window_count; jx++ )
  {
    working;
    switch_window(jx);
    if(((window_attr & 0x80) == 0) && (cur_file_time != 0) && (caps(file_name) != "?NO-FILE?"))
    {
      find_result = first_file( file_name );
      if(find_result != 0)
      {
        DlgCreate(dlg);
        DlgAddCtrl( dlg, DLG_Icon, "IC_EXCLAMATION", 1, 1, 0, 0, 1101, 0, "");
        DlgAddCtrl (dlg, DLG_Static,
          "This file has been deleted by another program!"
          ,8, 2, 45, 1, 1100,  0, "");

        DlgAddCtrl (dlg, DLG_Static,
          file_name,
          3, DLG_PosOffset | 2, 45, 1, 1101,  0, "");


        if(eof_in_mem)
        {
          tstr = "The entire file is in memory and it may be saved without loss of data.";
        }
        else
        {
          tstr =  "The entire file is NOT in memory!! " +
          "In order for you to save this file without loss of data " +
          "you need to attempt to recover the deleted file before exiting Multi-Edit!"
          ;
        }
          DlgAddCtrl (dlg, DLG_Static, tstr,
            3, DLG_PosOffset | 2, 51, 3, 1102,  0, "");

        DlgAddCtrl (dlg, DLG_PushButton,
          "OK",
          13, Dlg_PosOffset | 3, DLG_StanBtnWidth, 0, 100, DLGF_DefButton, "/R=1");

        DlgAddCtrl (dlg, DLG_PushButton,
          "&Close file",
          DLG_PosOffset | (DLG_Stanbtnwidth + 2), Dlg_PosOffset, 16, 0, 101, 0, "/R=10");

        res = DlgExecute (dlg, 100, "Warning!", "", "", 0);
        DlgKill( dlg );

        if(res == 10)
        {
          --jx;
          RM("DelWin");
          refresh = false;
        }

      }
      else
      {
        cfa = orig_file_attr | (file_locking != 0);
        if((last_file_time != cur_file_time) || (last_file_attr != cfa))
        {
          if(!yesall)
          {
            DlgCreate(dlg);
            DlgAddCtrl( dlg, DLG_Icon, "IC_EXCLAMATION", 1, 1, 0, 0, 1601, 0, "");
            DlgAddCtrl (dlg, DLG_Static,
              "This file has been modified by another program!"
              ,8, 2, 45, 1, 1100,  0, "");

            DlgAddCtrl (dlg, DLG_Static,
              file_name,
              3, DLG_PosOffset | 2, 45, 1, 1101,  0, "");


            DlgAddCtrl (dlg, Dlg_Static, "Original:"
              , 3, 5,
              0,0, 1150, 0, "" );
            DlgAddCtrl( dlg, Dlg_BlackFrame, "", DLG_PosOffset, DLG_PosOffset | 1,
            22, 3, 1151, 0, "" );

            tstr = FileDateTimeStr( cur_file_time ) + "\n\r" +
              Str( cur_file_size ) + " bytes";
            if(cur_file_attr & 1)
              tstr += "\r\nRead-Only";
            if(cur_file_attr & 0x20)
              tstr += "\r\nArchive";
            if((cfa & 1) && (file_locking))
            {
              tstr += "\r\nLocked";
            }

            DlgAddCtrl (dlg, Dlg_Static,
              tstr
              , DLG_PosOffset | 1, DLG_PosOffset,
              20,3, 1152, 0, "" );

            DlgAddCtrl (dlg, Dlg_Static, "New:"
              , 28, 5,
              0,0, 1160, 0, "" );
            DlgAddCtrl( dlg, Dlg_BlackFrame, "", DLG_PosOffset, DLG_PosOffset | 1,
            22, 3, 1161, 0, "" );

            tstr = FileDateTimeStr( last_file_time ) + "\n\r" +
              Str( last_file_size ) + " bytes";
            if(last_file_attr & 1)
              tstr += "\r\nRead-Only";
            if(last_file_attr & 0x20)
              tstr += "\r\nArchive";
            if((last_file_attr & 1) && (file_locking))
            {
              tstr += "\r\nLocked";
            }

            DlgAddCtrl (dlg, Dlg_Static,
              tstr
              , DLG_PosOffset + 1, DLG_PosOffset,
              20,3, 1162, 0, "" );


              /*
            DlgAddCtrl (dlg, Dlg_Static, "New:"
              , 1, DLG_PosOffset | 1,
              0,0, 1160, 0, "" );

            DlgAddCtrl (dlg, Dlg_Static,
              FileDateTimeStr( last_file_time ), 12, DLG_PosOffset,
              0,0, 1161, 0, "" );
               */


            DlgAddCtrl( dlg, DLG_Icon, "IC_QUESTION", 1, DLG_PosOffset | 5, 0, 0, 1602, 0, "");
            DlgAddCtrl (dlg, DLG_Static,
              "Do you wish to load the modified file?",
              10, DLG_PosOffset | DLG_Units | DLG_Units_QLine, 45, 0, 1102,  0, "");

              /*
            DlgAddCtrl (mdlg, DLG_CheckBox,
              "Don't show this warning anymore",
              8, Dlg_PosOffset + 2, 0, 0, 1200, 0, "")
               */
            DlgAddCtrl (dlg, DLG_PushButton,
              "&Yes",
              9, Dlg_PosOffset | 1, DLG_StanBtnWidth, 0, 100, DLGF_DefButton, "/R=1");
            DlgAddCtrl (dlg, DLG_PushButton,
              "Yes to &All",
              DLG_PosOffset | (DLG_StanBtnWidth + 2), Dlg_PosOffset, 14, 0, 101, 0, "/R=11");
            DlgAddCtrl (dlg, DLG_PushButton,
              "&No",
              DLG_PosOffset | 16, DLG_PosOffset, DLG_StanBtnWidth, 0, 102, 0, "/R=0");
            res = DlgExecute (dlg, 100, "Warning!", "", "", 0);
            DlgKill( dlg );
            if(res == 11)
            {
              yesall = 1;
            }
          }
          if((res == 1) || (yesall))
          {
            res = 0;
            BufferLoadFile( file_name, 0, TRUE );
            if(error_level)
            {
              rm("MEERROR");
            }
          }
          else
          {
            cur_file_time = last_file_time;
            orig_file_attr = last_file_attr & ((file_locking == 0) | $FFFE );
          }
        }
      }
    }
  }

  file_search_rec = t_search_rec;
  file_search_attr = t_file_search_attr;
  switch_window(tw);
  refresh = tr;
}