/* file cfg1.c
 *
 * First configuration window
 * device and printer choice
 *
 */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <dirent.h>

#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xlib.h>
#include <Xm/Xm.h>
#include <Xm/MwmUtil.h>
#include <X11/Core.h>
#include <X11/Shell.h>
#include <Xm/PanedW.h>
#include <Xm/MainW.h>
#include <Xm/Form.h>
#include <Xm/ScrollBar.h>
#include <Xm/ScrolledW.h>
#include <Xm/List.h>
#include <Xm/Separator.h>
#include <Xm/RowColumn.h>
#include <Xm/TextF.h>
#include <Xm/RowColumn.h>
#include <Xm/ToggleB.h>
#include <Xm/PushB.h>
#include <Xm/Label.h>
#include <Xm/MessageB.h>
#include <Xm/MwmUtil.h>
#include <Xm/Scale.h>

#include "mtink.h"
#include "cfg1.h"
#include "cfg2.h"
#include "wheelmouse.h"
#include "micon.h"
#include "access.h"

#include "rdPrtDesc.h"
#define defaultConfigData configData
#define defaultConfigDataSize configEntries;

static Widget      configWindow;
static Widget      cfg1Next_PB;
static Widget      cfg1_LB;
static Widget      title_LB;
static Widget      printerList;
static Widget      separator;

static int         count;

static int leaveLoop;

/* create the coonfiguration window */
static void cfgNext_CB(Widget w, XtPointer clientData, XtPointer callData);

char *deviceList[] = {
   "/dev/lp0",      /* Linux */
   "/dev/lp1",	    /* on new kernel /dev/printer/0,... /dev/printer/3 */
   "/dev/lp2",
   "/dev/lp3",
   "/dev/printers/0",
   "/dev/printers/1",
   "/dev/printers/2",
   "/dev/printers/3",
   "/dev/usb/lp0",
   "/dev/usb/lp1",
   "/dev/usb/lp2",
   "/dev/usb/lp3",
   "/dev/usb/lp4",
   "/dev/usb/lp5",
   "/dev/usb/lp6",
   "/dev/usb/lp7",
   "/dev/usb/lp9",
   "/dev/usb/lp9",
   "/dev/usb/lp10",
   "/dev/usb/lp11",
   "/dev/usb/lp12",
   "/dev/usb/lp13",
   "/dev/usb/lp14",
   "/dev/usb/lp15",
   "/dev/usblp0",
   "/dev/usblp1",
   "/dev/usblp2",
   "/dev/usblp3",
   "/dev/usblp4",
   "/dev/usblp5",
   "/dev/usblp6",
   "/dev/usblp7",
   "/dev/usblp8",
   "/dev/usblp9",
   "/dev/usblp10",
   "/dev/usblp11",
   "/dev/usblp12",
   "/dev/usblp13",
   "/dev/usblp14",
   "/dev/usblp15",

   "/dev/ecpp0",       /* Solaris */
   "/dev/ecpp1",
   "/dev/ecpp2",
   "/dev/ecpp3",
   "/dev/ecpp4",

   "/dev/lpt0",        /* FreeBSD */
   "/dev/lpt1",
   "/dev/lpt2",
   "/dev/ulpt0",
   "/dev/ulpt1",
   "/dev/ulpt2",
   "/dev/unlpt0",
   "/dev/unlpt1",
   "/dev/unlpt2",
   NULL
};

static char **knownDevices;

/*******************************************************************/
/* Function createAlignButtons()                                   */
/*                                                                 */
/* Create the window for device and printer selection              */
/*                                                                 */  
/* Input: Widget parent not used                                   */
/*        int   *next   not used                                   */
/*                                                                 */
/* return: -                                                       */
/*                                                                 */
/*******************************************************************/

