summaryrefslogtreecommitdiff
path: root/noncore/apps/opie-gutenbrowser/LibraryDialog.cpp
blob: 6c246e97ac46ed74761a307ede2a6414c7f95fd2 (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
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
/***************************************************************************
//                            LibraryDialog.cpp  -  description
//                               -------------------
//      begin                : Sat Aug 19 2000
//      copyright            : (C) 2000 - 2004 by llornkcor
//      email                : ljp@llornkcor.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.                                   *
//   ***************************************************************************/
//ftp://ibiblio.org/pub/docs/books/gutenberg/GUTINDEX.ALL

#include "LibraryDialog.h"
#include "output.h"

/* OPIE */
#include <qpe/applnk.h>
#include <qpe/qpeapplication.h>
#include <qpe/qpedialog.h>
//#include <opie2///odebug.h>

/* QT */
#include <qpushbutton.h>
#include <qmultilineedit.h>
//#include <qlayout.h>

/* STD */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

/*
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  true to construct a modal dialog. */
LibraryDialog::LibraryDialog( QWidget* parent,  const char* name , bool /*modal*/, WFlags fl )
   : QDialog( parent, name, true/* modal*/, fl )
{
   if ( !name )
      setName( "LibraryDialog" );
   indexLoaded=false;
   initDialog();

   //      this->setMaximumWidth(240);

   index = "GUTINDEX.ALL";
   local_library = (QDir::homeDirPath ()) +"/Applications/gutenbrowser/";
   local_index = local_library + index;

   QString iniFile ;
   iniFile = local_library + "/gutenbrowserrc";
   new_index = local_library + "/PGWHOLE.TXT";
   old_index = local_index;
   //     iniFile = local_library+"gutenbrowserrc";
   //     new_index = local_library + "PGWHOLE.TXT";
   //     old_index = local_library + "GUTINDEX.ALL";

   Config config("Gutenbrowser");

   config.setGroup( "HttpServer" );
   proxy_http = config.readEntry("Preferred", "http://sailor.gutenbook.org");

   config.setGroup( "FTPsite" );
   ftp_host = config.readEntry("SiteName", "sailor.gutenberg.org");
   //odebug << "Library Dialog: ftp_host is "+ftp_host << oendl;
   //      ftp_host=ftp_host.right(ftp_host.length()-(ftp_host.find(") ",0,true)+1) );
   //      ftp_host=ftp_host.stripWhiteSpace();
   ftp_base_dir= config.readEntry("base",  "/pub/gutenberg");

   i_binary = 0;

   config.setGroup("SortAuth");
   if( config.readEntry("authSort", "false") == "true")
      authBox->setChecked(true);

   config.setGroup("General");
   downDir = config.readEntry( "DownloadDirectory",local_library);
   //odebug << "downDir is "+downDir << oendl;
   newindexLib.setName( old_index);
   indexLib.setName( old_index);

   new QPEDialogListener(this);
   QTimer::singleShot( 1000, this, SLOT( FindLibrary()) );

}

LibraryDialog::~LibraryDialog()
{
}

void  LibraryDialog::clearItems() {
		ListView1->clear();
		ListView2->clear();
		ListView3->clear();
		ListView4->clear();
		ListView5->clear();
}

/*This groks using PGWHOLE.TXT */
void  LibraryDialog::Newlibrary()
{
		clearItems();
#ifndef Q_WS_QWS //sorry embedded gutenbrowser cant use zip files
   ////odebug << "Opening new library index " << newindexLib << "" << oendl;
   if ( newindexLib.open( IO_ReadOnly) ) {
      setCaption( tr( "Library Index - using master pg index."  ) );// file opened successfully
      QTextStream indexStream( &newindexLib );
      QString indexLine;
      while ( !indexStream.atEnd() )  { // until end of file..
         indexLine = indexStream.readLine();
         if ( ( indexLine.mid(4,4)).toInt() && !( indexLine.left(3)).toInt())  {
            year = indexLine.mid(4,4);
            file = indexLine.mid( indexLine.find( "[", 0, true )+1, 12 );
            number = indexLine.mid(  indexLine.find( "]", 0, true ) +1, indexLine.find( " ", 0, true )+1 );
            if( year.toInt() < 1984)
               number = number.left( number.length() -1 );
            title = indexLine.mid( indexLine.find(" ", 26, true), indexLine.length() );

						addItems();

         }// end if
      }// end while
      newindexLib.close();
   }
#ifndef Q_WS_QWS
   setCursor(  arrowCursor);
#endif
#endif
} // end Newlibrary()


void LibraryDialog::Library() {
   clearItems();
		
//		qDebug( "opening GUTINDEX.ALL file");
   IDontKnowWhy = "";
   system("date");
   if ( indexLib.open( IO_ReadOnly) ) {
// file opened successfully
      QTextStream indexStream( &indexLib );
      QString indexLine;
      qApp->processEvents();
      
      bool okToRead = false;
      while ( !indexStream.eof() ) {
         indexLine = indexStream.readLine();
         if(indexLine == "<==Start GUTINDEX.ALL listings==>")
            okToRead = true;
         if(indexLine == "<==End of GUTINDEX.ALL==>") {
            okToRead = false;
            indexLib.at(indexLib.size());
         }

         if(okToRead) {
            QStringList token = QStringList::split(' ', indexLine);
            int textNumber;
            if(( textNumber = token.last().toInt() ))
               if(textNumber > 10001) {
//            qWarning("Last "+token.last());
// newer files with numbers > 100000 have new dir structure and need to be parsed differently..
                  if(textNumber < 10626)
                     year = "2003";
                  else if(textNumber >= 10626 && textNumber < 14600)
                     year = "2004";
                  else if(textNumber >= 14600)
                     year = "2005";

                  file = token.last();
                  title = indexLine.mid(0,72);

                  addItems(); //author and qlistview
                  //	qDebug("file number is " + number + " title is " + title );

               } else { //end new etexts
                  
                  if(token[1].toInt() && token[1].toInt() > 1969) {
                     year = token[1];
                     file = indexLine.mid(60,12);

                     if(file.left(1).find("[",0,TRUE) != -1) {
                        file.remove(1,1);
                        if( file.find("]",0,TRUE) != -1)
                           file = file.left( file.find("]",0,TRUE));

                        if(file.find("?", 0, false) != -1 ) {
                           QString tmpfile = file.replace(QRegExp("[?]"), "8");
                           file = tmpfile;
                        }
                     title = indexLine.mid( 9, 50);

                     addItems(); 
                  }
                  } else { // then try new format texts
                     file = token.last();
                     title = indexLine.mid(0,72);
                     year = "1980";

                     addItems(); //author and qlistview
                  }
               } //end old etexts

         } //end okToTRead
      }
      indexLib.close();
   } else {
      QString sMsg;
      
      sMsg = ( tr("<p>Error opening library index file. Please download a new one.</P> "));
      QMessageBox::message( "Error",sMsg);
   }
   system("date");
   sortLists(0);
   
} //end Library()


/*
  Groks the author out of the title */
bool LibraryDialog::getAuthor()
{
   if( title.contains( ", by", true)) {
      int auth;
      auth = title.find(", by", 0, true);
      author = title.right(title.length() - (auth + 4) );
      if( int finder = author.find("[", 0, true)) {
         author = author.left(finder);
      }
   }
   else if ( title.contains( "by, ", true) ) {
      int auth;
      auth = title.find("by, ", 0, true);
      author = title.right(title.length() - (auth + 4) );
      if( int finder = author.find("[", 0, true)) {
         author = author.left( finder);
      }
   }
   else if ( title.contains( " by", true) ) {
      int auth;
      auth = title.find(" by", 0, true);
      author = title.right(title.length() - (auth + 3) );
      if( int finder = author.find("[", 0, true)) {
         author = author.left( finder);
      }
   }
   else if ( title.contains( "by ", true) ) {
      int auth;
      auth = title.find("by ", 0, true);
      author = title.right(title.length() - (auth + 3) );
      if( int finder = author.find("[", 0, true)) {
         author = author.left( finder);
      }
   }
   else if ( title.contains( ",", true) ) {
      int auth;
      auth = title.find(",", 0, true);
      author = title.right( title.length() - (auth + 1) );
      if ( author.contains( ",", true) ) {
         int auth;
         auth = author.find(",", 0, true);
         author = author.right( author.length() - (auth + 1) );
      }
      if( int finder = author.find("[", 0, true)) {
         author = author.left( finder);
      }
   }
   else if ( title.contains( "/", true) ) {
      int auth;
      auth = title.find("/", 0, true);
      author = title.right(title.length() - (auth + 1) );
      if( int finder = author.find("[", 0, true)) {
         author = author.left( finder);
      }
   }
   else if ( title.contains( "of", true) ) {
      int auth;
      auth = title.find("of", 0, true);
      author = title.right(title.length() - (auth + 2) );
      if( int finder = author.find("[", 0, true))
      {
         author = author.left( finder);
      }
   } else {
      author = "";
   }
   if ( author.contains("et. al")) {
      int auth;
      auth = author.find("et. al", 0, true);
      author = author.left( auth );
   }
   if ( author.contains("#")) {
      int auth;
      auth = author.find("#", 0, true);
      author = author.left( auth);
   }
   if ( author.contains("(")) {
      int auth;
      auth = author.find("(", 0, true);
      author = author.left( auth);
   }
   if ( author.contains("et al")) {
      int auth;
      auth = author.find("et al", 0, true);
      author = author.left( auth );
   }
   QRegExp r = QRegExp("[0-9]", true, false);
   if ( author.left(2).find( r) != -1 ) {
			 author = "";
   }

	 author = author.stripWhiteSpace();
	 if (authBox->isChecked() == TRUE) { // this reverses the first name and last name of the author
			 QString lastName, firstName="";
			 int finder = author.findRev( ' ', -1, TRUE);
			 lastName = author.right( author.length()-finder);
			 firstName = author.left(finder);
			 lastName = lastName.stripWhiteSpace();
			 firstName = firstName.stripWhiteSpace();

			 if( lastName.find( firstName, 0, true)  == -1) // this avoids dup names
					 author = lastName+", "+firstName;
	 }
   return true;
}////// end getAuthor()

void LibraryDialog::addItems()
{
   cleanStrings();
   getAuthor();  // grok author

    etext etextStruct;
   if(  /*!number.isEmpty()
          && */
      (title.find( "reserved",0, FALSE) == -1)
       && (file.find( "]",0, true) == -1)
       &&(title.find( "Audio",0, FALSE) == -1)) {
//				qDebug("new item "+title);
      // fill string list or something to be able to sort by Author
       etextStruct.title = title;
       etextStruct.author = author;
       etextStruct.year = year;
       etextStruct.file = file;
      
      etextLibrary.append( etextStruct);

      if( author.isEmpty() )
         QList_Item5 = new QListViewItem( ListView5,  /*number, */author, title,  year, file );
      else  {
         if( author.find(QRegExp("[^a-fA-F]")) )
            QList_Item1 = new QListViewItem( ListView1, /* number,*/author,  title, year, file );

         else if(author.find(QRegExp("[^g-mG-M]")) )
            QList_Item2 = new QListViewItem( ListView2, /* number,*/ author, title,year, file );

         else if(author.find(QRegExp("[^n-rN-R]")) )
            QList_Item3 = new QListViewItem( ListView3, /* number,*/ author, title, year, file );

         else if(author.find(QRegExp("[^s-zS-Z]")) )
            QList_Item4 = new QListViewItem( ListView4, /* number,*/ author, title, year, file );
      }
   }
}

/*
  selected one etext*/
void LibraryDialog::select_title( QListViewItem * item)
{
   if(item != NULL) {
      i++;
      int index = tabWidget->currentPageIndex();
      DlglistItemTitle = item->text(0);
      DlglistItemYear = item->text(2);
      DlglistItemFile = item->text(3);

      switch (index) {
      case 0: {
         ListView1->clearSelection();
      }
         break;
      case 1: {
         ListView2->clearSelection();
      }
         break;
      case 2: {
         ListView3->clearSelection();
      }
         break;
      case 3: {
         ListView4->clearSelection();
      }
         break;
      case 4: {
         ListView5->clearSelection();
      }
         break;
      };
   }

   if(DlglistItemTitle.length() > 2) {
      item = 0;
      // todo check for connection here

      bool ok = false;
			qDebug(DlglistItemFile);
			
      if(	DlglistItemFile.toInt() > 10000 ) {
         // new directory sturcture
         if( download_newEtext())
            ok = true;
      } else {
         if(download_Etext())
            ok = true;
      }
      if(ok) {
         if(checkBox->isChecked () ) 
            accept();
      }
	 }
}

bool LibraryDialog::download_newEtext()
{ // ftp method
		QString fileName = DlglistItemFile;

    QString directory;
    int stringlength = DlglistItemFile.length();
    for(i = 0; i < stringlength - 1;  i++ ) {
				directory += "/"+ DlglistItemFile[i];
    }

		directory += "/" + DlglistItemFile;

//    qWarning(directory);

    Config cfg("Gutenbrowser");
		cfg.setGroup("FTPsite");
		ftp_host = cfg.readEntry("SiteName", "sailor.gutenberg.org");
		ftp_base_dir = cfg.readEntry("base",  "/pub/gutenberg");

		if( ftp_base_dir.find("=",0,true) )
				ftp_base_dir.remove(  ftp_base_dir.find("=",0,true),1);

		QString dir = ftp_base_dir + directory;
		QString outputFile = local_library + ".guten_temp";
		QString file =  fileName + ".txt";

		QStringList networkList;
		networkList.append((const char *)ftp_host); //host
		networkList.append((const char *)dir); //ftp base directory
		networkList.append((const char *)outputFile); //output filepath
		networkList.append((const char *)file); //filename

		getEtext( networkList);
   
		return true;		
}

bool LibraryDialog::getEtext(const QStringList &networkList)
{
   NetworkDialog *NetworkDlg;
   NetworkDlg = new NetworkDialog( this,"Network Protocol Dialog", true, 0, networkList);

// use new, improved, *INSTANT* network-dialog-file-getterer
   if( NetworkDlg->exec() != 0 ) {
      File_Name = NetworkDlg->localFileName;

      qDebug("Just downloaded " + NetworkDlg->localFileName);

      if(NetworkDlg->successDownload) {
         //odebug << "Filename is "+File_Name << oendl;
         if(File_Name.right(4) == ".txt") {
            QString  s_fileName = File_Name;
            s_fileName.replace( s_fileName.length() - 3, 3, "gtn");
            //                s_fileName.replace( s_fileName.length()-3,3,"etx");
            rename( File_Name.latin1(), s_fileName.latin1());
            File_Name = s_fileName;

            //odebug << "Filename is now "+File_Name << oendl;

         }
         if(File_Name.length() > 5 ) {
            setTitle();
            QFileInfo fi(File_Name);
            QString  name_file = fi.fileName();
            name_file = name_file.left( name_file.length() - 4);

            //odebug << "Setting doclink" << oendl;
            DocLnk lnk;
            //odebug << "name is "+name_file << oendl;
            lnk.setName(name_file); //sets file name
            //odebug << "Title is "+DlglistItemTitle << oendl;
            lnk.setComment(DlglistItemTitle);

            //odebug << "Filename is "+File_Name << oendl;
            lnk.setFile(File_Name); //sets File property
            lnk.setType("guten/plain");// hey is this a REGISTERED mime type?!?!? ;D
            lnk.setExec(File_Name);
            lnk.setIcon("gutenbrowser/Gutenbrowser");
            if(!lnk.writeLink()) {
               //odebug << "Writing doclink did not work" << oendl;
            } else {
            }
         } else
            QMessageBox::message("Note","<p>There was an error with the file</p>");
      }
   }

   return true;
}

bool LibraryDialog::download_Etext()
{ // ftp method
  // might have to use old gpl'd ftp for embedded!!

   Config cfg("Gutenbrowser");
   cfg.setGroup("FTPsite");
   ftp_host = cfg.readEntry("SiteName", "sailor.gutenberg.org");
   ftp_base_dir = cfg.readEntry("base",  "/pub/gutenberg");

  qDebug( "about to network dialog");

	QString NewlistItemNumber, NewlistItemYear, ls_result, result_line, s, dir, /*networkUrl, */outputFile;

   //////////////////// FIXME- if 'x' is part of real name....
   NewlistItemFile = DlglistItemFile.left(DlglistItemFile.find(".xxx", 1, false)).left(DlglistItemFile.left(DlglistItemFile.find(".xxx", 1, false)).find("x", 1, false));

   if( NewlistItemFile.find( DlglistItemFile.left(4) ,0,true) ==-1 ) {
      NewlistItemFile.replace( 0,4, DlglistItemFile.left(4));
			qDebug("NewlistItemFile is now " + NewlistItemFile);
   }
	 
   NewlistItemYear = DlglistItemYear.right(2);
   int NewlistItemYear_Int = NewlistItemYear.toInt(0, 10);
   //odebug << NewlistItemYear << oendl;
   if (NewlistItemYear_Int < 91 && NewlistItemYear_Int > 70) {
      NewlistItemYear = "90";
   }

   Edir ="etext" +NewlistItemYear;

   dir = ftp_base_dir + "/etext"  + NewlistItemYear + "/";

   if( ftp_base_dir.find("=",0,true) )
      ftp_base_dir.remove(  ftp_base_dir.find("=",0,true),1);

//   networkUrl = "ftp://"+ftp_host+dir;

   outputFile = local_library+".guten_temp";

	 qDebug( "Download file: " +NewlistItemFile);
	 qDebug("Checking: " + ftp_host + " " + dir + " " + outputFile+" " + NewlistItemFile);
	

   QStringList networkList;
   networkList.append((const char *)ftp_host); //host
   networkList.append((const char *)dir); //ftp base directory
   networkList.append((const char *)outputFile); //output filepath
   networkList.append((const char *)NewlistItemFile); //filename
//<< (char *)ftp_host << (char *)dir << (char *)outputFile << (char *)NewlistItemFile;
   getEtext( networkList);
   
 return true;
}

bool LibraryDialog::httpDownload()
{//  httpDownload
#ifndef Q_WS_QWS
   Config config("Gutenbrowser");
   config.setGroup( "Browser" );
   QString brow = config.readEntry("Preferred", "");
   QString file_name = "./.guten_temp";
   //    config.setGroup( "HttpServer" );
   //    QString s_http = config.readEntry("Preferred", "http://sailor.gutenbook.org");
   QString httpName = proxy_http + "/"+Edir;
   //    progressBar->setProgress( i);
   i++;
   if ( brow != "Konq")    { /////////// use lynx
      //        QString cmd = "lynx -source " + httpName +" | cat >> " + file_name;
      //        system(cmd);
   }    else    { //////////// use KFM
      //        KFM::download( httpName, file_name);
   }
   i++;
   QFile tmp( file_name);
   QString str;
   if (tmp.open(IO_ReadOnly))    {
      QTextStream t( &tmp );   // use a text stream
      while ( !t.eof())  {
         QString s = t.readLine();
         if (s.contains( NewlistItemFile, false) && (s.contains(".txt")) ) {
            str = s.mid( s.find( ".txt\">"+NewlistItemFile, 0, true)+6, (s.find( ".txt</A>", 0, true) + 4) - ( s.find( ".txt\">"+NewlistItemFile, 0, true)+6 ) );
            httpName += "/" + str;
         }
      }  //end of while loop
   }
   tmp.close();
   m_getFilePath = local_library + str;
   i++;
   if ( brow != "KFM"){ ///////// use lynx
      QString cmd = "lynx -source " + httpName +" | cat >> " + m_getFilePath;
      //        QMessageBox::message("Error", cmd);
      system(cmd);
   } else { ////////// use KFM
      //        KFM::download( httpName, m_getFilePath);
   }
   i++;
#endif
   return false;
}

void LibraryDialog::cancelIt()
{
   saveConfig();

   DlglistItemNumber = "";
   this->reject();
}

bool LibraryDialog::setTitle()
{
   Config config("Gutenbrowser");
   //odebug << "setting title" << oendl;
   //odebug << DlglistItemTitle << oendl;

   if( DlglistItemTitle.find("[",0,true) != -1)
      DlglistItemTitle.replace(DlglistItemTitle.find("[",0,true),1, "(" );
   if( DlglistItemTitle.find("]",0,true) !=-1)
      DlglistItemTitle.replace(DlglistItemTitle.find("]",0,true),1, ")" );
   //odebug << "Title being set is "+DlglistItemTitle << oendl;
   int test = 0;
   QString ramble, temp;
   config.setGroup("Files");
   QString s_numofFiles = config.readEntry("NumberOfFiles", "0" );
   int  i_numofFiles = s_numofFiles.toInt();
   for ( int i = 0; i <= i_numofFiles; i++){
      temp.setNum( i);
      ramble  = config.readEntry( temp, "" );
      if( strcmp( ramble, File_Name) == 0){
         test = 1;
      }
   }

   if(test == 0 ) {

      config.setGroup("Files");
      config.writeEntry( "NumberOfFiles", i_numofFiles +1 );
      QString interger;
      interger.setNum( i_numofFiles +1);
      config.writeEntry( interger, File_Name);
      config.setGroup( "Titles" );
      config.writeEntry( File_Name, DlglistItemTitle);
   }
   test = 0;
   return true;
}


void LibraryDialog::saveConfig()
{
   Config config("Gutenbrowser");
   if( httpBox->isChecked() == true) {
      checked = 1;
      config.setGroup( "Proxy" );
      config.writeEntry("IsChecked", "true");
   } else {
      checked = 0;
      config.setGroup( "Proxy" );
      config.writeEntry("IsChecked", "false");
   }
   if (authBox->isChecked() == true) {
      config.setGroup("SortAuth");
      config.writeEntry("authSort", "true");
   } else {
      config.setGroup("SortAuth");
      config.writeEntry("authSort", "false");
   }
   //    config.write();
}

/*
  searches library index for user word*/
void LibraryDialog::onButtonSearch()
{
   ListView1->clearSelection();
   ListView2->clearSelection();
   ListView3->clearSelection();
   ListView4->clearSelection();
   ListView5->clearSelection();

   int curTab = tabWidget->currentPageIndex();
   SearchDialog* searchDlg;

   //  if( resultsList)
   searchDlg = new SearchDialog( this, "Library Search", true);
   searchDlg->setCaption( tr( "Library Search"  ) );
   searchDlg->setLabel( "- author or title");

   QString resultString;

	 int i_berger = 0;
   if( searchDlg->exec() != 0 )  {
      QString searcherStr = searchDlg->get_text();
      int fluff = 0;

      bool cS;
      if( searchDlg->caseSensitiveCheckBox->isChecked())
         cS = true; //case sensitive
      else
         cS = false;

        etext etextStruct;
         QValueList<etext>::Iterator it;

        for( it = etextLibrary.begin(); it != etextLibrary.end(); ++it ) {
           QString tempTitle = (*it).title;
           QString tempAuthor = (*it).author;
           QString tempFile = (*it).file;
           QString tempYear = (*it).year;
           if(tempTitle.find( searcherStr, 0, cS) != -1
              || tempAuthor.find( searcherStr, 0, cS) != -1) {
              qWarning(tempTitle);
              Searchlist.append( tempTitle + " : " + tempYear + " : " + tempFile);
           }
        }


      tabWidget->setCurrentPage( curTab);

      Searchlist.sort();
      SearchResultsDlg* SearchResultsDialog;
      SearchResultsDialog = new SearchResultsDlg( searchDlg, "Results Dialog", true, 0 , Searchlist);

      SearchResultsDialog->showMaximized();
      if( SearchResultsDialog->exec() != 0) {
         texter = SearchResultsDialog->selText;
         //           //odebug << texter << oendl;
         resultLs = SearchResultsDialog->resultsList;
         i_berger = 1;
      } else {
         resultLs.clear();
      }
      Searchlist.clear();

      QString tester;
      for ( QStringList::Iterator it = resultLs.begin(); it != resultLs.end(); ++it ) {
         texter.sprintf("%s \n",(*it).latin1());
         //           //odebug << texter << oendl;
         if( tester!=texter)
            parseSearchResults( texter);
         tester = texter;
      }
      if(searchDlg)
         delete searchDlg;
   }
   if(checkBox->isChecked() ) {
      accept();
   } else {
      setActiveWindow();
   }
}

/*
  splits the result string and calls download for the current search result*/
void  LibraryDialog::parseSearchResults( QString resultStr)
{
   int stringLeng = resultStr.length();

   QString my;
   my.setNum( stringLeng, 10);

   if( resultStr.length() > 2 && resultStr.length() < 130) {
      QStringList token = QStringList::split(" : ", resultStr);

      DlglistItemTitle  = token[0];
			DlglistItemTitle = DlglistItemTitle.stripWhiteSpace();
			
      DlglistItemYear  = token[1];
      DlglistItemYear = DlglistItemYear.stripWhiteSpace();
      
      DlglistItemFile = token[2];

      DlglistItemFile = DlglistItemFile.stripWhiteSpace();
      
//      qWarning(DlglistItemYear);


			if(DlglistItemFile.left(1) == "/")
					DlglistItemFile = DlglistItemFile.right( DlglistItemFile.length() - 1);

			if(	DlglistItemFile.toInt() > 10000 || DlglistItemYear == "1980" ) {
         // new directory sturcture
					download_newEtext(); //)
      } else {
					download_Etext(); //)
      }
   }
}

void LibraryDialog::sortLists(int index)
{
	 
    ListView1->setSorting(index);
    ListView2->setSorting(index);
    ListView3->setSorting(index);
    ListView4->setSorting(index);
    ListView5->setSorting(index);
    ListView1->sort();
    ListView2->sort();
    ListView3->sort();
    ListView4->sort();
    ListView5->sort();
}

/*
  Downloads the current selected listitem*/
bool LibraryDialog::getItem(QListViewItem *it)
{
   //    //odebug << "selected getItem" << oendl;

   //    DlglistItemNumber = it->text(0);
   DlglistItemTitle = it->text(0);
   DlglistItemYear = it->text(2);
   DlglistItemFile = it->text(3);

   if(download_Etext())  {
      if(i_binary == 1)  {
      }
   }
   return true;
}

/*
  download button is pushed so we get the current items to download*/
bool LibraryDialog::onButtonDownload()
{
   //    //odebug << "selected onButtonDownloadz" << oendl;

   QListViewItemIterator it1( ListView1 );
   QListViewItemIterator it2( ListView2 );
   QListViewItemIterator it3( ListView3 );
   QListViewItemIterator it4( ListView4 );
   QListViewItemIterator it5( ListView5 );

   // iterate through all items of the listview
   for ( ; it1.current(); ++it1 ) {
      if ( it1.current()->isSelected() )
         getItem(it1.current());
      it1.current()->setSelected(false);
   }
   for ( ; it2.current(); ++it2 ) {
      if ( it2.current()->isSelected() )
         getItem(it2.current());
      it2.current()->setSelected(false);
   }
   for ( ; it3.current(); ++it3 ) {
      if ( it3.current()->isSelected() )
         getItem(it3.current());
      it3.current()->setSelected(false);
   }
   for ( ; it4.current(); ++it4 ) {
      if ( it4.current()->isSelected() )
         getItem(it4.current());
      it4.current()->setSelected(false);
   }
   for ( ; it5.current(); ++it5 ) {
      if ( it5.current()->isSelected() )
         getItem(it5.current());
      it5.current()->setSelected(false);
   }
   return true;
}


/*
  handles the sorting combo box */
void LibraryDialog::comboSelect(int index)
{
   //    //odebug << "we are sorting" << oendl;
   ListView1->setSorting( index, true);
   ListView2->setSorting( index, true);
   ListView3->setSorting( index, true);
   ListView4->setSorting( index, true);
   ListView5->setSorting( index, true);

   ListView1->sort();
   ListView2->sort();
   ListView3->sort();
   ListView4->sort();
   ListView5->sort();

   //      ListView1->triggerUpdate();
   //      ListView2->triggerUpdate();
   //      ListView3->triggerUpdate();
   //      ListView4->triggerUpdate();
   //      ListView5->triggerUpdate();
}

void LibraryDialog::newList()
{
   if(indexLoaded) {
      onButtonDownload();
   } else {
      Output *outDlg;
      buttonNewList->setDown(true);
      //odebug << "changing dir "+QPEApplication::qpeDir()+"etc/gutenbrowser" << oendl;
      QString gutenindex1 = local_library + "/GUTINDEX.ALL";
         
      QString cmd="wget -O " + gutenindex1 + " http://www.gutenberg.org/dirs/GUTINDEX.ALL 2>&1";

      int result = QMessageBox::warning( this,"Download"
                                         ,"<p>Ok to use /'wget/' to download a new library list?</P>"
                                         ,"Yes","No",0,0,1);
      qApp->processEvents();
      if(result == 0) {
         outDlg = new Output( 0, tr("Downloading Gutenberg Index...."),true);
         outDlg->showMaximized();
         outDlg->show();
         qApp->processEvents();
         FILE *fp;
         char line[130];
         outDlg->OutputEdit->append( tr("Running wget") );
         outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false);
         sleep(1);
         fp = popen(  (const char *) cmd, "r");
         if ( !fp ) {
         } else {
            //odebug << "Issuing the command\n"+cmd << oendl;
            //                 system(cmd);
            while ( fgets( line, sizeof line, fp)) {
               outDlg->OutputEdit->append(line);
               outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false);
            }
            pclose(fp);
            outDlg->OutputEdit->append("Finished downloading\n");
            outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false);
            qApp->processEvents();

            //                  if( QFile(gutenindex1).exists() ) {
            //                      QString gutenindex=QPEApplication::qpeDir()+"etc/gutenbrowser/GUTINDEX.ALL";
            //                      if( rename(gutenindex1.latin1(),gutenindex.latin1()) !=0)
            //                          //odebug << "renaming error" << oendl;
            //                  }

         }
         //               outDlg->close();
         FindLibrary();
         if(outDlg) delete outDlg;
      }
      buttonNewList->setDown(false);
     
      //         if(outDlg)
      //             delete outDlg;
   }
}

