File: kexpression.cpp

package info (click to toggle)
kdewebdev 1%3A3.3.2-6
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 33,200 kB
  • ctags: 13,047
  • sloc: cpp: 165,029; sh: 9,033; perl: 3,315; makefile: 1,618; xml: 497; ansic: 83
file content (556 lines) | stat: -rw-r--r-- 17,845 bytes parent folder | download
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/***************************************************************************
                          kexpression.cpp  -  description
                             -------------------
    begin                : Mon Dec 20 1999
    copyright            : (C) 1999 by Franois Dupoux
                                  (C) 2004 Emiliano Gulmini <emi_barbarossa@yahoo.it>
    email                : dupoux@dupoux.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kexpression.h"
#include "resource.h"
#include "kfilereplacelib.h"

#include <kdebug.h>
#include <klocale.h>

#include <qfileinfo.h>
#include <qstringlist.h>
#include <qdatetime.h>
#include <qstring.h>

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

KExpression::KExpression(bool bCaseSensitive, bool bWildcards, bool bIgnoreWhitespaces, char cWord, char cLetter)
 {
   m_cLetter = cLetter; 
   m_cWord = cWord; 
   m_bCaseSensitive = bCaseSensitive; 
   m_bWildcards = bWildcards; 
   m_bIgnoreWhitespaces = bIgnoreWhitespaces;
 }
 
void KExpression::setWordWildcard(char cWord) 
{
  m_cWord = cWord;
 }
 
void KExpression::setLetterWildcard(char cLetter)
 {
  m_cLetter = cLetter;
 }
 
void KExpression::setCaseSensitive(bool bCaseSensitive)
 {
  m_bCaseSensitive = bCaseSensitive;
 }
 
void KExpression::setIgnoreWhitespaces(bool bIgnoreWhitespaces) 
{
 m_bIgnoreWhitespaces = bIgnoreWhitespaces;
}

char KExpression::wordWildcard() 
{
 return m_cWord;
}

char KExpression::letterWildcard() 
{
 return m_cLetter;
}

bool KExpression::isCaseSensitive() 
{
 return m_bCaseSensitive;
}

bool KExpression::doesIgnoreWhitespaces() 
{
 return m_bIgnoreWhitespaces;
}

bool KExpression::areWildcards()
{
 return m_bWildcards;
}

// Says if a wildcard string can be found inside a text
// Result: false = String not found
//         true = String found
// Result: nLenMatchingStr = Number of chars there are in the text the string is matching for
bool KExpression::doesStringMatch(const char *szText, int nTxtLen, const char *szString, int nStrWildcardLen, bool bBeginString, int *nLenMatchingStr/*=0*/)
{

  // --------------- 0. Check there are no errors in data passed -------------------

  if (nTxtLen < nStrWildcardLen)
    return false; // Not found

  if (nStrWildcardLen < 1)
    return false;

  // --------------- 1. Prepare comparaison ---------------------------------------

  int i;
  bool bCharMatches;
  int nLen;
  bool bRes;

  // Do the current char matches ?
  if (m_bCaseSensitive/* == true*/)
    {
      bCharMatches = (szString[0] == szText[0]);
    }
  else // case insensitive
    {        
     bCharMatches = (::tolower(szString[0]) == ::tolower(szText[0]));
    }

  // CASE 3: IGNORE WHITESPACES (\t, \n, \r, double-spaces) OPTIONS IS ACTIVATED, AND THERE IS ONE HERE
  // Very important to be before the most general cases (CASES 1 and 2), else the spaces don't work (ex: search "kde under linux" inside "kde under      linux")
  // In the example, the space before "linux" wouldn't be present before the "destruction" of the some spaces chars.
  if ((m_bIgnoreWhitespaces == true) && (bBeginString == false)) // If ignore whitespaces options enabled and can be used here
    {
      // Test if this option is need
      m_bIgnoreWhitespaces = false;
      bRes = doesStringMatch(szText, nTxtLen, szString, nStrWildcardLen, false, nLenMatchingStr);
      m_bIgnoreWhitespaces = true;

      if (bRes == false) // if matches without this option, do not make anything
        {
          bool bIsWhitespace = false;

          if (szText[0] == '\r' || szText[0] == '\t' || szText[0] == '\n' || szText[0] == ' ') // If current char is whitespace
            bIsWhitespace = true;

          /*if (szText[0] == ' ' && nTxtLen > 1 && szText[1] == ' ')
            bIsWhitespace = true;*/

          // if whitespace
          if (bIsWhitespace == true)
            {
              bRes = doesStringMatch(szText+1, nTxtLen-1, szString, nStrWildcardLen, false, &nLen);
              if (bRes) // If string is matching at the next char
                {
                  if (nLenMatchingStr)
                    *nLenMatchingStr = nLen+1;
                  return true;
                }
            }
        }
    }

  // ------------- 2. Make the comparaison ---------------------------------------

  // CASE 1: THE CURRENT CHAR MATCH BECAUSE GOOD CHAR OR CHAR WILDCARD FOUND
  // If current string char is '?' or is good --> char matches --> chech for net char
  if (bCharMatches || ((szString[0] == m_cLetter) && m_bWildcards))
    {
      // The first compared char of the string is good

      // If this is the end of the string
      if (nStrWildcardLen == 1)
        {
          if (nLenMatchingStr) // If result required
            *nLenMatchingStr = 1;

          return true; // Success --> the string matches
        }

      // If this is not the end of the searched string --> continue
      nLen=0;
      bRes = doesStringMatch(szText+1, nTxtLen-1, szString+1, nStrWildcardLen-1, false, &nLen);
      if (nLenMatchingStr) // If result required
        *nLenMatchingStr = nLen + 1; // Recursive + changed here
      return bRes;
    }

  // CASE 2: THERE IS AN EXPRESSION WILDCARD IN THE STRING
  // If current string char is '*' --> check if the word wildcard matches (if the string after '*' match)
  if (m_bWildcards && (szString[0] == m_cWord))
    {
      for (i=0; i < nTxtLen; i++) // With all next chars of the text to explore
        {
          if (nTxtLen >= nStrWildcardLen) // If it is possible the string matches with the text
            //if (nStrWildcardLen-1 >= nTxtLen-i) // If it is possible the string matches with the text
            {
              nLen = 0;
              bRes = doesStringMatch(szText+i, nTxtLen-i, szString+1, nStrWildcardLen-1, false, &nLen);

              if (bRes) // If string is matching at this char position of the text
                {
                  if (nLenMatchingStr) // If result is required
                    *nLenMatchingStr = i+nLen; // How many chars of the text the word wildcard '*' is coding for ?
                  return true;
                }
                                // if bRes == false, the string is not matching at this position, then continue the search, with for
            }
        }
    }

  // CASE 4: (ELSE) THERE IS A BAD CHAR
  // Current string char does not match
  return false;
}


