summaryrefslogtreecommitdiffstats
path: root/src/fetch/z3950fetcher.cpp
blob: bd517ae309bd3740fe27487f3b9bf796494f8925 (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
/***************************************************************************
    copyright            : (C) 2003-2006 by Robby Stephenson
    email                : [email protected]
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of version 2 of the GNU General Public License as  *
 *   published by the Free Software Foundation;                            *
 *                                                                         *
 *   In addition, as a special exception, the author gives permission to   *
 *   link the code of this program with the OpenSSL library released by    *
 *   the OpenSSL Project (or with modified versions of OpenSSL that use    *
 *   the same license as OpenSSL), and distribute linked combinations      *
 *   including the two.  You must obey the GNU General Public License in   *
 *   all respects for all of the code used other than OpenSSL.  If you     *
 *   modify this file, you may extend this exception to your version of    *
 *   the file, but you are not obligated to do so.  If you do not wish to  *
 *   do so, delete this exception statement from your version.             *
 *                                                                         *
 ***************************************************************************/

#include <config.h>

#include "z3950fetcher.h"
#include "z3950connection.h"
#include "messagehandler.h"
#include "../collection.h"
#include "../latin1literal.h"
#include "../translators/xslthandler.h"
#include "../translators/tellicoimporter.h"
#include "../translators/grs1importer.h"
#include "../tellico_debug.h"
#include "../gui/lineedit.h"
#include "../gui/combobox.h"
#include "../isbnvalidator.h"
#include "../lccnvalidator.h"

#include <tdelocale.h>
#include <kstandarddirs.h>
#include <tdeapplication.h>
#include <knuminput.h>
#include <tdeconfig.h>
#include <kcombobox.h>
#include <tdeaccelmanager.h>
#include <kseparator.h>

#include <tqfile.h>
#include <tqlayout.h>
#include <tqlabel.h>
#include <tqwhatsthis.h>
#include <tqdom.h>

namespace {
  static const int Z3950_DEFAULT_PORT = 210;
  static const TQString Z3950_DEFAULT_ESN = TQString::fromLatin1("F");
}

using Tellico::Fetch::Z3950Fetcher;

Z3950Fetcher::Z3950Fetcher(TQObject* parent_, const char* name_)
    : Fetcher(parent_, name_), m_conn(0), m_port(Z3950_DEFAULT_PORT), m_esn(Z3950_DEFAULT_ESN),
      m_started(false), m_done(true), m_MARC21XMLHandler(0),
      m_UNIMARCXMLHandler(0), m_MODSHandler(0) {
}

Z3950Fetcher::~Z3950Fetcher() {
  delete m_MARC21XMLHandler;
  m_MARC21XMLHandler = 0;
  delete m_UNIMARCXMLHandler;
  m_UNIMARCXMLHandler = 0;
  delete m_MODSHandler;
  m_MODSHandler = 0;
  delete m_conn;
  m_conn = 0;
}

TQString Z3950Fetcher::defaultName() {
  return i18n("z39.50 Server");
}

TQString Z3950Fetcher::source() const {
  return m_name.isEmpty() ? defaultName() : m_name;
}

bool Z3950Fetcher::canFetch(int type) const {
  return type == Data::Collection::Book || type == Data::Collection::Bibtex;
}

void Z3950Fetcher::readConfigHook(const TDEConfigGroup& config_) {
  TQString preset = config_.readEntry("Preset");
  if(preset.isEmpty()) {
    m_host = config_.readEntry("Host");
    int p = config_.readNumEntry("Port", Z3950_DEFAULT_PORT);
    if(p > 0) {
      m_port = p;
    }
    m_dbname = config_.readEntry("Database");
    m_sourceCharSet = config_.readEntry("Charset");
    m_syntax = config_.readEntry("Syntax");
    m_user = config_.readEntry("User");
    m_password = config_.readEntry("Password");
  } else {
    m_preset = preset;
    TQString serverFile = locate("appdata", TQString::fromLatin1("z3950-servers.cfg"));
    if(!serverFile.isEmpty()) {
      TDEConfig cfg(serverFile, true /* read-only */, false /* read KDE */);
      const TQStringList servers = cfg.groupList();
      for(TQStringList::ConstIterator server = servers.begin(); server != servers.end(); ++server) {
        cfg.setGroup(*server);

        const TQString id = *server;
        if(id == preset) {
          const TQString name = cfg.readEntry("Name");
          m_host = cfg.readEntry("Host");
          m_port = cfg.readNumEntry("Port", Z3950_DEFAULT_PORT);
          m_dbname = cfg.readEntry("Database");
          m_sourceCharSet = cfg.readEntry("Charset");
          m_syntax = cfg.readEntry("Syntax");
          m_user = cfg.readEntry("User");
          m_password = cfg.readEntry("Password");
        }
      }
    }
  }

  m_fields = config_.readListEntry("Custom Fields");
}

void Z3950Fetcher::saveConfigHook(TDEConfigGroup& config_) {
  config_.writeEntry("Syntax", m_syntax);
  config_.sync();
}

void Z3950Fetcher::search(FetchKey key_, const TQString& value_) {
#ifdef HAVE_YAZ
  m_started = true;
  m_done = false;
  if(m_host.isEmpty() || m_dbname.isEmpty()) {
    myDebug() << "Z3950Fetcher::search() - settings are not set!" << endl;
    stop();
    return;
  }
  m_key = key_;
  m_value = value_;
  m_started = true;

  TQString svalue = m_value;
  TQRegExp rx1(TQString::fromLatin1("['\"].*\\1"));
  if(!rx1.exactMatch(svalue)) {
    svalue.prepend('"').append('"');
  }

  switch(key_) {
    case Title:
      m_pqn = TQString::fromLatin1("@attr 1=4 ") + svalue;
      break;
    case Person:
//      m_pqn = TQString::fromLatin1("@or ");
//      m_pqn += TQString::fromLatin1("@attr 1=1 \"") + m_value + '"';
      m_pqn = TQString::fromLatin1(" @attr 1=1003 ") + svalue;
      break;
    case ISBN:
      {
        m_pqn.truncate(0);
        TQString s = m_value;
        s.remove('-');
        TQStringList isbnList = TQStringList::split(TQString::fromLatin1("; "), s);
        // also going to search for isbn10 values
        for(TQStringList::Iterator it = isbnList.begin(); it != isbnList.end(); ++it) {
          if((*it).startsWith(TQString::fromLatin1("978"))) {
            TQString isbn10 = ISBNValidator::isbn10(*it);
            isbn10.remove('-');
            isbnList.insert(it, isbn10);
          }
        }
        const size_t count = isbnList.count();
        if(count > 1) {
          m_pqn = TQString::fromLatin1("@or ");
        }
        for(size_t i = 0; i < count; ++i) {
          m_pqn += TQString::fromLatin1(" @attr 1=7 ") + isbnList[i];
          if(count > 1 && i < count-2) {
            m_pqn += TQString::fromLatin1(" @or");
          }
        }
      }
      break;
    case LCCN:
      {
        m_pqn.truncate(0);
        TQString s = m_value;
        s.remove('-');
        TQStringList lccnList = TQStringList::split(TQString::fromLatin1("; "), s);
        while(!lccnList.isEmpty()) {
          m_pqn += TQString::fromLatin1(" @or @attr 1=9 ") + lccnList.front();
          if(lccnList.count() > 1) {
            m_pqn += TQString::fromLatin1(" @or");
          }
          m_pqn += TQString::fromLatin1(" @attr 1=9 ") + LCCNValidator::formalize(lccnList.front());
          lccnList.pop_front();
        }
      }
      break;
    case Keyword:
      m_pqn = TQString::fromLatin1("@attr 1=1016 ") + svalue;
      break;
    case Raw:
      m_pqn = m_value;
      break;
    default:
      kdWarning() << "Z3950Fetcher::search() - key not recognized: " << key_ << endl;
      stop();
      return;
  }
//  m_pqn = TQString::fromLatin1("@attr 1=7 0253333490");
  myLog() << "Z3950Fetcher::search() - PQN query = " << m_pqn << endl;

  if(m_conn) {
    m_conn->reset(); // reset counts
  }

  process();
#else // HAVE_YAZ
  Q_UNUSED(key_);
  Q_UNUSED(value_);
  stop();
  return;
#endif
}

void Z3950Fetcher::continueSearch() {
#ifdef HAVE_YAZ
  m_started = true;
  process();
#endif
}

void Z3950Fetcher::stop() {
  if(!m_started) {
    return;
  }
//  myDebug() << "Z3950Fetcher::stop()" << endl;
  m_started = false;
  if(m_conn) {
   // give it a second to cleanup
    m_conn->abort();
    m_conn->wait(1000);
  }
  emit signalDone(this);
}

bool Z3950Fetcher::initMARC21Handler() {
  if(m_MARC21XMLHandler) {
    return true;
  }

  TQString xsltfile = locate("appdata", TQString::fromLatin1("MARC21slim2MODS3.xsl"));
  if(xsltfile.isEmpty()) {
    kdWarning() << "Z3950Fetcher::initHandlers() - can not locate MARC21slim2MODS3.xsl." << endl;
    return false;
  }

  KURL u;
  u.setPath(xsltfile);

  m_MARC21XMLHandler = new XSLTHandler(u);
  if(!m_MARC21XMLHandler->isValid()) {
    kdWarning() << "Z3950Fetcher::initHandlers() - error in MARC21slim2MODS3.xsl." << endl;
    delete m_MARC21XMLHandler;
    m_MARC21XMLHandler = 0;
    return false;
  }
  return true;
}

bool Z3950Fetcher::initUNIMARCHandler() {
  if(m_UNIMARCXMLHandler) {
    return true;
  }

  TQString xsltfile = locate("appdata", TQString::fromLatin1("UNIMARC2MODS3.xsl"));
  if(xsltfile.isEmpty()) {
    kdWarning() << "Z3950Fetcher::initHandlers() - can not locate UNIMARC2MODS3.xsl." << endl;
    return false;
  }

  KURL u;
  u.setPath(xsltfile);

  m_UNIMARCXMLHandler = new XSLTHandler(u);
  if(!m_UNIMARCXMLHandler->isValid()) {
    kdWarning() << "Z3950Fetcher::initHandlers() - error in UNIMARC2MODS3.xsl." << endl;
    delete m_UNIMARCXMLHandler;
    m_UNIMARCXMLHandler = 0;
    return false;
  }
  return true;
}

bool Z3950Fetcher::initMODSHandler() {
  if(m_MODSHandler) {
    return true;
  }

  TQString xsltfile = locate("appdata", TQString::fromLatin1("mods2tellico.xsl"));
  if(xsltfile.isEmpty()) {
    kdWarning() << "Z3950Fetcher::initHandlers() - can not locate mods2tellico.xsl." << endl;
    return false;
  }

  KURL u;
  u.setPath(xsltfile);

  m_MODSHandler = new XSLTHandler(u);
  if(!m_MODSHandler->isValid()) {
    kdWarning() << "Z3950Fetcher::initHandlers() - error in mods2tellico.xsl." << endl;
    delete m_MODSHandler;
    m_MODSHandler = 0;
    // no use in keeping the MARC handlers now
    delete m_MARC21XMLHandler;
    m_MARC21XMLHandler = 0;
    delete m_UNIMARCXMLHandler;
    m_UNIMARCXMLHandler = 0;
    return false;
  }
  return true;
}

void Z3950Fetcher::process() {
  if(m_conn) {
    m_conn->wait();
  } else {
    m_conn = new Z3950Connection(this, m_host, m_port, m_dbname, m_sourceCharSet, m_syntax, m_esn);
    if(!m_user.isEmpty()) {
      m_conn->setUserPassword(m_user, m_password);
    }
  }

  m_conn->setQuery(m_pqn);
  m_conn->start();
}

void Z3950Fetcher::handleResult(const TQString& result_) {
  if(result_.isEmpty()) {
    myDebug() << "Z3950Fetcher::handleResult() - empty record found, maybe the character encoding or record format is wrong?" << endl;
    return;
  }

#if 0
  kdWarning() << "Remove debug from z3950fetcher.cpp" << endl;
  {
    TQFile f1(TQString::fromLatin1("/tmp/marc.xml"));
    if(f1.open(IO_WriteOnly)) {
//      if(f1.open(IO_WriteOnly | IO_Append)) {
      TQTextStream t(&f1);
      t.setEncoding(TQTextStream::UnicodeUTF8);
      t << result_;
    }
    f1.close();
  }
#endif
  // assume always utf-8
  TQString str, msg;
  Data::CollPtr coll = 0;
  // not marc, has to be grs-1
  if(m_syntax == Latin1Literal("grs-1")) {
    Import::GRS1Importer imp(result_);
    coll = imp.collection();
    msg = imp.statusMessage();
  } else { // now the MODS stuff
    if(m_syntax == Latin1Literal("mods")) {
      str = result_;
    } else if(m_syntax == Latin1Literal("unimarc") && initUNIMARCHandler()) {
      str = m_UNIMARCXMLHandler->applyStylesheet(result_);
    } else if(initMARC21Handler()) { // got to be usmarc/marc21
      str = m_MARC21XMLHandler->applyStylesheet(result_);
    }
    if(str.isEmpty() || !initMODSHandler()) {
      myDebug() << "Z3950Fetcher::handleResult() - empty string or can't init" << endl;
      stop();
      return;
    }
#if 0
    kdWarning() << "Remove debug from z3950fetcher.cpp" << endl;
    {
      TQFile f2(TQString::fromLatin1("/tmp/mods.xml"));
//      if(f2.open(IO_WriteOnly)) {
      if(f2.open(IO_WriteOnly | IO_Append)) {
        TQTextStream t(&f2);
        t.setEncoding(TQTextStream::UnicodeUTF8);
        t << str;
      }
      f2.close();
    }
#endif
    Import::TellicoImporter imp(m_MODSHandler->applyStylesheet(str));
    imp.setOptions(imp.options() & ~Import::ImportProgress); // no progress needed
    coll = imp.collection();
    msg = imp.statusMessage();
  }

  if(!coll) {
    if(!msg.isEmpty()) {
      message(msg, MessageHandler::Warning);
    }
    myDebug() << "Z3950Fetcher::handleResult() - no collection pointer: " << msg << endl;
    return;
  }

  if(coll->entryCount() == 0) {
//    myDebug() << "Z3950Fetcher::handleResult() - no Tellico entry in result" << endl;
    return;
  }

  const StringMap customFields = Z3950Fetcher::customFields();
  for(StringMap::ConstIterator it = customFields.begin(); it != customFields.end(); ++it) {
    if(!m_fields.contains(it.key())) {
      coll->removeField(it.key());
    }
  }

  Data::EntryVec entries = coll->entries();
  for(Data::EntryVec::Iterator entry = entries.begin(); entry != entries.end(); ++entry) {
    TQString desc = entry->field(TQString::fromLatin1("author")) + '/'
                   + entry->field(TQString::fromLatin1("publisher"));
    if(!entry->field(TQString::fromLatin1("cr_year")).isEmpty()) {
      desc += TQChar('/') + entry->field(TQString::fromLatin1("cr_year"));
    } else if(!entry->field(TQString::fromLatin1("pub_year")).isEmpty()){
      desc += TQChar('/') + entry->field(TQString::fromLatin1("pub_year"));
    }
    SearchResult* r = new SearchResult(this, entry->title(), desc, entry->field(TQString::fromLatin1("isbn")));
    m_entries.insert(r->uid, entry);
    emit signalResultFound(r);
  }
}

void Z3950Fetcher::done() {
  m_done = true;
  stop();
}

Tellico::Data::EntryPtr Z3950Fetcher::fetchEntry(uint uid_) {
  return m_entries[uid_];
}

void Z3950Fetcher::customEvent(TQCustomEvent* event_) {
  if(!m_conn) {
    return;
  }

  if(event_->type() == Z3950ResultFound::uid()) {
    if(m_done) {
      kdWarning() << "Z3950Fetcher::customEvent() - result returned after done signal!" << endl;
    }
    Z3950ResultFound* e = static_cast<Z3950ResultFound*>(event_);
    handleResult(e->result());
  } else if(event_->type() == Z3950ConnectionDone::uid()) {
    Z3950ConnectionDone* e = static_cast<Z3950ConnectionDone*>(event_);
    if(e->messageType() > -1) {
      message(e->message(), e->messageType());
    }
    m_hasMoreResults = e->hasMoreResults();
    m_conn->wait();
    done();
  } else if(event_->type() == Z3950SyntaxChange::uid()) {
    if(m_done) {
      kdWarning() << "Z3950Fetcher::customEvent() - syntax changed after done signal!" << endl;
    }
    Z3950SyntaxChange* e = static_cast<Z3950SyntaxChange*>(event_);
    if(m_syntax != e->syntax()) {
      m_syntax = e->syntax();
      // it gets saved when saveConfigHook() get's called from the Fetcher() d'tor
    }
  } else {
    kdWarning() << "Z3950Fetcher::customEvent() - weird type: " << event_->type() << endl;
  }
}

void Z3950Fetcher::updateEntry(Data::EntryPtr entry_) {
//  myDebug() << "Z3950Fetcher::updateEntry() - " << source() << ": " << entry_->title() << endl;
  TQString isbn = entry_->field(TQString::fromLatin1("isbn"));
  if(!isbn.isEmpty()) {
    search(Fetch::ISBN, isbn);
    return;
  }

  TQString lccn = entry_->field(TQString::fromLatin1("lccn"));
  if(!lccn.isEmpty()) {
    search(Fetch::LCCN, lccn);
    return;
  }

  // optimistically try searching for title and rely on Collection::sameEntry() to figure things out
  TQString t = entry_->field(TQString::fromLatin1("title"));
  if(!t.isEmpty()) {
    search(Fetch::Title, t);
    return;
  }

  myDebug() << "Z3950Fetcher::updateEntry() - insufficient info to search" << endl;
  emit signalDone(this); // always need to emit this if not continuing with the search
}

Tellico::Fetch::ConfigWidget* Z3950Fetcher::configWidget(TQWidget* parent_) const {
  return new Z3950Fetcher::ConfigWidget(parent_, this);
}

Z3950Fetcher::ConfigWidget::ConfigWidget(TQWidget* parent_, const Z3950Fetcher* fetcher_/*=0*/)
    : Fetch::ConfigWidget(parent_) {
  TQGridLayout* l = new TQGridLayout(optionsWidget(), 7, 2);
  l->setSpacing(4);
  l->setColStretch(1, 10);

  int row = -1;

  m_usePreset = new TQCheckBox(i18n("Use preset &server:"), optionsWidget());
  l->addWidget(m_usePreset, ++row, 0);
  connect(m_usePreset, TQT_SIGNAL(toggled(bool)), TQT_SLOT(slotTogglePreset(bool)));
  m_serverCombo = new GUI::ComboBox(optionsWidget());
  connect(m_serverCombo, TQT_SIGNAL(activated(int)), TQT_SLOT(slotPresetChanged()));
  l->addWidget(m_serverCombo, row, 1);
  ++row;
  l->addMultiCellWidget(new KSeparator(optionsWidget()), row, row, 0, 1);
  l->setRowSpacing(row, 10);

  TQLabel* label = new TQLabel(i18n("Hos&t: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_hostEdit = new GUI::LineEdit(optionsWidget());
  connect(m_hostEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotSetModified()));
  connect(m_hostEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SIGNAL(signalName(const TQString&)));
  l->addWidget(m_hostEdit, row, 1);
  TQString w = i18n("Enter the host name of the server.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_hostEdit, w);
  label->setBuddy(m_hostEdit);

  label = new TQLabel(i18n("&Port: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_portSpinBox = new KIntSpinBox(0, 999999, 1, Z3950_DEFAULT_PORT, 10, optionsWidget());
  connect(m_portSpinBox, TQT_SIGNAL(valueChanged(int)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_portSpinBox, row, 1);
  w = i18n("Enter the port number of the server. The default is %1.").arg(Z3950_DEFAULT_PORT);
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_portSpinBox, w);
  label->setBuddy(m_portSpinBox);

  label = new TQLabel(i18n("&Database: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_databaseEdit = new GUI::LineEdit(optionsWidget());
  connect(m_databaseEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_databaseEdit, row, 1);
  w = i18n("Enter the database name used by the server.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_databaseEdit, w);
  label->setBuddy(m_databaseEdit);

  label = new TQLabel(i18n("Ch&aracter set: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_charSetCombo = new KComboBox(true, optionsWidget());
  m_charSetCombo->insertItem(TQString());
  m_charSetCombo->insertItem(TQString::fromLatin1("marc8"));
  m_charSetCombo->insertItem(TQString::fromLatin1("iso-8859-1"));
  m_charSetCombo->insertItem(TQString::fromLatin1("utf-8"));
  connect(m_charSetCombo, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_charSetCombo, row, 1);
  w = i18n("Enter the character set encoding used by the z39.50 server. The most likely choice "
           "is MARC-8, although ISO-8859-1 is common as well.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_charSetCombo, w);
  label->setBuddy(m_charSetCombo);

  label = new TQLabel(i18n("&Format: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_syntaxCombo = new GUI::ComboBox(optionsWidget());
  m_syntaxCombo->insertItem(i18n("Auto-detect"), TQString());
  m_syntaxCombo->insertItem(TQString::fromLatin1("MODS"), TQString::fromLatin1("mods"));
  m_syntaxCombo->insertItem(TQString::fromLatin1("MARC21"), TQString::fromLatin1("marc21"));
  m_syntaxCombo->insertItem(TQString::fromLatin1("UNIMARC"), TQString::fromLatin1("unimarc"));
  m_syntaxCombo->insertItem(TQString::fromLatin1("USMARC"), TQString::fromLatin1("usmarc"));
  m_syntaxCombo->insertItem(TQString::fromLatin1("GRS-1"), TQString::fromLatin1("grs-1"));
  connect(m_syntaxCombo, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_syntaxCombo, row, 1);
  w = i18n("Enter the data format used by the z39.50 server. Tellico will attempt to "
           "automatically detect the best setting if <i>auto-detect</i> is selected.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_syntaxCombo, w);
  label->setBuddy(m_syntaxCombo);

  label = new TQLabel(i18n("&User: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_userEdit = new GUI::LineEdit(optionsWidget());
  m_userEdit->setHint(i18n("Optional"));
  connect(m_userEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_userEdit, row, 1);
  w = i18n("Enter the authentication user name used by the z39.50 database. Most servers "
           "do not need one.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_userEdit, w);
  label->setBuddy(m_userEdit);

  label = new TQLabel(i18n("Pass&word: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_passwordEdit = new GUI::LineEdit(optionsWidget());
  m_passwordEdit->setHint(i18n("Optional"));
  m_passwordEdit->setEchoMode(TQLineEdit::Password);
  connect(m_passwordEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_passwordEdit, row, 1);
  w = i18n("Enter the authentication password used by the z39.50 database. Most servers "
           "do not need one. The password will be saved in plain text in the Tellico "
           "configuration file.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_passwordEdit, w);
  label->setBuddy(m_passwordEdit);

  l->setRowStretch(++row, 1);

  // now add additional fields widget
  addFieldsWidget(Z3950Fetcher::customFields(), fetcher_ ? fetcher_->m_fields : TQStringList());

  loadPresets(fetcher_ ? fetcher_->m_preset : TQString());
  if(fetcher_) {
    m_hostEdit->setText(fetcher_->m_host);
    m_portSpinBox->setValue(fetcher_->m_port);
    m_databaseEdit->setText(fetcher_->m_dbname);
    m_userEdit->setText(fetcher_->m_user);
    m_passwordEdit->setText(fetcher_->m_password);
    m_charSetCombo->setCurrentText(fetcher_->m_sourceCharSet);
    // the syntax is detected automatically by the fetcher
    // since the config group gets deleted in the config file,
    // the value needs to be retained here
    m_syntax = fetcher_->m_syntax;
    m_syntaxCombo->setCurrentData(m_syntax);
  }
  TDEAcceleratorManager::manage(optionsWidget());

  // start with presets turned off
  m_usePreset->setChecked(fetcher_ && !fetcher_->m_preset.isEmpty());

  slotTogglePreset(m_usePreset->isChecked());
}

Z3950Fetcher::ConfigWidget::~ConfigWidget() {
}

void Z3950Fetcher::ConfigWidget::saveConfig(TDEConfigGroup& config_) {
  if(m_usePreset->isChecked()) {
    TQString presetID = m_serverCombo->currentData().toString();
    config_.writeEntry("Preset", presetID);
    return;
  }
  config_.deleteEntry("Preset");

  TQString s = m_hostEdit->text().stripWhiteSpace();
  if(!s.isEmpty()) {
    config_.writeEntry("Host", s);
  }
  int port = m_portSpinBox->value();
  if(port > 0) {
    config_.writeEntry("Port", port);
  }
  s = m_databaseEdit->text().stripWhiteSpace();
  if(!s.isEmpty()) {
    config_.writeEntry("Database", s);
  }
  s = m_charSetCombo->currentText();
  if(!s.isEmpty()) {
    config_.writeEntry("Charset", s);
  }
  s = m_userEdit->text();
  if(!s.isEmpty()) {
    config_.writeEntry("User", s);
  }
  s = m_passwordEdit->text();
  if(!s.isEmpty()) {
    config_.writeEntry("Password", s);
  }
  s = m_syntaxCombo->currentData().toString();
  if(!s.isEmpty()) {
    m_syntax = s;
  }
  config_.writeEntry("Syntax", m_syntax);

  saveFieldsConfig(config_);
  slotSetModified(false);
}

// static
Tellico::StringMap Z3950Fetcher::customFields() {
  StringMap map;
  map[TQString::fromLatin1("address")]  = i18n("Address");
  map[TQString::fromLatin1("abstract")] = i18n("Abstract");
  map[TQString::fromLatin1("illustrator")] = i18n("Illustrator");
  return map;
}

void Z3950Fetcher::ConfigWidget::slotTogglePreset(bool on) {
  m_serverCombo->setEnabled(on);
  if(on) {
    emit signalName(m_serverCombo->currentText());
  }
  m_hostEdit->setEnabled(!on);
  if(!on && !m_hostEdit->text().isEmpty()) {
    emit signalName(m_hostEdit->text());
  }
  m_portSpinBox->setEnabled(!on);
  m_databaseEdit->setEnabled(!on);
  m_userEdit->setEnabled(!on);
  m_passwordEdit->setEnabled(!on);
  m_charSetCombo->setEnabled(!on);
  m_syntaxCombo->setEnabled(!on);
  if(on) {
    emit signalName(m_serverCombo->currentText());
  }
}

void Z3950Fetcher::ConfigWidget::slotPresetChanged() {
  emit signalName(m_serverCombo->currentText());
}

void Z3950Fetcher::ConfigWidget::loadPresets(const TQString& current_) {
  TQString lang = TDEGlobal::locale()->languageList().first();
  TQString lang2A;
  {
    TQString dummy;
    TDEGlobal::locale()->splitLocale(lang, lang2A, dummy, dummy);
  }

  TQString serverFile = locate("appdata", TQString::fromLatin1("z3950-servers.cfg"));
  if(serverFile.isEmpty()) {
    kdWarning() << "Z3950Fetcher::loadPresets() - no z3950 servers file found" << endl;
    return;
  }

  int idx = -1;

  TDEConfig cfg(serverFile, true /* read-only */, false /* read KDE */);
  const TQStringList servers = cfg.groupList();
  // I want the list of servers sorted by name
  TQMap<TQString, TQString> serverNameMap;
  for(TQStringList::ConstIterator server = servers.constBegin(); server != servers.constEnd(); ++server) {
    if((*server).isEmpty()) {
      myDebug() << "Z3950Fetcher::ConfigWidget::loadPresets() - empty id" << endl;
      continue;
    }
    cfg.setGroup(*server);
    const TQString name = cfg.readEntry("Name");
    if(!name.isEmpty()) {
      serverNameMap.insert(name, *server);
    }
  }
  for(TQMap<TQString, TQString>::ConstIterator it = serverNameMap.constBegin(); it != serverNameMap.constEnd(); ++it) {
    const TQString name = it.key();
    const TQString id = it.data();
    cfg.setGroup(id);

    m_serverCombo->insertItem(i18n(name.utf8()), id);
    if(current_.isEmpty() && idx == -1) {
      // set the initial selection to something depending on the language
      const TQStringList locales = cfg.readListEntry("Locale");
      if(locales.findIndex(lang) > -1 || locales.findIndex(lang2A) > -1) {
        idx = m_serverCombo->count() - 1;
      }
    } else if(id == current_) {
      idx = m_serverCombo->count() - 1;
    }
  }
  if(idx > -1) {
    m_serverCombo->setCurrentItem(idx);
  }
}

TQString Z3950Fetcher::ConfigWidget::preferredName() const {
  if(m_usePreset->isChecked()) {
    return m_serverCombo->currentText();
  }
  TQString s = m_hostEdit->text();
  return s.isEmpty() ? i18n("z39.50 Server") : s;
}

#include "z3950fetcher.moc"