Logo Search packages:      
Sourcecode: cb2bib version File versions

c2bEditor.cpp

/***************************************************************************
 *   Copyright (C) 2004-2009 by Pere Constans
 *   constans@molspaces.com
 *   cb2Bib version 1.3.0. Licensed under the GNU GPL version 3.
 *   See the LICENSE file that comes with this distribution.
 ***************************************************************************/
#include "c2bEditor.h"

#include "bookmarkPlugin.h"
#include "c2b.h"
#include "c2bBibHighlighter.h"
#include "c2bBibParser.h"
#include "c2bExportDialog.h"
#include "c2bFileDialog.h"
#include "c2bPostprocess.h"
#include "c2bREHighlighter.h"
#include "c2bReferenceList.h"
#include "c2bSettings.h"
#include "c2bTextBrowser.h"
#include "c2bTextEdit.h"
#include "c2bUpdateMetadata.h"
#include "c2bUtils.h"
#include "findDialog.h"

#include <QCloseEvent>
#include <QDir>
#include <QDockWidget>
#include <QLabel>
#include <QMessageBox>
#include <QStackedWidget>
#include <QTextCursor>
#include <QTextStream>



/** \page c2beditor Embedded File Editor

    The cb2Bib contains a practical editor suitable to manipulate the files
    related to a cb2Bib session. Abbreviations, bookmarks, regular expressions,
    and BibTeX are readily available. On BibTeX mode, the editor contains a
    Reference List to easy file navigation and to extend the editor
    functionality. The BibTeX editor can optionally be turned to a reference
    browser.

    - \ref bookmarks
    - \ref update_metadata
    - \ref export_entries
    - \ref c2beditor_menu
    - \ref references_menu
    - \ref browser_menu
    - \ref c2beditor_qt


    \section bookmarks Bookmarks

    Bookmarks pointing to local or network files are available at the editor
    menu bar. They provide a fast access to external resources. Concretely,
    they are suitable for retrieving working documents, writing notes, or for
    accessing internet databases.

    The editor bookmark functionality had been introduced in the cb2Bib version
    0.9.3. Currently, bookmarks are set manually in the <tt>netqinf.txt</tt>
    file, see \ref c2bconf_files. Each bookmark is an entry line with the form
\htmlonly
<pre style="color : #005600; background : #d5d5d5; border : #6D8CC3 solid 1px;">
editorbookmark=Description|Target file name|Shortcut|Icon file name
</pre>
    having four fields, description, target file name, shortcut, and icon
    file name, separated with three (required) vertical bars |.

<pre style="color : #005600; background : #d5d5d5; border : #6D8CC3 solid 1px;">
# Bookmark Examples:
# - A Url:
editorbookmark=Url Description|http://www.molspaces.com/d_cb2bib-c2beditor.php#bookmarks||
# - A separator, which is a blank line:
editorbookmark=
# - A TeX document, which will be opened with its default application:
editorbookmark=Document Description|/home/doc/chapter1.tex||
# - An application, specifying a shortcut and an icon:
editorbookmark=Application Description|/opt/kde3/bin/kile|Alt+K|/usr/share/icons/kile.png
</pre>
\endhtmlonly

    <p>&nbsp;</p>
    \section update_metadata Update Documents Metadata

    The Update Documents Metadata functionality is available at the Edit and
    context menus on the BibTeX editor mode. Documents referred in the BibTeX
    file tags are scanned for metadata. If the BibTeX reference does not
    coincide with the bibliographic metadata, the document metadata is updated.
    In this way, metadata is synchronized with the BibTeX file contents. A log
    window appears, and possible errors are reported. Reported errors are,
    non-existence of a document file, read-only files, mismatches between
    BibTeX references and the actual metadata (often due to HTML tags or other
    illegal characters in BibTeX), or that the writing to the document format
    is not implemented. Note that this process will update all documents
    referenced in the BibTeX file. <b>While this process is safe, it implies
    writing into the documents.</b> Therefore take the usual measures and
    backup your data. See also \ref metadata_write.


    <p>&nbsp;</p>
    \section export_entries Export Selected Entries

    Selected entries can be exported to a separate BibTeX document. Click on
    'File->Export Entries' menu option, and provide an export filename at the
    Export Dialog. Optionally, export will copy the document files attached to
    the citation. The copy of documents is similar to the cb2Bib
    'rename/copy/move' general procedure. See \ref c2bconf_documents, on <b>Set
    directory relative to the BibTeX File Directory</b>, for copying options.
    Documents will not be overwritten: copying of existing documents is
    skipped. Possible issues are reported in the new document, as LaTeX
    comments.


    <p>&nbsp;</p>
    \section c2beditor_menu Right-Click Menu Functionality

\htmlonly
<center><table cellpadding="4" cellspacing="2" border="1"
summary="Summary table of Right-Click Menu Functionality">
<tr> <th valign="top">Keys</th> <th valign="top">Action</th></tr>
<tr> <td valign="top">Ctrl+F</td> <td valign="top">Find in text</td></tr>
<tr> <td valign="top"></td> <td valign="top">Wrap text</td></tr>
<tr> <td valign="top"></td> <td valign="top">Unwrap text</td></tr>
<tr> <td valign="top"></td> <td valign="top">Selection to LaTeX</td></tr>
<tr> <td valign="top"></td> <td valign="top">Selection to Unicode</td></tr>
<tr> <td valign="top"></td> <td valign="top">Journals to Full Name</td></tr>
<tr> <td valign="top"></td> <td valign="top">Journals to Abbreviated Name</td></tr>
<tr> <td valign="top"></td> <td valign="top">Update Documents Metadata</td></tr>
<tr> <td valign="top">Shift+Ins</td> <td valign="top">Paste current BibTeX</td></tr>
<tr> <td valign="top">Alt+P</td> <td valign="top">Save and Postprocess BibTeX file</td></tr>
</table></center>
\endhtmlonly

    <p>&nbsp;</p>
    \section references_menu Reference List Right-Click Menu Functionality

\htmlonly
<center><table cellpadding="4" cellspacing="2" border="1"
summary="Summary table of References Right-Click Menu Functionality">
<tr> <th valign="top">Keys</th> <th valign="top">Action</th></tr>
<tr> <td valign="top">Alt+C</td> <td valign="top">Cite Selected Entries</td></tr>
<tr> <td valign="top"></td> <td valign="top">Open Document File</td></tr>
<tr> <td valign="top"></td> <td valign="top">Browse by DOI</td></tr>
<tr> <td valign="top"></td> <td valign="top">Web Search by Authors</td></tr>
<tr> <td valign="top"></td> <td valign="top">Web Search by Title</td></tr>
<tr> <td valign="top"></td> <td valign="top">Web Search Settings</td></tr>
<tr> <td valign="top"></td> <td valign="top">Clear Entry Selection</td></tr>
<tr> <td valign="top"></td> <td valign="top">Refresh List and Browser View</td></tr>
</table></center>
\endhtmlonly

    <p>&nbsp;</p>
    \section browser_menu BibTeX Browser Right-Click Menu Functionality

\htmlonly
<center><table cellpadding="4" cellspacing="2" border="1"
summary="Summary table of Browser Right-Click Menu Functionality">
<tr> <th valign="top">Keys</th> <th valign="top">Action</th></tr>
<tr> <td valign="top">Alt+C</td> <td valign="top">Cite Selected Entries</td></tr>
<tr> <td valign="top"></td> <td valign="top">Local Search for selected text</td></tr>
<tr> <td valign="top"></td> <td valign="top">Web Search for selected text</td></tr>
<tr> <td valign="top"></td> <td valign="top">Web Search Settings</td></tr>
<tr> <td valign="top"></td> <td valign="top">Clear Entry Selection</td></tr>
<tr> <td valign="top"></td> <td valign="top">Refresh List and Browser View</td></tr>
</table></center>
\endhtmlonly

    <p>&nbsp;</p>
    \section c2beditor_qt Additional Functionality

\htmlonly
<center><table cellpadding="4" cellspacing="2" border="1"
summary="Summary table of Additional Functionality">
<tr> <td valign="top">Backspace</td> <td valign="top">Deletes the character to the left of the cursor</td></tr>
<tr> <td valign="top">Delete</td> <td valign="top">Deletes the character to the right of the cursor</td></tr>
<tr> <td valign="top">Ctrl+A</td> <td valign="top">Selects all text</td></tr>
<tr> <td valign="top">Ctrl+C</td> <td valign="top">Copy the selected text to the clipboard</td></tr>
<tr> <td valign="top">Ctrl+Insert</td> <td valign="top">Copy the selected text to the clipboard</td></tr>
<tr> <td valign="top">Ctrl+K</td> <td valign="top">Deletes to the end of the line</td></tr>
<tr> <td valign="top">Ctrl+V</td> <td valign="top">Pastes the clipboard text into text edit</td></tr>
<tr> <td valign="top">Shift+Insert</td> <td valign="top">Pastes the clipboard text into text edit</td></tr>
<tr> <td valign="top">Ctrl+X</td> <td valign="top">Deletes the selected text and copies it to the clipboard</td></tr>
<tr> <td valign="top">Shift+Delete</td> <td valign="top">Deletes the selected text and copies it to the clipboard</td></tr>
<tr> <td valign="top">Ctrl+Z</td> <td valign="top">Undoes the last operation</td></tr>
<tr> <td valign="top">Ctrl+Y</td> <td valign="top">Redoes the last operation</td></tr>
<tr> <td valign="top">LeftArrow</td> <td valign="top">Moves the cursor one character to the left</td></tr>
<tr> <td valign="top">Ctrl+LeftArrow</td> <td valign="top">Moves the cursor one word to the left</td></tr>
<tr> <td valign="top">RightArrow</td> <td valign="top">Moves the cursor one character to the right</td></tr>
<tr> <td valign="top">Ctrl+RightArrow</td> <td valign="top">Moves the cursor one word to the right</td></tr>
<tr> <td valign="top">UpArrow</td> <td valign="top">Moves the cursor one line up</td></tr>
<tr> <td valign="top">Ctrl+UpArrow</td> <td valign="top">Moves the cursor one word up</td></tr>
<tr> <td valign="top">DownArrow</td> <td valign="top">Moves the cursor one line down</td></tr>
<tr> <td valign="top">Ctrl+Down Arrow</td> <td valign="top">Moves the cursor one word down</td></tr>
<tr> <td valign="top">PageUp</td> <td valign="top">Moves the cursor one page up</td></tr>
<tr> <td valign="top">PageDown</td> <td valign="top">Moves the cursor one page down</td></tr>
<tr> <td valign="top">Home</td> <td valign="top">Moves the cursor to the beginning of the line</td></tr>
<tr> <td valign="top">Ctrl+Home</td> <td valign="top">Moves the cursor to the beginning of the text</td></tr>
<tr> <td valign="top">End</td> <td valign="top">Moves the cursor to the end of the line</td></tr>
<tr> <td valign="top">Ctrl+End</td> <td valign="top">Moves the cursor to the end of the text</td></tr>
<tr> <td valign="top">Alt+Wheel</td> <td valign="top">Scrolls the page horizontally</td></tr>
<tr> <td valign="top">Ctrl+Wheel</td> <td valign="top">Zooms the text</td></tr>
</table></center>
\endhtmlonly

    <p>&nbsp;</p>
*/