int KExpression::extractWildcardsContentsFromFullString(const char *szText, int nTxtLen, const char *szString, int nStrWildcardLen, QStringList *strlResult)
{
  int nLen;
  bool bRes;
  int nRes;
  int i, j;
  char szTemp[MAX_TEXTLEN];

  // --------------- 0. Check there are no errors in data passed -------------------

  if (nTxtLen < nStrWildcardLen)
    return -1;

  if (nStrWildcardLen < 1)
    return -1;

  // ------------- 1. Make extraction ---------------------------------------

  // CASE 1: THIS IS NOT A WILDCARD
  if ((szString[0] != m_cLetter) && (szString[0] != m_cWord))
    {
      // if this is the end of the string
      if (nStrWildcardLen == 1)
        return 0;

      // This is good, recursivity will continue to read the string
      nRes = extractWildcardsContentsFromFullString(szText+1, nTxtLen-1, szString+1, nStrWildcardLen-1, strlResult);
      return nRes;
    }

  // CASE 2: THERE IS AN SIMPLE CHAR WILDCARD IN THE STRING '?'
  if (szString[0] == m_cLetter)
    {
      sprintf(szTemp, "%c", szText[0]);
      strlResult->append(szTemp);
      //printf ("APPEND CHAR (%c)\n", szText[0]);

      // if this is the end of the string
      if (nStrWildcardLen == 1)
        return 0;

      // Continue the operation
      nRes = extractWildcardsContentsFromFullString(szText+1, nTxtLen-1, szString+1, nStrWildcardLen-1, strlResult);
      return nRes;
    }

  // CASE 3: THERE IS AN EXPRESSION WILDCARD IN THE STRING '*'
  if (szString[0] == m_cWord)
    {        // We need to know how many chars the expression wildcards is coding for

      for (i=0; i < nTxtLen; i++) // With all next chars of the text to explore
        {
          if (nTxtLen-i >= nStrWildcardLen-1) // If it is possible the string matches with the text
            {
              nLen = 0;
              bRes = doesStringMatch(szText+i, nTxtLen-i, szString+1, nStrWildcardLen-1, false, &nLen);
              if (bRes) // If string is matching at this char position of the text
                {
                  for (j=0; j < i; j++)
                    szTemp[j] = szText[j];
                  szTemp[j] = 0;

                  // Copy the passed text, what '*' was coding for
                  strlResult->append(szTemp);
                  //printf ("APPEND WORD ***(%s)***\n\n", szTemp);

                  // if this is the end of the string
                  if (nStrWildcardLen+i == 0)
                    return 0;

                  // Continue the operation
                  nRes = extractWildcardsContentsFromFullString(szText+i, nTxtLen-i, szString+1, nStrWildcardLen-1, strlResult);
                  return nRes;

                }
                                // (bRes == false) must be impossible for all positions
            }
        }
    }

  return 0;
}