Widget createConfigurePrinter(Widget parent, int *next)
{
   Arg         args[20];
   int         n = 0;

   configWindow = XtVaCreateWidget("configWindow",
                                 xmFormWidgetClass,
                                 mainForm,
                                 XmNmarginHeight,     0,
                                 XmNmarginWidth,      0,
                                 XmNresizePolicy,     XmRESIZE_GROW,
                                 XmNresizable,        True,
                                 XmNleftAttachment,   XmATTACH_FORM,
                                 XmNrightAttachment,  XmATTACH_FORM,
                                 XmNtopAttachment,    XmATTACH_FORM,
                                 XmNbottomAttachment, XmATTACH_FORM,
                                 NULL);

   if (configWindow == NULL)
   {
      return False;
   }
   XtManageChild(configWindow);

   title_LB = XtVaCreateWidget("title_LB",
                             xmLabelWidgetClass,
                             configWindow,
                             XmNleftAttachment,   XmATTACH_FORM,
                             XmNleftOffset,       5,
                             XmNrightAttachment,  XmATTACH_FORM,
                             XmNrightOffset,      5,
                             XmNtopAttachment,    XmATTACH_FORM,
                             XmNtopOffset,        10,
                             XmNalignment,        XmALIGNMENT_CENTER,
                             NULL);
    
   XtManageChild(title_LB);

   cfg1_LB = XtVaCreateWidget("cfg1_LB",
                             xmLabelWidgetClass,
                             configWindow,
                             XmNleftAttachment,   XmATTACH_FORM,
                             XmNleftOffset,       5,
                             XmNrightAttachment,  XmATTACH_FORM,
                             XmNrightOffset,      5,
                             XmNtopAttachment,    XmATTACH_WIDGET,
                             XmNtopOffset,        10,
                             XmNtopWidget,        title_LB,
                             XmNalignment,        XmALIGNMENT_BEGINNING,
                             NULL);
    
   XtManageChild(cfg1_LB);

   /* create a list for the printer and a list for the device */
   
   n = 0;
   XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNtopOffset, 5); n++;
   XtSetArg(args[n], XmNtopWidget, cfg1_LB); n++;
   XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNleftOffset, 5); n++;
   XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNrightOffset, 5); n++;
   printerList = XmCreateScrolledList(configWindow, "printerLIST",args,n);
   XtManageChild(printerList);

   cfg1Next_PB = XtVaCreateWidget("next_PB",
                            xmPushButtonWidgetClass,
                            configWindow,
                            XmNleftAttachment,   XmATTACH_POSITION,
                            XmNleftOffset,       5,
                            XmNleftPosition,     65,
                            XmNrightAttachment,  XmATTACH_POSITION,
                            XmNrightOffset,      5,
                            XmNrightPosition,    95,
                            XmNbottomAttachment, XmATTACH_FORM,
                            XmNbottomOffset,     5,
                            NULL); 
   XtManageChild(cfg1Next_PB);


   separator = XtVaCreateWidget("separator",
                               xmSeparatorWidgetClass,
                               configWindow,
                               XmNbottomAttachment,   XmATTACH_WIDGET,
                               XmNbottomOffset,       5,
                               XmNbottomWidget,       cfg1Next_PB,
                               XmNleftAttachment,     XmATTACH_FORM,
                               XmNleftOffset,         0,
                               XmNrightAttachment,    XmATTACH_FORM,
                               XmNrightOffset,        0,
                               NULL); 
   XtManageChild(separator);
   XtVaSetValues(XtParent(printerList), 
                 XmNbottomAttachment,   XmATTACH_WIDGET,
                 XmNbottomOffset,       5,
                 XmNbottomWidget,       separator,
                 NULL);

   XtAddCallback(cfg1Next_PB, XmNactivateCallback, cfgNext_CB, &leaveLoop);
   xmAddMouseEventHandler(printerList);

   return configWindow;
}

/*******************************************************************/
/* Function alignNext_CB()                                         */
/*                                                                 */
/* set loop flag to 1                                              */
/*                                                                 */  
/* Input: Widget     w          not used                           */
/*        XtPointer  clientData not used                           */
/*        XtPointer  callData   not used                           */
/*                                                                 */
/* return: -                                                       */
/*                                                                 */
/*******************************************************************/

static void cfgNext_CB(Widget w, XtPointer clientData, XtPointer callData)
{
   *((int*)clientData) = 1;
}

/*******************************************************************/
/* Function readDevDir()                                           */
/*                                                                 */
/* show if the device files stated in the global device list       */
/* are present and if we have read and write right to them.        */
/* If all is OK insert them in the list deviceName                 */
/*                                                                 */
/* Output: char  **deviceName                                      */
/*                                                                 */
/* return: number of device file found                             */
/*                                                                 */
/*******************************************************************/

static int readDevDir(char **deviceName)
{
   int i;
   int count = 0;
   DIR *dir;
   struct dirent *ent;
   char *fname = NULL;

   for (i = 0;  deviceList[i] != NULL; i++)
   {
      /* acess as group or user */
      if (fileAccess(deviceList[i], R_OK|W_OK) == 0 )
      {
         deviceName[count++] = strdup(deviceList[i]);
      }
   }
   /* add entries found under /var/mtink */
   if ( (dir = opendir("/var/mtink")) )
   {
      while ( (ent = readdir(dir)) != NULL )
      {
         if ( ent->d_name[0] == '.' )
            continue;
         fname = (char*)calloc(strlen("/var/mtink/")+ strlen(ent->d_name)+1,1);    
         sprintf(fname, "/var/mtink/%s", ent->d_name);
         if (fileAccess(fname,  W_OK) == 0 )
         {
            deviceName[count++] = strdup(fname);
         }
      }
      closedir(dir);
   }
   
   return count;
}

