summaryrefslogtreecommitdiff
path: root/iup/src/iup_mask.c
blob: f241a22e35620b135b8614eead5783f06e7c43d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/** \file
 * \brief mask pattern matching
 *
 * See Copyright Notice in "iup.h"
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "iup_maskparse.h"
#include "iup_mask.h"
#include "iup_str.h"


#define IUP_MASK_FLOAT      "[+/-]?(/d+/.?/d*|/./d+)"
#define IUP_MASK_UFLOAT     "(/d+/.?/d*|/./d+)"
#define IUP_MASK_INT	      "[+/-]?/d+"
#define IUP_MASK_UINT     	"/d+"

struct _Imask
{
  char* mask_str;
  ImaskParsed* fsm;
  int casei;
  char type;
  float fmin, 
        fmax;
  int   imin,
        imax;
};


int iupMaskCheck(Imask* mask, const char *val)
{
  int ret;

  /* empty text or no mask */
  if (!val || !(*val) || !mask) 
    return 1;

  ret = iupMaskMatch(val,mask->fsm,0,NULL,NULL,NULL,mask->casei);
  if (ret == IMASK_PARTIALMATCH)
    return -1;
  if (ret != (int)strlen(val))
    return 0;

  switch(mask->type)
  {
  case 'I':
    {
      int ival = 0;
      sscanf(val,"%d",&ival);
      if(ival < mask->imin || ival > mask->imax)
        return 0;
      break;
    }
  case 'F':
    {
      float fval = 0;
      sscanf(val,"%f",&fval);
      if(fval < mask->fmin || fval > mask->fmax)
        return 0;
      break;
    }
  }

  return 1;
}

Imask* iupMaskCreate(const char* mask_str, int casei)
{
  ImaskParsed* fsm;
  Imask* mask;
  char* copy_mask_str;

  if (!mask_str)
    return NULL;

  /* Parse the mask first */
  copy_mask_str = iupStrDup(mask_str);
  if (iupMaskParse(copy_mask_str, &fsm) != IMASK_PARSE_OK)
  {
    free(copy_mask_str);
    return NULL;
  }

  mask = (Imask*)malloc(sizeof(Imask));
  memset(mask, 0, sizeof(Imask));

  mask->mask_str = copy_mask_str;
  mask->casei = casei;
  mask->fsm = fsm;

  return mask;
}

Imask* iupMaskCreateInt(int min, int max)
{
  Imask* mask;

  if (min < 0)
    mask = iupMaskCreate(IUP_MASK_INT, 0);
  else
    mask = iupMaskCreate(IUP_MASK_UINT, 0);

  if (mask)
  {
    mask->imin = min;
    mask->imax = max;
    mask->type = 'I';
  }

  return mask;
}

Imask* iupMaskCreateFloat(float min, float max)
{
  Imask* mask;

  if (min < 0)
    mask = iupMaskCreate(IUP_MASK_FLOAT, 0);
  else
    mask = iupMaskCreate(IUP_MASK_UFLOAT, 0);

  if (mask)
  {
    mask->fmin = min;
    mask->fmax = max;
    mask->type = 'F';
  }

  return mask;
}

void iupMaskDestroy(Imask* mask)
{
  free(mask->mask_str); 
  free(mask->fsm); 
  free(mask); 
}

char* iupMaskGetStr(Imask* mask)
{
  return mask->mask_str;
}