summaryrefslogtreecommitdiffstats
path: root/src/kbibtex_part.cpp
blob: 2ea704136ea464eecb900fe7f5adb00a2529c06f (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
/***************************************************************************
*   Copyright (C) 2004-2009 by Thomas Fischer                             *
*   fischer@unix-ag.uni-kl.de                                             *
*                                                                         *
*   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.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   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.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/
#include <string>
#include <fcntl.h>

#include <tqstring.h>
#include <tqsplitter.h>
#include <tqtimer.h>
#include <tqvaluelist.h>
#include <tqlayout.h>
#include <tqlineedit.h>
#include <tqbuffer.h>
#include <tqtoolbutton.h>
#include <tqtabwidget.h>
#include <tqlabel.h>
#include <tqtextedit.h>
#include <tqclipboard.h>
#include <kinstance.h>
#include <tdeaction.h>
#include <kstdaction.h>
#include <tdelistview.h>
#include <kdebug.h>
#include <tdelocale.h>
#include <tdefiledialog.h>
#include <tdetempfile.h>
#include <tdeconfigdialog.h>
#include <kstatusbar.h>
#include <tdeglobalsettings.h>
#include <tdemessagebox.h>
#include <kinputdialog.h>
#include <tdeshortcut.h>
#include <kstandarddirs.h>
#include <kiconloader.h>
#include <tdeapplication.h>
#include <kxmlguifactory.h>
#include <tdepopupmenu.h>
#include <tdeio/netaccess.h>
#include <tdemainwindow.h>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string.h>
#include "entry.h"
#include "documentlistviewitem.h"
#include "documentlistview.h"
#include "fileexporter.h"
#include "fileexporterbibtex.h"
#include "fileexporterxml.h"
#include "fileexporterxslt.h"
#include "settings.h"
#include "encoderlatex.h"
#include "kbibtex_part.h"

const TQString inPipeFilename = TQDir::homeDirPath() + "/.kbibtex.in";

KBibTeXPart::KBibTeXPart( TQWidget *parentWidget, const char *widgetName,
                          TQObject *parent, const char *name )
        : KParts::ReadWritePart( parent, name ), m_defInitCounter( 0 ), m_settingsDlg( NULL ), m_initializationDone( FALSE ), m_inPipe( NULL )
{
    m_mainWindow = dynamic_cast<TDEMainWindow*>( parent );
    if ( m_mainWindow == NULL )
        kdDebug( ) << "Cannot determine main window" << endl;

    // we need an instance
    setInstance( KBibTeXPartFactory::instance() );

    // set our XML-UI resource file
    setXMLFile( "kbibtex_part.rc" );

    // setup GUI elements
    setupGUI( parentWidget, widgetName );

    // create our actions
    setupActions();

    // we are read-write by default
    setReadWrite( TRUE );

    // we are not modified since we haven't done anything yet
    setModified( FALSE );

    // read configuration
    readSettings();

    TQTimer::singleShot( 100, this, TQ_SLOT( slotDeferredInitialization() ) );
}

KBibTeXPart::~KBibTeXPart()
{
    BibTeX::EncoderLaTeX::deleteCurrentEncoderLaTeX();

    if ( m_settingsDlg != NULL )
        delete m_settingsDlg;
}

void KBibTeXPart::setReadWrite( bool rw )
{
    if ( rw )
    {
        connect( m_documentWidget, TQ_SIGNAL( modified( ) ), this, TQ_SLOT( setModified( ) ) );
        m_actionEditElement->setText( i18n( "&Edit" ) );
    }
    else
    {
        disconnect( m_documentWidget, TQ_SIGNAL( modified( ) ), this, TQ_SLOT( setModified( ) ) );
        m_actionEditElement->setText( i18n( "&View" ) );
    }
    ReadWritePart::setReadWrite( rw );
    m_documentWidget->setReadOnly( !rw );
}

void KBibTeXPart::setModified( bool modified )
{
    // get a handle on our Save action and make sure it is valid
    TDEAction * save = actionCollection() ->action( KStdAction::stdName( KStdAction::Save ) );

    if ( save )
    {
        // if so, we either enable or disable it based on the current
        // state
        save->setEnabled( modified );

        // in any event, we want our parent to do it's thing
        KParts::ReadWritePart::setModified( modified );
    }
}

bool KBibTeXPart::queryClose()
{
    writeSettings();

    if ( !isReadWrite() || !isModified() )
        return TRUE;

    TQString docName = url().fileName();
    if ( docName.isEmpty() ) docName = i18n( "Untitled" );

    int res = KMessageBox::warningYesNoCancel( widget(),
              i18n( "The document '%1' has been modified.\n"
                    "Do you want to save your changes or discard them?" ).arg( docName ),
              i18n( "Close Document" ), KStdGuiItem::save(), KStdGuiItem::discard() );

    bool abortClose = false;
    bool handled = false;

    switch ( res )
    {
    case KMessageBox::Yes :
        sigQueryClose( &handled, &abortClose );
        if ( !handled )
        {
            if ( m_url.isEmpty() )
                return saveAs();
            else
                save();
        }
        else if ( abortClose ) return FALSE;
        return waitSaveComplete();
    case KMessageBox::No :
        return TRUE;
    default:
        return FALSE;
    }

}

bool KBibTeXPart::closeURL()
{
    writeSettings();

    if ( isReadWrite() && isModified() )
    {
        if ( !queryClose() )
            return false;
    }
    // Not modified => ok and delete temp file.
    return KParts::ReadOnlyPart::closeURL();
}

bool KBibTeXPart::openFile()
{
    return m_documentWidget->open( m_file, FALSE );
}

/**
 * Save document to a filename as given in String m_file.
 */
bool KBibTeXPart::saveFile()
{
    if ( isReadWrite() == FALSE )
        return FALSE;

    if ( !url().isValid() || url().isEmpty() )
        return saveAs();
    else
    {
        /** make backup if defined by the user */
        KBibTeX::Settings * settings = KBibTeX::Settings::self( NULL );
        settings->createBackup( url(), widget() );

        KTempFile tempBibFile = KTempFile( locateLocal( "tmp", "bibsave" ) );
        tempBibFile.setAutoDelete( TRUE );
        bool success =  m_documentWidget->save( tempBibFile.file() );
        tempBibFile.close();
        if ( success )
        {
            TQString usedFileName = m_file;
            TQFileInfo fi( usedFileName );
            if ( !fi.readLink().isNull() && KMessageBox::questionYesNo( widget(), TQString( i18n( "The selected filename \"%1\" is a symbolic link pointing to \"%2\".\nReplace the link with a new file or overwrite the existing file the link points to?" ) ).arg( usedFileName ).arg(KBibTeX::Settings::resolveLink( m_file, fi.readLink() ) ), i18n( "Symbolic Link" ), KGuiItem( i18n( "Replace link" ) ), KGuiItem( i18n( "Overwrite file the link points to" ) ) ) == KMessageBox::No )
                usedFileName = KBibTeX::Settings::resolveLink( m_file, fi.readLink() );

            m_documentWidget->dirWatch().stopScan();
            success = TDEIO::NetAccess::file_copy( KURL( tempBibFile.name() ), KURL( usedFileName ), -1, true, false, widget() );
            m_documentWidget->dirWatch().startScan();
        }

        return success;
    }
}

void KBibTeXPart::slotFileSaveAs()
{
    saveAs();
}

bool KBibTeXPart::saveAs()
{
    bool result = FALSE;
    KBibTeX::Settings * settings = KBibTeX::Settings::self( NULL );

    TQString startDir = ! url().isEmpty() ? url().url() : TQDir::currentDirPath();
    KURL saveURL = KFileDialog::getSaveURL( startDir, "*.bib|" + i18n( "BibTeX (*.bib)" ) + "\n*.ris|" + i18n( "Reference Manager (*.ris)" ) +
                                            ( settings->external_xml2bibAvailable ? "\n*.ref *.refer *.rfr *.txt|" + i18n( "EndNote (Refer format) (*.ref *.refer *.rfr *.txt)" ) + "\n*.isi *.cgi|" + i18n( "ISI Web of Knowledge (*.isi *.cgi)" ) : "" ) + "\n*.xml|" + ( settings->external_xml2bibAvailable ? i18n( "DocBook 5 or MODS (*.xml)" ) : i18n( "DocBook 5 (*.xml)" ) ), widget() );

    if ( saveURL.isValid() && !saveURL.isEmpty() )
    {
        if ( TDEIO::NetAccess::exists( saveURL, FALSE, widget() ) && KMessageBox::warningContinueCancel( widget(), i18n( "A file named '%1' already exists. Are you sure you want to overwrite it?" ).arg( saveURL.filename() ), TQString::null, i18n( "Overwrite" ) ) != KMessageBox::Continue )
            return result;

        if ( ReadWritePart::saveAs( saveURL ) )
        {
            emit signalAddRecentURL( saveURL );
            result = TRUE;
        }
    }

    return result;
}

void KBibTeXPart::slotFileExport()
{
    KBibTeX::Settings * settings = KBibTeX::Settings::self( NULL );
    TQString startDir = ! url().isEmpty() ? url().url() : TQDir::currentDirPath();
    KURL exportURL = KFileDialog::getSaveURL( startDir, "*.pdf|" + i18n( "Portable Document File (*.pdf)" ) + "\n*.ps|" + i18n( "PostScript (*.ps)" ) + "\n*.ris|" + i18n( "Reference Manager (*.ris)" ) + ( settings->external_xml2bibAvailable ?  "\n*.ref *.refer *.rfr *.txt|" + i18n( "EndNote (Refer format) (*.ref *.refer *.rfr *.txt)" ) + "\n*.isi *.cgi|" + i18n( "ISI Web of Knowledge (*.isi *.cgi)" ) : "" ) +   "\n*.xml|" + ( settings->external_xml2bibAvailable ? i18n( "DocBook 5 or MODS (*.xml)" ) :  i18n( "DocBook 5 (*.xml)" ) ) + "\n*.html|" + i18n( "Hypertext Markup Langage (*.html)" ) + "\n*.rtf|" + i18n( "Rich Text Format (*.rtf)" ), widget() );

    if ( exportURL.isValid() && !exportURL.isEmpty() )
    {
        if ( TDEIO::NetAccess::exists( exportURL, FALSE, widget() ) )
        {
            if ( KMessageBox::warningContinueCancel( widget(), i18n( "A file named '%1' already exists. Are you sure you want to overwrite it?" ).arg( exportURL.filename() ), TQString::null, i18n( "Overwrite" ) ) != KMessageBox::Continue )
                return ;

            /** make backup if defined by the user */
            KBibTeX::Settings * settings = KBibTeX::Settings::self( NULL );
            settings->createBackup( exportURL, widget() );
        }

        KTempFile tempBibFile = KTempFile( locateLocal( "tmp", "bibexport" ) );
        tempBibFile.setAutoDelete( TRUE );
        BibTeX::File::FileFormat format = BibTeX::File::formatBibTeX;
        if ( exportURL.fileName().endsWith( ".rtf", FALSE ) )
            format = BibTeX::File::formatRTF;
        else if ( exportURL.fileName().endsWith( ".pdf", FALSE ) )
            format = BibTeX::File::formatPDF;
        else if ( exportURL.fileName().endsWith( ".ps", FALSE ) )
            format = BibTeX::File::formatPS;
        else if ( settings->external_xml2bibAvailable && settings->external_end2xmlAvailable && ( exportURL.fileName().endsWith( ".ref", FALSE ) || exportURL.fileName().endsWith( ".refer", FALSE ) || exportURL.fileName().endsWith( ".txt", FALSE ) || exportURL.fileName().endsWith( ".rfr", FALSE ) ) )
            format = BibTeX::File::formatEndNote;
        else if ( settings->external_xml2bibAvailable && settings->external_end2xmlAvailable && ( exportURL.fileName().endsWith( ".isi", FALSE ) || exportURL.fileName().endsWith( ".cgi", FALSE ) ) )
            format = BibTeX::File::formatISI;
        else if ( exportURL.fileName().endsWith( ".ris", FALSE ) )
            format = BibTeX::File::formatRIS;
        else if ( exportURL.fileName().endsWith( ".xml", FALSE ) )
        {
            TQStringList options = TQStringList::split( '|', ( settings->external_xml2bibAvailable && settings->external_end2xmlAvailable ? "DocBook5|MODS|internal XML" : "DocBook5|internal XML" ) );
            bool ok = false;
            TQString answer = KInputDialog::getItem( i18n( "Choose file format" ), TQString( i18n( "Choose file format of file '%1':" ) ).arg( exportURL.fileName() ), options, 0, false, &ok, widget() );
            if ( ok && !answer.isNull() && answer == "DocBook5" )
                format = BibTeX::File::formatDocBook5;
            else if ( ok && !answer.isNull() && answer == "MODS" )
                format = BibTeX::File::formatMODS;
            else if ( ok && !answer.isNull() && answer == "internal XML" )
                format = BibTeX::File::formatXML;
        }
        else if ( exportURL.fileName().endsWith( ".html", FALSE ) )
            format = BibTeX::File::formatHTML;
        else
        {
            TQStringList options = TQStringList::split( '|', ( settings->external_xml2bibAvailable && settings->external_end2xmlAvailable ? "BibTeX|EndNote|ISI|RIS" : "BibTeX|RIS" ) );
            bool ok = false;
            TQString answer = KInputDialog::getItem( i18n( "Choose file format" ), TQString( i18n( "Choose file format of file '%1':" ) ).arg( exportURL.fileName() ), options, 0, false, &ok, widget() );
            if ( ok && !answer.isNull() && answer == "BibTeX" )
                format = BibTeX::File::formatBibTeX;
            else if ( ok && !answer.isNull() && answer == "EndNote" )
                format = BibTeX::File::formatEndNote;
            else if ( ok && !answer.isNull() && answer == "ISI" )
                format = BibTeX::File::formatISI;
            else if ( ok && !answer.isNull() && answer == "RIS" )
                format = BibTeX::File::formatRIS;
        }

        TQStringList errorLog;

        bool error = !m_documentWidget->save( tempBibFile.file(), format, i18n( "Exporting" ), &errorLog ) ;
        if ( !error )
        {
            tempBibFile.close();
            error = !TDEIO::NetAccess::file_copy( KURL( tempBibFile.name() ), exportURL, -1, TRUE, FALSE, widget() );
        }

        if ( error )
        {
#if (TDE_VERSION_MINOR>=4) && (TDE_VERSION_MAJOR>=3)
            if ( !errorLog.empty() )
                KMessageBox::errorList( widget(), TQString( i18n( "File could not be exported in '%1'." ) ).arg( exportURL.prettyURL() ).append( i18n( "\n\nSee the following error log for details." ) ), errorLog, i18n( "Exporting failed" ) );
            else
#endif
                KMessageBox::error( widget(), TQString( i18n( "File could not be exported to '%1'." ) ).arg( exportURL.prettyURL() ), i18n( "Exporting failed" ) );
        }

    }

}

void KBibTeXPart::slotFileStatistics()
{
    m_documentWidget->showStatistics();
}

void KBibTeXPart::slotFileFindDups()
{
    m_documentWidget->findDuplicates();
}

void KBibTeXPart::slotFileMerge()
{
    KBibTeX::Settings * settings = KBibTeX::Settings::self( NULL );
    TQString startDir = ! url().isEmpty() ? url().url() : TQDir::currentDirPath();
    KURL mergeURL = KFileDialog::getOpenURL( startDir, TQString( "*.bib *.ris" ) +
                    ( settings->external_xml2bibAvailable && settings->external_end2xmlAvailable ? " *.xml *.ref *.refer *.rfr *.txt *.isi *.cgi" : "" ) + "|" + i18n( "Supported Bibliographies" ) + "\n*.bib|" + i18n( "BibTeX (*.bib)" ) + "\n*.ris|" + i18n( "Reference Manager (*.ris)" ) + ( settings->external_xml2bibAvailable && settings->external_end2xmlAvailable ? "\n*.ref *.refer *.rfr *.txt|" + i18n( "EndNote (Refer format) (*.ref *.refer *.rfr *.txt)" ) + "\n*.isi *.cgi|" + i18n( "ISI Web of Knowledge (*.isi *.cgi)" ) + "\n*.xml|" + i18n( "MODS or EndNote XML (*.xml)" ) : "" ) + "\n*|" + i18n( "All files (*.*)" )
                    , widget() );

    if ( !mergeURL.isValid() || mergeURL.isEmpty() )
        return;

    TQString extension = mergeURL.fileName();
    int extPos = extension.find( '.' );
    if ( extPos < 0 )
        return;
    extension = extension.mid( extPos );

    if ( !TDEIO::NetAccess::exists( mergeURL, TRUE, widget() ) )
    {
        KMessageBox::error( widget(), i18n( "The given file could not be read, check if it exists or if it is readable for the current user." ) );
        return ;
    }

    KTempFile tempBibFile = KTempFile( locateLocal( "tmp", "bibmerge" ), extension );
    tempBibFile.setAutoDelete( TRUE );
    bool error = !TDEIO::NetAccess::file_copy( mergeURL, KURL( tempBibFile.name() ),  -1, TRUE, FALSE, widget() );

    if ( !error )
        error = !m_documentWidget->open( tempBibFile.name(), TRUE );

    tempBibFile.close();

    if ( error )
    {
        KMessageBox::error( widget(), i18n( "The given file could not be merged." ) );
        return;
    }
    else
        setModified( TRUE );
}

void KBibTeXPart::slotPreferences()
{
    if ( !m_settingsDlg )
        m_settingsDlg = new KBibTeX::SettingsDlg( widget(), "settings_dlg" );

    m_documentWidget->saveState();
    if ( m_settingsDlg->exec() == TQDialog::Accepted )
        m_documentWidget->restoreState();
}

void KBibTeXPart::setupGUI( TQWidget *parentWidget, const char *name )
{
    m_documentWidget = new KBibTeX::DocumentWidget( !isReadWrite(), parentWidget, name );

    // notify the part that this is our internal widget
    setWidget( m_documentWidget );
}

void KBibTeXPart::setupActions()
{
    if ( isReadWrite() )
    {
        KStdAction::save( this, TQ_SLOT( save() ), actionCollection() ) ->setToolTip( i18n( "Save the current file" ) );
        KStdAction::saveAs( this, TQ_SLOT( slotFileSaveAs() ), actionCollection() ) ->setToolTip( i18n( "Save the current file under a new filename" ) );
    }
    m_actionFileStatistics = new TDEAction( i18n( "Statistics..." ), CTRL + SHIFT + Key_I, this, TQ_SLOT( slotFileStatistics() ), actionCollection(), "file_statistics" );
    m_actionFileFindDups = new TDEAction( i18n( "Find Duplicates..." ), CTRL + SHIFT + Key_D, this, TQ_SLOT( slotFileFindDups() ), actionCollection(), "file_finddups" );
    m_actionFileExport = new TDEAction( i18n( "Export..." ), SmallIconSet( "goto" ), CTRL + Key_E, this, TQ_SLOT( slotFileExport() ), actionCollection(), "file_export" );
    m_actionFileExport->setToolTip( i18n( "Export to a different file format" ) );
    m_actionFileMerge = new TDEAction( i18n( "Merge..." ), SmallIconSet( "reload" ), CTRL + Key_M, this, TQ_SLOT( slotFileMerge() ), actionCollection(), "file_merge" );
    m_actionFileMerge->setToolTip( i18n( "Merge BibTeX entries from another file" ) );

    m_actionEditCut = KStdAction::cut( m_documentWidget, TQ_SLOT( cutElements() ), actionCollection() );
    m_actionEditCut->setToolTip( i18n( "Cut the selected BibTeX elements to the clipboard" ) );
    m_actionEditCut->setEnabled( FALSE );
    m_actionEditCopy = KStdAction::copy( m_documentWidget, TQ_SLOT( copyElements() ), actionCollection() );
    m_actionEditCopy->setToolTip( i18n( "Copy the selected BibTeX elements to the clipboard" ) );
    m_actionEditCopy->setEnabled( FALSE );
    m_actionEditUndo =  KStdAction::undo( m_documentWidget, TQ_SLOT( undoEditor() ), actionCollection() );
    connect( m_documentWidget, TQ_SIGNAL( undoChanged( bool ) ), this, TQ_SLOT( slotUndoChanged( bool ) ) );
    m_actionEditCopyRef = new TDEAction( i18n( "Copy &Reference" ), CTRL + SHIFT + Key_C, m_documentWidget, TQ_SLOT( copyRefElements() ), actionCollection(), "edit_copyref" );
    m_actionEditCopyRef->setToolTip( i18n( "Copy a reference of the selected BibTeX elements to the clipboard" ) );
    m_actionEditCopyRef->setEnabled( FALSE );
    m_actionEditPaste = KStdAction::paste( m_documentWidget, TQ_SLOT( pasteElements() ), actionCollection() );
    m_actionEditPaste->setToolTip( i18n( "Paste BibTeX elements from the clipboard" ) );
    m_actionEditSelectAll = KStdAction::selectAll( m_documentWidget, TQ_SLOT( selectAll() ), actionCollection() );
    m_actionEditSelectAll->setToolTip( i18n( "Select all BibTeX elements" ) );
    m_actionElementSendToLyX = new TDEAction( i18n( "Send Reference to &LyX" ), CTRL + SHIFT + Key_L, m_documentWidget, TQ_SLOT( sendSelectedToLyx() ), actionCollection(), "element_sendtolyx" );
    m_actionElementSendToLyX->setToolTip( i18n( "Send a reference of the selected BibTeX elements to LyX" ) );
    m_actionElementSendToLyX->setEnabled( FALSE );
    m_actionEditFind = KStdAction::find( m_documentWidget, TQ_SLOT( find() ), actionCollection() );
    m_actionEditFind->setToolTip( i18n( "Find text" ) );
    m_actionEditFindNext = KStdAction::findNext( m_documentWidget, TQ_SLOT( findNext() ), actionCollection() );
    m_actionEditFindNext->setToolTip( i18n( "Find next occurrence" ) );
    m_actionEditFind->setEnabled( FALSE );
    m_actionEditFindNext->setEnabled( FALSE );

    m_actionSearchOnlineDatabases = new TDEAction( i18n( "Search Online Databases" ), SmallIconSet( "network" ), CTRL + SHIFT + Key_S, m_documentWidget, TQ_SLOT( onlineSearch() ), actionCollection(), "search_onlinedatabases" );
    m_actionSearchOnlineDatabases->setToolTip( i18n( "Search online databases to import bibliography data" ) );

    m_actionMenuSearchWebsites = new TDEActionMenu( i18n( "Search Document Online" ), actionCollection(), "search_document_online" );
    m_actionMenuSearchWebsites->setToolTip( i18n( "Search websites for the selected BibTeX element" ) );
    connect( m_actionMenuSearchWebsites->popupMenu(), TQ_SIGNAL( activated( int ) ), this, TQ_SLOT( slotSearchWebsites( int ) ) );
    m_actionMenuSearchWebsites->setEnabled( FALSE );

    m_actionViewShowColumns = new TDEActionMenu( i18n( "&Show Columns" ), actionCollection(), "view_showcolumns" );
    m_actionViewShowColumns->setToolTip( i18n( "Select columns to show in the main list" ) );
    m_actionViewDocument = new TDEActionMenu( i18n( "View Document" ), actionCollection(), "view_document" );
    m_actionViewDocument->setToolTip( i18n( "View the documents associated with this BibTeX entry" ) );
    m_actionViewDocument->setEnabled( FALSE );
    m_actionViewFirstDocument = new TDEAction( i18n( "View Primary Document" ), 0, m_documentWidget, TQ_SLOT( slotViewFirstDocument() ), actionCollection(), "view_first_document" );
    m_actionViewFirstDocument->setShortcut( TQt::Key_F4 );
    m_actionViewDocumentOnlineRef = new TDEAction( i18n( "View Primary Online Reference" ), 0, m_documentWidget, TQ_SLOT( slotViewFirstDocumentsOnlineRef() ), actionCollection(), "view_first_documents_online_ref" );
    m_actionViewDocumentOnlineRef->setShortcut( TQt::Key_F5 );
    m_actionAssignKeywords = new TDEActionMenu( i18n( "Assign Keywords" ), actionCollection(), "assign_keywords" );
    m_actionAssignKeywords->setToolTip( i18n( "Assign keywords to this entry" ) );
    m_actionAssignKeywords->setEnabled( FALSE );
    m_actionNormalizeIds = new TDEAction( i18n( "Normalize Entry Ids" ), 0, m_documentWidget, TQ_SLOT( slotNormalizeIds() ), actionCollection( ), "normalize_ids" );
    m_actionNormalizeIds->setToolTip( i18n( "Set entry ids as specified in the id suggestion settings" ) );
    m_actionNormalizeIds->setEnabled( FALSE );

    m_actionPreferences = KStdAction::preferences( this, TQ_SLOT( slotPreferences() ), actionCollection() );
    m_actionPreferences->setToolTip( i18n( "Configure KBibTeX" ) );
    TDEAction *actionSourceEditor = new TDEAction( i18n( "Configure Source View..." ), 0, m_documentWidget, TQ_SLOT( configureEditor() ), actionCollection(), "options_configure_editor" );
    actionSourceEditor ->setToolTip( i18n( "Configure the Source Editor" ) );

    ( new TDEAction( i18n( "Article" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_article" ) ) ->setToolTip( i18n( "Add an article to the BibTeX file" ) );
    ( new TDEAction( i18n( "Book" ), "element_new_entry_book", CTRL + Key_B, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_book" ) ) ->setToolTip( i18n( "Add a book to the BibTeX file" ) );
    ( new TDEAction( i18n( "Booklet" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_booklet" ) ) ->setToolTip( i18n( "Add a booklet to the BibTeX file" ) );
    ( new TDEAction( i18n( "Electronic (IEEE)" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_electronic" ) ) ->setToolTip( i18n( "Add an electronic reference (IEEE) to the BibTeX file" ) );
    ( new TDEAction( i18n( "InBook" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_inbook" ) ) ->setToolTip( i18n( "Add a part of a book to the BibTeX file" ) );
    ( new TDEAction( i18n( "InCollection" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_incollection" ) ) ->setToolTip( i18n( "Add a publication which is part of some collection to the BibTeX file" ) );
    ( new TDEAction( i18n( "InProceedings" ), "element_new_entry_inproceedings", CTRL + Key_I, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_inproceedings" ) ) ->setToolTip( i18n( "Add a publication which is part of some proceedings to the BibTeX file" ) );
    ( new TDEAction( i18n( "Manual" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_manual" ) ) ->setToolTip( i18n( "Add a manual to the BibTeX file" ) );
    ( new TDEAction( i18n( "MastersThesis" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_mastersthesis" ) ) ->setToolTip( i18n( "Add a master or diploma thesis to the BibTeX file" ) );
    ( new TDEAction( i18n( "Misc" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_misc" ) ) ->setToolTip( i18n( "Add a not specified document or reference to the BibTeX file" ) );
    ( new TDEAction( i18n( "PhDThesis" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_phdthesis" ) ) ->setToolTip( i18n( "Add a PhD thesis to the BibTeX file" ) );
    ( new TDEAction( i18n( "Proceedings" ), "element_new_entry_phdthesis" , CTRL + Key_P, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_proceedings" ) ) ->setToolTip( i18n( "Add some proceedings to the BibTeX file" ) );
    ( new TDEAction( i18n( "TechReport" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_techreport" ) ) ->setToolTip( i18n( "Add a technical report to the BibTeX file" ) );
    ( new TDEAction( i18n( "Unpublished" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_entry_unpublished" ) ) ->setToolTip( i18n( "Add an unpublished document to the BibTeX file" ) );
    ( new TDEAction( i18n( "Preamble" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_preamble" ) ) ->setToolTip( i18n( "Add a preamble to the BibTeX file" ) );
    ( new TDEAction( i18n( "Comment" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_comment" ) ) ->setToolTip( i18n( "Add a comment to the BibTeX file" ) );
    ( new TDEAction( i18n( "Macro" ), 0, this, TQ_SLOT( slotNewElement() ), actionCollection(), "element_new_macro" ) ) ->setToolTip( i18n( "Add a macro to the BibTeX file" ) );

    m_actionEditElement = new TDEAction( i18n( "&Edit" ), 0, m_documentWidget, TQ_SLOT( editElement() ), actionCollection(), "element_edit" );
    m_actionEditElement->setToolTip( i18n( "Edit the selected BibTeX element" ) );
    m_actionEditElement->setEnabled( FALSE );
    m_actionDeleteElement = new TDEAction( i18n( "&Delete" ), 0, m_documentWidget, TQ_SLOT( deleteElements() ), actionCollection(), "element_delete" );
    m_actionDeleteElement->setToolTip( i18n( "Delete the selected BibTeX elements" ) );
    m_actionDeleteElement->setEnabled( FALSE );

    m_actionShowComments = new TDEToggleAction( i18n( "Show &Comments" ), 0, this, TQ_SLOT( slotToggleShowSpecialElements() ), actionCollection(), "view_showcomments" );
    m_actionShowComments->setToolTip( i18n( "Show the comments of a BibTeX document" ) );
    m_actionShowMacros = new TDEToggleAction( i18n( "Show &Macros" ), 0, this, TQ_SLOT( slotToggleShowSpecialElements() ), actionCollection(), "view_showmacros" );
    m_actionShowMacros->setToolTip( i18n( "Show the macros of a BibTeX document" ) );

    m_actionUseInPipe = new TDEToggleAction( i18n( "Accept input from other programs" ), 0, this , TQ_SLOT( slotUseInPipe() ), actionCollection(), "useinpipe" );

    connect( m_documentWidget, TQ_SIGNAL( listViewSelectionChanged( int ) ), this, TQ_SLOT( slotUpdateMenu( int ) ) );

    if ( m_mainWindow != NULL )
    {
        KStatusBar * statusBar = m_mainWindow->statusBar();
        if ( statusBar != NULL )
        {
            connect( actionCollection(), TQ_SIGNAL( actionStatusText( const TQString & ) ), statusBar, TQ_SLOT( message( const TQString & ) ) );
            connect( actionCollection(), TQ_SIGNAL( clearStatusText() ), statusBar, TQ_SLOT( clear() ) );
        }
    }

    actionCollection() ->setHighlightingEnabled( true );

    TDEActionMenu *acmElementNew = new TDEActionMenu( i18n( "&New" ), TQIconSet( SmallIcon( "document-new" ) ), actionCollection(), "element_new" );
    acmElementNew->setToolTip( i18n( "Add a new element to this BibTeX document" ) );
    acmElementNew->setEnabled( FALSE );
}

bool KBibTeXPart::slotNewElement()
{
    if ( isReadWrite() && sender() )
    {
        TQString elementType;

        if ( strncmp( sender() ->name(), "element_new_entry_", 18 ) == 0 )
            elementType = TQString( sender() ->name() + 18 );
        else if ( strcmp( sender() ->name(), "element_new_comment" ) == 0 )
            elementType = "comment";
        else if ( strcmp( sender() ->name(), "element_new_macro" ) == 0 )
            elementType = "macro";
        else if ( strcmp( sender() ->name(), "element_new_preamble" ) == 0 )
            elementType = "preamble";
        else
            return FALSE;

        bool result = m_documentWidget->newElement( elementType );
        if ( result )
            setModified( TRUE );
        return result;
    }

    return FALSE;
}

void KBibTeXPart::readSettings()
{
    KBibTeX::Settings * settings = KBibTeX::Settings::self();
    TDEConfig * config = KBibTeXPartFactory::instance() ->config();
    settings->load( config );

    m_actionShowComments->setChecked( settings->editing_ShowComments );
    m_actionShowMacros->setChecked( settings->editing_ShowMacros );
}

void KBibTeXPart::writeSettings()
{
    if ( !m_initializationDone )
        return ;

    KBibTeX::Settings * settings = KBibTeX::Settings::self();
    m_documentWidget->saveState();

    TDEConfig * config = KBibTeXPartFactory::instance() ->config();

    settings->editing_ShowComments = m_actionShowComments->isChecked();
    settings->editing_ShowMacros = m_actionShowMacros->isChecked();

    settings->save( config );

    config->sync();
}

void KBibTeXPart::slotUpdateMenu( int numSelectedItems )
{
    m_documentWidget->updateViewDocumentMenu();
    m_documentWidget->updateAssignKeywords();

    m_actionEditElement->setEnabled( numSelectedItems == 1 );
    m_actionDeleteElement->setEnabled( isReadWrite() && numSelectedItems > 0 );
    m_actionEditCut->setEnabled( isReadWrite() && numSelectedItems > 0 );
    m_actionEditCopy->setEnabled( numSelectedItems > 0 );
    m_actionEditCopyRef->setEnabled( numSelectedItems > 0 );
    m_actionElementSendToLyX->setEnabled( numSelectedItems > 0 );
    m_actionMenuSearchWebsites->setEnabled( numSelectedItems == 1 );
    m_actionViewDocument->setEnabled( numSelectedItems == 1 && m_actionViewDocument->popupMenu() ->count() > 0 );
    m_actionAssignKeywords->setEnabled( numSelectedItems > 0 );
    m_actionNormalizeIds->setEnabled( numSelectedItems > 0 && isReadWrite() );
}

void KBibTeXPart::slotUndoChanged( bool undoAvailable )
{
    m_actionEditUndo->setEnabled( undoAvailable );
}

void KBibTeXPart::slotUseInPipe()
{
    if ( m_inPipe == NULL && TQFile::exists( inPipeFilename ) )
    {
        KMessageBox::error( widget(), TQString( i18n( "Some other KBibTeX instance is using the pipe.\nIf this assumption is wrong, please delete '%1'." ) ).arg( inPipeFilename ), i18n( "Pipe already in use" ) );
    }
    else
    {
        if ( m_inPipe != NULL )
        {
// remove pipe
            m_inPipe->close();
            m_inPipe->remove();
            delete m_inPipe;
            m_inPipe = NULL;
            TQFile::remove( inPipeFilename );
        }
        else
        {
// create pipe
            if ( ::mkfifo( inPipeFilename.latin1(), 0600 ) == 0 )
            {
                m_inPipe = new TQFile( inPipeFilename );
                if ( !m_inPipe->open( IO_ReadOnly ) || fcntl( m_inPipe->handle(), F_SETFL, O_NONBLOCK ) < 0 )
                {
                    m_inPipe->close();
                    m_inPipe = NULL;
                }
                if ( m_inPipe == NULL )
                    TQFile::remove( inPipeFilename );
            }

            if ( m_inPipe == NULL )
                KMessageBox::error( widget(), TQString( i18n( "Could not create pipe at '%1'." ) ).arg( inPipeFilename ), i18n( "Error creating pipe" ) );
        }
    }

    m_actionUseInPipe->setChecked( m_inPipe != NULL );
}

void KBibTeXPart::slotSearchWebsites( int id )
{
    KBibTeX::Settings * settings = KBibTeX::Settings::self();
    m_documentWidget->searchWebsites( settings->searchURLs[ id - 1 ] ->url, settings->searchURLs[ id - 1 ] ->includeAuthor );
}

void KBibTeXPart::slotToggleShowSpecialElements()
{
    KBibTeX::Settings * settings = KBibTeX::Settings::self();
    settings->editing_ShowComments = m_actionShowComments->isChecked();
    settings->editing_ShowMacros = m_actionShowMacros->isChecked();

    m_documentWidget->updateViews();
}

bool KBibTeXPart::save()
{
    if ( !url().isValid() || url().isEmpty() )
        return saveAs();
    else
        return KParts::ReadWritePart::save();
}

void KBibTeXPart::slotDeferredInitialization()
{
    if ( factory() != NULL )
    {
        m_documentWidget->setFactory( factory(), this );
        m_documentWidget->deferredInitialization();
        m_initializationDone = TRUE;
    }
    else
    {
        m_defInitCounter++;

        if ( m_defInitCounter > 5 )
        {
            KMessageBox::sorry( widget(), i18n( "The KBibTeX part has problems to initialize itself. Only limited functionality will be available." ), i18n( "KBibTeX Part" ) );
            return ;
        }
        TQTimer::singleShot( 250, this, TQ_SLOT( slotDeferredInitialization() ) );
    }
}

// It's usually safe to leave the factory code alone.. with the
// notable exception of the TDEAboutData data
#include <tdeaboutdata.h>
#include <tdelocale.h>

TDEInstance* KBibTeXPartFactory::s_instance = 0L;
TDEAboutData* KBibTeXPartFactory::s_about = 0L;

KBibTeXPartFactory::KBibTeXPartFactory()
        : KParts::Factory()
{
    // nothing
}

KBibTeXPartFactory::~KBibTeXPartFactory()
{
    delete s_instance;
    delete s_about;

    s_instance = 0L;
}

KParts::Part* KBibTeXPartFactory::createPartObject( TQWidget *parentWidget, const char *widgetName,
        TQObject *parent, const char *name,
        const char *classname, const TQStringList & /* args */ )
{
    // Create an instance of our Part
    KBibTeXPart * obj = new KBibTeXPart( parentWidget, widgetName, parent, name );

    // See if we are to be read-write or not
    if ( TQCString( classname ) == "KParts::ReadOnlyPart" )
        obj->setReadWrite( false );

    return obj;
}

TDEInstance* KBibTeXPartFactory::instance()
{
    if ( !s_instance )
    {
        s_about = new TDEAboutData( "kbibtexpart", I18N_NOOP( "KBibTeXPart" ), "0.2.3.91" );
        s_about->addAuthor( "Thomas Fischer", 0, "fischer@unix-ag.uni-kl.de" );
        s_instance = new TDEInstance( s_about );
    }
    return s_instance;
}

extern "C"
{
    KDE_EXPORT void* init_libkbibtexpart()
    {
        return new KBibTeXPartFactory;
    }
};

#include "kbibtex_part.moc"