c2bEditor::c2bEditor(const QString& file, const QString& mode, QWidget* main, QWidget* parentw) : QMainWindow(parentw)
{
    EFile = QDir::toNativeSeparators(file);
    EditorMode = mode;
    _c2b_mainP = main;
    bibSearcher = 0;
    initEditor();
}

c2bEditor::c2bEditor(const QString& file, c2bBibSearcher* searcher, QWidget* main, QWidget* parentw) : QMainWindow(parentw)
{
    EFile = QDir::toNativeSeparators(file);
    EditorMode = "BibTeX";
    _c2b_mainP = main;
    bibSearcher = searcher;
    initEditor();
}

c2bEditor::~c2bEditor()
{
    if (Browser)
        settings->setValue("c2bEditor/BrowserFontPointSize", Browser->font().pointSize());
}


void c2bEditor::initEditor()
{
    ui.setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);

    settings = c2bSettingsP;
    if (EditorMode == "BibTeX")
        bp = c2b::bibParser();
    else
        bp = 0;
    Browser = 0;
    Editor = new c2bTextEdit(this);
    RList = 0;
    stackedWidget = new QStackedWidget(this);
    setCentralWidget(stackedWidget);
    stackedWidget->addWidget(Editor);
    textFinder = new findDialog(this);
    lineLabel = new QLabel();
    lineLabel->setText(tr(" Line: 1 Col: 1 "));
    lineLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
    lineLabel->setFrameStyle(QFrame::NoFrame);
    lineLabel->setLineWidth(1);
    lineLabel->setFixedHeight(lineLabel->fontMetrics().height());
    statusBar()->addWidget(lineLabel, 1);
    connect(Editor, SIGNAL(cursorPositionChanged()), this, SLOT(cursorPositionChanged()));
    overwriteLabel = new QLabel();
    overwriteLabel->setText(tr(" INS "));
    overwriteLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
    overwriteLabel->setFrameStyle(QFrame::NoFrame);
    overwriteLabel->setLineWidth(1);
    overwriteLabel->setFixedHeight(overwriteLabel->fontMetrics().height());
    statusBar()->addWidget(overwriteLabel);
    Editor->setOverwriteMode(false);
    connect(Editor, SIGNAL(overwriteModeChanged()), this, SLOT(overwriteModeChanged()));
    connect(ui.fileCloseAction, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui.fileExecAction, SIGNAL(triggered()), this, SLOT(saveAndExecute()));
    connect(ui.fileExitAction, SIGNAL(triggered()), c2b::instance(), SLOT(exitRequested()));
    connect(ui.fileSaveAction, SIGNAL(triggered()), this, SLOT(fileSave()));
    connect(ui.fileSaveAsAction, SIGNAL(triggered()), this, SLOT(fileSaveAs()));
    connect(ui.helpEditorAction, SIGNAL(triggered()), this, SLOT(helpEditor()));
    connect(ui.helpCb2BibAction, SIGNAL(triggered()), this, SLOT(helpCb2Bib()));
    connect(ui.viewCb2BibAction, SIGNAL(triggered()), this, SLOT(viewCb2Bib()));

    // Standard shortcuts
    ui.fileCloseAction->setShortcut(QKeySequence(QKeySequence::Close));
    ui.fileOpenAction->setShortcut(QKeySequence(QKeySequence::Open));
    ui.fileSaveAction->setShortcut(QKeySequence(QKeySequence::Save));