bool LibraryDialog::moreInfo()
{

   QListViewItem * item;
   item = 0;
   QString titleString;
   item = ListView1->currentItem();
   if( item != 0) {
      titleString = item->text(0);
      ListView1->clearSelection();
      item = 0;
   }
   if( item == 0)
      item = ListView2->currentItem();
   if( item != 0) {
      titleString = item->text(0);
      ListView2->clearSelection();
      item = 0;
   }
   if( item == 0)
      item = ListView3->currentItem();
   if( item != 0) {
      titleString = item->text(0);
      ListView3->clearSelection();
      item = 0;
   }
   if( item == 0)
      item = ListView4->currentItem();
   if( item != 0) {
      titleString = item->text(0);
      ListView4->clearSelection();
      item = 0;
   }
   if( item == 0)
      item = ListView5->currentItem();
   if( item != 0) {
      titleString = item->text(0);
      ListView5->clearSelection();
      item = 0;
   }
   item=0;
   if(titleString.length()>2) {
      //odebug << "Title is "+titleString << oendl;
      titleString.replace( QRegExp("\\s"), "%20");
      titleString.replace( QRegExp("'"), "%20");
      titleString.replace( QRegExp("\""), "%20");
      titleString.replace( QRegExp("&"), "%20");
      QString cmd= "http://google.com/search?q="+titleString+"&num=30&sa=Google+Search";
      cmd="opera "+cmd;
      system(cmd);
   } else
      QMessageBox::message( "Note","<p>If you select a title, this will search google.com for that title.</p>");
   return true;

}

/*
  This loads the library Index*/
void LibraryDialog::FindLibrary()
{
   buttonLibrary->setDown(true);

   qApp->processEvents();
   if( QFile( new_index).exists() /* && this->isHidden() */) {
      newindexLib.setName( new_index);
      indexLib.setName( new_index);
      //odebug << "index file is "+ new_index << oendl;
      Newlibrary();
   } else {
      newindexLib.setName( old_index);
      indexLib.setName( old_index);
      //odebug << "new index nameis "+ old_index << oendl;
      Library();
   }
   indexLoaded =true;
   buttonSearch->setEnabled(true);
   moreInfoButton->setEnabled(true);

   buttonLibrary->setDown(false);
   buttonNewList->setText("Download");
   qApp->processEvents();

}

void LibraryDialog::cleanStrings() {
   year = year.stripWhiteSpace();
   file = file.stripWhiteSpace();
   title = title.stripWhiteSpace();
   number = number.stripWhiteSpace();
	 
}

void LibraryDialog::authBoxClicked()
{
   qApp->processEvents();
   FindLibrary();
}