/*******************************************************************/
/* Function popupCfg1()                                            */
/*                                                                 */
/* popup the mask and wait for user interaction                    */
/*                                                                 */  
/* Input: Widget          old   caller mask                        */
/*        wConfig_data_t *data  data for window                    */
/*        configData_t    *pData printer data                      */
/*                                                                 */
/* return: -                                                       */
/*                                                                 */
/*******************************************************************/

void popupCfg1(Widget old, wConfig_data_t *data, configData_t *pData)
{
   int i;
   XmString *tbl;
   XmString  xms;
   int       position_count;
   int      *position_list;
   int       selectedPos = 0;

   XmListDeleteAllItems(printerList);
   if ( data->wType == QUERY_PRINTER )
   {
       /* build the printer list */
      count = defaultConfigDataSize;

      tbl = calloc(sizeof(XmString), count);
      for ( i = 0; i < count; i++)
      {
         if ( defaultConfigData[i].name[0] == '?' )
         {
            tbl[i] = XmStringCreateSimple(appResourceRec.addPrinterTxt);
         }
         else
         {
            tbl[i] = XmStringCreateSimple(defaultConfigData[i].name);
         }
         if ( pData->name &&
              strcmp(pData->name, defaultConfigData[i].name) == 0 )
         {
            selectedPos = i+1;
         }
      }
      if ( count )
         XmListAddItems(printerList, tbl, count, 1);
      /* set label */
      XtVaGetValues(cfg2Printer_PB, XmNlabelString, &xms, NULL);
      if ( xms )
      {
         XtVaSetValues(cfg1_LB, XmNlabelString, xms, NULL);
         XmStringFree(xms);
      }
   }
   else
   {  
      /* build the device list */
      count = (sizeof(deviceList) / sizeof(char **));
      tbl = calloc(sizeof(XmString), count);
      knownDevices = calloc(count*2, sizeof(char **));
      count = readDevDir(knownDevices);
      for ( i = 0; i < count; i++)
      {
         tbl[i] = XmStringCreateSimple(knownDevices[i]);
         if ( pData->dev &&
              strcmp(pData->dev, knownDevices[i]) == 0 )
         {
            selectedPos = i+1;
         }
      }

      if ( count )
         XmListAddItems(printerList, tbl, count, 1);
      /* set label */
      XtVaGetValues(cfg2Device_PB, XmNlabelString, &xms, NULL); 
      if ( xms )
      {
         XtVaSetValues(cfg1_LB, XmNlabelString, xms, NULL);
         XmStringFree(xms);
      }      
   }

   for ( i = 0; i < count; i++ )
   {
      XmStringFree(tbl[i]);
   }
   free(tbl);

   /* if we have no element in the list a fatal error */
   /* has occured                                    */
   
   if ( count == 0 )
   {
      data->ptrVal = NULL;
      *data->wait  = -1;
      data->actWindow = configWindow;
      return;
   }

   if ( data->printerName && data->printerName[0] != '?' )
   {
      xms = XmStringCreateSimple(data->printerName);
      XtVaSetValues(title_LB,XmNlabelString,xms,NULL);
      XmStringFree(xms);
   }

   /* manage here, we must know the number of visible items */
   XtUnmanageChild(old);
   XtManageChild(configWindow);

   if ( selectedPos > 0 )
   {
      XmListSelectPos(printerList, selectedPos, False);
      /* set selected item at top if possible */
      XtVaGetValues(printerList, XmNvisibleItemCount, &i, NULL);
      if ( selectedPos + i > count )
         selectedPos = count - i +1;
      if ( selectedPos < 0 )
         selectedPos = 1;
      XmListSetPos(printerList, selectedPos);
   }

   /* privat loop */
   data->ptrVal = NULL;
   while (data->ptrVal == NULL)
   {
      *data->wait = 0;
      leaveLoop = 0;
      while(!leaveLoop)
         XtAppProcessEvent(theApp, XtIMAll);
     
      /* check for selection */
      if ( XmListGetSelectedPos(printerList, &position_list, &position_count ) )
      {
         if ( position_count )
         {
            if ( data->wType == QUERY_PRINTER )
            {            
               data->ptrVal = &defaultConfigData[position_list[0]-1];
            }
            else
            {
               data->ptrVal = strdup(knownDevices[position_list[0]-1]);
            }
            free(position_list);
         }
      }
   }

   /* free at exit of this module */
   if ( knownDevices )
   {
      for ( i = 0; i < count; i++ )
         free(knownDevices[i]);
      free(knownDevices);
      knownDevices = NULL;
   }
   data->actWindow = configWindow;
   *data->wait = 1;
}