#if QT_VERSION >= 0x040500
    ui.fileSaveAsAction->setShortcut(QKeySequence(QKeySequence::SaveAs));
#endif
    ui.helpEditorAction->setShortcut(QKeySequence(QKeySequence::HelpContents));
    ui.viewZoomInAction->setShortcut(QKeySequence(QKeySequence::ZoomIn));
    ui.viewZoomOutAction->setShortcut(QKeySequence(QKeySequence::ZoomOut));

    // Editor Settings
    resize(settings->value("c2bEditor/size", size()).toSize());
    ui.menuView->addAction(ui.toolBar->toggleViewAction());
    ui.setLyXPipeAction->setVisible(false);
    Editor->setFont(settings->c2bMonoFont);
    connect(ui.settingsCb2BibAction, SIGNAL(triggered()), c2b::instance(), SLOT(configure()));

    // Bookmarks
    bookmarkPlugin* bookmarks = new bookmarkPlugin(this);
    menuBar()->insertMenu(ui.menuSettings->menuAction(), bookmarks);
    connect(bookmarks, SIGNAL(openFile(const QString&)), this, SIGNAL(openFile(const QString&)));
    connect(bookmarks, SIGNAL(editBookmarks()), this, SIGNAL(openBookmarks()));

    load();
    setEditorMode();
    importActions();
    connect(Editor->document(), SIGNAL(contentsChange(int, int, int)), this, SLOT(isModified(int, int, int)));
    connect(c2b::instance(), SIGNAL(statusMessage(const QString&)), this, SLOT(showMessage(const QString&)));
}

