summaryrefslogtreecommitdiffstats
path: root/knode/utilities.cpp
blob: 31d36369c3b0d8cb242f6abf285157c2cc45b32f (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
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
/*
    KNode, the KDE newsreader
    Copyright (c) 1999-2005 the KNode authors.
    See file AUTHORS for details

    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.
    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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US
*/

#include <tqlayout.h>
#include <tqregexp.h>
#include <tqapplication.h>
#include <tqcursor.h>

#include <klocale.h>
#include <kmessagebox.h>
#include <kglobalsettings.h>
#include <kdebug.h>
#include <kio/netaccess.h>
#include <ktempfile.h>
#include <kfiledialog.h>

#include "knwidgets.h"
#include "knglobals.h"
#include "utilities.h"



//================================================================================

KNFile::KNFile(const TQString& fname)
 : TQFile(fname), filePos(0), readBytes(0)
{
  buffer.resize(512);
  dataPtr=buffer.data();
  dataPtr[0]='\0';
}


KNFile::~KNFile()
{
}


const TQCString& KNFile::readLine()
{
  filePos=at();
  readBytes=TQFile::readLine(dataPtr, buffer.size()-1);
  if(readBytes!=-1) {
    while ((dataPtr[readBytes-1]!='\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) {  // don't get tricked by files without newline
      at(filePos);
      if (!increaseBuffer() ||
         (readBytes=TQFile::readLine(dataPtr, buffer.size()-1))==-1) {
        readBytes=1;
        break;
      }
    }
  } else
    readBytes=1;

  dataPtr[readBytes-1] = '\0';
  return buffer;
}


const TQCString& KNFile::readLineWnewLine()
{
  filePos=at();
  readBytes=TQFile::readLine(dataPtr, buffer.size()-1);
  if(readBytes!=-1) {
    while ((dataPtr[readBytes-1]!='\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) {  // don't get tricked by files without newline
      at(filePos);
      if (!increaseBuffer() ||
         (readBytes=TQFile::readLine(dataPtr, buffer.size()-1))==-1) {
        dataPtr[0] = '\0';
        break;
      }
    }
  }
  else dataPtr[0] = '\0';

  return buffer;
}


int KNFile::findString(const char *s)
{
  TQCString searchBuffer;
  searchBuffer.resize(2048);
  char *buffPtr = searchBuffer.data(), *pos;
  int readBytes, currentFilePos;

  while (!atEnd()) {
    currentFilePos = at();
    readBytes = readBlock(buffPtr, 2047);
    if (readBytes == -1)
      return -1;
    else
      buffPtr[readBytes] = 0;       // terminate string

    pos = strstr(buffPtr,s);
    if (pos == 0) {
      if (!atEnd())
        at(at()-strlen(s));
      else
        return -1;
    } else {
      return currentFilePos + (pos-buffPtr);
    }
  }

  return -1;
}


bool KNFile::increaseBuffer()
{
  if(buffer.resize(2*buffer.size())) {;
    dataPtr=buffer.data();
    dataPtr[0]='\0';
    kdDebug(5003) << "KNFile::increaseBuffer() : buffer doubled" << endl;
    return true;
  }
  else return false;
}


//===============================================================================

TQString KNSaveHelper::lastPath;

KNSaveHelper::KNSaveHelper(TQString saveName, TQWidget *parent)
  : p_arent(parent), s_aveName(saveName), file(0), tmpFile(0)
{
}


KNSaveHelper::~KNSaveHelper()
{
  if (file) {       // local filesystem, just close the file
    delete file;
  } else
    if (tmpFile) {      // network location, initiate transaction
      tmpFile->close();
      if (TDEIO::NetAccess::upload(tmpFile->name(),url, 0) == false)
        KNHelper::displayRemoteFileError();
      tmpFile->unlink();   // delete temp file
      delete tmpFile;
    }
}


TQFile* KNSaveHelper::getFile(const TQString &dialogTitle)
{
  url = KFileDialog::getSaveURL(lastPath + s_aveName, TQString(), p_arent, dialogTitle);

  if (url.isEmpty())
    return 0;

  lastPath = url.upURL().url();

  if (url.isLocalFile()) {
    if (TQFileInfo(url.path()).exists() &&
        (KMessageBox::warningContinueCancel(knGlobals.topWidget,
                                            i18n("<qt>A file named <b>%1</b> already exists.<br>Do you want to replace it?</qt>").arg(url.path()),
                                            dialogTitle, i18n("&Replace")) != KMessageBox::Continue)) {
      return 0;
    }

    file = new TQFile(url.path());
    if(!file->open(IO_WriteOnly)) {
      KNHelper::displayExternalFileError();
      delete file;
      file = 0;
    }
    return file;
  } else {
    tmpFile = new KTempFile();
    if (tmpFile->status()!=0) {
      KNHelper::displayTempFileError();
      delete tmpFile;
      tmpFile = 0;
      return 0;
    }
    return tmpFile->file();
  }
}


//===============================================================================

TQString KNLoadHelper::l_astPath;

KNLoadHelper::KNLoadHelper(TQWidget *parent)
  : p_arent(parent), f_ile(0)
{
}


KNLoadHelper::~KNLoadHelper()
{
  delete f_ile;
  if (!t_empName.isEmpty())
    TDEIO::NetAccess::removeTempFile(t_empName);
}


KNFile* KNLoadHelper::getFile( const TQString &dialogTitle )
{
  if (f_ile)
    return f_ile;

  KURL url = KFileDialog::getOpenURL(l_astPath,TQString(),p_arent,dialogTitle);

  if (url.isEmpty())
    return 0;

  l_astPath = url.url(-1);
  l_astPath.truncate(l_astPath.length()-url.fileName().length());

  return setURL(url);
}


KNFile* KNLoadHelper::setURL(KURL url)
{
  if (f_ile)
    return f_ile;

  u_rl = url;

  if (u_rl.isEmpty())
    return 0;

  TQString fileName;
  if (!u_rl.isLocalFile()) {
    if (TDEIO::NetAccess::download(u_rl, t_empName, 0))
      fileName = t_empName;
  } else
    fileName = u_rl.path();

  if (fileName.isEmpty())
    return 0;

  f_ile = new KNFile(fileName);
  if(!f_ile->open(IO_ReadOnly)) {
    KNHelper::displayExternalFileError();
    delete f_ile;
    f_ile = 0;
  }
  return f_ile;
}


//===============================================================================


// **** keyboard selection dialog *********************************************
int KNHelper::selectDialog(TQWidget *parent, const TQString &caption, const TQStringList &options, int initialValue)
{
  KDialogBase *dlg=new KDialogBase(KDialogBase::Plain, caption, KDialogBase::Ok|KDialogBase::Cancel,
                                   KDialogBase::Ok, parent);
  TQFrame *page = dlg->plainPage();
  TQHBoxLayout *pageL = new TQHBoxLayout(page,8,5);

  KNDialogListBox *list = new KNDialogListBox(true, page);
  pageL->addWidget(list);

  TQString s;
  for ( TQStringList::ConstIterator it = options.begin(); it != options.end(); ++it ) {
    s = (*it);
    s.replace(TQRegExp("&"),"");   // remove accelerators
    list->insertItem(s);
  }

  list->setCurrentItem(initialValue);
  list->setFocus();
  restoreWindowSize("selectBox", dlg, TQSize(247,174));

  int ret;
  if (dlg->exec())
    ret = list->currentItem();
  else
    ret = -1;

  saveWindowSize("selectBox", dlg->size());
  delete dlg;
  return ret;
}

// **** window geometry managing *********************************************

void KNHelper::saveWindowSize(const TQString &name, const TQSize &s)
{
  TDEConfig *c=knGlobals.config();
  c->setGroup("WINDOW_SIZES");
  c->writeEntry(name, s);
}


void KNHelper::restoreWindowSize(const TQString &name, TQWidget *d, const TQSize &defaultSize)
{
  TDEConfig *c=knGlobals.config();
  c->setGroup("WINDOW_SIZES");

  TQSize s=c->readSizeEntry(name,&defaultSize);

  if(s.isValid()) {
    TQRect max = TDEGlobalSettings::desktopGeometry(TQCursor::pos());
    if ( s.width() > max.width() ) s.setWidth( max.width()-5 );
    if ( s.height() > max.height() ) s.setHeight( max.height()-5 );
    d->resize(s);
  }
}

// **** scramble password strings **********************************************

const TQString KNHelper::encryptStr(const TQString& aStr)
{
  uint i,val,len = aStr.length();
  TQCString result;

  for (i=0; i<len; i++)
  {
    val = aStr[i] - ' ';
    val = (255-' ') - val;
    result += (char)(val + ' ');
  }

  return result;
}


const TQString KNHelper::decryptStr(const TQString& aStr)
{
  return encryptStr(aStr);
}

// **** rot13 *******************************************************************

TQString KNHelper::rot13(const TQString &s)
{
  TQString r(s);

  for (int i=0; (uint)i<r.length(); i++) {
    if ( r[i] >= TQChar('A') && r[i] <= TQChar('M') ||
         r[i] >= TQChar('a') && r[i] <= TQChar('m') )
         r[i] = (char)((int)TQChar(r[i]) + 13);
    else
      if  ( r[i] >= TQChar('N') && r[i] <= TQChar('Z') ||
            r[i] >= TQChar('n') && r[i] <= TQChar('z') )
        r[i] = (char)((int)TQChar(r[i]) - 13);
  }

  return r;
}

// **** text rewraping *********************************************************

int findBreakPos(const TQString &text, int start)
{
  int i;
  for(i=start;i>=0;i--)
    if(text[i].isSpace())
      break;
  if(i>0)
    return i;
  for(i=start;i<(int)text.length();i++)   // ok, the line is to long
    if(text[i].isSpace())
      break;
  return i;
}


void appendTextWPrefix(TQString &result, const TQString &text, int wrapAt, const TQString &prefix)
{
  TQString txt=text;
  int breakPos;

  while(!txt.isEmpty()) {

    if((int)(prefix.length()+txt.length()) > wrapAt) {
      breakPos=findBreakPos(txt,wrapAt-prefix.length());
      result+=(prefix+txt.left(breakPos)+"\n");
      txt.remove(0,breakPos+1);
    } else {
      result+=(prefix+txt+"\n");
      txt=TQString();
    }
  }
}


TQString KNHelper::rewrapStringList(TQStringList text, int wrapAt, TQChar quoteChar, bool stopAtSig, bool alwaysSpace)
{
  TQString quoted, lastPrefix, thisPrefix, leftover, thisLine;
  int breakPos;

  for(TQStringList::Iterator line=text.begin(); line!=text.end(); ++line) {

    if(stopAtSig && (*line)=="-- ")
      break;

    thisLine=(*line);
    if (!alwaysSpace && (thisLine[0]==quoteChar))
      thisLine.prepend(quoteChar);  // second quote level without space
    else
      thisLine.prepend(TQString(quoteChar)+' ');

    thisPrefix=TQString();
    TQChar c;
    for(int idx=0; idx<(int)(thisLine.length()); idx++) {
      c=thisLine.at(idx);
      if( (c==' ') ||
          (c==quoteChar) || (c=='>') ||(c=='|') || (c==':') || (c=='#') || (c=='[') || (c=='{'))
        thisPrefix.append(c);
      else
        break;
    }

    thisLine.remove(0,thisPrefix.length());
    thisLine = thisLine.stripWhiteSpace();

    if(!leftover.isEmpty()) {   // don't break paragraphs, tables and quote levels
      if(thisLine.isEmpty() || (thisPrefix!=lastPrefix) || thisLine.contains("  ") || thisLine.contains('\t'))
        appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);
      else
        thisLine.prepend(leftover+" ");
      leftover=TQString();
    }

    if((int)(thisPrefix.length()+thisLine.length()) > wrapAt) {
      breakPos=findBreakPos(thisLine,wrapAt-thisPrefix.length());
      if(breakPos < (int)(thisLine.length())) {
        leftover=thisLine.right(thisLine.length()-breakPos-1);
        thisLine.truncate(breakPos);
      }
    }

    quoted+=thisPrefix+thisLine+"\n";
    lastPrefix=thisPrefix;
  }

  if (!leftover.isEmpty())
    appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);

  return quoted;
}

// **** misc. message-boxes **********************************************************

void KNHelper::displayInternalFileError(TQWidget *w)
{
  KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to load/save configuration.\nWrong permissions on home folder?\nYou should close KNode now to avoid data loss."));
}


void KNHelper::displayExternalFileError(TQWidget *w)
{
  KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to load/save file."));
}


void KNHelper::displayRemoteFileError(TQWidget *w)
{
  KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to save remote file."));
}


void KNHelper::displayTempFileError(TQWidget *w)
{
  KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to create temporary file."));
}