QString KExpression::addWildcardsContentToString(const char *szNewString, int nNewStrLen, QStringList *strList)
{
  QString strReplace;
  bool bWildcards;
  int nLenMatchingStr;
  int nWildcardsAsked;
  QStringList strlTemp;
  char szWildcard[64];
  bool bRes;
  int i;

  bWildcards = m_bWildcards; // save old value
  m_bWildcards = true;
  memset(szWildcard, 0, sizeof(szWildcard)-1);
  sprintf(szWildcard, "[#%c#]", m_cWord); // is "[#*#]" in general

  i=0;
  while(i < nNewStrLen)
    {
      // check if the current expression of (szNewString+i) is "[#*#]" (with * wildcard)
      bRes = doesStringMatch(szNewString+i, nNewStrLen-i, szWildcard, strlen(szWildcard), false, &nLenMatchingStr);

      if (bRes != true) // not a wildcard
        {
          strReplace.append(szNewString[i]);
          i++;
        }
      else // If there is a wildcard: [#*#]
        {
          strlTemp.clear();
          extractWildcardsContentsFromFullString(szNewString+i, nNewStrLen-i, szWildcard, strlen(szWildcard), &strlTemp);

          if (!strlTemp.count()) // if empty
            kdError(23000) << QString("strlTemp.count() == 0 --- String0=(%1)").arg(strlTemp[0]) << endl;
          nWildcardsAsked = strlTemp[0].toLong();

          // strList = number of wildcards in the search string
          if (nWildcardsAsked >= (int)strList->count())
            {
              g_szErrMsg = i18n("<qt>You want to insert wildcard number %1 with [#%2#], but there are only %3 wildcards. The first is [#0#] "
                                       "and not [#1#]. Then the last is [#%4#].</qt>").arg(nWildcardsAsked).arg(nWildcardsAsked).arg(strList->count()).arg( strList->count()-1);
              kdDebug(23000) << g_szErrMsg << endl;
              return QString::null;
            }

          strReplace.append((*strList)[nWildcardsAsked]);

          i += strlen(szWildcard);
        }
    }

  // restore value
  m_bWildcards = bWildcards; // save old value

  return strReplace;
}


QString KExpression::substVariablesWithValues(const QString &strOriginal, const char *szFilepath)
{
  // Save the "m_bWildcards" and "m_bIgnoreWhitespaces" values because current function need m_bWildcards to be true
  int nWildcards;
  bool bIgnoreWhitespaces;

  nWildcards = m_bWildcards;
  m_bWildcards = true;
  bIgnoreWhitespaces = m_bIgnoreWhitespaces;
  m_bIgnoreWhitespaces = false;

  QString strFormat;
  QString strResult;
  int nLenMatchingStr;
  bool bRes;
  QString strVarName, strVarFormat;
  QString strTemp;
  int i;
  QStringList strList;

  strFormat.sprintf("[$%c:%c$]", m_cWord, m_cWord); // "[$VarName:VarFormat$]"

  // For all chars of the original string...
  i = 0;
  while (i < (int)strOriginal.length())
    {
      nLenMatchingStr = 0;
      bRes = doesStringMatch(strOriginal.ascii()+i, strOriginal.length()-i, strFormat.utf8(), strFormat.length(), true, &nLenMatchingStr);

      if (bRes == true) // If a variable was found
        {
          // Get the variable name, and the variable format: "[$VarName:VarFormat$]"
          extractWildcardsContentsFromFullString(strOriginal.ascii()+i, strOriginal.length()-i, strFormat.utf8(), strFormat.length(), &strList);

          strVarName = strList[0];
          strVarFormat = strList[1];

          strTemp = variableValue(strVarName, strVarFormat, szFilepath);
          kdDebug(23000) << QString("VAR: (%1, %2) ---> (%3)").arg(strVarName).arg(strVarFormat).arg(strTemp) << endl;
          if (strTemp == QString::null) // If error
            {
              m_bIgnoreWhitespaces = bIgnoreWhitespaces;
              return QString::null;
            }


          // Add variable value to the result string
          strResult += strTemp;

          i += nLenMatchingStr; // Position in the string
        }
      else // If no variable was found
        {
          strResult.append( strOriginal[i] );
          i++;
        }
    }

  // Restore the "m_bWildcards" value
  m_bWildcards = nWildcards;
  m_bIgnoreWhitespaces = bIgnoreWhitespaces;

  return strResult;
}