void c2bEditor::setEditorMode()
{
    if (EditorMode == "RegExp")
    {
        sH = new c2bREHighlighter(Editor->document());
        ui.fileExecAction->setText(tr("Restart Recognition"));
        ui.fileExecAction->setStatusTip(tr("Restart Recognition"));
        ui.fileExecAction->setShortcut(tr("Alt+R"));
        connect(this, SIGNAL(execute()), this, SIGNAL(restartEngine()));
        ui.toolBar->setVisible(settings->value("c2bEditor/ToolBar", true).toBool());
        setViewMode(true);
    }
    else if (EditorMode == "NetQInfo")
    {
        sH = new c2bREHighlighter(Editor->document());
        ui.fileExecAction->setText(tr("Restart Network Query"));
        ui.fileExecAction->setStatusTip(tr("Restart Network Query"));
        ui.fileExecAction->setShortcut(tr("Alt+N"));
        connect(this, SIGNAL(execute()), this, SIGNAL(restartQuery()));
        ui.toolBar->setVisible(settings->value("c2bEditor/ToolBar", true).toBool());
        setViewMode(true);
    }
    else if (EditorMode == "JAbbrev")
    {
        ui.fileExecAction->setVisible(false);
        ui.toolBar->setVisible(settings->value("c2bEditor/ToolBar", true).toBool());
        setViewMode(true);
    }
    else if (EditorMode == "BibTeX")
    {
        // Editor
        sH = new c2bBibHighlighter(Editor->document());
        ui.fileOpenAction->setVisible(true);
        connect(ui.fileOpenAction, SIGNAL(triggered()), this, SLOT(fileOpen()));
        Editor->setBibTeXActions();
        connect(Editor->pasteCurrentBibTeXAction, SIGNAL(triggered()), this, SLOT(pasteCurrentBibTeX()));
        connect(Editor->journalsToFullAction, SIGNAL(triggered()), this, SLOT(journalsToFull()));
        connect(Editor->journalsToAbbreviatedAction, SIGNAL(triggered()), this, SLOT(journalsToAbbreviated()));
        connect(Editor->updateMetadataAction, SIGNAL(triggered()), this, SLOT(updateMetadata()));
        connect(_c2b_mainP, SIGNAL(addedBibToFile(const QString&)), this, SLOT(reload(const QString&)));
        ui.fileExecAction->setText(tr("Save and Postprocess"));
        ui.fileExecAction->setStatusTip(tr("Save and Postprocess"));
        ui.fileExecAction->setShortcut(tr("Alt+P"));
        connect(this, SIGNAL(execute()), this, SLOT(postProcess()));

        // Browser
        Browser = new c2bTextBrowser(this);
        Browser->setFont(QFont(QFont().family(), settings->value("c2bEditor/BrowserFontPointSize", QFont().pointSize()).toInt()));
        stackedWidget->addWidget(Browser);
        ui.viewEditorModeAction->setVisible(true);
        connect(ui.viewEditorModeAction, SIGNAL(triggered(bool)), this, SLOT(setViewMode(bool)));
        connect(ui.viewZoomInAction, SIGNAL(triggered()), Browser, SLOT(zoomIn()));
        connect(ui.viewZoomOutAction, SIGNAL(triggered()), Browser, SLOT(zoomOut()));

        // Reference List
        createReferenceList();
        RList->loadList(Editor->toPlainText(), bibSearcher);
        bool edit_mode = false;
        if (bibSearcher)
        {
            edit_mode = (bibSearcher->hitCount() == 0 && bibSearcher->errorCount() > 0);
            connect(RList, SIGNAL(openFile(const QString&)), this, SIGNAL(openFile(const QString&)));
        }
        if (!edit_reference_at_position.isEmpty())
        {
            edit_mode = true;
            RList->goToReference(edit_reference_at_position.toInt());
        }
        ui.viewEditorModeAction->setChecked(edit_mode);
        setViewMode(edit_mode);
        ui.setLyXPipeAction->setVisible(true);

        // Export entries
        ui.fileExportEntriesAction->setVisible(true);
        connect(ui.fileExportEntriesAction, SIGNAL(triggered()), this, SLOT(exportEntries()));
        connect(RList, SIGNAL(hasSelectedItems(bool)), ui.fileExportEntriesAction, SLOT(setEnabled(bool)));
    }
    else
        c2bUtils::debug(tr("c2bEditor::setEditorMode: '%1' invalid Editor Mode.").arg(EditorMode));
}

void c2bEditor::importActions()
{
    QList<QAction*> acts = textFinder->actions();
    for (int i = 0; i < acts.count(); ++i)
        ui.menuEdit->addAction(acts.at(i));
    acts = Editor->actions();
    for (int i = 0; i < acts.count(); ++i)
        ui.menuEdit->addAction(acts.at(i));
    if (Browser)
    {
        ui.menuEdit->addSeparator();
        acts = Browser->actions();
        for (int i = 0; i < acts.count(); ++i)
            ui.menuEdit->addAction(acts.at(i));
    }
}

void c2bEditor::createReferenceList()
{
    dwRList = new QDockWidget(this);
    dwRList->setObjectName("dwRList");
    RList = new c2bReferenceList(Editor, Browser, dwRList);
    addDockWidget(Qt::BottomDockWidgetArea, dwRList);
    dwRList->setWidget(RList);
    dwRList->setWindowTitle("Reference List");
    QByteArray state = settings->value("c2bEditor/state").toByteArray();
    restoreState(state);
    ui.menuView->addAction(dwRList->toggleViewAction());
    // State contains toolBar info, too, but it can be changed from non BibTeX editors
    // State can not be used for non BibTeX editors. They don't have referenceList.
    ui.toolBar->setVisible(settings->value("c2bEditor/ToolBar", true).toBool());
    connect(ui.setLyXPipeAction, SIGNAL(triggered()), RList, SLOT(setLyXPipe()));
}