QString KExpression::variableValue(const QString &strVarName, const QString &strVarFormat, const char *szFilepath)
{
  QFileInfo fi;
  fi.setFile(szFilepath);
  fi.convertToAbs();
  QString strTemp;

  //kDebugInfo("VARIABLES: [%s]: (%s)(%s)\n", szFilepath, strVarName.ascii(), strVarFormat.ascii());

  /**  FILENAME */
  if (strVarName == "filename") // Ex: "/home/fdupoux/kfilereplace.htm"
    {
      if (strVarFormat == "fullpath") // Must copy "/home/fdupoux/kfilereplace.htm"
        {
          return fi.filePath();
        }
      else if (strVarFormat == "path") // Must copy "/home/fdupoux"
        {
          return fi.dirPath(true); // absolute path
        }
      else if (strVarFormat == "fullname") // Must copy "kfilereplace.htm"
        {
          return fi.fileName();
        }
      else if (strVarFormat == "basename") // Must copy "kfilereplace"
        {
          return fi.baseName();
        }
      else // Invalid "filename" format
        {
          return QString::null;
        }
    }
  /**  FILE-LAST-WRITE-TIME */
  else if (strVarName == "filelwtime")
    {
      return formatDateTime(fi.lastModified(), strVarFormat);
    }
  /** FILE-LAST-READ-TIME */
  else if (strVarName == "filelrtime")
    {
      return formatDateTime(fi.lastRead(), strVarFormat);
    }
  // ** FILE-SIZE */
  else if (strVarName == "filesize")
    {
      if (strVarFormat == "bytes") // ex: 111222333
        {
          strTemp.sprintf("%lu", (DWORD) fi.size());
          return strTemp;
        }
      if (strVarFormat == "best") // ex: 125 MB
        {
          return KFileReplaceLib::instance()->formatSize(fi.size());
        }
      else // invalid format
        {
          return QString::null;
        }
    }
  // ** FILE-OWNER */
  else if (strVarName == "owner")
    {
      if (strVarFormat == "userid")
        {
          strTemp.sprintf("%d", fi.ownerId());
          return strTemp;
        }
      else if (strVarFormat == "groupid")
        {
          strTemp.sprintf("%d", fi.groupId());
          return strTemp;
        }
      else if (strVarFormat == "username")
        {
          return fi.owner();
        }
      else if (strVarFormat == "groupname")
        {
          return fi.group();
        }
      else // invalid format
        {
          return QString::null;
        }
    }
  // ** DATETIME  */
  else if (strVarName == "datetime")
    {
      return formatDateTime(QDateTime::currentDateTime(), strVarFormat);
    }
  
  else // ERROR: unknown variable
    {
      return QString::null;
    }

}


QString KExpression::formatDateTime(const QDateTime& dt, const QString &strVarFormat)
{
  QString strTemp;

  if (strVarFormat == "mm/dd/yyyy") // Ex: "12/31/1999"
    {
      strTemp.sprintf("%.2d/%.2d/%.4d", dt.date().month(), dt.date().day(), dt.date().year());
      return strTemp;
    }
  else if (strVarFormat == "dd/mm/yyyy") // Ex: "31/12/1999"
    {
      strTemp.sprintf("%.2d/%.2d/%.4d", dt.date().day(), dt.date().month(), dt.date().year());
      return strTemp;
    }
  else if (strVarFormat == "yyyy/mm/dd") // Ex: "1999/12/31"
    {
      strTemp.sprintf("%.4d/%.2d/%.2d", dt.date().year(), dt.date().month(), dt.date().day());
      return strTemp;
    }
  else if (strVarFormat == "string") // Ex: "Say May 20 1995"
    {
      strTemp = dt.date().toString();
      return strTemp;
    }
  else if ((strVarFormat == "yyyy/dd/mm hh:mm:ss") || (strVarFormat == "date&time")) // Ex: "1999/31/12 15:26:46"
    {
      strTemp.sprintf("%.4d/%.2d/%.2d %.2d:%.2d:%.2d", dt.date().year(), dt.date().month(), dt.date().day(), dt.time().hour(), dt.time().minute(), dt.time().second());
      return strTemp;
    }
  else if (strVarFormat == "hh/mm/ss") // Ex: "15:26:46"
    {
      strTemp.sprintf("%.2d:%.2d:%.2d", dt.time().hour(), dt.time().minute(), dt.time().second());
      return strTemp;
    }
  else // Invalid "date" format
    {
      return QString::null;
    }
}