void c2bEditor::closeEvent(QCloseEvent* qevent)
{
    if (closeEditor())
        qevent->accept();
    else
        qevent->ignore();
}

bool c2bEditor::closeEditor()
{
    if (ui.fileSaveAction->isEnabled())
    {
        int button = QMessageBox::information(this, tr("Information - cb2Bib"),
                                              tr("The document has been modified.\nDo you want to save the changes?"),
                                              QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,
                                              QMessageBox::Save);
        if (button == QMessageBox::Save)
        {
            if (!fileSave())
                return false;
        }
        else if (button == QMessageBox::Cancel)
            return false;
    }
    settings->setValue("c2bEditor/size", size());
    if (EditorMode == "BibTeX")
        settings->setValue("c2bEditor/state", saveState());
    settings->setValue("c2bEditor/ToolBar", !ui.toolBar->isHidden());
    return true;
}

void c2bEditor::isModified(int position, int charsRemoved, int charsAdded)
{
    if (position == 0 && charsAdded == charsRemoved)
        return;
    ui.fileSaveAction->setEnabled(true);
    setWindowModified(true);
}

void c2bEditor::fileOpen()
{
    if (EditorMode == "BibTeX")
    {
        QString filename = c2bFileDialog::getOpenFilename(this, "Select a BibTeX filename", EFile, "BibTeX (*.bib)");
        if (!filename.isEmpty())
            emit openFile(filename);
    }
}

bool c2bEditor::fileSave()
{
    if (EFile.contains("unnamed_"))
        return fileSaveAs();
    QFile file(EFile);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::warning(this, tr("Warning - cb2Bib"),
                             tr("Unable to open the file %1 for writing.\nError: '%2'.").
                             arg(EFile).arg(file.errorString()),
                             QMessageBox::Ok);
        return false;
    }
    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    stream.setAutoDetectUnicode(true);
    stream << Editor->toPlainText();
    ui.fileSaveAction->setEnabled(false);
    Editor->document()->setModified(false);
    setWindowModified(false);
    return true;
}

bool c2bEditor::fileSaveAs()
{
    QString filename;
    if (EditorMode == "BibTeX")
        filename = c2bFileDialog::getSaveFilename(this, "", EFile, "BibTeX (*.bib);;All (*)");
    else
        filename = c2bFileDialog::getSaveFilename(this, "", EFile, "Text (*.txt);;All (*)");
    if (filename.isEmpty() || filename.contains("unnamed_"))
        return false;
    QString old_name = EFile;
    EFile = filename;
    setWindowTitle(tr("%1[*] - cb2Bib").arg(EFile));
    Editor->setEditorFilename(EFile);
    emit editFileRenamed(old_name, EFile);
    return fileSave();
}

void c2bEditor::saveAndExecute()
{
    if (ui.fileSaveAction->isEnabled())
    {
        if (fileSave())
            emit execute();
    }
    else
        emit execute();
}

void c2bEditor::load()
{
    bool modified_flag = false;
    QFileInfo fi(EFile);
    if (EFile.isEmpty() || fi.isDir())  // Set an appropriate working name
    {
        QStringList unamedList;
        foreach(QWidget* widget, QApplication::topLevelWidgets())
        {
            if (widget->inherits("c2bEditor"))
                unamedList.append(widget->objectName());
        }
        int i = 1;
        while (unamedList.indexOf(QRegExp(QString(".*unnamed_%1.bib").arg(i))) > -1) ++i;
        EFile = QDir::toNativeSeparators(QDir::cleanPath(EFile + QDir::separator() + QString("unnamed_%1.bib").arg(i)));
        if (bibSearcher)
        {
            Editor->setPlainText(bibSearcher->logString + bibSearcher->hitString);
            modified_flag = true;
        }
    }
    else
    {
        QRegExp edit_ref_id(":(\\d+)$");
        if (edit_ref_id.indexIn(EFile) > -1)
        {
            edit_reference_at_position = edit_ref_id.cap(1);
            EFile.remove(edit_ref_id);
        }
        QFile file(EFile);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QMessageBox::warning(_c2b_mainP,
                                 tr("Warning - cb2Bib"), tr("Unable to open the file %1 for reading.\nError: '%2'.").
                                 arg(EFile).arg(file.errorString()),
                                 QMessageBox::Ok);
        }
        else
        {
            QTextStream stream(&file);
            stream.setCodec("UTF-8");
            stream.setAutoDetectUnicode(true);
            Editor->setPlainText(stream.readAll());
        }
    }
    setWindowTitle(tr("%1[*] - cb2Bib").arg(EFile));
    Editor->setEditorFilename(EFile);
    ui.fileSaveAction->setEnabled(modified_flag);
    Editor->document()->setModified(modified_flag);
    setWindowModified(modified_flag);
}

void c2bEditor::reload(const QString& f)
{
    // This function must be called ONLY in BibTeX mode
    // Pointers are undefined otherwise
    if (EditorMode != "BibTeX" || EFile != f)
        return;

    if (ui.fileSaveAction->isEnabled())
    {
        QMessageBox msgBox(this);
        msgBox.addButton(tr("Discard and Reload"), QMessageBox::AcceptRole);
        msgBox.addButton(QMessageBox::Cancel);
        msgBox.setDefaultButton(msgBox.addButton(QMessageBox::Save));
        msgBox.setWindowTitle(tr("Information - cb2Bib"));
        msgBox.setText(tr("The document has been modified on disk when the reference was inserted. "
                          "No automatic reloading is done because it also has local changes. "
                          "To preserve local changes press Save and insert again the last reference.\n\n"
                          "Do you want to save the changes?"));
        msgBox.setIcon(QMessageBox::Information);
        int button = msgBox.exec();
        if (button == QMessageBox::Save)
        {
            fileSave();
            RList->refreshList();
            return;
        }
        else if (button == QMessageBox::Cancel)
            return;
    }
    load();
    RList->refreshList();
    QTextCursor cur = Editor->textCursor();
    cur.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
    Editor->setTextCursor(cur);
    Editor->ensureCursorVisible();
}

void c2bEditor::exportEntries()
{
    const QStringList keys = RList->selectedKeys();
    if (keys.count() == 0)
        return;
    c2bExportDialog ed(EFile, keys, this);
    if (ed.exec())
        emit openFile(ed.exportFilename());
}

void c2bEditor::pasteCurrentBibTeX()
{
    Editor->insertPlainText(bp->toBibTeX(false));
}

void c2bEditor::journalsToFull()
{
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    const QString text = bp->setJournalsToFull(Editor->toPlainText());
    Editor->updatePlainText(text);
    QApplication::restoreOverrideCursor();
}

void c2bEditor::journalsToAbbreviated()
{
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    const QString text = bp->setJournalsToAbbreviated(Editor->toPlainText());
    Editor->updatePlainText(text);
    QApplication::restoreOverrideCursor();
}

void c2bEditor::updateMetadata()
{
    c2bUpdateMetadata um(this);
    um.update(EFile, Editor->toPlainText());
}

void c2bEditor::postProcess()
{
    c2bPostprocess* ppBib = new c2bPostprocess(EFile, this);
    ppBib->show();
}

void c2bEditor::helpEditor()
{
    c2bUtils::displayHelp("http://www.molspaces.com/d_cb2bib-c2beditor.php");
}

void c2bEditor::helpCb2Bib()
{
    c2bUtils::displayHelp("http://www.molspaces.com/cb2bib/index.html");
}

void c2bEditor::viewCb2Bib()
{
    c2bUtils::setWidgetOnTop(_c2b_mainP);
}

void c2bEditor::setViewMode(bool edit_mode)
{
    QList<QAction*> acts;
    if (edit_mode)
    {
        textFinder->setEditor(Editor);
        if (Browser)
        {
            acts = Browser->actions();
            for (int i = 0; i < acts.count(); ++i)
                acts.at(i)->setVisible(false);
            ui.viewZoomInAction->setVisible(false);
            ui.viewZoomOutAction->setVisible(false);
        }
        acts = Editor->actions();
        for (int i = 0; i < acts.count(); ++i)
            acts.at(i)->setVisible(true);
        stackedWidget->setCurrentWidget(Editor);
    }
    else
    {
        // Browser defined
        textFinder->setEditor(Browser);
        acts = Editor->actions();
        for (int i = 0; i < acts.count(); ++i)
            acts.at(i)->setVisible(false);
        acts = Browser->actions();
        for (int i = 0; i < acts.count(); ++i)
            acts.at(i)->setVisible(true);
        ui.viewZoomInAction->setVisible(true);
        ui.viewZoomOutAction->setVisible(true);
        stackedWidget->setCurrentWidget(Browser);
    }
}

void c2bEditor::showMessage(const QString& ms)
{
    statusBar()->showMessage(ms, C2B_MESSAGE_TIME);
}

void c2bEditor::cursorPositionChanged()
{
    int lineNumber = 0;
    QTextBlock current = Editor->textCursor().block();
    QTextBlock b;
    for (b = Editor->document()->begin(); b.isValid(); b = b.next())
    {
        ++lineNumber;
        if (b == current)
            break;
    }
    int linePosition = Editor->textCursor().position() - current.position() + 1;
    lineLabel->setText(tr(" Line: %1 Col: %2 ").arg(lineNumber).arg(linePosition));
}

void c2bEditor::overwriteModeChanged()
{
    if (Editor->overwriteMode())
        overwriteLabel->setText(tr(" OVR "));
    else
        overwriteLabel->setText(tr(" INS "));
}

QString c2bEditor::editorFilename() const
{
    return EFile;
}

Generated by  Doxygen 1.6.0   Back to index